Skip to content Skip to sidebar Skip to footer

Pass Variable From Python To Bash

I am writing a bash script in which a small python script is embedded. I want to pass a variable from python to bash. After a few search I only found method based on os.environ. I

Solution 1:

  1. Unless Python is used to do some kind of operation on the original data, there's no need to import anything. The answer could be as lame as:

     myvar=$(python - <<< "print 'second'") ; echo "$myvar"
    
  2. Suppose for some reason Python is needed to spit out a bunch of bash variables and assignments, or (cautiously) compose code on-the-fly. An eval method:

     myvar=first
     eval "$(python - <<< "print('myvar=second')" )"
     echo "$myvar"
    

Solution 2:

Complementing the useful Cyrus's comment in question, you just can't do it. Here is why,

Setting an environment variable sets it only for the current process and any child processes it launches. os.environ 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.

You can pretty much do that with a shell script itself and just source it to reflect it on the current shell.


Solution 3:

There are a few "dirty" ways of getting something like this done. Here is an example:

#!/bin/bash

myvar=$(python - <<EOF
print "second"
EOF
)

echo "$myvar"

The output of the python process is stored in a bash variable. It gets a bit messy if you want to return more complex stuff, though.


Solution 4:

You can make python return val and pass it to bash:

pfile.py

print(100)

bfile.sh

var=$(python pfile.py)
echo "$var"

output: 100


Solution 5:

Well, this may not be what you want but one option could be running the other batch commands in python using subprocess

import subprocess
x =400
subprocess.call(["echo", str(x)])

But this is more of a temporary work around. The other solutions are more along what you are looking for. Hope I was able to help!


Post a Comment for "Pass Variable From Python To Bash"