Temporary PYTHONPATH on Windows

How to set a temporary environment variable PYTHONPATH just before running a Python script?

In * nix, I can do this:

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

On Windows, this syntax does not work, of course. Which is equivalent, however?

+5
source share
4 answers

To install and restore an environment variable on the Windows command line, unfortunately, a "somewhat painful" approach is required ...:

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

You can use a small helper Python script to make it less painful, for example.

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 call for example

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

( , , Python script - Python, cal "python" sys.argv[i-1] , sys.argv[i-1:] subprocess.call).

+8

? Windows (cmd.exe), :

set PYTHONPATH=.

PYTHONPATH , . python, , PYTHONPATH. , .

+6

Windows PYTHONPATH , GUI. Windows , " " "".

+1

You are using SETon Windows:

SET PYTHONPATH=.
python scripts/doit.py
+1
source

All Articles