我有一个使用线程并发出大量HTTP请求的python脚本.我认为发生的事情是,当HTTP请求(使用urllib2)正在读取时,它会阻塞并且不响应CtrlC以停止程序.有没有办法解决?
如何对Ctrl + C键事件进行多线程python程序响应?
编辑:代码是这样的:
import threading
current = 0
class MyThread(threading.Thread):
def __init__(self, total):
threading.Thread.__init__(self)
self.total = total
def stop(self):
self._Thread__stop()
def run(self):
global current
while current<self.total:
lock = threading.Lock()
lock.acquire()
current+=1
lock.release()
print current
if __name__=='__main__':
threads = []
thread_count = 10
total = 10000
for i in range(0, thread_count):
t = MyThread(total)
t.setDaemon(True)
threads.append(t)
for i in range(0, thread_count):
threads[i].start()
Run Code Online (Sandbox Code Playgroud)
我试图在所有线程上删除join()但它仍然无效.是因为每个线程的run()过程中的锁段?
编辑:上面的代码应该可以工作但是当当前变量在5,000-6,000范围内并且通过如下错误时它总是被中断
Exception in thread Thread-4 (most likely raised during interpreter shutdown):
Traceback (most recent call …Run Code Online (Sandbox Code Playgroud) 我正在运行这个简单的代码:
import threading, time
class reqthread(threading.Thread):
def run(self):
for i in range(0, 10):
time.sleep(1)
print('.')
try:
thread = reqthread()
thread.start()
except (KeyboardInterrupt, SystemExit):
print('\n! Received keyboard interrupt, quitting threads.\n')
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,它会打印出来
$ python prova.py
.
.
^C.
.
.
.
.
.
.
.
Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored
Run Code Online (Sandbox Code Playgroud)
实际上python线程忽略我的Ctrl+ C键盘中断而不打印Received Keyboard Interrupt.为什么?这段代码有什么问题?
有没有办法等待终止线程,但仍然拦截信号?
考虑以下C程序:
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void* server_thread(void* dummy) {
sleep(10);
printf("Served\n");
return NULL;
}
void* kill_thread(void* dummy) {
sleep(1); // Let the main thread join
printf("Killing\n");
kill(getpid(), SIGUSR1);
return NULL;
}
void handler(int signum) {
printf("Handling %d\n", signum);
exit(42);
}
int main() {
pthread_t servth;
pthread_t killth;
signal(SIGUSR1, handler);
pthread_create(&servth, NULL, server_thread, NULL);
pthread_create(&killth, NULL, kill_thread, NULL);
pthread_join(servth, NULL);
printf("Main thread finished\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它在一秒后结束并打印:
Killing
Handling 10 …Run Code Online (Sandbox Code Playgroud) 我在某处读到KeyboardInterrupt异常只在Python的主线程中引发.我还读到在子线程执行时主线程被阻塞.那么,这是否意味着CTRL+ C永远不会到达子线程.我尝试了以下代码:
def main():
try:
thread = threading.Thread(target=f)
thread.start() # thread is totally blocking (e.g., while True)
thread.join()
except KeyboardInterrupt:
print "Ctrl+C pressed..."
sys.exit(1)
def f():
while True:
pass # do the actual work
Run Code Online (Sandbox Code Playgroud)
在这种情况下,CTRL+ C对执行没有影响.它就像是无法收听信号.我理解这是错误的方式吗?有没有其他方法可以使用CTRL+ 杀死线程C?
我正在制作一个简单的多线程端口扫描器.它扫描主机上的所有端口并返回打开的端口.麻烦在于中断扫描.扫描完成需要花费大量时间,有时我希望在扫描过程中用Cc杀死程序.麻烦的是扫描不会停止.主线程被锁定在queue.join()上,并且忘记了KeyboardInterrupt,直到处理了队列中的所有数据,因此解除了主线程并正常退出程序.我的所有线程都被守护进来,所以当主线程死掉时,他们应该和他一起死掉.
我尝试使用信号库,没有成功.覆盖threading.Thread类和正常终止的添加方法不起作用...主线程在执行queue.join()时不会收到KeyboardInterrupt
import threading, sys, Queue, socket
queue = Queue.Queue()
def scan(host):
while True:
port = queue.get()
if port > 999 and port % 1000 == 0:
print port
try:
#sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#sock.settimeout(2) #you need timeout or else it will try to connect forever!
#sock.connect((host, port))
#----OR----
sock = socket.create_connection((host, port), timeout = 2)
sock.send('aaa')
data = sock.recv(100)
print "Port {} open, message: {}".format(port, data)
sock.shutdown()
sock.close()
queue.task_done()
except:
queue.task_done()
def main(host):
#populate queue
for i in range(1, …Run Code Online (Sandbox Code Playgroud) 目前在Docker遇到问题; 我用它来运行一个启动时启动ipython笔记本的图像.我想对ipython笔记本本身进行一些编辑,所以我需要在启动后关闭它.
但是,在终端中按CTRL + C只输入"^ C"作为字符串.似乎没有真正的方法使用CTRL + C来实际关闭ipython笔记本实例.
任何人都有任何线索可以解决这个问题,或者知道任何解决方案吗?
我编写了一个多线程应用程序来监视和响应给定文件列表中的更改.我有一个Watch 获取文件大小的类,并size在第一次调用时将其设置为变量.然后,几秒钟后,它再次获取文件的大小,并将其与之前的大小进行比较,如果更改,则设置size为文件的当前大小.此外,还有一个WatchWorker类是它的子类threading.Thread.在WatchWorker这使得使用Watch类"手表"给定的文件.
现在这是真正的问题:我编写的代码正在工作,并在检测到更改时通知用户.但是当我尝试使用Ctrl+ 从应用程序退出时没有响应C.我在Windows上.
码:
import time
import threading
import os
class Watch(object):
def __init__(self, path, time=5):
self.path = path
self.time = time
self.size = os.stat(path).st_size
def loop(self):
while True:
time.sleep(self.time)
size = os.stat(self.path).st_size
if size != self.size:
self.size = size
print "Change detected in file {}".format(self.path)
class Watch_Worker(threading.Thread):
def __init__(self, path, *args, **kwargs):
super(Watch_Worker, self).__init__(*args, **kwargs)
self.path = path
def run(self):
super(Watch_Worker, …Run Code Online (Sandbox Code Playgroud) 我正在制作我的第一个 Flask/python 网络应用程序。该应用程序最初显示邀请用户填写的表单,然后他们单击“提交”按钮,然后服务器运行模拟并创建一个带有显示结果的图形的 PNG 文件,最后页面被重新绘制显示的图形。我的python代码大致是这种形式:
# flask_app.py
@app.route("/", methods=["POST", "GET"])
def home():
if request.method == 'POST':
# bunch of request.form things to scoop the contents of the form
if form_answers_all_good:
for i in range(huge_number):
# some maths
# create png file with results
return render_template("index.htm", foo=bar)
Run Code Online (Sandbox Code Playgroud)
程序运行良好,但huge_number循环可能需要几十秒。所以我想要的是某种进度指示器——它不必是一个漂亮的动画——即使是百分比进度的字符串读数也可以。
大概我可以将我的 for 循环更改为类似...
for i in range(huge_number):
# some maths
percentage_done = str(i * 100/huge_number)
Run Code Online (Sandbox Code Playgroud)
然后以某种方式在客户端安排阅读(民意调查?),percentage_done以便我输入以下内容:
Completed {% percentage_done %}% so far.
Run Code Online (Sandbox Code Playgroud)
在我的index.htm. 顺便说一句,我对 Javascript、AJAX 之类的知识或想到它,几乎所有客户端(除了 HTML)的知识都是初学者级别。 …