彩票网站建设与推广,企业建设网站个人总结报告,开网络网站建设公司的优势,长沙棋牌软件开发公司需求
1 创建多个进程#xff0c;并发执行多个终端指令 2 每个进程的进程号不同#xff08;以供记录#xff0c;并在异常退出时进行进程清理#xff09; 3 每个子进程的输出可被python变量记录 #xff08;别问#xff0c;就是想看#xff09; 4 这些子…需求
1 创建多个进程并发执行多个终端指令 2 每个进程的进程号不同以供记录并在异常退出时进行进程清理 3 每个子进程的输出可被python变量记录 别问就是想看 4 这些子进程的输出不要显示在终端上 别问就是不想看
一套自用模板
进程创建
import subprocess #fork进程
import tempfile #临时文件
child_process [] #记录所有子进程以供清理
def sub_boot():command your shell commandwith tempfile.NamedTemporaryFile(deleteTrue) as temp_file:process subprocess.Popen(command, shellTrue,stdouttemp_file, # write into temp_filestderrsys.stdout, # output into you terminalprexxes_fnos.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) #这个信号相当于 ctrlCos.killpg(pgid,signal.SIGKILL) # 这个信号会强行杀死else:passexcept:passdef clean_all():for process in child_process:sub_kill(process)child_process[]