How to determine pid of process started via os.system

前端 未结 3 508
南笙
南笙 2020-12-19 04:51

I want to start several subprocesses with a programm, i.e. a module foo.py starts several instances of bar.py.

Since I sometimes have to te

3条回答
  •  我在风中等你
    2020-12-19 05:43

    os.system return exit code. It does not provide pid of the child process.

    Use subprocess module.

    import subprocess
    import time
    argument = '...'
    proc = subprocess.Popen(['python', 'bar.py', argument], shell=True)
    time.sleep(3) # <-- There's no time.wait, but time.sleep.
    pid = proc.pid # <--- access `pid` attribute to get the pid of the child process.
    

    To terminate the process, you can use terminate method or kill. (No need to use external kill program)

    proc.terminate()
    

提交回复
热议问题