関数 check_Temp が終了/例外を発生させたときにメインプロセスを強制終了したい。これが最善の方法ではないことはわかっていますが、多くのコードを統合する必要があり、これははるかに簡単です。また、ハードシャットダウンが必要なので、プログラムをシャットダウンした後にエラーが発生しても問題ありません。
os.taskskill()、sys.exit()を試しました。os.exit() などですが、子プロセスはメイン プロセスを強制終了しません。すべての python プロセスが強制終了されてもかまいません。psutil のダウンロードは、私の会社の有益な IT 部門によってファイアウォールで保護されているため、誰かが別の解決策を持っているかどうか疑問に思っていました。
import threading
import time
import os
from subprocess import call
#import psutil
def check_Temp(temp, delay, run_event,pid):
while run_event.is_set(): ##code for checking temperature will go here.
time.sleep(delay)
print "temp is %s \n"%temp
temp=temp-1
#print os.getpid()
if temp<=38:
raise Exception('LowTemp')
#call('pkill python', shell=True)
os.popen('TASKKILL /PID '+str(pid)+' /F')
#os.killall()
#sys.exit() #want to exit main loop here
if __name__ == "__main__":
run_event = threading.Event()
run_event.set()
temp =45
d1=.1
#print os.getpid()
pid=os.getpid();
t1 = threading.Thread(target = check_Temp, args = (temp,d1,run_event,pid))
t1.start()
print "Starting"
########## main code will go here, just have a simple counter here to test the functionality.
x=25
try:
while 1:
time.sleep(.1)
x=x-1
print "x is %s \n"%x
if x<0:
print "x is %s"%x
raise Exception('spam', 'eggs')
#exit()
except Exception as e:
print e # the exception instance
run_event.clear()
t1.join()
print "thread successfully closed"
出力は
Starting
temp is 45
x is 24
temp is 44
x is 23
temp is 43
x is 22
temp is 42
x is 21
temp is 41
x is 20
temp is 40
x is 19
temp is 39
x is 18
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python26\lib\threading.py", line 532, in __bootstrap_inner
self.run()
File "C:\Python26\lib\threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\PythonSv\multithread6.py", line 14, in check_Temp
raise Exception('LowTemp')
Exception: LowTemp
x is 17
x is 16
x is 15
x is 14
x is 13
x is 12
x is 11
x is 10
x is 9
x is 8
x is 7
x is 6
x is 5
x is 4
x is 3
x is 2
x is 1
x is 0
x is -1
x is -1
('spam', 'eggs')
thread successfully closed