版权声明:本文为CSDN博主「qiaoyurensheng」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qiaoyurensheng/article/details/123410218
编写python程序时,需要多个py文件在不同终端内同时运行,从而配合实现某种功能,经过多方查找与实验,排除了很多无法使用的方案,最终确定了以下两个方案,现将其记录下来,以免后期忘记,同时也给他人以参考!
多线程执行程序
:::tips 创建文件 run.py 并将以下文件修改后填入,之后运行 python run.py 即可。 :::
#coding=utf-8import time# from selenium import webdriverimport threadingimport os# 根据需要填写需要运行的命令def frpc():os.system('/usr/local/bin/frpc')def httpServer():os.system('python ./httpServer.py 8888 ')def face2rmtp():os.system('python ./face2rmtp.py')threads = []# threads.append(threading.Thread(target=frpc))threads.append(threading.Thread(target=httpServer)) #args为函数接受的参数,多个threads.append(threading.Thread(target=face2rmtp))print(threads)if __name__ == '__main__':os.system('/usr/local/bin/frpc')for t in threads:t.setDaemon(True)#我拿来做selenium自动化模拟多个用户使用浏览器的时候,加了这个就启动不了,要去掉,原因找到了 :# 加了这个是说明 主线程 执行完了 子线程也停止(无论是否执行完毕)t.start()t.join()# print("all over %s" %ctime())
多进程执行程序
import timeimport multiprocessingimport os# 根据需要填写需要运行的命令def frpc():os.system('/usr/local/bin/frpc')def httpServer():os.system('python ./httpServer.py 8888 ')def face2rmtp():os.system('python ./face2rmtp.py')if __name__ == '__main__':start = time.time()p1 = multiprocessing.Process(target=frpc,)p2 = multiprocessing.Process(target=httpServer,)p3 = multiprocessing.Process(target=face2rmtp,)# 启动子进程p1.start()p2.start()p3.start()# 等待fork的子进程终止再继续往下执行,可选填一个timeout参数p1.join()p2.join()p3.join()end = time.time()
