Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable from Python to Bash

Tags:

python

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 just cannot make it work. Here is my simple test.

#!/bin/bash

export myvar='first'

python - <<EOF
import os
os.environ["myvar"] = "second"
EOF

echo $myvar

I expected it to output second, however it still outputs first. What is wrong with my script? Also is there any way to pass variable without export?


summary

Thanks for all answers. Here is my summary.

A python script embedded inside bash will run as child process which by definition is not able to affect parent bash environment.

The solution is to pass assignment strings out from python and eval it subsequently in bash.

An example is

#!/bin/bash
a=0
b=0

assignment_string=$(python -<<EOF
var1=1
var2=2
print('a={};b={}'.format(var1,var2))
EOF
)

eval $assignment_string

echo $a
echo $b
like image 335
user15964 Avatar asked Apr 23 '17 15:04

user15964


2 Answers

  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"
    
like image 54
agc Avatar answered Oct 04 '22 16:10

agc


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.

like image 31
Inian Avatar answered Oct 04 '22 14:10

Inian