Search code examples
pythonunixchain

Chain of UNIX commands within Python


I'd like to execute the following UNIX command in Python:

cd 2017-02-10; pwd; echo missing > 123.txt

The date directory DATE = 2017-02-10 and OUT = 123.txt are already variables in Python so I have tried variations of

call("cd", DATE, "; pwd; echo missing > ", OUT)

using the subprocess.call function, but I’m struggling to find documentation for multiple UNIX commands at once, which are normally separated by ; or piping with >

Doing the commands on separate lines in Python doesn’t work either because it “forgets” what was executed on the previous line and essentiality resets.


Solution

  • You can pass a shell script as a single argument, with strings to be substituted as out-of-band arguments, as follows:

    date='2017-02-10'
    out='123.txt'
    
    subprocess.call(
      ['cd "$1"; pwd; echo missing >"$2"',  # shell script to run
       '_',                                 # $0 for that script
       date,                                # $1 for that script
       out,                                 # $2 for that script
      ], shell=True)
    

    This is much more secure than substituting your date and out values into a string which is evaluated by the shell as code, because these values are treated as literals: A date of $(rm -rf ~) will not in fact try to delete your home directory. :)