Search code examples
pythonorganizationpythonpath

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.


Solution

  • 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.