使用Python的“子进程”运行“导出”命令不起作用 [英] Running 'export' command with Pythons 'subprocess' does not work
问题描述
subprocess.run('export FOO=BAR', shell=True)
这根本行不通,我也不知道为什么。
This simply doesn't work, and I have no idea why.
我要做的所有工作都是通过python设置环境变量( 3.5.1)脚本,当我运行上述代码时,什么也没发生。没有错误,并且当我自己检查环境变量时,还没有设置它。
All I am trying to do I set an environment variable from my python (3.5.1) script, and when I run the above line, nothing happens. No errors are raised, and when I check the environment variable myself, it has not been set.
带有 subprocess.run()的其他shell命令
做工作,例如 ls
和 pwd
,但是不是 export
。
Other shell commands with subprocess.run()
do work, such as ls
and pwd
, but not export
.
.run()
已添加在Python 3.5中(以防您不认识它),但是我还尝试了使用 .call()
和 .Popen( )
,结果不变。
.run()
was added in Python 3.5 (in case you didn't recognise it), but I have also tried the above line with .call()
and .Popen()
, with no change in results.
我知道我可以使用 os.environ ['FOO'] = BAR $ c $在python中设置环境变量c>,但是我将在项目中大量使用shell命令,并且我希望我需要将多个命令串在一起,这将使
export
的使用比 os.environ
。
I am aware that I can set environment variables in python with os.environ['FOO'] = "BAR"
, but I will be using shell commands a lot in my project, and I expect that I will need to string multiple commands together, which will make using export
easier than os.environ
.
我的项目将在Linux上运行,而这正是我的机器在运行。
My project will run on Linux, which is what my machine is running on.
推荐答案
工作正常;但是,变量设置仅存在于子过程中。您不能从孩子那里影响本地过程的环境。
It works fine; however, the variable setting only exists in the subprocess. You cannot affect the environment of the local process from a child.
os.environ
是正确的解决方案,因为它将更改本地进程的环境,并且这些更改将由以 subprocess.run
开始的任何进程继承。
os.environ
is the correct solution, as it changes the environment of the local process, and those changes will be inherited by any process started with subprocess.run
.
您也可以将 env
参数用于 run
:
subprocess.run(["cmdname", "arg1", "arg number 2"], env=dict(FOO='BAR', **os.environ))
这将在包含 FOO = BAR
而不修改当前环境。
This runs the command in a modified environment that includes FOO=BAR
without modifying the current environment.
这篇关于使用Python的“子进程”运行“导出”命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!