1

Suppose you have a bunch of commands as would be typed into a shell

export x=1
cd foo/the\ bar/baz
grep x y z
cd "the/quoted path"
ls -l

To run a single command you can do:

subprocess.run(['ls','l'])

But the commands aren't independent. Later commands depend on earlier commands, exported variables, etc. What is the pythonic way to run these commands as if these were lines of code in a shell script? Is there a way around using the shell=True "taboo"?

# DOESN'T work, each run is independent:
for c in cmds: 
    subprocess.run(c, shell=True)

# Seems to work but is mashing everything into a giant string the best way?
subprocess.run(';'.join(cmds), shell=True)
1
  • If you are open to trying a library, I would suggest taking a look at Invoke. It makes it very easy to write python scripts that run console commands. It also lets you run multiple commands within the same context, to do things like cd to a directory and then run commands inside that directory. Commented Mar 13, 2018 at 23:09

1 Answer 1

1

Creating a single string containing all the commands is probably the quickest and easiest way. It may not be the most pretty, but you could always create a helper function to abstract away the string joining.

def run_commands(*commands)
    subprocess.run(' ; '.join(commands), shell=True)

And then call it like this

run_commands('cd foo', 'ls')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.