Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run another script in Python without waiting for it to finish? [duplicate]

I am creating a little dashboard for a user that will allow him to run specific jobs. I am using Django so I want him to be able to click a link to start the job and then return the page back to him with a message that the job is running. The results of the job will be emailed to him later.

I believe I am supposed to use subprocess.Popen but I'm not sure of that. So in pseudocode, here is what I want to do:

if job == 1:     run script in background: /path/to/script.py     return 'Job is running' 
like image 887
sheats Avatar asked Feb 13 '09 13:02

sheats


People also ask

How do I run a Python script without closing?

cmd /k is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k and then drag&drop the script you want to the Run dialog. Fantastic answer. You should have got this.

What happens if you change a Python script while its running?

It happens nothing. Once the script is loaded in memory and running it will keep like this. An "auto-reloading" feature can be implemented anyway in your code, like Flask and other frameworks does.

How do I keep a Python script running forever?

Challenge: Run a piece of Python code forever—until it is forcefully interrupted by the user. Solution: use a while loop with a Boolean expression that always evaluates to True . Examples: have a look at the following variants of an infinite while loop.


1 Answers

p = subprocess.Popen([sys.executable, '/path/to/script.py'],                                      stdout=subprocess.PIPE,                                      stderr=subprocess.STDOUT) 

That will start the subprocess in background. Your script will keep running normally.

Read the documentation here.

like image 176
nosklo Avatar answered Sep 19 '22 11:09

nosklo