简体   繁体   English

从 python 设置的环境变量在 shell 脚本中不可见

[英]Environment variables set from python not visible in shell script

I have a python script which sets environment variables.我有一个设置环境变量的 python 脚本。 I am running this python script from a shell script and the expectation is to read the value of environment variables set by the python script.我正在从 shell 脚本运行这个 python 脚本,期望读取由 python 脚本设置的环境变量的值。

#Python script - x.py# #Python 脚本 - x.py#

import os
os.environ['FRUIT'] = 'APPLE'

#Shell script - x.sh# #Shell 脚本 - x.sh#

python -c "import x"
echo $FRUIT

But that does not seem to be working.但这似乎不起作用。 Nothing gets printed by the shell script. shell 脚本不会打印任何内容。 Can any one please explain why it is so and how to fix this?谁能解释一下为什么会这样以及如何解决这个问题?

Environment variables set in your Python script will be visible only from processes launched by the Python script, because that's how environment variables work.在 Python 脚本中设置的环境变量将仅在 Python 脚本启动的进程中可见,因为这就是环境变量的工作方式。 You can't chnage environment variables in someone else's process.您不能在其他人的进程中更改环境变量。 There is no way to "fix" it because it's that way by design.没有办法“修复”它,因为它就是这样设计的。

As mentioned, You can't really do this because of the process boundary.如前所述,由于流程边界,您无法真正做到这一点。 However, if you absolutely must (and I really don't recommend it), there are hacky way.但是,如果你绝对必须(而且我真的不推荐),有一些 hacky 方法。 Here is an example where the author makes the shell into evaluating commands coming from Python which happen to be export commands. 是一个示例,作者将 shell 用于评估来自 Python 的命令,这些命令恰好是导出命令。 It's pretty neat, but really, don't do it.这很整洁,但真的,不要这样做。 Reconsider if you do this information exchange through environment variables.重新考虑是否通过环境变量进行信息交换。

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

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