How to Run Two Python Scripts Simultaneously from a Master Script

Run multiple python scripts in parallel from master script

When you want to spawn a new thread, you need to pass the address of the function you want the thread to execute, and not to call it. What you are doing here is essentially spawning a new thread that immediately calls function_1() which of course runs forever.

Also, you won't be able to reach this line of code:

print("thread finished")

As the threads are executing a while loop - forever, so it is redundent..

from time import sleep
from threading import Thread


def function_1():
print('function 1 started...')
while True:
print('1')
sleep(1)


def function_2():
print('function 2 started...')
while True:
print('2')
sleep(1)


thread_1 = Thread(target=function_1)
thread_2 = Thread(target=function_2)
thread_1.start()
thread_2.start()

thread_1.join()
thread_2.join()
# print("thread finished") - redundant

How to run multiple python scripts using single python(.py) script

using a master python script is a possibility (and it's cross platform, as opposed to batch or shell). Scan the directory and open each file, execute it.

import glob,os
os.chdir(directory) # locate ourselves in the directory
for script in sorted(glob.glob("*.py")):
with open(script) as f:
contents = f.read()
exec(contents)

(There was a execfile method in python 2 but it's gone, in python 3 we have to read file contents and pass it to exec, which also works in python 2)

In that example, order is determined by the script name. To fix a different order, use an explicit list of python scripts instead:

for script in ["a.py","z.py"]:

That method doesn't create subprocesses. It just runs the scripts as if they were concatenated together (which can be an issue if some files aren't closed and used by following scripts). Also, if an exception occurs, it stops the whole list of scripts, which is probably not so bad since it avoids that the following scripts work on bad data.

run multiple python scripts at the same time

You can always open a terminal terminal window -- with either Python: Create Terminal or Open New Terminal -- and launch the script(s) manually in separate terminals.



Related Topics



Leave a reply



Submit