使用Popen在Python中设置环境变量 [英] Set Environmental Variables in Python with Popen
问题描述
我想通过python脚本在linux终端中设置环境变量.使用os.environ['BLASTDB'] = '/path/to/directory'
时,我似乎能够设置环境变量.
I want to set an environmental variable in linux terminal through a python script. I seem to be able to set environmental variables when using os.environ['BLASTDB'] = '/path/to/directory'
.
但是,我最初尝试使用subprocess.Popen
设置此变量,但没有成功.
However I was initially trying to set this variable with subprocess.Popen
with no success.
import subprocess
import shlex
cmd1 = 'export BLASTDB=/path/to/directory'
args = shlex.split(cmd1)
p = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()
为什么subprocess.Popen
无法将环境变量BLASTDB设置为'/path/to/directory'?
Why does subprocess.Popen
fail to set the environmental variable BLASTDB to '/path/to/directory'?
注意: 使用以下方法时也会失败:
NOTE: This also fails when using:
import os
os.system('export BLASTDB=/path/to/directory')
推荐答案
使用env
参数设置子进程的环境变量:
Use the env
parameter to set environment variables for a subprocess:
proc = subprocess.Popen(args, stdout=subprocess.PIPE,
env={'BLASTDB': '/path/to/directory'})
每个文档:
如果env不为None,则它必须是定义环境的映射 新流程的变量;这些用于代替继承 当前流程的环境,这是默认行为.
If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of inheriting the current process’ environment, which is the default behavior.
注意:如果指定,env必须提供程序所需的任何变量 执行.在Windows上,为了运行并行程序集, 指定的环境必须包含有效的SystemRoot.
Note: If specified, env must provide any variables required for the program to execute. On Windows, in order to run a side-by-side assembly the specified env must include a valid SystemRoot.
os.environ
可用于访问 python进程的当前环境变量.如果您的系统还支持 putenv ,则os.environ
也可以用于设置环境变量(因此可以代替上面显示的Popen的env
参数使用).但是,对于某些操作系统,例如FreeBSD和MacOS,设置os.environ
可能会导致内存泄漏,因此设置os.environ
并不是可靠的解决方案.
os.environ
can used for accessing current environment variables of the python process. If your system also supports putenv, then os.environ
can also be used for setting environment variables (and thus could be used instead of Popen's env
parameter shown above). However, for some OSes such as FreeBSD and MacOS, setting os.environ
may cause memory leaks, so setting os.environ
is not a robust solution.
os.system('export BLASTDB=/path/to/directory')
运行一个子进程,该子进程仅为该子进程设置BLASTDB
环境变量.由于该子进程结束,因此它对后续的subprocess.Popen
调用无效.
os.system('export BLASTDB=/path/to/directory')
runs a subprocess which sets the BLASTDB
environment variable only for that subprocess. Since that subprocess ends, it has no effect on subsequent subprocess.Popen
calls.
这篇关于使用Popen在Python中设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!