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
How to Remove All Characters Before a Specific Character in Python
Importing Modules from Parent Folder
How to Check If a String Column in Pyspark Dataframe Is All Numeric
How to Extract Hours and Minutes from a Datetime.Datetime Object
How Does \R (Carriage Return) Work in Python
Print the Student Name and the Score of Student in Python3
How to Store Python Dictionary in to MySQL Db Through Python
How to Limit a Number to Be Within a Specified Range (Python)
How to Get All Users in a Telegram Channel Using Telethon
Python: How to Turn CSV Data in to Array
Using SQL Server Stored Procedures from Python (Pyodbc)
How to Get the Response Json Data from Network Call in Xhr Using Python Selenium Web Driver Chorme