当我使用python中使用Linux时,我找到了关闭OS.System('Kill -9 {0}'。格式(PID))的方法的方法但是它失败了。
我的代码是运行两个进度。第一个进度完成后,我也希望第二个进度结束(第二个进度,如果您不关闭,它一直在自我运行)。
sys.setrecursionlimit(1000000)
progress1 = Process(target=main)
progress2 = Process(target=run_proxypool)
progress1.daemon = True
progress2.start()
pid = progress2.pid
time.sleep(10)
progress1.start()
progress1.join()
os.system('kill -9 {0}'.format(pid))
确保您在Linux上运行。还考虑使用os.kill(pid, signal.SIGKILL)
。
不是您要问的是什么,而是考虑切换到跨平台的良好和便利,例如wait_procs,它将优雅地发送Sigterm,Wait,然后发送Sigkill。
。 signal.SIGKILL
应该在Linux上可用(不在Windows上)。
多处理模块最近获得了kill()
方法,该方法落在Windows上的terminate
。
来自https://clang.llvm.org/extra/doxygen/run-clang-tidy_8py_source.html:
# This is a sad hack. Unfortunately subprocess goes
# bonkers with ctrl-c and we start forking merrily.
print('nCtrl-C detected, goodbye.')
if tmpdir:
shutil.rmtree(tmpdir)
os.kill(0, 9)
如果您没有PID,则可以将其提取并将其传递给OS.kill
import os, signal
def process(name):
try:
# iterating through each instance of the proess
for line in os.popen("ps ax | grep " + name + " | grep -v grep"):
fields = line.split()
# extracting Process ID from the output
pid = fields[0]
# terminating process
#os.kill(int(pid), signal.SIGKILL)
print("Process Successfully terminated")
except:
print("Error Encountered while running script")
process()