简体   繁体   English

Python:环境变量未更新

[英]Python: Environment Variables not updating

I am trying to overwrite to environment variables in Python.我正在尝试覆盖 Python 中的环境变量。 I can read the value and then write the value and print the updated value.我可以读取该值,然后写入该值并打印更新后的值。 But then if I check the value in command line its still the original value.但是,如果我检查命令行中的值,它仍然是原始值。 Why is that?这是为什么?

First, I create the variable首先,我创建变量

export MYVAR=old_val

My test script myvar.py我的测试脚本myvar.py

#!/usr/bin/env python3
import os
print (os.environ['MYVAR'])
os.environ['MYVAR'] = "new_val"
print (os.environ['MYVAR'])

Outputs输出

$ ./myvar.py 
old_val
new_val
$ echo $MYVAR
old_val

As you can see, the last line of the output still shows the old_val如您所见,输出的最后一行仍然显示old_val

Short version:精简版:

The python script changes its environment. python 脚本改变了它的环境。 However this does not affect the environment of the parent process (The shell)但是这不会影响父进程的环境(外壳)

Long version:长版:

Well this is a well know, but quite confusing problem.嗯,这是一个众所周知但非常令人困惑的问题。

What you have to know is, that there is not the environment , each process has its own environment.你必须知道的是,没有环境,每个进程都有自己的环境。

So in your example above the shell (where you type your code) has one environment.所以在你上面的例子中,shell(你输入代码的地方)有一个环境。 When you call ./myvar.py , a copy of the current environment is created and passed to your python script.当您调用./myvar.py ,会创建当前环境的副本并将其传递给您的 Python 脚本。 Your code 'only' changes this copy of the environment.您的代码“仅”更改此环境副本。 As soon as the python script is finished this copy is destroyed and the shell will see its initial unmodified environment.一旦 python 脚本完成,这个副本就会被销毁,shell 将看到它的初始未修改环境。

This is true for most operating systems (Windows, Linux, MS-DOS, ...)这适用于大多数操作系统(Windows、Linux、MS-DOS 等)

In other words: No child process can change the environment of the process, that called it.换句话说:没有子进程可以改变调用它的进程的环境。

In bash there is a trick, where you source a script instead of calling it as a process.在 bash 中有一个技巧,您可以在其中获取脚本而不是将其作为进程调用。

However if your python script starts another process (for example /bin/bash ), then the child process would see the modified environment.但是,如果您的 python 脚本启动另一个进程(例如/bin/bash ),则子进程将看到修改后的环境。

You started a new process that changed its environment and exited.您启动了一个改变其环境并退出的新进程。 That's all really.真的就是这样。

You shouldn't expect that to affect the process you started it from (your shell).您不应该期望这会影响您从(您的外壳)启动它的过程。

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

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