Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess call with greater sign (>) not working [duplicate]

I have a executable that accepts string and outputs another string. Now I need to feed a file to it as input and write output to another file. The standard command for that is like the following executable_path < input > output. Now I wrap this in python. But I get errors.

 cmd = [executable_path , '<', 'tmp/input.txt', '>',
           'tmp/output.txt']
    p = subprocess.Popen(cmd)
    p.communicate()

invalid argument: <

I also tried joining the cmd arguments:

cmd = [executable_path, ' '.join(['<', 'tmp/input.txt', '>',
       'tmp/output.txt'])]

invalid argument: < tmp/input.txt > tmp/output.txt

Passing the command as string didn't work either.

 p = subprocess.Popen(' '.join(cmd))

OSError: [Errno 2] No such file or directory

What am I missing here?

like image 997
CentAu Avatar asked Jul 06 '15 14:07

CentAu


People also ask

What is the difference between subprocess call and Popen?

Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

Does Popen block?

Popen is nonblocking. call and check_call are blocking. You can make the Popen instance block by calling its wait or communicate method.

What does subprocess Check_call return?

subprocess. check_call() gets the final return value from the script, and 0 generally means "the script completed successfully".

How do I capture the output of a subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.


1 Answers

Redirects (<, >) are interpreted by shell. You need to specify shell=True to use them.

cmd = [executable_path , '<', 'tmp/input.txt', '>', 'tmp/output.txt']
p = subprocess.Popen(cmd, shell=True)
p.communicate()
like image 79
falsetru Avatar answered Sep 28 '22 00:09

falsetru