简体   繁体   English

使用Python更改环境变量

[英]Using Python change Environment Variables

I am having a problem with the environment variables in python. 我在python中遇到环境变量的问题。 How do I get python to export variables to the parent shell? 如何让python将变量导出到父shell?

I am using ubuntu, python 2.7.4 我使用的是ubuntu,python 2.7.4

I get this: 我明白了:

$ python
>>> import os
>>> os.environ
{'HOME':'~'}
>>> os.environ['foo']='bar'
>>> os.environ
{'HOME':'~','foo':'bar'}
>>> quit()
$ echo $foo
    # Place #1
$ python
>>> import os
>>> os.environ
{'HOME':'~'}    # Place #2
>>> 

My expected output is: 我的预期输出是:

  • At Place #1: bar 在地方#1: bar
  • At Place #2: {'HOME':'~','foo':'bar'} 地点#2: {'HOME':'~','foo':'bar'}

Thanks 谢谢

Environment variables set in a child process (eg python) do not affect the parent process. 在子进程(例如python)中设置的环境变量不会影响父进程。

It's a one-way street; 这是一条单行道; if this could be done it would be very easy to exploit shells! 如果可以这样做,那么利用shell会非常容易! The environment variables must be set in the parent process itself. 必须在父进程本身中设置环境变量。 This restriction is enforced by the operating system and is not specific to Python. 此限制由操作系统强制执行,并非特定于Python。

Note that sourcing a file in a shell (eg . script.sh ) doesn't create a new process; 请注意,在shell中获取文件 (例如. script.sh )不会创建新进程; but there is no way to "source" Python files. 但是没有办法“获取”Python文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM