Python:线程不会启动

Luc*_*man 0 python multithreading

我有一个继承自threading.Thread. 由于某种原因,线程不想启动。

这是我的代码:

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()
Run Code Online (Sandbox Code Playgroud)

代码正在运行,它没有返回任何错误,但由于某种原因它永远不会到达run()零件。

Joh*_*web 5

您需要删除该行:

            yield line
Run Code Online (Sandbox Code Playgroud)

这导致run()不,好吧……跑!为什么它首先在那里并不明显。

根据Python 文档yield表达式仅在定义生成器函数时使用,并且当调用生成器函数时,它返回一个称为生成器的迭代器。该生成器然后控制生成器函数的执行。当调用生成器的方法之一时,执行开始。

由于您没有调用任何生成器方法(例如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
>>> 
Run Code Online (Sandbox Code Playgroud)

作为对Python 中“yield”关键字的作用的回答,yield 表达式一个很好的解释.