1

In my django view, i need to send email notification after subprocess is done because the script launched by subprocess is running some commands in background so the email is sent before the script is done, does anyone have an idea about how i could do this ?

My view:

def getor(request):
# process
    subprocess.call("./step1.sh", shell=True)
#send notification
    current_site = get_current_site(request)
    user = User.objects.values('username').order_by('id').last()
    us = user['username']
    subject = 'Notification of endprocess.'
    message = render_to_string('notify.html', {
       'us':us,
       'domain':current_site.domain,
    })
    eml = User.objects.values('email').order_by('id').last()
    toemail = eml['email']
    email = EmailMessage(subject, message, to=[toemail])
    email.send()
    return render(request, 'endexecut.html')
c.ceti
  • 183
  • 2
  • 5
  • 12
  • does https://stackoverflow.com/questions/14043030/checking-status-of-process-with-subprocess-popen-in-python help? – Stael Aug 10 '17 at 10:03
  • I had some errors with comunicate() function, what i did is on the comment of the answer, thank you anyway. – c.ceti Aug 11 '17 at 12:42

1 Answers1

1

A quick fix can be put the email send in a function and create a python file. Call it from step1.sh

What I can't understand is, subprocess.call is a blocking function. i.e. until the command in call function doesn't complete, it will not go to next line of code.

I'd go with gevent. Put all the function is gevent spawn. Inside the function call the subprocess first and store the PID. Next code should be a while loop and check if the PID exists. If not the send mail and break the loop. Or else sleep for certain seconds.

Swagat
  • 617
  • 5
  • 16
  • Thank you for you answer, I just put the email code in a python script and imported django settings so that i can use email settings and called this python script from the bash script in subprocess. subprocess.call() is not blocking for this case, because the commands in the script are run in the background. – c.ceti Aug 11 '17 at 12:39
  • Good to hear. If my answer helped, consider to make it tick mark for both of ours karma. – Swagat Aug 16 '17 at 10:23