需求
1> 創建多個進程,并發執行多個終端指令
2> 每個進程的進程號不同(以供記錄,并在異常退出時進行進程清理)
3> 每個子進程的輸出可被python變量記錄 (別問,就是想看)
4> 這些子進程的輸出不要顯示在終端上 (別問,就是不想看)
一套自用模板
進程創建
import subprocess #fork進程
import tempfile #臨時文件
child_process = [] #記錄所有子進程,以供清理
def sub_boot():command = 'your shell command'with tempfile.NamedTemporaryFile(delete=True) as temp_file:process = subprocess.Popen(command, shell=True,stdout=temp_file, # write into temp_filestderr=sys.stdout, # output into you terminalprexxes_fn=os.setsid) # create new process-id # do anything you like with process,like recordchild_process.append(process)# because below process would not stop your main processprocess,wait() # 阻塞主進程,等待子進程結束with open(temp_file.name,'r') as file:txt = file.read()# after this line , the temp_file would be auto-deletedprint(txt)# do anything you like with txt sub_boot()
進程清理
import os
import signal
child_process = []
def sub_kill(process):main_pid = os.getpid() #獲得主進程的進程號try: #防止進程已經關閉導致的報錯pgid = os.getpgid(process.pid) #獲取進程idif pgid != main_pid: #防止殺死自己os.killpg(pgid,signal.SIGTERM) #這個信號相當于 ctrl+Cos.killpg(pgid,signal.SIGKILL) # 這個信號會強行殺死else:passexcept:passdef clean_all():for process in child_process:sub_kill(process)child_process=[]