Search code examples
pythonsubprocesspid

How to get PID of the subprocess with subprocess check_output


In my python script I'm trying to run some long lasting download process, like in the example below, and need to find a PID of the process started by check_output:

out = subprocess.check_output(["rsync","-azh","file.log",...])

Is it possible to do?


Solution

  • You can run your subprocess using Popen instead:

    import subprocess
    proc = subprocess.Popen(["rsync","-azh","file.log",...], stdout=subprocess.PIPE)
    out = proc.communicate()[0]
    pid = proc.pid
    

    Generally, Popen object gives you better control and more info of the subprocess, but requires a bit more to setup. (Not much, though.) You can read more in the official documentation.