Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's os.chdir function isn't working [duplicate]

Tags:

python

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.

like image 612
J-bob Avatar asked May 12 '14 21:05

J-bob


People also ask

What does OS chdir (' ') do?

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.

How do I change directory in OS chdir?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .


2 Answers

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
like image 115
Kyle James Walker Avatar answered Sep 27 '22 19:09

Kyle James Walker


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
like image 45
stanleyxu2005 Avatar answered Sep 27 '22 19:09

stanleyxu2005