Python: Using popen poll on background process

前端 未结 3 564
陌清茗
陌清茗 2021-01-31 10:31

I am running a long process (actually another python script) in the background. I need to know when it has finished. I have found that Popen.poll() always returns 0

3条回答
  •  半阙折子戏
    2021-01-31 10:43

    You don't need to use the shell backgrounding & syntax, as subprocess will run the process in the background by itself

    Just run the command normally, then wait until Popen.poll returns not None

    import time
    import subprocess
    
    p = subprocess.Popen("sleep 30", shell=True)
    # Better: p = subprocess.Popen(["sleep", "30"])
    
    # Wait until process terminates
    while p.poll() is None:
        time.sleep(0.5)
    
    # It's done
    print("Process ended, ret code:", p.returncode)
    

提交回复
热议问题