Python 2.7.3 process.Popen()失败
我目前正在Windows7 64位机器上使用Python2.7.3(也是在Linux32位、Ubuntu12.04上开发的),在让python成功地与命令提示符/终端通信时遇到了一些奇怪的困难。我的代码如下所示:Python 2.7.3 process.Popen()失败,process,python-2.7,windows-7-x64,Process,Python 2.7,Windows 7 X64,我目前正在Windows7 64位机器上使用Python2.7.3(也是在Linux32位、Ubuntu12.04上开发的),在让python成功地与命令提示符/终端通信时遇到了一些奇怪的困难。我的代码如下所示: import subprocess, logging, platform, ctypes class someClass (object): def runTerminalCommand: try: terminalOrCmdLineCommand = s
import subprocess, logging, platform, ctypes
class someClass (object):
def runTerminalCommand:
try:
terminalOrCmdLineCommand = self.toString()
process = subprocess.Popen(terminalOrCmdLineCommand, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output = process.stdout.readlines()
if len(output) < 1:
logging.exception("{} error : {}".format(self.cmd,process.stderr.readlines()))
raise ConfigError("cmd issue : {}".format(self.cmd))
return output
except ValueError as err:
raise err
except Exception as e:
logging.exception("Unexpected error : " + e.message)
raise ConfigError("unexpected error")
我试图做的是运行一个命令,然后读回输入。但我似乎无法自动执行我想要运行的呼叫:(
有什么想法吗?(如果我遗漏了任何需要的细节,请告诉我)
非常感谢,提前通知。:
使用communicate()而不是.stdin.write、.stdout.read或
.stderr.read以避免由于任何其他操作系统管道而导致死锁
缓冲区填满并阻塞子进程
您可以使用.communicate()
,如下所示:
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout_data, stderr_data = p.communicate()
if p.returncode != 0:
raise RuntimeError("%r failed, status code %s stdout %r stderr %r" % (
cmd, p.returncode, stdout_data, stderr_data))
output_lines = stdout_data.splitlines() # you could also use `keepends=True`
请参阅。您的代码无效Python:
def runternalcommand:
因此我认为这可能是因为子进程与父进程并行运行,但事实并非如此。在为输出赋值之前调用process.wait()时,我遇到了同样的问题。当我尝试注释代码时:“process=subprocess.Popen”(terminalOrCmdLineCommand,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)”并将其替换为“process=subprocess.check_call(self.cmd)”它告诉我我的一个标志后面有一个无效的参数。然后它列出了允许的参数,其中一个是我使用的参数…仍在筛选APIAha,因此,这现在给我带来了一致的问题--当我在powershell中运行命令时,似乎没问题,但当我在常规cmd提示符下运行它时,它会出错--我怀疑子shell在常规cmd提示符下运行。另外,再次感谢您提供的有用帮助!
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout_data, stderr_data = p.communicate()
if p.returncode != 0:
raise RuntimeError("%r failed, status code %s stdout %r stderr %r" % (
cmd, p.returncode, stdout_data, stderr_data))
output_lines = stdout_data.splitlines() # you could also use `keepends=True`