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?
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.
Popen is nonblocking. call and check_call are blocking. You can make the Popen instance block by calling its wait or communicate method.
subprocess. check_call() gets the final return value from the script, and 0 generally means "the script completed successfully".
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With