在 Windows 上使用 python 3.4。
我正在尝试终止模拟一个人按 Ctrl+C(在 linux 上为 Ctrl+D)的子进程。
我只是添加了处理程序来检查信号是否正在被处理。我使用了这个问题的想法
目标是捕获 KeyboardInterrupt (SIGINT),并释放资源。但如果 SIGINT 不是来自键盘,似乎不会抛出异常。这就是为什么我创建了一个处理程序,但该进程似乎根本没有运行该处理程序......
import multiprocessing
import time
import signal
import signal
import os
import sys
def handler(signal, frame):
print("handler!!!")
sys.exit(10)
def worker():
p = multiprocessing.current_process()
try:
signal.signal(signal.SIGINT,handler)
print("[PID:{}] acquiring resources".format(p.pid))
while(True):
#working...
time.sleep(0.5)
except (KeyboardInterrupt, SystemExit):
pass
finally:
print("[PID:{}] releasing resources".format(p.pid))
if __name__ == "__main__":
lst = []
for i in range(1):
p = multiprocessing.Process(target=worker)
p.start()
lst.append(p)
time.sleep(3)
for p in lst:
os.kill(p.pid,signal.SIGINT)
p.join()
print(p)
print(p.exitcode) …Run Code Online (Sandbox Code Playgroud) 我有几个类看起来或多或少是这样的:
import threading
import time
class Foo():
def __init__(self, interval, callbacks):
self.thread = threading.Thread(target=self.loop)
self.interval = interval
self.thread_stop = threading.Event()
self.callbacks = callbacks
def loop():
while not self.thread_stop.is_set():
#do some stuff...
for callback in self.callbacks():
callback()
time.sleep(self.interval)
def start(self):
self.thread.start()
def kill(self):
self.thread_stop.set()
Run Code Online (Sandbox Code Playgroud)
我在我的主线程中使用的是这样的:
interval = someinterval
callbacks = [some callbacks]
f = Foo(interval, callbacks)
try:
f.start()
except KeyboardInterrupt:
f.kill()
raise
Run Code Online (Sandbox Code Playgroud)
在所有回调完成后,但在循环重复之前,我想要一个 KeyboardInterrupt 来终止线程。目前它们被忽略,我不得不求助于终止程序运行的终端进程。
我从这篇文章中看到了使用 threading.Event 的想法,但看起来我做错了,这让这个项目的工作变得非常麻烦。
我不知道它是否相关,但是我从 Internet 传递访问数据的回调并大量使用重试装饰器来处理不可靠的连接。
编辑
在大家的帮助下,循环现在在 Foo 中看起来像这样:
def thread_loop(self):
while not …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个看门狗类,它将在指定时间后抛出异常:
from threading import Timer
from time import sleep
class watchdog():
def _timeout(self):
#raise self
raise TypeError
def __init__(self):
self.t = Timer(1, self._timeout)
def start(self):
self.t.start()
try:
w = watchdog()
w.start()
sleep(2)
except TypeError, e:
print "Exception caught"
else:
print "Of course I didn't catch the exception"
Run Code Online (Sandbox Code Playgroud)
该异常未被捕获,因为该异常是从完全不同的上下文引发的,因此我们将看到最后一条消息。
我的问题是,如何修改代码,以便捕获异常?
我有这个代码,如何从func1停止func2?类似的东西Thread(target = func1).stop()不起作用
import threading
from threading import Thread
def func1():
while True:
print 'working 1'
def func2():
while True:
print 'Working2'
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
Run Code Online (Sandbox Code Playgroud) python模块线程有一个对象Thread,用于在不同的线程中运行进程和函数.这个对象有一个start方法,但没有stop方法.什么是Thread无法阻止我调用简单stop方法的原因?我可以想象使用这种join方法不方便的情况......
我正在尝试使用提供的StoppableThread课程作为另一个问题的答案:
import threading
# Technique for creating a thread that can be stopped safely
# Posted by Bluebird75 on StackOverflow
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
Run Code Online (Sandbox Code Playgroud)
但是,如果我运行如下:
st = StoppableThread(target=func)
Run Code Online (Sandbox Code Playgroud)
我明白了:
TypeError:
__init__()得到一个意外的关键字参数'target'
可能是对如何使用它的疏忽.
class My_Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print "Starting " + self.name
cmd = [ "bash", 'process.sh']
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
print ("-- " + line.rstrip())
print "Exiting " + self.name
def stop(self):
print "Trying to stop thread "
self.run = False
thr = My_Thread()
thr.start()
time.sleep(30)
thr.stop()
thr.join()
Run Code Online (Sandbox Code Playgroud)
所以我有如上所示的线程,实际上在windows上工作,process.sh是在cygwin中运行的bash脚本,需要大约5分钟才能完成执行所以它不是一个循环它的一些模拟proecess
我想在这个类中创建stop()函数,以便我可以在需要时立即终止脚本.终止后,我不希望process.sh脚本有任何有用的结果
请你建议任何方法,如果可能的话请给出一点解释..
python multithreading subprocess python-multithreading python-2.7
我正在使用线程库,并且希望有一个线程可以调用多个线程。该程序的背景是我有一个摄像头,可以捕获Image并使它们在TCP-SocketServer的类中可用。
因此,我需要一个运行相机捕获的线程和另一个运行TCPServer的线程,但是在此线程中,每个进入的连接都有多个线程。
最后一个线程意味着我需要一个可以自己创建线程的线程。不幸的是,这没有用。
我设法将巨大的代码分解成一个小片段,代表了问题所在:
import threading
def adder(x,res,i):
res[i] = res[i] + x*i;
def creator(a,threads,results):
results = []
for i in range(0,a):
results.append(0)
threads.append(threading.Thread(target=adder,args=(a,results,i)))
threads[i].start()
for i in range(0,len(threads)):
threads[i].join()
return results;
threads = [];
results = [];
mainThread = threading.Thread(target=creator,args=([5,threads,results]))
mainThread.start()
mainThread.join()
for i in range(0,len(results)):
print results[i]
print threads[i]
Run Code Online (Sandbox Code Playgroud)
在creator称为线程的函数中,应该使用funciton创建多个线程adder。
但是结果是空的,为什么会这样呢?
这是我的较大程序中发生的相同问题。
为了简化我遇到的情况:我试图终止一个仍在 Python 2.7 中运行的线程,但我不知道该怎么做。
拿这个简单的代码:
import time
import threading
def thread1():
print "Starting thread 1"
while True:
time.sleep(0.5)
print "Working"
thread1 = threading.Thread(target=thread1, args=())
thread1.start()
time.sleep(2)
print "Killing thread 1"
thread2.stop()
print "Checking if it worked:"
print "Thread is: " + str(thread1.isAlive())
Run Code Online (Sandbox Code Playgroud)
线程 1 继续“工作”,我试图在主线程中杀死它。关于如何做到这一点的任何想法?我试过了:
threat1.terminate
threat1.stop
threat1.quit
threat1.end
Run Code Online (Sandbox Code Playgroud)
这一切似乎都表明,没有办法用一行简单的代码来真正阻止它。你有什么建议?
所以我目前有 python 打印函数运行完成后需要多长时间,例如:
import time
t = time.time()
# do something in here
print "\n Time Taken: %.3f sec" % (time.time()-t)
Run Code Online (Sandbox Code Playgroud)
但我想显示自函数启动以来已经过去的生存时间,但我不太想出一种方法来实现这一点。
例如在终端中我希望它说这样的话:
Working on xFunction. Time Elapsed 72.485 sec... (live updated time)
xFunction Has finished.
Time Taken: 1152.546 sec
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。
python ×10
exception ×1
kwargs ×1
python-2.7 ×1
subclass ×1
subprocess ×1
timer ×1
watchdog ×1
windows ×1