How do I execute a file but keep the python code running?

Question:

So I am wondering how I can execute an app via the python code but keep the code running?

Here is an example:

File1.py

from time import sleep
print("File1 has started")
sleep(3)
print("File1 has ended")

main.py

from time import sleep
print("main.py has started")
# start the File1.py here
sleep(2)
print("main.py is still running")
sleep(2)
print("main.py has ended")

I want the output to look like this:

>> main.py has started
>> File1 has started
>> main.py is still running
>> File1 has ended
>> main.py has ended

And is it possible to execute the files with the standard app that is assigned to the app?
Example:

  • If someone has the default program for ".txt" Word, then word should open that file
  • If someone has the default program for ".txt" Notepad, then notepad should open that file.

Thanks!

Asked By: Tousend1000

||

Answers:

First of all, you need to organize the code in File1.py into a function, like this:

from time import sleep

def file_one_process():
    print("File1 has started")
    sleep(3)
    print("File1 has ended")

The you can call the function by importing the module at the top of main.py and calling the function, like this:

import File1

File1.file_one_process()

This produces the following output in the terminal:

File1 has started

(sleeps/pauses for 3 seconds, doesn't print anything)

File1 has ended

If you wanted to intertwine the prints of main.py and File1.py Al you have to do is create multiple functions for each of the prints in main.py and File1.py, then call them in the order you want.

If you aren’t dealing with a Python file, (for example, a mov file) then you should look at this question. You can use this code to run a file called example.mov.

import subprocess, os, platform

if platform.system() == 'Darwin':       # macOS
    subprocess.call(('open', "example.mov"))

elif platform.system() == 'Windows':    # Windows
    os.startfile("example.mov")

else:                                   # linux variants
    subprocess.call(('xdg-open', "example.mov"))

This isn’t my code, it’s Nick’s.

Answered By: Ben the Coder
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.