os.environ没有设置环境变量 [英] os.environ not setting environment variables

查看:676
本文介绍了os.environ没有设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python设置Windows环境变量.

I'm trying to set a Windows environment variable using Python.

与文档相反,似乎 os.environ 可以获取环境变量,但不能设置它们.尝试在Windows命令提示符中运行这些命令:

It seems that, contrary to the docs, os.environ can get environment variables but cannot set them. Try running these in a Windows Command Prompt:

这有效:

python -c "import os; print(os.environ['PATH'])"

这不是:

python -c "import os; os.environ['FOO'] = 'BAR'"

尝试在命令提示符下键入set.环境变量FOO不存在.

Try typing set in the Command Prompt. The environment variable FOO does not exist.

如何从Python设置永久的Windows环境变量?

How can I set a permanent Windows environment variable from Python?

推荐答案

os.environ[...] = ...仅在python进程(或其子进程)期间设置环境变量.

os.environ[...] = ... sets the environment variable only for the duration of the python process (or its child processes).

不可能(即不使用特定于操作系统的工具)也不可能,并且绝对不建议为运行Python的shell设置变量.请参阅aumo的评论,以了解解决该问题的替代方法和有些晦涩的方法.

It is not easily (i.e. without employing OS-specific tools) possible and surely not advisable to set the variable for the shell from which you run Python. See aumo's comment for alternative and somewhat obscure approaches to the problem.

这篇关于os.environ没有设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆