Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporary PYTHONPATH in Windows

How do I set, temporarily, the PYTHONPATH environment variable just before executing a Python script?

In *nix, I can do this:

$ PYTHONPATH='.' python scripts/doit.py

In Windows, this syntax does not work, of course. What is the equivalent, though?

like image 362
Santa Avatar asked May 25 '10 01:05

Santa


People also ask

How do I find my Python path in CMD?

For the first approach, open the Command Prompt and utilize the “where python” command. In the second approach, search “python.exe” in the “Startup” menu and open the file location. In the third approach, you can find out Python location through the “Path” Environment Variable.

How do I permanently set Pythonpath?

System > Control Panel > Advanced system settings > Advanced (tap) Environment Variables > System variables > (if you don't see PYTHONPATH in Variable column) (click) New > Variable name: PYTHONPATH > Variable value: Please, write the directory in the Variable value.

How do I set Environment Variables in Python Windows 10?

To permanently modify the default environment variables, click Start and search for 'edit environment variables', or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables.


3 Answers

How temporarily? If you open a Windows console (cmd.exe), typing:

set PYTHONPATH=.

will change PYTHONPATH for that console only and any child processes created from it. Any python scripts run from this console will use the new PYTHONPATH value. Close the console and the change will be forgotten.

like image 151
Mark Tolonen Avatar answered Nov 01 '22 02:11

Mark Tolonen


To set and restore an environment variable on Windows' command line requires an unfortunately "somewhat torturous" approach...:

SET SAVE=%PYTHONPATH%
SET PYTHONPATH=.
python scripts/doit.py
SET PYTHONPATH=%SAVE%

You could use a little auxiliary Python script to make it less painful, e.g.

import os
import sys
import subprocess

for i, a in enumerate(sys.argv[1:]):
    if '=' not in a: break
    name, _, value = a.partition('=')
    os.environ[name] = value

sys.exit(subprocess.call(sys.argv[i:]))

to be called as, e.g.,

python withenv.py PYTHONPATH=. python scripts/doit.py

(I've coded it so it works for any subprocess, not just a Python script -- if you only care about Python scripts you could omit the second python in the cal and put 'python' in sys.argv[i-1] in the code, then use sys.argv[i-1:] as the argument for subprocess.call).

like image 28
Alex Martelli Avatar answered Nov 01 '22 00:11

Alex Martelli


In Windows, you can set PYTHONPATH as an environment variable, which has a GUI front end. On most versions of Windows, you can launch by right click on My Computer and right click Properties.

like image 34
Kevin Le - Khnle Avatar answered Nov 01 '22 01:11

Kevin Le - Khnle