Skip to content Skip to sidebar Skip to footer

Python: How To Run Multiple Files At The Same Time?

I'm trying to create a For-loop which automatically starts different python files at the exact same time, but they always seem to run one after one. import os import multiprocessin

Solution 1:

If you want to start the files in three separate interpreters, start them as subprocesses:

import subprocess
path = r"C:\Users\Max\Desktop\python\tasks"
tasks = ['1.py', '2.py', '3.py']
task_processes = [
    subprocess.Popen(r'python %s\%s' % (path, task), shell=True)
    for task
    in tasks
]
for task in task_processes:
    task.wait()

Solution 2:

If you want to keep using multiprocessing, you can just encapsulate your system calls in a function:

import os
from multiprocessing import Process

path = "C:\\Users\\Max\\\\Desktop\\\python\\tasks\\"
tasks = ['1.py', '2.py', '3.py']

deffoo(task):
    os.system('python ' + path + task)

for task in tasks:
    p = Process(target=foo, args=(task,))
    p.start()

Solution 3:

Based on OP's actual goal from a comment:

I'm trying to open different links at the same time in my browser with the webbrowser module. Essentially time.sleep(10) webbrowser.open("google.com") But the link is different in each file

we can instead use threads. I added the option for a different delay per URL, because otherwise there'd be no point in having each thread sleep on its own.

import webbrowser
import threading
import time


defdelayed_open_url(delay, url):
    time.sleep(delay)
    webbrowser.open(url)


threads = []
for delay, url in [
    (3, "http://google.com"),
    (5, "http://example.com"),
    (11, "http://stackoverflow.com"),
]:
    threads.append(
        threading.Thread(target=delayed_open_url, args=(url,)).start()
    )

for thread in threads:
    thread.join()  # Wait for each thread# This code will be executed after each thread is done

Post a Comment for "Python: How To Run Multiple Files At The Same Time?"