Sergey Asryan Sergey Asryan - 3 months ago 10
Bash Question

Set shell environment variable via python script

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:


  1. I insert following code in my python script

    import os
    os.system("export ENV_VAR=/some_path")

  2. 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")

  3. I also tried os.putenv() and os.environ["ENV_VAR"] = "some_path"




Is it possible to set(export) environment variable using python, i.e
without directly exporting it to shell?

Answer

As long as you start the "instrument" (a script I supposed) 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.

Comments