【问题标题】:Scrapy cmdline.execute stops scriptScrapy cmdline.execute 停止脚本
【发布时间】:2014-07-21 21:38:14
【问题描述】:

当我打电话时

cmdline.execute("scrapy crawl website".split())
print "Hello World"

它在 cmdline.execute 之后停止脚本,并且不运行脚本的其余部分并打印“Hello World”。我该如何解决这个问题?

【问题讨论】:

    标签: command-line scrapy


    【解决方案1】:

    通过查看 Scrapy 的 cmdline.py 中的 execute 函数,您会看到最后一行是:

    sys.exit(cmd.exitcode)
    

    如果你直接调用execute 函数,那么这个sys.exit 调用确实没有办法,至少在不改变它的情况下是这样。猴子补丁是一种选择,尽管不是一个好选择!更好的选择是完全避免调用execute 函数,而是使用下面的自定义函数:

    from twisted.internet import reactor
    
    from scrapy import log, signals
    from scrapy.crawler import Crawler as ScrapyCrawler
    from scrapy.settings import Settings
    from scrapy.xlib.pydispatch import dispatcher
    from scrapy.utils.project import get_project_settings
    
    def scrapy_crawl(name):
    
        def stop_reactor():
            reactor.stop()
    
        dispatcher.connect(stop_reactor, signal=signals.spider_closed)
        scrapy_settings = get_project_settings()
        crawler = ScrapyCrawler(scrapy_settings)
        crawler.configure()
        spider = crawler.spiders.create(name)
        crawler.crawl(spider)
        crawler.start()
        log.start()
        reactor.run()
    

    你可以这样称呼它:

    scrapy_crawl("your_crawler_name")
    

    【讨论】:

      【解决方案2】:

      我刚刚尝试了以下代码,它对我有用:

      import os
      os.system("scrapy crawl website")
      print("Hello World")
      

      【讨论】:

        【解决方案3】:

        可以运行 subprocess.call。例如在带有 powershell 的 Windows 上:

        import subprocess
        
        subprocess.call([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                                     '-ExecutionPolicy',
                                     'Unrestricted',
                         'scrapy crawl website -o items.json -t json'])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-28
          • 2023-04-11
          • 1970-01-01
          • 2011-07-01
          • 2019-10-14
          相关资源
          最近更新 更多