Python file runs on Import

Is it normal that if I use Import example_file in my main.py runs the full example file? Bc most ppl said I would need subprocess to run multiple files. (Yep I am new to python, and not long programming)

1 Like

Yes, it is normal. There’s just a bit of confusion between what is meant by “run multiple files”.

If you want to run multiple processes concurrently (at the same time), you need threading or something similar.

If you want to run an entirely separate python program from your program, you would use subprocess.

If you just want to run or access code that is located in other python files (the most common case), you would import them. Importing a python file runs all of the code inside.

5 Likes

Importing a file in python adds the commands that are in that file. Here is an example:

in test.py:

def foo():
      print('hi')

and now in main.py:

import test
test.foo()

output:

hi

To run multiple functions at the same time, you can do something like this (credit to AI because I had the same question yesterday)

import threading

def function1():
    # Your code for function 1

def function2():
    # Your code for function 2

# Create threads for each function
thread1 = threading.Thread(target=function1)
thread2 = threading.Thread(target=function2)

# Start both threads
thread1.start()
thread2.start()

# Wait for both threads to finish
thread1.join()
thread2.join()

Hope this helps!

4 Likes

basically what an import does is run the entire code file. Why does it do this? The reason is because it’s a sort of work around because instead of defining your functions within your current file you define them in your other file and the code runs it to define it. It needs to run in order to be defined

2 Likes

I would mark all answers as solution but sadly doesn’t work

1 Like

mark mine. I haven’t gotten a single mark… ever

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.