Skip to content
Advertisement

Problem with running shell script echo in Python

I am trying to run this shell script in Python:

set THENAME = PETER
echo THENAME = $THENAME

So in Python3 I do this:

import subprocess

shell_command = "set THENAME = PETER"
subprocess.check_call(shell_command, shell=True)
shell_command = "echo THENAME =$THENAME"
subprocess.check_call(shell_command, shell=True)

So I expect when I run the python code on Linux or Unix I get:

THENAME=PETER

But instead I get:

THENAME=

What am I doing wrong?

Advertisement

Answer

There are two problem with this:

  1. This is not how you set a variable in a shell. Instead, the syntax is THENAME=PETER.
  2. 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:

import subprocess
shell_command = "THENAME=PETER; echo THENAME =$THENAME"
subprocess.check_call(shell_command, shell=True)

or pass in the variable in the environment for the command:

import os
import subprocess
shell_command = "echo THENAME =$THENAME"
subprocess.check_call(shell_command, shell=True, env=dict(os.environ, THENAME="PETER"))

or set it in your Python process so that all future subprocesses will inherit it:

import os
import subprocess
shell_command = "echo THENAME =$THENAME"
os.environ["THENAME"]="PETER"
subprocess.check_call(shell_command, shell=True)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement