我想在函数 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
最佳答案
诀窍是使用标志和回调而不是异常。
import threading
import time
import os
from subprocess import call
def check_Temp(temp, delay, run_event,pid, endit):
while run_event.is_set():
time.sleep(delay)
##code for checking temperature will go here.
print "temp is %s \n"%temp
temp=temp-1
#print os.getpid()
if temp<=38:
print 'LowTemp %s!' % (temp, )
endit()
run_event.clear()
if __name__ == "__main__":
run_ok = True
def Terminator():
global run_ok
print "Terminating"
run_ok = False
run_event = threading.Event()
run_event.set()
temp =45
d1=.1
#print os.getpid()
pid=os.getpid();
run_ok = True
t1 = threading.Thread(target = check_Temp, args = (temp,d1,run_event,pid, Terminator))
t1.start()
print "Starting"
########## main code will go here, just have a simple counter here to test the functionality.
x=25
try:
while run_ok:
time.sleep(.1)
x=x-1
print "x is %s "%x
if x<0:
print "x is %s"%x
raise Exception('spam', 'eggs')
#exit()
t1.join()
print 'Finished!'
关于python - 从子线程 python 中杀死 main thead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18064901/
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o
我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的
本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决
2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p
我正在尝试使用ruby编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是Ruby似乎无法捕获线程内的错误,这是一个示例:#!/usr/bin/rubyThread.new{loop{$stdout.puts"hi"abc.putsefsleep1}}loop{sleep1}显然,如果我在线程外键入abc.putsef,代码将永远不会运行,因为Ruby将报告“undefinedvariableabc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让Ruby捕获这样的错误?或者至少,报告线程中的错误?
ValidPalindromeGivenastring,determineifitisapalindrome,consideringonlyalphanumericcharactersandignoringcases. [#125]Example:"Aman,aplan,acanal:Panama"isapalindrome."raceacar"isnotapalindrome.Haveyouconsiderthatthestringmightbeempty?Thisisagoodquestiontoaskduringaninterview.Forthepurposeofthisproblem