'Open (and run) a new Python file by a Python file

I need to run a second python file (2) using a first Python file (1) and I need that the first file continue to be runned. For example: I have the file A.py and with it I run the file B.py I need that also the file A.py continue to do his work.

I tried with os, subprocess and (-I’m using python 3.8) execfile (that run the file B.py but “kill” the file A.py)

Using subprocess.Popen([path_file_B], shell = True)
I get a lot of error like: From: can’t read /var/mail/sqalchemy (or other modules) And also other errors like: Path_file_B :line 15: import: command not found

There is a way to solve this problem and run both A.py and B.py?

I need something like a sort of execfile(f"{file_name}") or
exec(open(f"{file_name}").read()) but that open a new terminal and doesn't overwrite the new file B (2°) on the file A (1°)

Thanks a lot to everyone that will help me :)

(Sorry for my bad English 😅)



Solution 1:[1]

Here is a demo: I have two scripts, main.py and secondary.py:

# main.py
import subprocess
import time


# Start the second script in background
p = subprocess.Popen(["python3", "secondary.py"])

# Back to the main script
# This will be running at the same time as secondary.py
for i in range(3):
    print(i)
    time.sleep(2)

# When main script is done, terminate the second script
p.terminate()

Notes

  • The secondary script can be anything
  • After calling p = subprocess.Popen(...), do not call p.communicate() because that call will block the main script until secondary.py is finished
  • At the end, we need to terminate the second script, if not, it will run forever.

Solution 2:[2]

Ok, so a small note about python imports: importing a file runs it! That's why stuff like if __name__ == '__main__':. If you have never heard about it, check this great video.

This is why libraries that you import usually have everything written in functions; so that when you import them, the functions get defined, but they don't get executed.

Ok, so we figured out how to run a script using another script. Now, how do we run both of them at the same time? This is a topic about concurrency (things happening at the same time). This is kind of an intermediate-level topic and you need to know how to choose between multithreading and multiprocessing. Since you haven't provided a code snippet, I will assume that multiprocessing will work best for you. Multiprocessing works as if each process is an app of its own (like running chrome and Spotify together at the same time).

I create two .py files, the first one is A.py:

import time
print('Script A is running')
time.sleep(10)
print('Script A finished after 10 seconds')

The second file is B.py:

from multiprocessing import Process
def runFile1():
    import A
def runFile2():
    print("This should print after the print from Script A")
    print("But this script is not waiting for script A's sleep")
process1 = Process(target = runFile1)
process2 = Process(target = runFile2)
process1.start()
process2.start()

The output will look like this:

Script A is running
This should print after the print from Script A
But this script is not waiting for script A's sleep
Script A finished

A kind of a long answer (sorry). Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hai Vu
Solution 2