与 time.sleep() 兼容的 subprocess.wait() 的非阻塞替代方案

问题描述 投票:0回答:0

我正在尝试运行一个实现非阻塞子进程的程序。该程序有效...如果我不包括 time.sleep()。但是,在休眠的情况下,程序会根据最短休眠时间运行每个部分。我需要按照编写的顺序运行我的代码,同时还要睡觉,并且不要阻塞。

问题与子进程的运行方式有关。具体来说,如果没有 wait() 方法,它只是将不同的进程视为同一个进程。

下面是Main.py和Subprocess.py的代码

Main.py

from subprocess import Popen
import sys

class Main:
    def __init__(self):
        self.start_process(0)
    def start_process(self, id):
        if id == 0:
            process = Popen([sys.executable, 'Subprocess.py', "0"])
            process.wait()   # Need to remove wait() so as to prevent blocking.
            self.start_process(1)
        elif id == 1:
            process = Popen([sys.executable, 'Subprocess.py', "1"])
            process.wait()   # Need to remove wait() so as to prevent blocking.
            self.start_process(2)
        elif id == 2:
            process = Popen([sys.executable, 'Subprocess.py', "2"])
            process.wait()   # Need to remove wait() so as to prevent blocking.
            self.start_process(3)
        elif id == 3:
            process = Popen([sys.executable, 'Subprocess.py', "3"])
            process.wait()   # Need to remove wait() so as to prevent blocking.
            
if __name__ == "__main__":
    test_app = Main()

子进程.py

import sys
import time

class Subprocess:
    def __init__(self, num):
        self.num = num
        self.num = int(self.num)
    def start_sleep(self):
        if self.num == 0:
            time.sleep(3)
            print("I slept for 3 seconds")
        elif self.num == 1:
            time.sleep(2)
            print("I slept for 2 seconds")
        elif self.num == 2:
            time.sleep(10)
            print("I slept for 10 seconds")
        elif self.num == 3:
            time.sleep(1.5)
            print("I slept for 1.5 seconds")

obj = Subprocess(sys.argv[1])
obj.start_sleep()

需要输出,不使用 wait(): 3 秒后:

I slept for 3 seconds
3 + 2 秒后:
I slept for 2 seconds
3 + 2 + 10 秒后:
I slept for 10 seconds
3 + 2 + 10 + 1.5 秒后:
I slept for 1.5 seconds

不使用 wait() 得到的输出: 1.5 秒后:

I slept for 1.5 seconds
3.5 秒后:
I slept for 2 seconds
6.5 秒后:
I slept for 3 seconds
16.5 秒后:
I slept for 10 seconds

如您所知,我得到的输出显示 4 个子流程被视为一个。

python time subprocess popen blocking
© www.soinside.com 2019 - 2024. All rights reserved.