Reputation: 2639
According to voithos's answer, os.environ
can set environment variables and subprocess automatically inherit from parent process.
However, compare below to cases
First case, in python interaction mode
>>>import os
>>>os.environ['a']='1'
>>>os.system('echo $a')
1
0
The result is fine.
Second case, in bash script
#!/bin/bash
python3 - <<EOF
import os
os.environ['a']='1'
os.system('echo $a')
EOF
save the above as test.bash
and run bash test.bash
we got nothing!
Why in the second case, os.system
doesn't inherit variable?
summary
Any dollar sign $
in bash here document will be expanded by default, no matter it is inside single quotes or not.
One way is to escape $
with backslash \
like \$
There is another way to avoid this expand, that is to single quote the first here doc delimiter, compare following
a=0
python3 - <<here
import os
os.environ['a']='1'
os.system('echo $a')
here
python3 - <<'here'
import os
os.environ['a']='1'
os.system('echo $a')
here
Upvotes: 1
Views: 4763
Reputation: 1114
What @ChristosPapoulas says is right. The $a
is getting evaluated by the shell when you're typing it in. The $a
never makes it to your python interpreter. This can be seen in the following:
$ cat >/tmp/foo <<EOF
> import os
> os.environ['a'] = '1'
> os.system('echo $a')
> EOF
$ cat /tmp/foo
import os
os.environ['a'] = '1'
os.system('echo ')
$
Upvotes: 1