Search code examples
pythonpython-importworking-directoryexecfile

execfile in it's working directory from other file


I have structure like this:

c
|-myMain.py
|-.....\someDir
              |-startup.py
              |-subDir
                     |-x.py

I've found few similar questions, and answers bring me to this:

#myMain.py
import os
if __name__ == '__main__':
    os.chdir("c:\\......\\someDir")
    execfile("startup.py")

#startup.py
from subDir import x
if __name__ == '__main__':
    x.doSomething()

Problem is that import fails in startup.py when I run myMain.py:

ImportError: No module named subDir

but, it works when I run startup.py directly. Any help would be appreciated.


Solution

  • In order for python to see subDir as a valid python structure, you must make it a package. You make it a package by including a __init__.py file in that directory. The file can be empty.

    Once subDir has such a file, the statement from subDir import x should work.