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.
This os. chdir() method changes the current working directory to a specified path instance. It does not return any value. This descriptor path must refer to the open directory, not to an open file.
To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With