我正在编写一个程序来解析10个网站,查找数据文件,保存文件,然后解析它们以生成可以在NumPy库中使用的数据.有吨的错误该文件通过遇到不良链接,不好的XML,缺项,其他的事情我还没有进行分类.我最初制作这个程序来处理这样的错误:
try:
do_stuff()
except:
pass
Run Code Online (Sandbox Code Playgroud)
但现在我想记录错误:
try:
do_stuff()
except Exception, err:
print Exception, err
Run Code Online (Sandbox Code Playgroud)
请注意,这是打印到日志文件以供以后查看.这通常会打印非常无用的数据.我想要的是打印错误触发时打印的完全相同的行,没有try-except拦截异常,但我不希望它暂停我的程序,因为它嵌套在一系列for循环中,我想看完成了.
我对Python和多线程编程很新.基本上,我有一个脚本,将文件复制到另一个位置.我希望将它放在另一个线程中,以便我可以输出....以指示脚本仍在运行.
我遇到的问题是,如果文件无法复制,它将引发异常.如果在主线程中运行,这是可以的; 但是,具有以下代码不起作用:
try:
threadClass = TheThread(param1, param2, etc.)
threadClass.start() ##### **Exception takes place here**
except:
print "Caught an exception"
Run Code Online (Sandbox Code Playgroud)
在线程类本身,我试图重新抛出异常,但它不起作用.我看到这里的人问类似的问题,但他们似乎都在做一些比我想做的更具体的事情(而且我不太了解提供的解决方案).我见过人们提到使用它sys.exc_info(),但我不知道在哪里或如何使用它.
非常感谢所有帮助!
编辑:线程类的代码如下:
class TheThread(threading.Thread):
def __init__(self, sourceFolder, destFolder):
threading.Thread.__init__(self)
self.sourceFolder = sourceFolder
self.destFolder = destFolder
def run(self):
try:
shul.copytree(self.sourceFolder, self.destFolder)
except:
raise
Run Code Online (Sandbox Code Playgroud) The requirement is to start five threads, and wait only in the fastest thread. All five threads went to look for the same data 5 directions, and one is enough to continue the control flow.
Actually, I need to wait for the first two threads to return, to verify against each other. But I guess if I know how to wait for the fastest. I can figure out how to wait for the second-fastest.
很多人都在谈论join(timeout),但你事先并不知道哪一个要等(哪一个join提前申请).
我正在尝试使用Python 2.7中的Queue.Queue实现多线程生产者 - 消费者模式.我试图找出如何使消费者,即工人线程,一旦完成所有必要的工作,停止.
请参阅Martin James对此答案的第二条评论:https://stackoverflow.com/a/19369877/1175080
发送'我完成'任务,指示池线程终止.任何获得此类任务的线程都会重新排队,然后自杀.
但这对我不起作用.例如,请参阅以下代码.
import Queue
import threading
import time
def worker(n, q):
# n - Worker ID
# q - Queue from which to receive data
while True:
data = q.get()
print 'worker', n, 'got', data
time.sleep(1) # Simulate noticeable data processing time
q.task_done()
if data == -1: # -1 is used to indicate that the worker should stop
# Requeue the exit indicator.
q.put(-1)
# Commit suicide.
print 'worker', n, 'is …Run Code Online (Sandbox Code Playgroud) python concurrency multithreading producer-consumer python-2.7
我是python的新手并且取得了一些进展threading- 我正在做一些音乐文件转换,并希望能够在我的机器上使用多个核心(每个核心一个活动的转换线程).
class EncodeThread(threading.Thread):
# this is hacked together a bit, but should give you an idea
def run(self):
decode = subprocess.Popen(["flac","--decode","--stdout",self.src],
stdout=subprocess.PIPE)
encode = subprocess.Popen(["lame","--quiet","-",self.dest],
stdin=decode.stdout)
encode.communicate()
# some other code puts these threads with various src/dest pairs in a list
for proc in threads: # `threads` is my list of `threading.Thread` objects
proc.start()
Run Code Online (Sandbox Code Playgroud)
一切正常,所有文件都被编码,勇敢!...但是,所有进程立即生成,但我只想一次运行两个(每个核心一个).一旦完成,我希望它继续到列表中的下一个,直到它完成,然后继续该程序.
我该怎么做呢?
(我查看了线程池和队列函数,但我找不到简单的答案.)
编辑:也许我应该添加我的每个线程subprocess.Popen用于运行单独的命令行解码器(flac)管道输出到stdout,它被送入命令行编码器(lame/mp3).
由于其并发期货模块,我刚刚转到python3.我想知道我是否可以让它来检测错误.我想将并发期货用于并行程序,如果有更高效的模块请告诉我.
我不喜欢多处理,因为它太复杂,没有太多的文档.然而,如果有人可以编写一个没有类的Hello World,那么将使用多处理来并行计算,这样很容易理解.
这是一个简单的脚本:
from concurrent.futures import ThreadPoolExecutor
def pri():
print("Hello World!!!")
def start():
try:
while True:
pri()
except KeyBoardInterrupt:
print("YOU PRESSED CTRL+C")
with ThreadPoolExecutor(max_workers=3) as exe:
exe.submit(start)
Run Code Online (Sandbox Code Playgroud)
上面的代码只是一个演示,关于CTRL + C如何无法打印satement.
我想要的是能够调用函数是一个错误存在.此错误检测必须来自函数本身.
另一个例子
import socket
from concurrent.futures import ThreadPoolExecutor
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def con():
try:
s.connect((x,y))
main()
except: socket.gaierror
err()
def err():
time.sleep(1)
con()
def main():
s.send("[+] Hello")
with ThreadPoolExecutor as exe:
exe.submit(con)
Run Code Online (Sandbox Code Playgroud) python multiprocessing python-2.7 python-3.4 concurrent.futures
如何在以下代码中将打开的线程的最大值限制为20?我知道过去曾提出过一些类似的问题,但我特别想知道如何使用队列以及如果可能的工作示例做得最好.
# b is a list with 10000 items
threads = [threading.Thread(target=targetFunction, args=(ptf,anotherarg)) for ptf in b]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
Run Code Online (Sandbox Code Playgroud)