Temporary PYTHONPATH in Windows

后端 未结 4 2083
感情败类
感情败类 2021-01-13 04:25

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

In *nix, I can do this:

$ PYTHONPATH=\'.\' pyth         


        
4条回答
  •  走了就别回头了
    2021-01-13 05:13

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

提交回复
热议问题