Las*_*yes 4 process windows-7-x64 python-2.7
我目前在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")
Run Code Online (Sandbox Code Playgroud)
现在,我知道如果我手动输入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]"
Run Code Online (Sandbox Code Playgroud)
我正在尝试做的是运行命令,然后读回输入.但我似乎无法自动执行我想要运行的调用.:(
有什么想法吗?(如果我遗漏了任何需要的细节,请告诉我)
非常感谢,提前.
jfs*_*jfs 11
文档说:
使用communic()而不是.stdin.write,.stdout.read或.stderr.read来避免由于任何其他OS管道缓冲区填满和阻塞子进程而导致的死锁.
您可以使用.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`
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12839 次 |
最近记录: |