简体   繁体   中英

Python run one function multiple times at the same time

I am writing one bot and it needs to run multiple instances: first you input how many you want:

instances = int(input('How many instances?: '))

Then the code will run one function (the main and only thing it does) and thats it. The bot is just Selenium, if that is relevant in any way

Tldr: Need to execute one function multiple times but at the same time

I tried

    if __name__ == '__main__':
        executor.submit(functionname)

but the problem is that I need to input how many instances of the bot at the same time should be ran, and this way of adding lines is extremely janky

Pythons multiprocessing module should do what you want. From the docs :

from multiprocessing import Process

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

Multiple processes can be called like this:

for num in range(10):
        Process(target=f, args=(lock, num)).start()

you should use loop for this and initialize with a constant value 1 if you want to run your function one time and also Use methods of start and join.

Thank you user-na! What I did was

if __name__ == '__main__':
    for num in range(instances):
        Process(target=functionname).start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM