在不终止i的情况下与进程进行多次通信

2024-10-01 11:25:45 发布

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

我有一个120k行的文件。每一行都必须由外部应用程序处理。我启动一个子进程并将每一行发送到stdin。启动应用程序至少需要一秒钟,这是一个真正的瓶颈。在

我正在寻找一种方法使它,这样我就可以开始一次的过程,并发送数据到它一行一行。在

我的当前代码:

    #not pictured: the loop that iterates over all lines. Here the text var is the line I need to pass to the application
pdebug("Sending to tomita:\n----\n", text,"\n----")
    try:
        p = Popen(['tomita/tomitaparser.exe', "tomita/config.proto"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
        stdout_data, stderr_data = p.communicate(input=bytes(text, 'UTF-8'), timeout=45)
        pdebug("Tomita returned stderr:\n", "stderr: "+stderr_data.decode("utf-8").strip()+"\n" )
    except TimeoutExpired:
        p.kill()
        pdebug("Tomita killed")
    stdout_data = stdout_data.decode("utf-8")
    facts = parse_tomita_output(stdout_data)
    pdebug('Received facts:\n----\n',str(facts),"\n----")

我最近尝试的代码:

^{pr2}$

最近的代码产生以下错误:

ValueError: Cannot send input after starting communication

那么,在我启动exe,读取stdout,flush stdin和stdout,重复这个过程之后,有没有方法发送输入?在


Tags: theto方法代码textdata过程stderr
1条回答
网友
1楼 · 发布于 2024-10-01 11:25:45

I have a 120k lines file. ... I am looking for a way to make it so I can start the process once and send data to it line by line.

import subprocess

with open(filename, 'rb', 0) as input_file:
    subprocess.check_call(external_app, stdin=input_file)

要回答标题中的问题,请参阅Interacting with a subprocess while it is still running部分下的subprocess标记描述中的链接,例如代码示例using ^{} and ^{}。在

相关问题 更多 >