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)
Kevin Kostlan
  • 3,311
  • 7
  • 29
  • 33
  • If you are open to trying a library, I would suggest taking a look at [Invoke](http://www.pyinvoke.org/). 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. – Jesse Webb Mar 13 '18 at 23:09

1 Answers1

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')
ndmeiri
  • 4,979
  • 12
  • 37
  • 45