Reputation: 7
In my app I have a setup python script (/root/ha/setup.py) which looks through a directory called modules and runs setup.py in each of the subdirectories.
The relevant code is this:
""" Exec the module's own setup file """
if os.path.isfile(os.path.join(root, module, "setup.py")):
execfile(os.path.join(root, module, "setup.py"))
The thing is I want /root/ha/modules/modulename/setup.py to work no matter where it's called from.
If I am in modules/modulename and run python setup.py it's fine but if I run it from the directory above modules/ i get this error
idFile = open(os.path.dirname(os.path.abspath(__file__)) + "/id.txt", "r").read()
IOError: [Errno 2] No such file or directory: '/root/ha/id.txt'
as you can see it is getting the path of the script that is calling it instead of the script that is running. It should be trying to read /root/ha/modules/modulename/id.txt
I've tried using different methods to get the path but all end up with this error...
Upvotes: 0
Views: 930
Reputation: 44112
If what you need is to access a file from some of your packages, then consider using pkg_resources
as documented here: http://pythonhosted.org/setuptools/pkg_resources.html#basic-resource-access
Example of getting content of a file stored as part of package named package
is in this SO answer
Upvotes: 0
Reputation: 4029
execfile
does not modify the globals (as __file__
) so the exectued script will indeed take an incorrect path.
You can pass global variables to execfile
so you can modify its __file__
variable:
script = os.path.join(root, module, "setup.py")
if os.path.isfile(script):
g = globals().copy()
g['__file__'] = script
execfile(script, g)
Upvotes: 1