bash - Python 2.7 keep env variables from a subprocess -


i'm calling bash script exporting few variables, found way variables , it's working, once i'm trying add args bash script it's failing. here part of python script:

bash_script = "./testbash.sh" script_execution = popen(["bash", "-c", "trap 'env' exit; source \"$1\"  > /dev/null 2>&1",                                    "_", bash_script], shell=false, stdout=pipe) err_code = script_execution.wait() variables = script_execution.communicate()[0] 

this sample bash script:

export var1="test1"  export var2=$var1/test2  echo "this firsr var: var1=$var1" echo "this second var: var2=$var2" 

once i'm changing bash_script = "./testbash.sh" bash_script = "./testbash.sh test test" i'm not getting exported variables bash script variables variable in python script. provided above sample, , of course real scripts more bigger.

if change bash_script = "./testbash.sh" bash_script = "./testbash.sh test test" name of bash_script changes "./testbash.sh test test". 'test test' not interpreted separate arguments.

instead, add arguments list being passed popen:

bash_script = "./testbash.sh" script_execution = popen( ["bash", "-c", "trap 'env' exit; source \"$1\"  > /dev/null 2>&1",  "_", bash_script, 'test', 'test'], shell=false, stdout=pipe) 

then err_code 0 (indicating success), instead of 1. it's not clear posted code want happen. test arguments ignored.

the argument received bash script, however. if instead put

export var1="$2" 

in testbash.sh, variables (in python script) contain

var1=test 

you might find more convenient use

import subprocess import os  def source(script, update=true):     """     http://pythonwise.blogspot.fr/2010/04/sourcing-shell-script.html (miki tebeka)     http://stackoverflow.com/a/20669683/190597 (unutbu)     """     proc = subprocess.popen(         ". %s; env -0" % script, stdout=subprocess.pipe, shell=true)     output = proc.communicate()[0]     env = dict((line.split("=", 1) line in output.split('\x00') if line))     if update:         os.environ.update(env)     return env  bash_script = "./testbash.sh" variables = source(bash_script) print(variables) 

which yields environment variables

{ 'var1': 'test1', 'var2': 'test1/test2', ... } 

in dict.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -