简体   繁体   English

如何在 Python 中将目录添加到系统路径变量

[英]How to add a directory to System path variable in Python

I am running python 3.9 on Windows.我在 Windows 上运行 python 3.9。

print(sys.path)
currDir = os.getcwd()
currDir += "\node"

sys.path.append(currDir)
print(sys.path)

I see the 2nd print out of sys.path has my c:\\working\\node\\我看到sys.path的第二个打印有我的c:\\working\\node\\

But my issue is when I run the command under c:\\working\\node\\ , eg npm install但我的问题是当我在c:\\working\\node\\下运行命令时,例如npm install

p = subprocess.Popen(["npm.cmd", "install]),

I get error saying 'The system cannot find the file specified'我收到错误消息“系统找不到指定的文件”

And after my script is run , I try 'echo %PATH%', I don't see c:\\working\\node\\ in the %PATH% varaible too?在我的脚本运行后,我尝试使用 'echo %PATH%',我在 %PATH% 变量中也没有看到c:\\working\\node\\

Can you please tell me how can I add a new directory to system path variable so that subprocess.Popen can see the new addition?你能告诉我如何向系统路径变量添加一个新目录,以便subprocess.Popen可以看到新添加的内容吗?

sys.path is not the same as the PATH variable specifying where to search for binaries: sys.path与指定在何处搜索二进制文件的PATH变量不同:

sys.path系统路径

A list of strings that specifies the search path for modules.指定模块搜索路径的字符串列表。 Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.从环境变量 PYTHONPATH 初始化,加上依赖于安装的默认值。

You want to set the PATH variable in os.environ instead.您想os.environ设置PATH变量

app_path = os.path.join(root_path, 'other', 'dir', 'to', 'app')
os.environ["PATH"] += os.pathsep + os.path.join(os.getcwd(), 'node')

Despite the name, sys.path is NOT the system PATH.尽管名称如此,但sys.path不是系统 PATH。 It is (from the documentation ):它是(来自文档):

A list of strings that specifies the search path for modules.指定模块搜索路径的字符串列表。 Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.从环境变量 PYTHONPATH 初始化,加上依赖于安装的默认值。

Additionally, any changes to the environment won't propagate to a new process you open w/in a python session unless you tell it explicitly to do so.此外,对环境的任何更改都不会传播到您在 python 会话中打开的新进程,除非您明确告诉它这样做。

You can solve both of these with the env flag of Popen You can get the current environment from os.environ , then simply extend the PATH variable and pass this environment through to Popen via the env flag您可以使用Popenenv标志解决这两个问题您可以从os.environ获取当前环境,然后只需扩展 PATH 变量并通过 env 标志将此环境传递给Popen

Something like:就像是:

new_env = os.environ.copy()
new_env['PATH'] = os.pathsep.join((new_env['PATH'].split(os.pathsep) if 'PATH' in new_env else []) + [currDir])
p = subprocess.Popen(["npm.cmd", "install"], env=new_env)

Additionally, make sure you are properly escaping your paths on Windows if using backslash, see this answer for more details此外,如果使用反斜杠,请确保您在 Windows 上正确转义您的路径,有关更多详细信息,请参阅此答案

currDir += "\\node"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM