Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flexibly change PYTHONPATH

To specify the classpath in Java, I use the -cp or -classpath option to java. What is the equivalent option in Python?

I know I can set the OS variable PYTHONPATH but there shouldn't be one PYTHONPATH to rule them all.

I sometimes use PyDev in Eclipse. It can handle multiple source directories. How?

I often have multiple source directories. Sometimes I separate production and testing code. Sometimes I have a Git submodule with with some Python packages.

like image 790
Paul Draper Avatar asked Apr 19 '13 14:04

Paul Draper


2 Answers

To specify the classpath in Java, I use the -cp or -classpath option to java. What is the equivalent option in Python?

Well, there's no "equivalent option" in Python as far as I'm aware, but any Unix-like shell will let you set/override it on a per-process basis, if you were to run Python like this...

$ PYTHONPATH=/put/path/here python myscript.py

...a syntax which you could also use for Java with...

$ CLASSPATH=/put/path/here java MyMainClass

The closest Windows equivalent to this would be...

> cmd /c "set PYTHONPATH=\put\path\here && python myscript.py"

...if you don't want the environment variable to be set in the calling cmd.exe.

I sometimes use PyDev in Eclipse. It can handle multiple source directories. How?

When running code, it probably does something similar by setting the variable in the execve(2) call.

like image 190
Aya Avatar answered Oct 01 '22 09:10

Aya


To do this programmatically, you use the following code:

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

If necessary you could specify the directory to append from a command line argument.

Depending on what exactly your aims are, this might not be the best solution, but for small one-off kinds of issues, it works alright.

like image 32
mattg Avatar answered Oct 01 '22 09:10

mattg