运行 python 使用不同参数多次编写脚本

Running python script several times with different parameters

我想运行同时多次使用下面这样的脚本,但每次都使用不同的标记,为此我已经有了一个标记列表。

问题是,我怎样才能同时运行这个脚本 n 次(令牌数)?

我尝试过线程处理,但没有用,很可能是因为异步函数(我对此经验不多)。我也尝试过将所有脚本放在一个函数中,并将令牌作为参数,但异步函数也以某种方式阻止了它?

有没有办法使用子进程或类似的方法来做到这一点?

import module

client = module.Client()


async def on_some_event():
    do_something_using_current_client_token

def ask_for_something():
    return something


ask_for_something()
client.run(token)

谢谢。

假设您有一个包含 N 个项目的令牌列表,下面的代码将遍历令牌列表并 运行 并行生成 N 个线程,并将令牌作为参数:

import threading
import time

def doWork(token):
    count = 0
    while count < 3:
        print('Doing work with token', token)
        time.sleep(1)
        count+=1

N = 3
tokens = [n for n in range(N)]
threads = []

for token in tokens:
    thread = threading.Thread(target=doWork, args=(token,))
    thread.start()
    threads.append(thread)

for i, thread in enumerate(threads):
    thread.join()
    print('Done with thread', i)

输出:

Doing work with token 0
Doing work with token 1
Doing work with token 2
Doing work with token 1
Doing work with token 2
Doing work with token 0
Doing work with token 1
Doing work with token 2
Doing work with token 0
Done with thread 0
Done with thread 1
Done with thread 2

Asyncio解决方案:

import asyncio

async def doWork(token):
    count = 0
    while count < 3:
        print('Doing work with token', token)
        await asyncio.sleep(1)
        count+=1

N = 3
tokens = [n for n in range(N)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([doWork(token) for token in tokens]))
print('Done')

输出:

Doing work with token 2
Doing work with token 0
Doing work with token 1
Doing work with token 2
Doing work with token 0
Doing work with token 1
Doing work with token 2
Doing work with token 0
Doing work with token 1
Done

我只需要在一开始就添加 asyncio.set_event_loop(asyncio.new_event_loop()),因为 asyncio 的循环仅在主线程中循环 运行 而不是新循环。