Home > database >  Problem with running shell script echo in Python
Problem with running shell script echo in Python

Time:06-04

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?

CodePudding user response:

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)
  • Related