简体   繁体   中英

Make a Python Script that can run two python scripts concurrently

I have two python programs that I want to run. I want to make a python script which execute the two scripts concurrently. How can I do that?

import os

import threading

def start():
    os.system('python filename.py')


t1 = threading.Thread(target=start)

t2 = threading.Thread(target=start)

t1.start()

t2.start()

You can also use a ThreadPoolExecutor from the concurrent.futures library and be more flexible on how many workers should be spawned to execute your target script. Something like this should just fine:

from concurrent.futures import ThreadPoolExecutor as Pool
import os

n_workers = 2

def target_task():
    os.system("python /path/to/target/script.py")

def main(n_workers):
    executor = Pool(n_workers)
    future = executor.submit(target_task)

if __name__ == "__main__":
    main(n_workers=n_workers)

This way you won't have to start your threads manually.

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