繁体   English   中英

Python与子流程互动

[英]Python interact with subprocess

我想与流程互动。 我可以启动该过程并打印出前两行(类似于“过程已成功启动”)。 现在,我想向该进程发送一个新命令,该命令应再次返回类似“命令已完成”的内容,但什么也没有发生。

请帮我。

import subprocess

def PrintAndPraseOutput(output, p):
    print(output)
    if 'sucessfully' in output:
        p.stdin.write('command')

cmd = ["./programm"]
p = subprocess.Popen(cmd, universal_newlines=True, shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
while p.poll() is None:
    output = p.stdout.readline()
    PrintAndPraseOutput(output, p)

更新:同样的问题,“进程成功启动”后无输出

import subprocess

def print_and_parse_output(output, p):
    print(output)
    if 'successfully' in output:
        p.stdin.write('command\n')


with subprocess.Popen(["./programm"], universal_newlines=True, shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE) as proc:
    while proc.poll() is None:
        output = proc.stdout.readline()
        print_and_parse_output(output, proc)

您的I / O应该是行缓冲的,因此PrintAndPraseOutput应该在字符串的末尾发送一个'\\n'

顺便说一句,您有几个拼写错误。 该函数应命名为print_and_parse_output以符合PEP-0008的要求 ,并且“成功”具有2个c。

def print_and_parse_output(output, p):
    print(output)
    if 'successfully' in output:
        p.stdin.write('command\n')

当使用这样的subprocess最好将其放在with语句中。 subprocess.Popen` docs

通过with语句支持将Popen对象用作上下文管理器:退出时,关闭标准文件描述符,然后等待过程。

 with Popen(["ifconfig"], stdout=PIPE) as proc: log.write(proc.stdout.read()) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM