栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用子进程和Popen从.exe中获取所有输出?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用子进程和Popen从.exe中获取所有输出?

要将所有标准输出作为字符串获取:

from subprocess import check_output as qxcmd = r'C:ToolsDvb_pid_3_0.exe'output = qx(cmd)

要将stdout和stderr都作为单个字符串获取:

from subprocess import STDOUToutput = qx(cmd, stderr=STDOUT)

要将所有行作为列表:

lines = output.splitlines()

要获得子进程正在打印的行,请执行以下操作:

from subprocess import Popen, PIPEp = Popen(cmd, stdout=PIPE, bufsize=1)for line in iter(p.stdout.readline, ''):    print line,p.stdout.close()if p.wait() != 0:   raise RuntimeError("%r failed, exit status: %d" % (cmd, p.returnpre))

添加

stderr=STDOUT
Popen()
合并stdout / stderr的调用中。

注意:如果

cmd
在非交互模式下使用块缓冲,则直到缓冲区刷新后才会出现行。
winpexpect
模块可能能够更快地获取输出。

要将输出保存到文件:

import subprocesswith open('output.txt', 'wb') as f:    subprocess.check_call(cmd, stdout=f)# to read line by linewith open('output.txt') as f:    for line in f:        print line,

如果

cmd
总是要求输入,即使是空的;设置
stdin

import oswith open(os.devnull, 'rb') as DEVNULL:    output = qx(cmd, stdin=DEVNULL) # use subprocess.DEVNULL on Python 3.3+

您可以结合使用以下解决方案,例如,合并stdout / stderr并将输出保存到文件中,并提供空输入:

import osfrom subprocess import STDOUT, check_call as xwith open(os.devnull, 'rb') as DEVNULL, open('output.txt', 'wb') as f:    x(cmd, stdin=DEVNULL, stdout=f, stderr=STDOUT)

要将所有输入作为单个字符串提供,您可以使用

.communicate()
方法:

#!/usr/bin/env pythonfrom subprocess import Popen, PIPEcmd = ["python", "test.py"]p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)stdout_text, stderr_text = p.communicate(input="1nn")print("stdout: %rnstderr: %r" % (stdout_text, stderr_text))if p.returnpre != 0:    raise RuntimeError("%r failed, status pre %d" % (cmd, p.returnpre))

在哪里

test.py

print raw_input('abc')[::-1]raw_input('press enter to exit')

如果您与程序的交互更像是对话,而不需要

winpexpect
模块。这是docs的示例
pexpect

# This connects to the openbsd ftp site and# downloads the recursive directory listing.from winpexpect import winspawn as spawnchild = spawn ('ftp ftp.openbsd.org')child.expect ('Name .*: ')child.sendline ('anonymous')child.expect ('Password:')child.sendline ('noah@example.com')child.expect ('ftp> ')child.sendline ('cd pub')child.expect('ftp> ')child.sendline ('get ls-lR.gz')child.expect('ftp> ')child.sendline ('bye')

要发送特殊密钥,例如

F3
F10
在Windows上,您可能需要
SendKeys
模块或其纯Python实现
SendKeys-ctypes
。就像是:

from SendKeys import SendKeysSendKeys(r"""    {LWIN}    {PAUSE .25}    r    C:ToolsDvb_pid_3_0.exe{ENTER}    {PAUSE 1}    1{ENTER}    {PAUSE 1}    2{ENTER}    {PAUSE 1}    {F3}    {PAUSE 1}    {F10}""")

它不捕获输出。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637628.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号