There is a script with an input argument that must be run asynchronously in a separate process (the function to start is presented below). At the moment there is code, however, it works synchronously with the main executing thread and blocks its execution until its completion:

import shlex import subprocess import sys def CreateSubProcess(script, params): command_line = '\"{0}\" \"{1}\" \"{2}\"'.format(sys.executable, script, params) args = shlex.split(command_line) script_process = subprocess.Popen(args, stdout=subprocess.PIPE) out, err = script_process.communicate() exit_code = scriptprocess.returncode 

How to implement asynchronous script operation in a separate process with the ability to check the viability of the process?

    1 answer 1

    p = subprocess.Popen() NOT waiting for the process to complete. To check the status without blocking the current stream for a long time, you can use p.poll() .

    In your case, the program hangs on a .communicate() call that will not return as long as the process is alive or as long as there is an output that can be read . There are various methods that allow you to read the output of the child process without blocking the main thread: background thread, non-blocking / asynchronous IO provided by different libraries, see links in the response to launching a program from the GUI ( Widget.tk.createfilehandler() , GObject.io_add_watch() and others) . Here are code examples using streams, fcntl, asyncio, twisted, select to read a line from the output of an external program in general, code examples to read the output from several processes at the same time . What to choose specifically depends on the specific task.

    • Thanks for the detailed answer! Yes, indeed, using p.poll () solved the problem. At least, after calling this function and completing the process, you can get its status code, which is what I needed. Thank! - neo
    • one
      @neo: note that if you do not read the output, then you should not use stdout=PIPE , otherwise you can suspend the child process when the system buffer for the pipe is full. If you need only status, use stdout=DEVNULL to ignore the output of the process - jfs