将变量传递给环境 [英] Passing a variable to environment

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

问题描述

如果我的问题不是很清楚,我很抱歉.

I am sorry if my question not very clear.

我正在尝试创建一个变量,将它传递给 linux 中的环境.然后,我希望能够在其他地方获得这个变量.到目前为止我在 linux 命令行上尝试过的:

I am trying to create a variable pass it to the environment in linux. Then, I want to be able to get this variable some where else. What i have tried so far on the linux command line:

local_pc:~/home$ export variable=10
local_pc:~/home$ python -c 'import os; print os.getenv("variable")'
10

听起来不错.但是当我在 python 中设置 export 时,我将无法获得它

which all sound fine. But when I set export in python I will not be able to get it

subprocess.call(["export","variable=20"],shell = True)
print(os.getenv("variable"))
None

所以我的问题是如何在 python 中做 xport variable=10

So my question here is how to do xport variable=10 in python

推荐答案

您只能更改当前进程或其子进程的环境变量.要在其父进程中更改环境将需要 hacks,例如,使用 gdb.

You can change environment variable only for current process or its children. To change environment in its parent process would require hacks e.g., using gdb.

在您的示例中,export variable=10 在同一进程中运行,而 python -c .. 命令是(shell 的)子进程.因此它有效.

In your example export variable=10 is run in the same process and python -c .. command is a child process (of the shell). Therefore it works.

在您的 Python 示例中,您尝试(错误地)在 进程中导出变量并在父进程中获取它.

In your Python example, you are trying (incorrectly) to export variable in a child process and get it in a parent process.

总结:

  • 工作示例:父级为子级设置环境变量
  • 非工作示例:子项尝试为父项设置环境变量

要重现您的 bash 示例:

To reproduce your bash example:

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 参数显式设置它.

Subprocess either inherits parent's environment or you could set it explicitly using env argument.

例如,要更改 time 模块使用的本地时区,您可以更改 posix 系统上当前 python 进程的 TZ 环境变量:

For example, to change a local timezone that is used by time module, you could change TZ environment variable for the current python process on posix systems:

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.))

这篇关于将变量传递给环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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