Python Subprocess: Command Fails in Python but Works in Shell

心已入冬 提交于 2021-01-04 05:59:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!