1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Aleksandar
  • 3,541
  • 4
  • 34
  • 57
  • 1
    Does `subDir` have a `__init__.py` file? – Martijn Pieters Nov 23 '12 at 15:10
  • 1
    FWIW, you could avoid having to do the `chdir()` to a hardcoded fully qualified path with something like `STARTUP_FILE = os.path.join(os.path.dirname(__file__), 'someDir', 'startup.py')` followed by `execfile(STARTUP_FILE)`. – martineau Nov 23 '12 at 16:11

2 Answers2

1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Future readers:

Pradyumna's answer from here solved this issue for me:

import sys, change "sys.path" by appending the path during run time,then import the module that will help

[i.e. sys.path.append(execfile's directory)]

Shmuelt
  • 119
  • 8