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?
asked Nov 21, 2018 at 1:27
Armster
9091 gold badge13 silver badges26 bronze badges
-
You would need more than one processor. You could then run multiple processes concurrently (docs.python.org/3.7/library/multiprocessing.html). You might actually want multithreading depending on what you're trying to do (medium.com/@nbosco/…).NotAnAmbiTurner– NotAnAmbiTurner2018年11月21日 01:37:10 +00:00Commented Nov 21, 2018 at 1:37
-
@NotAnAmbiTurner: You don't need more than one processor, just an OS that supports multitasking.martineau– martineau2018年11月21日 02:21:14 +00:00Commented Nov 21, 2018 at 2:21
-
@martineau but then is it truly concurrent?NotAnAmbiTurner– NotAnAmbiTurner2018年11月21日 02:46:02 +00:00Commented Nov 21, 2018 at 2:46
-
@NotAnAmbiTurner: No, technically not—but depending on what the tasks are actually doing it may not matter. i.e. Such as when one is doing I/O and therefore spending a lot of its time waiting for physical devices. multitasking would prevent that from hanging the entire system down.martineau– martineau2018年11月21日 03:04:27 +00:00Commented Nov 21, 2018 at 3:04
-
But is there a script to run two python scripts concurrently?Armster– Armster2018年11月22日 20:43:15 +00:00Commented Nov 22, 2018 at 20:43
2 Answers 2
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()
Nirav Patel
1,3271 gold badge12 silver badges23 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Aug 4, 2020 at 15:13
anddt
1,6811 gold badge13 silver badges31 bronze badges
Comments
lang-py