如何在当前python脚本中执行和终止另一个python脚本

时间:2019-04-04 08:33:30

标签: python python-2.7 raspberry-pi subprocess

我正在用python编写代码,该代码从txt文件读取状态(即“ on”),然后执行python脚本(a.py),如果它从txt文件读取“ off”,则

我想终止a.py并启动另一个脚本b.py。

到目前为止,状态为“ on”时,我可以运行a.py,但是 状态为“关闭”时无法关闭此脚本。

我哪里错了?

我在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']))

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

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'])