Set shell environment variable via python script

后端 未结 3 1645
囚心锁ツ
囚心锁ツ 2020-12-06 11:40

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 we

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 12:16

    Setting an environment variable sets it only for the current process and any child processes it launches. So using os.system will set it only for the shell that is running to execute the command you provided. When that command finishes, the shell goes away, and so does the environment variable. Setting it using os.putenv or os.environ has a similar effect; the environment variables are set for the Python process and any children of it.

    I assume you are trying to have those variables set for the shell that you launch the script from, or globally. That can't work because the shell (or other process) is not a child of the Python script in which you are setting the variable.

    You'll have better luck setting the variables in a shell script. If you then source that script (so that it runs in the current instance of the shell, rather than in a subshell) then they will remain set after the script ends.

提交回复
热议问题