In my build (I'm using Linux) I need to call a Python script and set some env variables. I need these variables to be set even after I exit the script. I am able to set it using os.environ within the script but whenever I exit the script and try to see if the env variable is set from the terminal (echo $myenv) - I get nothing.
在我的构建中(我正在使用Linux),我需要调用Python脚本并设置一些env变量。我需要在退出脚本之后设置这些变量。我可以使用os设置它。但每当我退出脚本并尝试查看env变量是否从终端(echo $myenv)设置时,我什么都得不到。
I am new to Python and did quite a bit googling to figure this out. However, I am not quite sure if it's possible. I tried using the subprocess:
我是Python的新手,我在谷歌上搜索了很多次才发现这个问题。然而,我不太确定是否有可能。我尝试使用子过程:
subprocess.call('setenv myenv 4s3', shell=True)
Also tried using os.system:
也试着用os.system:
os.system("setenv myenv 4s3")
So far, I didn't succeed.
到目前为止,我没有成功。
2 个解决方案
#1
3
You cannot set environment variables from a child process and have them be visible in the parent process. Every process gets its own copy of the environment, and changes do not propagate upwards.
不能从子进程中设置环境变量,并让它们在父进程中可见。每个进程都有自己的环境副本,并且更改不会向上传播。
What you could do is have the Python script print the settings it wants to change and have the outside shell execute the appropriate commands.
您可以做的是让Python脚本打印它想要更改的设置,并让外部shell执行适当的命令。
#2
0
Maybe if you find some equivalent function like c vfork for Python.
如果你找到了类似于Python的c vfork这样的函数。
When you vfork, both processes share memory space so, you might overwrite environment variables in parent process from child process.
当您使用vfork时,两个进程共享内存空间,因此,您可能会从子进程中覆盖父进程中的环境变量。
Warning: vfork has many security issues, and therefore not recommended. Just use it if you are desperate.
警告:vfork有许多安全问题,因此不建议使用它。如果你不顾一切,就用它。
#1
3
You cannot set environment variables from a child process and have them be visible in the parent process. Every process gets its own copy of the environment, and changes do not propagate upwards.
不能从子进程中设置环境变量,并让它们在父进程中可见。每个进程都有自己的环境副本,并且更改不会向上传播。
What you could do is have the Python script print the settings it wants to change and have the outside shell execute the appropriate commands.
您可以做的是让Python脚本打印它想要更改的设置,并让外部shell执行适当的命令。
#2
0
Maybe if you find some equivalent function like c vfork for Python.
如果你找到了类似于Python的c vfork这样的函数。
When you vfork, both processes share memory space so, you might overwrite environment variables in parent process from child process.
当您使用vfork时,两个进程共享内存空间,因此,您可能会从子进程中覆盖父进程中的环境变量。
Warning: vfork has many security issues, and therefore not recommended. Just use it if you are desperate.
警告:vfork有许多安全问题,因此不建议使用它。如果你不顾一切,就用它。