Run multiple files

Hey there, could you please help me with that ,
I want to run 2 files at the same time

  1. which contains the code provided by the tutor
  2. which contains my code that I use to learn
1 Like

Hi @bbtparesh, please state what language you want to achieve this in.

If you are using python, you can either do:

with open("file2.py") as f:
    exec(f.read())

or…

import subprocess

subprocess.run(["python", "file2.py"])

Method 1 allows you to run another python file without the additional installation of any packages, but method 2 requires the import of a package called ‘subprocess’.

3 Likes

What about just importing the second file?

4 Likes

That will probably work but it has slightly different behaviour because the __name__ in the new file would be set to the name that the file was imported using, instead of being set to __main__

4 Likes

Considering that people always want to just “run multiple files” (rather than explicitly “execute two files in parallel”), maybe imports would actually work better in some cases.

4 Likes

Like @9pfs1 said, you can just use imports. For example:

import my_file2 

if __name__ == '__main__':
    # do something

Or, alternatively, you can use the os module.

from os import system

system('python my_file2')
4 Likes

I did not try, but can you just open two terminal windows and run manually like most progs do?

3 Likes

I think the OP wants two files to run upon clicking the run button, not manually typing python twice to run.

4 Likes

everyone OP is asking to run multiple files at the same time, not one after the other.

2 Likes

Oh, didn’t take notice of that :sweat_smile:
Importing the script also works, though - just do the import at the start of the main script.

2 Likes

Well, if you import a file, then you basically run it, and it has to wait for the import to be done.

3 Likes

I don’t really understand what you mean. Do you mean that it has to wait until it has successfully imported the file - or that the imported file executes first before the main file runs?

This is the correct one. Unless your import is in the middle of your code, imports will execute prior to main code execution.

Sorry to say, it’s impossible to run multiple programs at once in Python, because of something called the “Interpreter Lock”.

1 Like

Threads are good for running multiple things at once, what are you referencing here?

2 Likes

It’s what I learned from one of Tech With Tim’s tutorials.

Watching tim’s video on it, and while he says threads (because python) aren’t parallel, he does briefly mention multi-threading, which he says sidesteps the lock.

2 Likes

Well, how do you even use threads?

This is probably a poor example, but here’s an example from a Repl of mine.
And here’s an article on threading.

I believe you can do something like this:

import subprocess
import asyncio

class FileExec:
    def __init__(self, file_paths):
        self.file_paths = file_paths

    async def run_file(self, file_path):
        try:
            process = await asyncio.create_subprocess_exec("python", file_path)
            await process.wait()
        except Exception as e:
            print(f"Error running {file_path}: {e}")

    async def run_files(self):
        tasks = [self.run_file(file) for file in self.file_paths]
        await asyncio.gather(*tasks)

if __name__ == "__main__":
    files = ["file_1.py", "file_2.py"]
    runner = FileExec(files)
    asyncio.run(runner.run_files())
1 Like