How to kill a subprocess initiated by another function in the same class

I want to kill a process from another function in the class, considering the fact that it was initiated by another function. Here is an example:

import time class foo_class: global foo_global def foo_start(self): import subprocess self.foo_global =subprocess.Popen(['a daemon service']) def foo_stop(self): self.foo_start.foo_global.kill() self.foo_start.foo_global.wait() foo_class().foo_start() time.sleep(5) foo_class().foo_stop() 

How do I determine foo_stop?

+6
source share
2 answers

jterrace code works. If you do not want it to start on initialization, just call Popen in a separate function and pass nothing to the init function

 import subprocess import time class foo_class(object): def __init__(self): pass def start(self): self.foo = subprocess.Popen(['a daemon service']) def stop(self): self.foo.kill() self.foo.wait() #don't know if this is necessary? def restart(self): self.start() foo = foo_class() foo.start() time.sleep(5) foo.stop() 
+2
source

I assume you want something like this:

 import subprocess import time class foo_class(object): def __init__(self): self.foo = None def start(self): self.stop() self.foo = subprocess.Popen(['a daemon service']) self.foo.start() def stop(self): if self.foo: self.foo.kill() self.foo.wait() self.foo = None foo = foo_class() foo.start() time.sleep(5) foo.stop() 

Some things I changed:

  • Import should usually be at the top of the file.
  • Classes must inherit from object .
  • You want to use an instance variable.
  • For your class class names, it doesn't make sense to start with the class name.
  • When calling its methods, you created a new instance of foo_class . Instead, you want to create one instance and call it methods.
+2
source

All Articles