从父进程中断子进程循环

2024-04-25 01:22:53 发布

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

这里缺少什么来打破tok2.py和tok1.py之间的循环?你知道吗

我尝试发送一个包含“exit”的字符串,将发送的值读入我的\u输入并在tok2.py中中断循环?你知道吗

现在tok2永远运行。你知道吗

在python3.7中使用debian10buster。你知道吗

tok1.py:第1页

import sys
import time
import subprocess

command = [sys.executable, 'tok2.py']
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

i=0
while proc.poll() is None:
    if i > 5:
        #Send 'exit' after 5th iteration
        proc.stdin.write(b'exit')

    print('tok1: '  + str(i))

    time.sleep(0.5)
    i=i+1

tok2.py:

import sys
import time

ii=0
my_input =''
while True:
    my_input = sys.stdin.read()

    if my_input == b'exit':
        print('tok2: exiting')
        sys.stdout.flush()
        break

    print('tok2: ' + str(ii))
    sys.stdout.flush()
    ii=ii+1    
    time.sleep(0.5)

Tags: pyimporttimemystdinstdoutsysexit
2条回答

您可以简单地调用proc.terminate()来终止tok2.py进程,这在逻辑上等同于终止循环。你知道吗

由于下面的答案可能不被视为“优雅”的出口,您还可以设置一个环境变量并检查它。你知道吗

tok1.py

import sys
import time
import subprocess
import os

command = [sys.executable, 'tok2.py']
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

i=0
while proc.poll() is None:
    if i > 5:
        #Set 'exit' to 'true' after 5th iteration
        os.environ["EXIT"] = "true"
        proc.terminate()

    print('tok1: '  + str(i))

    time.sleep(0.5)
    i=i+1

tok2.py

import sys 
import time
import os

ii=0
my_input ='' 
while True:
    my_input = sys.stdin.read()

    if os.environ['EXIT'] == "true":
        print('tok2: exiting')
        sys.stdout.flush()
        break

    print('tok2: ' + str(ii))
    sys.stdout.flush()
    ii=ii+1
    time.sleep(0.5)

相关问题 更多 >