When using os.system to open a file, eg: os.system(r'C:/foo.txt'), the current Python process, of course, waits until the system-call returns. (ie.: the text-editor closes).
Do I have to use a Thread to make this asynchronous ?
Imagine the following situation:
I’m writing a File-manager for Windows using Python. The user clicks on a file. Now using os.system(the_path_to_the_file_clicked) will open the file with the default programm, as set in the registry.
Using a Thread to make the system-call asynchronous would work quite well, but what when the user closes the File-manager ? The Python process would stay alive until the Thread exits, but this isn’t this unnecessery ? And on the other hand, terminating the Python-process would terminate the Thread as well, the program closes.
Is there a way to use a system-call to open a new process, independent from the Python-process ?
If you want to open a file on windows with the default program, there’s a special function that opens it asynchronously and independently of your own program: os.startfile. This should do what you want.
More generally, for running programs asynchronously,
os.systemcan’t do it. However, the subprocess module can. The subprocess module does nearly everythingos.systemdoes, plus much more. However, like with os.system, when you use subprocess.Popen, the program is not opened independently of your process — when your process dies, so does the subprocess.