Pranjal Mishra
Pranjal Mishra

Reputation: 31

how to run and exit python scripts from another python program?

I wish to launch a python file when I send an on request and kill that python process once I send the off request . I am able to send the on and off requests but am not able to run the other python file or kill it from the program I have written.

I could make a subprocess call but I think there should be a way to call other python scripts inside a python script and also a way to kill those scripts once their purpose is fulfilled.

Upvotes: 0

Views: 631

Answers (1)

Tom Atix
Tom Atix

Reputation: 401

I suggest to use a thread.

Write all the code in your python script in a function doit (except import statements) and then import it:

content of thescript.py:

import time

def doit(athread):
   while not athread.stopped():
      print("Hello World")
      time.sleep(1)

your program should look like:

import threading
import time
import thescript

class FuncThread(threading.Thread):
   def __init__(self, target):
      self.target=target
      super(FuncThread,self).__init__()
      self._stop_event=threading.Event()

   def stop(self):
      self._stop_event.set()

   def stopped(self):
      return self._stop_event.is_set()

   def run(self):
      self.target(self)

t1=FuncThread(thescript.doit)
t1.start()
time.sleep(5)
t1.stop()
t1.join()

You can exit the thread any time, I just waited 5 seconds and then called the stop() method.

Upvotes: 1

Related Questions