多个py文件同时执行(多进程与多线程实现)

本人在编写python程序时,需要多个py文件在不同终端内同时运行,从而配合实现某种功能,经过多方查找与实验,排除了很多无法使用的方案,最终确定了以下两个方案,现将其记录下来,以免后期忘记,同时也给他人以参考!

1.多线程执行程序

创建文件 run.py 并将以下文件修改后填入,之后运行 python run.py 即可。

#coding=utf-8
import time
# from selenium import webdriver
import threading
import 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())

2.多进程执行程序

创建文件 run.py 并将以下文件修改后填入,之后运行 python run.py 即可。

import time
import multiprocessing
import 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()

本文首发于本人博客:https://blog.gitnote.cn/post/somePyRunTogether/

版权信息: CC BY-NC-SA 4.0 (自由转载-非商用-相同方式共享-保持署名)

  • 15
    点赞
  • 80
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值