python 线程的导入是什么?

Mar*_*oli 0 python scrapy python-2.7

我想每 120 秒运行一些 python 代码。

我试过这个:

class AppServerSvc :

    def f(self):
        # call f() again in 120 seconds
        spider = FantasySerieaSpider()
        settings = get_project_settings()
        crawler = Crawler(settings)
        crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
        crawler.configure()
        crawler.crawl(spider)
        crawler.start()
        log.start()
        reactor.run() # the script will block here until the spider_closed signal was sent
        threading.Timer(120, f).start()


if __name__ == '__main__':
        AppServerSvc().f();
Run Code Online (Sandbox Code Playgroud)

我得到了threading is not defined错误

这是我的进口:

import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from FantasySeriea.spiders.spider import FantasySerieaSpider
from scrapy.utils.project import get_project_settings
from threading import Thread
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 5

而不是(或除了?):

from threading import Thread
Run Code Online (Sandbox Code Playgroud)

你要:

import threading
Run Code Online (Sandbox Code Playgroud)

  • @MarcoDinatsoli `self.f`,最后没有`()`。 (3认同)

Max*_*ant 5

您使用threading.Timer在你的代码,但你只需要导入Thread来自threading并将其放入当前的命名空间。你想要的是导入整个模块:

import threading
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Thread,请确保替换Threadthreading.Thread。此外,您在一个类中,因此您需要添加self.前缀或f引用类成员:

threading.Timer(120, self.f).start()
Run Code Online (Sandbox Code Playgroud)