Skip to content Skip to sidebar Skip to footer

Set Environment Variable Of Calling Bash Script In Python

I have a bash script that looks like this: python myPythonScript.py python myOtherScript.py $VarFromFirstScript and myPythonScript.py looks like this: print('Running some code...

Solution 1:

you cannot propagate an environment variable to the parent process. But you can print the variable, and assign it back to the variable name from your shell:

VarFromFirstScript=$(python myOtherScript.py $VarFromFirstScript)

you must not print anything else in your code, or using stderr

sys.stderr.write("Running some code...\n")
VarFromFirstScript = someFunc()
sys.stdout.write(VarFromFirstScript)

an alternative would be to create a file with the variables to set, and make it parse by your shell (you could create a shell that the parent shell would source)

import shlex
withopen("shell_to_source.sh","w") as f:
   f.write("VarFromFirstScript={}\n".format(shlex.quote(VarFromFirstScript))

(shlex.quote allows to avoid code injection from python, courtesy Charles Duffy)

then after calling python:

source ./shell_to_source.sh

Solution 2:

You can only pass environment variables from parent process to child.

When the child process is created the environment block is copied to the child - the child has a copy, so any changes in the child process only affects the child's copy (and any further children which it creates).

To communicate with the parent the simplest way is to use command substitution in bash where we capture stdout:

Bash script:

#!/bin/bash
var=$(python myPythonScript.py)
echo"Value in bash: $var"

Python script:

print("Hollow world!")

Sample run:

$ bash gash.sh
Value inbash: Hollow world!

You have other print statements in python, you will need to filter out to only the data you require, possibly by marking the data with a well-known prefix.

If you have many print statements in python then this solution is not scalable, so you might need to use process substitution, like this:

Bash script:

#!/bin/bashwhileread -r line
doif [[ $line = ++++* ]]
    then# Strip out the marker
        var=${line#++++}elseecho"$line"fidone < <(python myPythonScript.py)

echo"Value in bash: $var"

Python script:

defsomeFunc():
    return"Hollow World"print("Running some code...")

VarFromFirstScript = someFunc()
# Prefix our data with a well-known markerprint("++++" + VarFromFirstScript)

print("Now I do other stuff")

Sample Run:

$ bash gash.sh
Running some code...
Now I do other stuff
Value inbash: Hollow World

Solution 3:

I would source your script, this is the most commonly used method. This executes the script under the current shell instead of loading another one. Because this uses same shell env variables you set will be accessible when it exits. . /path/to/script.sh or source /path/to/script.sh will both work, . works where source doesn't sometimes.

Post a Comment for "Set Environment Variable Of Calling Bash Script In Python"