简体   繁体   中英

Open another Python script from another Python process

I'm trying to open a python script from the main python program in a separate process.

For now let's just say that "main program" is a PyQt4 GUI program and "script" is the script (in a separate file) I am trying to run from my main program.

Why?

  1. So the script keeps running after the main program is closed

  2. So that when the script is ran my main program doesn't freeze while waiting for the script with an infinite loop to end.

I know that subprocess.Popen() , subprocess.call() and os.system() can open the file via the command line, but when they open a script with an infinite loop the main program hangs and crashes.

I also know that I could use QtCore.QCoreApplication.processEvents() to keep the main program running, but this does not work in my case.

So I figured the best solution to keep the script and the Main Program correctly running is the have separate processes.

How would I open script.py file in a separate process or in a way that would not freeze up my program.

Calling an external command in Python is probably what you're looking for. The author perfectly describes how to launch different python script that keeps running when your main program is closed.

Don't run python scripts as subprocesses, import the corresponding modules and call the desired functions instead. If you need to run Python code in a separate process, you could use multiprocessing :

multiprocessing.Process(target=infinite_loop, args=['arg 1', 2]).start()

Related: Call python script with input with in a python script using subprocess .

To avoid "freezing" your GUI, do not call functions that block for long in your GUI thread. Either use threads or async. API (here's tkinter code example that uses createfilehandler() and .after() calls, to read output from a subprocess without blocking the GUI ).

Popen() only starts a child process and it does not wait for it to exit. If Popen() "freezes" your program something else is broken. Here's code example that starts/stops a tkinter progressbar on start/end of a subprocess.

Qt has its own API: QThread, QProcess, signals that you could use to run a subprocess. Related: How to do stuff during and after a child process .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM