如果我的问题不是很清楚,我很抱歉。
我正在尝试创建一个变量,将其传递给 linux
中的环境。然后,我希望能够在其他地方获得这个变量。到目前为止我在 linux 命令行上尝试了什么:
local_pc:~/home$ export variable=10
local_pc:~/home$ python -c 'import os; print os.getenv("variable")'
10
听起来不错。但是当我在 python 中设置 export
时,我将无法获取它
subprocess.call(["export","variable=20"],shell = True)
print(os.getenv("variable"))
None
所以我的问题是如何在 python 中执行 xport variable=10
最佳答案
您只能为当前进程或其子进程更改环境变量。要更改其父进程中的环境,需要进行黑客攻击,例如使用 gdb。
在您的示例中,export variable=10
在同一进程中运行,python -c ..
命令是(shell 的)子进程。因此它有效。
在您的 Python 示例中,您试图(错误地)在子 进程中导出变量并在父进程中获取它。
总结:
- 工作示例: parent 为 child 设置环境变量
- 无效示例: child 尝试为 parent 设置环境变量
重现您的 bash 示例:
import os
import sys
from subprocess import check_call
#NOTE: it works but you shouldn't do it, there are most probably better ways
os.environ['variable'] = '10' # set it for current processes and its children
check_call([sys.executable or 'python', '-c',
'import os; print(os.getenv("variable"))'])
子进程要么继承父进程的环境,要么您可以使用 env
参数显式设置它。
例如,要更改 time
模块使用的本地时区,您可以更改 posix 系统上当前 python 进程的 TZ
环境变量:
import os
import time
os.environ['TZ'] = ':America/New_York'
time.tzset()
is_dst = time.daylight and time.localtime().tm_isdst > 0
# local time = utc time + utc offset
utc_offset = -time.timezone if not is_dst else -time.altzone
print("%s has utc offset: %.1f hours" % (
os.environ.get('TZ').lstrip(':'), utc_offset/3600.))
关于python - 将变量传递给环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20524797/