Set Environment Variable in Python Script

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

Set shell environment variable via python script

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.

How to set environment variables in GitHub actions using python

You cannot set environment variables directly. Instead, you need to write your environment variables into a file, whose name you can get via $GITHUB_ENV.

In a simple workflow step, you can append it to the file like so (from the docs):

echo "{name}={value}" >> $GITHUB_ENV

In python, you can do it like so:

import os

env_file = os.getenv('GITHUB_ENV')

with open(env_file, "a") as myfile:
myfile.write("MY_VAR=MY_VALUE")

Given this python script, you can set and use your new environment variable like the following:

- run: python write-env.py
- run: echo ${{ env.MY_VAR }}

How to run a script with a temporary environment variable?

Your shell command can be

BEAR_NAME="sleepybear" python hello.py


Related Topics



Leave a reply



Submit