新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python怎么關(guān)閉當(dāng)前進(jìn)程
利用命令行對進(jìn)程進(jìn)行刪除,windows下利用“taskkill /pid ' + str(pid) + ' /f”;linux下利用“kill + str(pid)”
簡介
在 python 的項目開發(fā)中,程序有時會需要管理(例如停止)其它后臺進(jìn)程。
可以通過 os.getpid() 函數(shù)以及 os.system() 來實現(xiàn)這一功能。
示例
在同一個目錄下創(chuàng)建 3 個腳本文件:
1 要停止的進(jìn)程
創(chuàng)建腳本文件 count.py ,內(nèi)容如下:
import time
import os
# 獲取進(jìn)程的pid
pid = os.getpid()
print('pid: ', pid)
# 將pid寫入本地文件
f1 = open(file='count_pid.txt', mode='w')
f1.write(pid.__str__())
f1.close()、
# 開始計數(shù)并打印
n = 0
while True:
n += 1
print(n)
time.sleep(1)運行這個腳本,這樣就得到了一個在后臺持續(xù)運行的進(jìn)程。
2 用來停止進(jìn)程的函數(shù)
創(chuàng)建腳本文件 kill.py ,內(nèi)容如下:
import os
def kill(pid):
# 本函數(shù)用于中止傳入pid所對應(yīng)的進(jìn)程
if os.name == 'nt':
# Windows系統(tǒng)
cmd = 'taskkill /pid ' + str(pid) + ' /f'
try:
os.system(cmd)
print(pid, 'killed')
except Exception as e:
print(e)
elif os.name == 'posix':
# Linux系統(tǒng)
cmd = 'kill ' + str(pid)
try:
os.system(cmd)
print(pid, 'killed')
except Exception as e:
print(e)
else:
print('Undefined os.name')從其它程序中調(diào)用這個腳本中定義的 kill() 函數(shù),即可中止指定進(jìn)程。
3 控制程序
創(chuàng)建腳本文件 manager.py ,內(nèi)容如下:
from kill import kill # 讀取pid f1 = open(file='count_pid.txt', mode='r') pid = f1.read() f1.close() # 調(diào)用kill函數(shù),終止進(jìn)程 kill(pid=pid)
運行這個腳本,就可以讀取到 count.py 對應(yīng)進(jìn)程的 pid ,并通過它中止該進(jìn)程。
推薦課程:零基礎(chǔ)入門學(xué)習(xí)Python(小甲魚)
新聞標(biāo)題:創(chuàng)新互聯(lián)Python教程:python怎么關(guān)閉當(dāng)前進(jìn)程
標(biāo)題URL:http://m.fisionsoft.com.cn/article/dhpphji.html


咨詢
建站咨詢

