views:

51

answers:

2

I have a view that gets data from a form and executes a subprocess:

def sync_job(request, job_id, src, dest):
  form = SyncJobForm()
  check = SyncJob.objects.get(id=job_id)
  check.status = True
  check.save()
  pre_sync = SyncJobCMD.objects.get(id=1)
  p = Popen([str(pre_sync), '-avu', str(src), str(dest)], stdout=PIPE)
  syncoutput,syncerror = p.communicate()
  check.log = syncoutput
  check.status = False
  check.save()
  return render_to_response('sync_form.html', {'syncoutput': syncoutput, 'form': form}, context_instance=RequestContext(request))

I would like to have an option to cancel the running process, but I have not found how to do that with subprocess. Also, what happens when a user runs a subprocess job and navigates to another page, does the process finish in the background? Is it advisable to use Shell=True in this scenario? Thanks.

A: 

Starting from Python 2.6 you can use Popen.terminate() to kill your processes:

p.terminate()

In earlier versions of Python you can use os.kill().

os.kill(p.pid, signal.SIGTERM)

Also, Popen.communicate() will block until your child process has terminated. This means that the response will not get sent to the user before your sync job has terminated.

Arlaharen
A: 

Also you could use signals (kill signal or others, more details see signal module):

import signal
p.send_signal(signal.SIGKILL)
iscarface