【发布时间】: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