Python与子进程交互

2024-10-01 15:46:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

请帮帮我。在

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)

更新: 同样的问题,进程成功启动后没有输出

^{pr2}$

Tags: import命令cmd内容output进程defstdin
1条回答
网友
1楼 · 发布于 2024-10-01 15:46:55

您的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语句中。从the subprocess.Popen` docs

Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for.

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

相关问题 更多 >

    热门问题