如何使用subprocess.wait()使其不阻塞主函数,而不会阻塞运行子进程的函数?

时间:2019-08-02 18:55:59

标签: python multithreading tkinter subprocess blocking

我很抱歉,因为我是Python新手,可能会弄错一些术语。

我正在使用Python tkinter库编写一个GUI程序(我正在使用python3.5),并且具有一些将字符串插入文本框小部件中的功能,以便可以显示有关正在运行的外部进程的状态更新

要点是,过程将是:

-按下按钮时开始

-显示一些初始状态更新,以开始外部过程

-完成后,显示更多更新并启动另一个外部过程

我正在为小部件对象使用insert方法显示新更新的每一行,并且我正在调用另一个函数,该函数将使用subprocess.Popen运行外部命令。

问题是我正在使用subprocess.wait()来通过外部命令来阻止该函数(它要求我必须先完成该子过程,然后才能继续执行另一个子过程),但是要代替它只是阻止子进程所在的函数,它将停止所有过程,包括在文本框中的插入。

我以为我可以使用线程来解决此问题,但是并不能解决任何问题。

这是我的主GUI程序中的内容:

    def show_stat():
        stat1 = status_out.insert(INSERT, "Update 1\n")
        stat2 = status_out.insert(INSERT, "Update 2\n")
        stat3 = status_out.insert(INSERT, "Update 3\n")
        return

    def pre_process():
        other_script.pre_process()

    def subproc():

        ##THE FUNCTION (IN ANOTHER PYTHON SCRIPT) WITH THE SUBPROCESS
        other_script.set_channel()

    def postproc()
             #another function


然后我在GUI中设置了一个线程:

    start_thread = threading.Thread(target=start_process)
    show_stat_thread = threading.Thread(target = show_stat)
    pre_process_thread = threading.Thread(target = pre_process)
    subproc_thread = threading.Thread(target = subproc)
    postproc_thread = threading.Thread(target = postproc)

    def full_process():
        pre_process_thread.start()
        pre_process_thread.join()
        show_stat_thread.start()
        subproc_thread.start()
        subproc_thread.join()
        postproc_thread.start()

    start_button = tk.Button(root,text = "Start", width = 10, height = 2, command = lambda:full_process())

这就是我所谓的子流程(在另一个脚本中):

   def set_channel():
        os.environ['TOP']="my environment name";
        os.system('echo $TOP');
        os.chdir('the dir I want')
        ddrss_ch = subprocess.Popen("MY COMMAND", shell = True)
        ddrss_ch.wait()

        return

由于.wait(我知道它正在阻止),因此在AFTER子进程完成之前,它不会在文本框中显示我的status_out.insert。我以为.wait只会阻止本地功能,而不是主要功能。

我不确定这是否与子流程PIPE的设置有关,但是我无法将文本输出“刷新”到文本框中,因为我不认为.insert方法具有该属性。 / p>

有什么方法可以运行线程,在文本框中查看输出,然后运行子进程,同时仍保留.wait()结尾?

0 个答案:

没有答案