stackofpancakes stackofpancakes - 7 months ago 46
Python Question

Using a variable in a subprocess.Popen command

Right now I have a test file.dat that I run hexdump on and put the output into a hexdump.dat file.

subprocess.Popen(['hexdump file.dat > hexdump.dat' ], shell=True)


As a side note, I have seen suggestions to not use
shell=True
but I essentially get the error
OSError: [Errno 2] No such file or directory
.

So, I would like to be able to pass in a variable or an array, files, instead of the hardcoded "file.dat". "files" could be a user input or an array/list generated from a previous subprocess section.

I have tried a user input case:

from subprocess import Popen, PIPE, STDOUT
files = raw_input('File Name: ')
p = subprocess.Popen(['hexdump files > hexdump.dat' ], stdout=PIPE, stderr=STDOUT)
out,err = p.communicate(input=files)


Also with:

p = subprocess.Popen(['hexdump', inputs, ' > hexdump.dat' ], stdout=PIPE, stderr=STDOUT)


Thanks for the help, I know I'm not appropriately understanding the structure needed here so some "handholdy" answers would be appreciated.

Answer

You need shell=True because otherwise it'll look for an executable with that name. shell=True tells the method to use the shell to execute the command so > and friends become what you originally intended them to be (redirection).

The following code you posted:

from subprocess import Popen, PIPE, STDOUT 
files = raw_input('File Name: ')                                                                                                 
p = subprocess.Popen(['hexdump files > hexdump.dat' ], stdout=PIPE, stderr=STDOUT)                                         
out,err = p.communicate(input=files)  

will not work because you're just passing files to hexdump, and if a file with the name files doesn't exist you'll get an error (and if it does exist, it's still probably not what you wanted.)

What you want is to build the string you're executing:

file = "input.dat"
p = subprocess.Popen("hexdump " + file + " > hexdump.dat", shell=True)