如果按照mhawkes的建议启动脚本,这是一个更好的选择,但要回答如何按名称终止已启动脚本的问题,可以使用pkill和subprocess.check_call:from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-9", "-f", script])
只要把名字传给kill:padraic@home:~$ cat kill.py
from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-9", "-f", script])
padraic@home:~$ cat test.py
from time import sleep
while True:
sleep(1)
padraic@home:~$ python test.py &
[60] 23361
padraic@home:~$ python kill.py test.py
[60] Killed python test.py
Killed
如果要终止,则使用SIGKIll终止进程,删除-9:padraic@home:~$ cat kill.py
from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-f", script])
padraic@home:~$ python test.py &
[61] 24062
padraic@home:~$ python kill.py test.py
[61] Terminated python test.py
Terminated