Windows 中的临时 PYTHONPATH
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2901404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Temporary PYTHONPATH in Windows
提问by Santa
How do I set, temporarily, the PYTHONPATH environment variable just before executing a Python script?
如何在执行 Python 脚本之前临时设置 PYTHONPATH 环境变量?
In *nix, I can do this:
在 *nix 中,我可以这样做:
$ PYTHONPATH='.' python scripts/doit.py
In Windows, this syntax does not work, of course. What is the equivalent, though?
在 Windows 中,这种语法当然不起作用。什么是等价物?
回答by Alex Martelli
To set and restore an environment variable on Windows' command line requires an unfortunately "somewhat torturous" approach...:
在 Windows 的命令行上设置和恢复环境变量需要一种不幸的“有点折磨”的方法......:
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.
您可以使用一些辅助 Python 脚本来减轻痛苦,例如
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 anysubprocess, 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).
(我已经对其进行了编码,因此它适用于任何子进程,而不仅仅是 Python 脚本——如果您只关心 Python 脚本,您可以省略 cal 中的第二个 python 并将“python”放入sys.argv[i-1]
代码中,然后sys.argv[i-1:]
用作subprocess.call 的参数)。
回答by Mark Tolonen
How temporarily? If you open a Windows console (cmd.exe), typing:
怎么临时?如果您打开 Windows 控制台 (cmd.exe),请键入:
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.
将仅更改该控制台的 PYTHONPATH 以及从它创建的任何子进程。从此控制台运行的任何 python 脚本都将使用新的 PYTHONPATH 值。关闭控制台,更改将被遗忘。
回答by Kevin Le - Khnle
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.
在 Windows 中,您可以将 PYTHONPATH 设置为具有 GUI 前端的环境变量。在大多数版本的 Windows 上,您可以通过右键单击“我的电脑”并右键单击“属性”来启动。
回答by Dean Harding
You use SET
on Windows:
您SET
在 Windows 上使用:
SET PYTHONPATH=.
python scripts/doit.py