7

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.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285

3 Answers3

7

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.

Aya
  • 39,884
  • 6
  • 55
  • 55
  • The per-process single command was what I was looking for. Does anyone know a way to do this with Windows too? – Paul Draper Apr 19 '13 at 15:47
  • @PaulDraper If you mean in `cmd.exe`, I think you have to do it in two calls, i.e. `SET PYTHONPATH=blah` then `python blah`. You could wrap it in a batch file, but it would remain set after the batch file terminated, unless you wrapped the batch file with another batch file which used `CALL` to call it, which, IIRC, creates a new environment. – Aya Apr 19 '13 at 16:00
  • 1
    @PaulDraper actually, there's an easier way - see updated answer. – Aya Apr 19 '13 at 16:08
2

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.

mattg
  • 1,731
  • 1
  • 12
  • 20
1

This is what virtualenv is for.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Yes...I looked at that, but I though I must have mistaken about its use. since nobody would require that, just where a simple command line arg could have sufficed... – Paul Draper Apr 19 '13 at 15:36