如何在Python中设置父shell的环境变量?
How to set environment variables of parent shell in Python?
我正在尝试从 Python 中修改父 shell 的环境变量。到目前为止我所做的尝试没有奏效:
~ $ export TESTING=test
~ $ echo $TESTING
test
~ $
~ $
~ $ python
Python 2.7.10 (default, Jun 1 2015, 18:05:38)
[GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['TESTING']
'test'
>>> os.environ['TESTING'] = 'changed'
>>> os.environ['TESTING']
'changed'
>>> quit()
~ $
~ $
~ $ echo $TESTING
test
我能想到的就这些了。可以吗?如何在 Python 中设置父 shell 的环境变量?
这是不可能的。
子进程从它们的父进程继承它们的环境而不是共享它们。因此,您对环境所做的任何修改都将 仅 反映在子 (python) 进程中。实际上,您只是覆盖 os
模块根据您的 shell 环境创建的字典,而不是 shell.
的实际环境变量
https://askubuntu.com/questions/389683/how-we-can-change-linux-environment-variable-in-python
Why can't environmental variables set in python persist?
你可以做的是通过使用 shell 的 Command Substitution 功能将 Python 命令的输出解析为 shell 命令,这更通常用于评估另一个命令的内联命令。例如。 chown `id -u` /somedir
。
在您的情况下,您需要将 shell 命令打印到标准输出,这将由 shell 进行评估。创建您的 Python 脚本并添加:
testing = 'changed'
print 'export TESTING={testing}'.format(testing=testing)
然后从你的 shell:
$ `python my_python.sh`
$ echo TESTING
changed
基本上,任何字符串都会被 shell、甚至 ls
、rm
等
解释
我正在尝试从 Python 中修改父 shell 的环境变量。到目前为止我所做的尝试没有奏效:
~ $ export TESTING=test
~ $ echo $TESTING
test
~ $
~ $
~ $ python
Python 2.7.10 (default, Jun 1 2015, 18:05:38)
[GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['TESTING']
'test'
>>> os.environ['TESTING'] = 'changed'
>>> os.environ['TESTING']
'changed'
>>> quit()
~ $
~ $
~ $ echo $TESTING
test
我能想到的就这些了。可以吗?如何在 Python 中设置父 shell 的环境变量?
这是不可能的。
子进程从它们的父进程继承它们的环境而不是共享它们。因此,您对环境所做的任何修改都将 仅 反映在子 (python) 进程中。实际上,您只是覆盖 os
模块根据您的 shell 环境创建的字典,而不是 shell.
https://askubuntu.com/questions/389683/how-we-can-change-linux-environment-variable-in-python
Why can't environmental variables set in python persist?
你可以做的是通过使用 shell 的 Command Substitution 功能将 Python 命令的输出解析为 shell 命令,这更通常用于评估另一个命令的内联命令。例如。 chown `id -u` /somedir
。
在您的情况下,您需要将 shell 命令打印到标准输出,这将由 shell 进行评估。创建您的 Python 脚本并添加:
testing = 'changed'
print 'export TESTING={testing}'.format(testing=testing)
然后从你的 shell:
$ `python my_python.sh`
$ echo TESTING
changed
基本上,任何字符串都会被 shell、甚至 ls
、rm
等