Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start a subprocess in python and not wait for it to return

I'm building a site in django that interfaces with a large program written in R, and I would like to have a button on the site that runs the R program. I have that working, using subprocess.call(), but, as expected, the server does not continue rendering the view until subprocess.call() returns. As this program could take several hours to run, that's not really an option.
Is there any way to run the R program and and keep executing the python code? I've searched around, and looked into subprocess.Popen(), but I couldn't get that to work.
Here's the generic code I'm using in the view:

if 'button' in request.POST:
    subprocess.call('R CMD BATCH /path/to/script.R', shell=True)
    return HttpResponseRedirect('')

Hopefully I've just overlooked something simple.
Thank you.

like image 893
clifton.mayhew Avatar asked Oct 15 '25 16:10

clifton.mayhew


1 Answers

subprocess.Popen(['R', 'CMD', 'BATCH', '/path/to/script.R'])

The process will be started asynchronously.

Example:

$ cat 1.py
import time
import subprocess

print time.time()
subprocess.Popen(['sleep', '1000'])
print time.time()

$ python 1.py
1340698384.08
1340698384.08

You must note that the child process will run even after the main process stops.

like image 111
Igor Chubin Avatar answered Oct 18 '25 05:10

Igor Chubin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!