python中的异步执行函数

赫连冠玉
2023-12-01

参考简单粗暴有效上手Python3异步asyncio_Dexter's Laboratory-CSDN博客_python3 异步

实验代码:

import asyncio
import subprocess 
async def first():
    print('first函数调用开始,下面将会等待3秒模拟函数运行完毕')
    await asyncio.sleep(3)
    print('first函数执行完毕')

async def last():
    print('last函数调用开始')
    await asyncio.sleep(2)
    print('last函数执行完毕')

async def func(delay):
    cmd1="python aa1.py"
    p=subprocess.Popen(cmd1,shell=True,cwd="E:/命令行自动化")
async def func1(delay):
    cmd="python aa.py"
    p=subprocess.Popen(cmd,shell=True,cwd="E:/命令行自动化")
    return_code=p.wait()  
async def main():
    await first()  # 这里先调用first()函数,并且等它执行完了才会开始
    await asyncio.gather(
        func(1),
        func1(1)
    )
    await last()
asyncio.run(main())

分函数aa.py

import subprocess 
#cmd='redis-server.exe redis.windows.conf'
cmd="redis-server.exe redis.windows.conf"
q=subprocess.Popen(cmd,shell=True,cwd="D:/Program Files/Redis")
return_code1=q.wait() 
print("zheg")

分函数aa1.py

import subprocess 
import socket
#获取本机电脑名
myname = socket.getfqdn(socket.gethostname(  ))
#获取本机ip
myaddr = socket.gethostbyname(myname)
cmd1="redis-cli -h "+str(myaddr)
print(cmd1)
p=subprocess.Popen(cmd1,shell=True,cwd="D:/Program Files/Redis")
return_code=p.wait() 
print("ddd")

 类似资料: