在子进程 python 中通过 child 调用 parent 实例

Calling parent instance thru child in subprocess python

我有一个文件 parent.py,它使用子进程调用它的 child child.py。类似这样:

p = subprocess.Popen(["C:/Users/.../child.py", some_arg1, some_arg2],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

在 child 进程启动后,我想将一个变量从 child 进程发送到 parent 进程。 child 不应在完成时发送消息,而是在执行的某个时刻发送消息。我怎样才能做到这一点? 搜索了几个小时后,我似乎只能找到相反的解决方案(从 Parent 到 child)。感谢您的帮助。

有几种方法可以促进这种 inter-process 交流。一种更常见的方法是使用 first-in-first-out (FIFO) 命名管道。

这是一个非常基本的演示。

parent.py:

#! /usr/bin/env python3

import os, tempfile, subprocess

# make a temp directory that's automatically removed when we're done
with tempfile.TemporaryDirectory() as dir:

    # create a FIFO in that directory
    fifo_path = os.path.join(dir, 'fifo')
    os.mkfifo(fifo_path)

    # start the child process
    proc = subprocess.Popen(['./child.py', '--fifo', fifo_path])
    print('process started')

    # open the FIFO
    with open(fifo_path, 'r') as fifo:

        # read output from the child process
        mid_output = fifo.readline()
        print(f'{mid_output = }')

        # wait for child to finish
        code = proc.wait()
        print(f'process finished')

child.py:

#! /usr/bin/env python3

import argparse, time

# read FIFO path from command line
parser = argparse.ArgumentParser()
parser.add_argument('--fifo', required=True)
args = parser.parse_args()

# open FIFO (created by parent)
with open(args.fifo, 'w') as fifo:

    # simulate some work being done
    time.sleep(1)

    # tell the parent that progress has been made
    fifo.write('Halfway there!\n')
    fifo.flush()  # make sure to flush FIFOs

    # Simulate some more work being done
    time.sleep(1)

然后,它运行如下:

./parent.py
process started
mid_output = 'Halfway there!\n'
process finished

您可以让 child 脚本输出它需要对 parent 说的任何内容,并且您可以让它这样做多次。只需确保 parent 知道从 child 读取的次数与 child 写入的次数相同。