0

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...

  • @J.F.Sebastian The questions seems to be about any random setup.py, so he hasn't control over whatever method is used to get file path – Antoine Apr 28 '14 at 00:00
  • @J.F.Sebastian What I'm saying is that the question is about "How to trick a script that uses `__file__` with execfile". – Antoine Apr 28 '14 at 00:03

2 Answers2

1

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)
Antoine
  • 3,880
  • 2
  • 26
  • 44
0

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

Community
  • 1
  • 1
Jan Vlcinsky
  • 42,725
  • 12
  • 101
  • 98