Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my python not add current working directory to the path?

I keep seeing sites mentioning that the directory that you execute 'python ' get added to the python path. For example on http://www.stereoplex.com/blog/understanding-imports-and-pythonpath, the author cd's to the /tmp folder then does 'print(sys.path)' and lo and behold, the /tmp folder appears in the path list. Here is me trying this out on my system (with 2.6.6 installed):

example structure:

app/   mymodule.py   inner_folder/     myscript.py 

in myscript.py contains the line:

import mymodule.py 

what I did:

cd app python inner_folder/myscript.py # ImportError 

Since I am executing the interpreter from the app/ directory, shouldn't 'app' be added to the python path? This is how a lot of the docs I have been reading have specified the behaviour should be.

Please enlighten!

(I have temporarily solved this by manually adding the folder I want into the environment but don't want to rely on that forever. Since many sites say this can be done, I'd like to reproduce it for myself)

like image 379
trinth Avatar asked Jun 20 '11 19:06

trinth


People also ask

How do I get the current working directory in Python?

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

How do I add a directory to a path in Python?

Clicking on the Environment Variables button o​n the bottom right. In the System variables section, selecting the Path variable and clicking on Edit. The next screen will show all the directories that are currently a part of the PATH variable. Clicking on New and entering Python's install directory.

How do I fix the working directory in Python?

To change the current working directory(CWD) os. chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.


1 Answers

It is the script's directory that is added, not the current directory. If you turn inner_folder/ into a package then you can use python -m inner_folder.myscript in order to run the script while having app/ added to sys.path.

like image 189
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 03:09

Ignacio Vazquez-Abrams