Python:线程将不会启动
我有一个从threading.Thread继承的类。由于某些原因,线程不希望启动 这是我的密码:Python:线程将不会启动,python,multithreading,Python,Multithreading,我有一个从threading.Thread继承的类。由于某些原因,线程不希望启动 这是我的密码: import time,threading,re,socket class PyWatch(threading.Thread): filename = "" def __init__(self,filename): threading.Thread.__init__(self) print "initiating..." se
import time,threading,re,socket
class PyWatch(threading.Thread):
filename = ""
def __init__(self,filename):
threading.Thread.__init__(self)
print "initiating..."
self.filename = filename
def run(self):
print "running..."
thefile = open (self.filename)
thefile.seek(0,2) # Go to the end of the file
while True:
line = thefile.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
yield line
self.process(line)
def process(self,line):
ip = self.filterIPFromLine(line)
print ip
def filterIPFromLine(self,line):
ip = None
if '/var/ossec/active-response/bin/firewall-drop.sh' in str( line ).lower():
ip = re.match( "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" )
try:
socket.inet_aton(ip[0])
ip = ip[0]
except socket.error:
pass
return ip
tom = PyWatch('example.log')
tom.start()
代码正在运行,不会返回任何错误,但由于某些原因,它从未到达运行部分 我无法重现这个问题: 当我运行您的代码时,我得到:
initiating...
running...
这表明run方法确实正确执行
您是否正确地在代码顶部导入了线程模块
import threading
您需要删除该行:
yield line
这导致了run不能,嗯。。。跑一开始它为什么会在那里还不清楚
根据,仅在定义生成器函数时使用,并且在调用生成器函数时,它返回称为生成器的迭代器。然后,该生成器控制生成器功能的执行。当调用生成器的一个方法时,执行开始
由于您没有调用任何生成器方法(如next),因此函数不会执行
下面是一个快速演示:
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def fun():
... print 'Starting'
... for i in range(10):
... yield i
...
>>> fun()
<generator object fun at 0x10678c460>
>>> _.next()
Starting
0
>>>
有一个答案。更新了代码,这是我的完整代码,如果我删除了一些确实运行的方法。我不知道添加方法会改变什么:/@LucasKauffman:不是添加方法改变了输出,而是添加了什么来运行。看看我的答案。