【问题标题】:Python 2.7.3 process.Popen() failuresPython 2.7.3 process.Popen() 失败
【发布时间】:2012-10-03 17:33:05
【问题描述】:

我目前在 Windows 7 64 位机器上使用 python 2.7.3(也在 Linux 32 位、Ubuntu 12.04 中开发)并且在让 python 与命令提示符/终端成功通信时遇到了奇怪的困难。我的代码如下所示:

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")

现在,我知道如果我手动输入 self.toString() 返回值将正确处理,因此我将其限制为我如何通过子进程将其发送到命令行的问题。我已经阅读了文档,发现 subprocess.check_call() 如果遇到错误不会返回任何内容,所以我使用的是 .Popen()

我得到的例外是,

    [date & time] ERROR: Unexpected error :
    Traceback (most recent call last):
      File "C:\[...]"
        raise ConfigError("cmd issue : {}".format(self.cmd))
    "ConfigError: cmd issue : [the list self.cmd printed out]"

我想做的是运行一个命令,然后读回输入。但我似乎无法自动化我想运行的呼叫。 :(

有什么想法吗? (如果我遗漏了任何需要的细节,请告诉我)

非常感谢,提前。

【问题讨论】:

  • 您的代码无效 Python:def runTerminalCommand:
  • 所以我认为这可能是因为子进程与父进程并行运行 - 但事实并非如此。当我在分配输出值之前调用 process.wait() 时,我遇到了同样的问题。当我尝试注释掉代码时:“process = subprocess.Popen(terminalOrCmdLineCommand, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)”并将其替换为“process = subprocess.check_call(self.cmd) “它告诉我我的一个标志后面有一个无效参数。然后它列出了允许的参数,其中一个是我用的……还在筛选API

标签: process python-2.7 windows-7-x64


【解决方案1】:

The docs say:

使用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`

other methods to get subprocess output in Python

【讨论】:

  • 啊哈,所以,这现在给我带来了一致的问题——似乎当我在 powershell 中运行命令时它很好,但是当我在常规 cmd 提示符下运行它时,它会出错——我怀疑子 shell 是在常规 cmd 提示符下运行的。另外,再次感谢您的有用帮助!
猜你喜欢
  • 1970-01-01
  • 2013-02-10
  • 1970-01-01
  • 2012-09-12
  • 2016-10-22
  • 2015-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
相关资源
最近更新 更多