通过python脚本设置外壳环境变量 [英] Set shell environment variable via python script
问题描述
我有一些仪器需要环境变量,我想从python代码中自动设置该变量.因此,我尝试了几种方法来实现它,但是没有一个成功. 以下是一些示例:
I have some instrument which requires environment variable which I want to set automatically from python code. So I tried several ways to make it happen, but none of them were successful. Here are some examples:
-
我在python脚本中插入以下代码
I insert following code in my python script
import os
os.system("export ENV_VAR=/some_path")
我创建了bash脚本(env.sh)并从python运行它:
I created bash script(env.sh) and run it from python:
#!/bin/bash
export ENV_VAR=some_path
#call it from python
os.system("source env.sh")
是否可以使用python设置(导出)环境变量,即 而不直接将其导出到shell?
Is it possible to set(export) environment variable using python, i.e without directly exporting it to shell?
推荐答案
只要启动"instrument" (我猜想是一个脚本),它应该在完全相同的过程中起作用:
As long as you start the "instrument" (a script I suppose) from the very same process it should work:
In [1]: os.putenv("VARIABLE", "123")
In [2]: os.system("echo $VARIABLE")
123
您不能更改其他进程或父进程的环境变量.
You can't change an environment variable of a different process or a parent process.
这篇关于通过python脚本设置外壳环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!