Python - add PYTHONPATH during command line module run

orokusaki picture orokusaki · Jan 2, 2011 · Viewed 144.3k times · Source

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.

Answer

ismail picture ismail · Jan 2, 2011

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