6

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?

asked May 25, 2010 at 1:17

5 Answers 5

10

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.

answered May 25, 2010 at 2:53
Sign up to request clarification or add additional context in comments.

Comments

9

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

Joey
357k88 gold badges705 silver badges700 bronze badges
answered May 25, 2010 at 1:36

1 Comment

Hm. A little more than what I need, but thanks! I'll try this tomorrow.
1

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.

answered May 25, 2010 at 1:21

Comments

1

You use SET on Windows:

SET PYTHONPATH=.
python scripts/doit.py
answered May 25, 2010 at 1:25

Comments

0

Windows can localize variables within the script. This will save having to set PYTHONPATH before running. It will also help when different scripts require different conflicting PYTHONPATHs.

setlocal
set PYTHONPATH=.
python.exe scripts\doit.py
endlocal

For more info, check MS documentation

answered Aug 7, 2022 at 14:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.