问题
I am trying to run a command through Python's subprocess, but it won't run properly. If I type into the shell:
pack < packfile.dat
where pack
is my software and packfile
is the input file, then the software runs fine.
If I try this in python:
import subprocess as sp
import shlex
cmd = 'pack < packfile.dat'.split()
p = sp.Popen(cmd)
The software complains:
Pack must be run with: pack < inputfile.inp
Reading input file... (Control-C aborts)
and it hangs there.
This last part is specific to my software, but the fact is that the two methods of running the same command give different results, when this shouldn't be the case.
Can anyone tell me what I'm doing wrong?
Actually, I intend to eventually do:
p = sp.Popen(cmd,stdout=sp.PIPE,stderr=sp.PIPE)
stdout, stderr = p.communicate()
Since I am a little new to this, if this is not best-practice, please let me know.
Thanks in advance.
回答1:
"<" isn't a parameter to the command, and shouldn't be passed as one.
Try:
p = sp.Popen(cmd,stdout=sp.PIPE,stderr=sp.PIPE, stdin=open('packfile.dat'))
回答2:
I/O redirection is a product of the shell, and by default Popen does not use one. Try this:
p = sp.Popen(cmd, shell=True)
subprocess.Popen() IO redirect
From there you'll also see that some don't prefer the shell option. In that case, you could probably accomplish it with:
with open('input.txt', 'r') as input:
p = subprocess.Popen('./server.py', stdin=input)
回答3:
Try this:
import subprocess as sp
p = sp.Popen(['pack'], stdin = open('packfile.dat', 'r'))
来源:https://stackoverflow.com/questions/12624646/python-subprocess-command-fails-in-python-but-works-in-shell