Skip to content
Advertisement

Problem with running shell script echo in Python

I am trying to run this shell script in Python:

JavaScript

So in Python3 I do this:

JavaScript

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

JavaScript

But instead I get:

JavaScript

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:

JavaScript

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

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement