Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - add PYTHONPATH during command line module run

I want to run:

python somescript.py somecommand 

But, when I run this I need PYTHONPATH to include a certain directory. I can't just add it to my environment variables because the directory I want to add changes based on what project I'm running. Is there a way to alter PYTHONPATH while running a script? Note: I don't even have a PYTHONPATH variable, so I don't need to worry about appending to it vs overriding it during running of this script.

like image 313
orokusaki Avatar asked Jan 02 '11 19:01

orokusaki


People also ask

How do I permanently add to Pythonpath?

Type open . bash_profile. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar. Save the file, restart the Terminal, and you're done.

How do I change Python path in CMD?

You will still need to click the Environment Variables... button in either case under the Advanced tab from the System Properties dialog box. Click Edit and add your C:\path\to\your\preferred\python.exe path to the appropriate PATH (User) and/or Path (System) variable list. Click OK when finished.

How do you assign a path to a Python module?

So, to ensure that your module is found, you need to do one of the following: Put mod.py in the directory where the input script is located, or the current directory if interactive. Modify the PYTHONPATH environment variable to contain the directory where mod.py is located before starting the interpreter.


2 Answers

For Mac/Linux;

PYTHONPATH=/foo/bar/baz python somescript.py somecommand 

For Windows, setup a wrapper pythonpath.bat;

@ECHO OFF setlocal set PYTHONPATH=%1 python %2 %3 endlocal 

and call pythonpath.bat script file like;

pythonpath.bat /foo/bar/baz somescript.py somecommand 
like image 150
ismail Avatar answered Oct 10 '22 10:10

ismail


 import sys  sys.path.append('your certain directory') 

Basically sys.path is a list with all the search paths for python modules. It is initialized by the interpreter. The content of PYTHONPATH is automatically added to the end of that list.

like image 21
Piotr Czapla Avatar answered Oct 10 '22 10:10

Piotr Czapla