Pass a 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 several searches, I found a method based on os.environ.

I just can't get it to 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 displays first. What happened to my script? Also is there a way to pass a variable without export?


Summary

Thanks for all the answers. Here is my resume.

The Python script built into bash will be executed as a child process, which by definition cannot affect the parent environment of bash.

The solution is to pass destination strings from python and evalsubsequently to 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
+4
5
  • Python - , . , :

    myvar=$(python - <<< "print 'second'") ; echo $myvar
    
  • , - Python , bash () . eval:

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

, . ,

, . os.environ , , . , , .

script , .

+2

"" - . :

#!/bin/bash

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

echo $myvar

python bash. , , .

+1

python val bash:

pfile.py

print(100)

bfile.sh

var='python pfile.py'

echo $var

: 100

0

, , , python

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

But this is more of a temporary job. Other solutions are more suited to what you are looking for. I hope I could help!

0
source

Source: https://habr.com/ru/post/1675448/


All Articles