这里缺少什么来中断tok1.py中tok2.py中的循环?
我尝试发送一个包含'exit‘的字符串,将发送的值读入my_input并在tok2.py中中断循环。
现在tok2永远在运行。
使用Debian 10 Buster和Python 3.7。
tok1.py:
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+1tok2.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)发布于 2019-08-19 10:57:05
您可以简单地调用proc.terminate()来终止tok2.py进程,这在逻辑上等同于终止循环。
发布于 2019-08-19 12:59:17
由于下面的答案可能不会被视为“优雅”退出,您还可以设置一个环境变量并检查它。
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+1tok2.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)https://stackoverflow.com/questions/57549945
复制相似问题