Start and terminate subprocess from python function -


how write function can start , kill subrocess in python??

this code far:

import subprocess import signal import time  def myfunction(action):     if action == 'start':         print 'start subrocess'         process = subprocess.popen("ping google.com", shell=true)     if action == 'stop':         print 'stop subrocess'         process.send_signal(signal.sigint)  myfunction('start') time.sleep(10) myfunction('stop') 

when run code error:

traceback (most recent call last):   file "test.py", line 15, in <module>     myfunction('stop')   file "test.py", line 11, in myfunction     process.send_signal(signal.sigint) unboundlocalerror: local variable 'process' referenced before assignment 

you need learn oop , define myclass constructor , destructor. assuming not need run many copies of process, , make more exotic can use class methods

class myclass(object):     @classmethod     def start(self)         print 'start subrocess'         self.process = subprocess.popen("ping google.com", shell=true)      @classmethod     def stop(self)         self.process.send_signal(signal.sigint)  myclass.start() myclass.stop() 

this not ideal allows create several new processes. quite in such cases singleton pattern used, insures there 1 process running yet bit out of fashion.

the minimal fix (keeping myfunction) save process in variable:

import subprocess import signal import time  def myfunction(action, process=none):     if action == 'start':         print 'start subrocess'         process = subprocess.popen("ping google.com", shell=true)         return process     if action == 'stop':         print 'stop subrocess'         process.send_signal(signal.sigint)  process = myfunction('start') time.sleep(10) myfunction('stop', process) 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -