Ad

How Can I Execute And Terminate Another Python Script In Current Python Script

I'm writing a code in python which reads a status(that is 'on') from txt file and then executes a python script (a.py) and if it reads 'off' from txt file,

I want to terminate a.py and start another script b.py.

so far, I am able to run a.py when status is 'on' but unable to close this script when status is 'off'.

Where I am wrong?

I am using subprocess library in Raspberry pi.

import subprocess as sp

while True:

        file = open("status.txt", "r")#open txt file
        status = file.read()#read the status of file
        print(status)#print the status
        time.sleep(2)


        if status =='on':                              
           extProc =  sp.Popen(['python','a.py'])

        elif status == off:
            print("stop")
            sp.Popen.terminate(sp.Popen(['python','a.py']))
Ad

Answer

You can try this:

import subprocess as sp
import time

procA = None
procB = None
while True:

    file = open("status.txt", "r")  # open txt file
    status = file.read()            # read the status of file
    file.close()
    print(status)                   # print the status
    time.sleep(2)

    if status == 'on':
        if procB:
            procB.terminate()
            procB = None

        if not procA:
            procA = sp.Popen(['python', 'a.py'])

    else:
        if procA:
            procA.terminate()
            procA = None

        if not procB:
            procB = sp.Popen(['python', 'b.py'])
Ad
source: stackoverflow.com
Ad