Calling a subprocess with mixed data type arguments in Python

I am a little confused as to how to do this.

What I need to do is call an external command from within a Python script that takes multiple arguments and a filename as input.

Let's call the executable I am calling "prog", the input file is "file", so the command line (in a Bash terminal) looks like this:

$ prog --{arg1} {arg2} < {file}

      

In the above, {arg1} is a string and {arg2} is an integer.

If I use the following:

#!/usr/bin/python
import subprocess as sbp 
sbp.call(["prog","--{arg1}","{arg2}","<","{file}"])

      

The result is an error output from "prog" where it asserts that there is no input (arg2)

Here's an interesting error:

#!/usr/bin/python
import subprocess as sbp 
sbp.call(["prog","--{arg1} {arg2} < {file}"])

      

all spaces seem to have been removed from the second line, and an equal sign added at the very end:

command not found --{arg1}{arg2}<{file}=

      

None of this behavior makes any sense to me, and little can be found in the Python man pages found on the Internet. Please note that replacing sbp.call with sbp.Popen does not fix the problem.

+3


source to share


1 answer


The problem is that < {file}

it is not actually an argument to the program, but is the syntax for the shell to redirect. You can tell Python to use a shell, or you can set up a redirect yourself.

from subprocess import *

# have shell interpret redirection
check_call('wc -l < /etc/hosts', shell=True)

# set up redirection in Python
with open('/etc/hosts', 'r') as f:
    check_call(['wc', '-l'], stdin=f.fileno())

      



The first method has the advantage of being faster and easier to type. However, there are many disadvantages: its potentially slower from the time the shell starts; it is potentially not portable as it depends on the syntax of the operating system shell; and it can break easily when there are spaces or other special characters in the filenames.

Thus, the second method is preferred.

+4


source







All Articles