python - subprocess.Popen().pid return the pid of the parent script

后端 未结 2 1014
刺人心
刺人心 2020-12-31 20:25

I am trying to run a Python script from another Python script, and getting its pid so I can kill it later.

I tried subprocess.Popen() with

2条回答
  •  无人及你
    2020-12-31 20:57

    So run it directly without a shell:

    proc = subprocess.Popen(['python', './script.py'])
    

    By the way, you may want to consider changing the hardcoded 'python' to sys.executable. Also, you can use proc.kill() to kill the process rather than extracting the PID and using that; furthermore, even if you did need to kill by PID, you could use os.kill to kill the process rather than spawning another command.

提交回复
热议问题