我在python中编写一个代码,它从txt文件中读取状态(即'on'),然后执行python脚本(a.py),如果它从txt文件中读取'off',
我想终止a.py并启动另一个脚本b.py.
到目前为止,我可以在状态为“on”时运行a.py,但在状态为“off”时无法关闭此脚本。
哪里错了?
我在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']))
你可以试试这个:
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'])