通过python设置OS env var

时间:2017-07-13 20:23:50

标签: python

在Python中是否有办法设置一个在Python脚本结束后存在的操作系统环境变量?..所以,如果我在Python脚本中分配一个var并且脚本结束了,我想让它在运行之后可用通过终端“printenv”。我尝试使用os.system使用sh库,但是一旦程序完成,var就不能通过“printenv”获得。

2 个答案:

答案 0 :(得分:2)

你做不到。默认情况下,子进程继承父进程的环境,但相反的情况是不可能的。

实际上,在子进程启动之后,所有其他进程的内存都受到保护(上下文执行的隔离)。这意味着它无法修改另一个进程的状态(内存)。

充其量它可以发送IPC信号......

更多技术说明:您需要调试进程(例如使用gdb)以控制其内部状态。调试器使用特殊的内核API来读写内存或控制其他进程的执行。

答案 1 :(得分:1)

You can do what ssh-agent, gpg-agent and similar tools do: Emit a shell script on your stdout, and document that the user should eval your program's output to activate the variables set by that script.

#!/usr/bin/env python
import shlex, pipes, sys

# pipes.quote on Python 2, shlex.quote on Python 3
quote = shlex.quote if hasattr(shlex, 'quote') else pipes.quote

# Detect when user **isn't** redirecting our output, and emit a warning to stderr
if sys.stdout.isatty():
    sys.stderr.write("WARNING: This program's output should be used as follows:\n")
    sys.stderr.write('           eval "$(yourprog)"\n')
    sys.stderr.write("         Otherwise environment variables will not be honored.\n")

new_vars={'foo': 'bar', 'baz': 'qux'}
for (k, v) in new_vars.items():
    sys.stdout.write('%s=%s; ' % (quote(k), quote(v)))
    sys.stdout.write('\n')

Use of quote() ensures that even a value like foo=$(run-something) is assigned as a literal value, rather than invoking run-something as a command.

相关问题