15

I'm having some very mysterious behavior with a script that fails to run. Obviously the script below is trivial and does nothing, but it's reproducing behavior in a real script. Here's the code inside a file called test.py.

import os
os.chdir('/home/jacob/twcSite')
import app

app is located in 'home/jacob/twcSite', which is a different directory than the current one, containing test.py. If I type python test.py at the command line, I get ImportError: No module named app. However, if I simply type python to launch the interactive interpreter and copy-paste the exact same three commands, then it works just fine without an import error.

What could possibly be causing this error? It's the same version of python. The exact same lines of code. Why do I get different behavior in either case? Just to give more details, if you print the output to os.getcwd() before and after calling os.chdir it does indeed claim to have changed to the right directory (though clearly that's not the case). I'm running Ubuntu 14.04, Python version 2.7.6.

J-bob
  • 8,380
  • 11
  • 52
  • 85
  • 2
    I would check out http://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path for importing your own custom python modules. Just remember to have a `__init__.py ` file to identify the module. – signus May 12 '14 at 22:02

2 Answers2

18

Changing directory doesn't alter you import paths, it just changes the directory for opening files and whatnot.

See sys.path

import sys
sys.path.append('/home/jacob/twcSite')
import app
Kyle James Walker
  • 1,238
  • 14
  • 16
  • can you explain, then, why the code works when I type it directly into the interpreter but not when I run it as a script inside a file? – J-bob May 13 '14 at 02:17
  • When your running in the interpreter it may actually be changing the directory, and as the code is `live` it works. But when you run `python example.py` it's being launched from the shell so it's working differently. That's just a guess though. – Kyle James Walker May 16 '14 at 20:09
  • Ok, that's reasonable explanation. Just to make this more complicated - the script totally worked the wrong way when I ran it on an OSX machine. It didn't start giving me trouble until I tried to run it on a linux machine. But the way you told me works in both scenarios. – J-bob May 16 '14 at 21:35
  • Great solution, works well – Kfcaio Sep 30 '18 at 17:33
2

Changing the current directory is not the way to deal with finding modules in Python. As the directory is not included in Python search scope, you'd add it manually by using the following code:

import os.path, sys
app_dir = os.path.join('home', 'jacob', 'twcSite')
sys.path.insert(0, app_dir)

import app
stanleyxu2005
  • 8,081
  • 14
  • 59
  • 94