I am trying to run this shell script in Python:
JavaScript
x
3
1
set THENAME = PETER
2
echo THENAME = $THENAME
3
So in Python3 I do this:
JavaScript
1
7
1
import subprocess
2
3
shell_command = "set THENAME = PETER"
4
subprocess.check_call(shell_command, shell=True)
5
shell_command = "echo THENAME =$THENAME"
6
subprocess.check_call(shell_command, shell=True)
7
So I expect when I run the python code on Linux or Unix I get:
JavaScript
1
2
1
THENAME=PETER
2
But instead I get:
JavaScript
1
2
1
THENAME=
2
What am I doing wrong?
Advertisement
Answer
There are two problem with this:
- This is not how you set a variable in a shell. Instead, the syntax is
THENAME=PETER
. - Each command runs in a subprocess, meaning they don’t share variables. There is no great way to “save” the variables that ended up being set in a subprocess.
You can fix the syntax and run both commands in the same subprocess:
JavaScript
1
4
1
import subprocess
2
shell_command = "THENAME=PETER; echo THENAME =$THENAME"
3
subprocess.check_call(shell_command, shell=True)
4
or pass in the variable in the environment for the command:
JavaScript
1
5
1
import os
2
import subprocess
3
shell_command = "echo THENAME =$THENAME"
4
subprocess.check_call(shell_command, shell=True, env=dict(os.environ, THENAME="PETER"))
5
or set it in your Python process so that all future subprocesses will inherit it:
JavaScript
1
6
1
import os
2
import subprocess
3
shell_command = "echo THENAME =$THENAME"
4
os.environ["THENAME"]="PETER"
5
subprocess.check_call(shell_command, shell=True)
6