###実現したいこと
KeyboardInterrupt(つまりCtrl-cを押した時)によって、twistedのreactorを終了させたい
###発生している問題
PythonのScrapyライブラリを使ってスクレイピングをしようとしています。
以下のスクリプトのように、スクレイピングの開始をスクリプトから制御しています。
python
1from scrapy.crawler import CrawlerProcess 2from scrapy.utils.project import get_project_settings 3 4 5def start_crawling(): 6 process = CrawlerProcess(get_project_settings()) 7 8 process.crawl("***") 9 process.start() 10 11 12if __name__ == "__main__": 13 start_crawling()
このスクリプトを走らせると1回目は正常に動きます。しかし、Ctrl-cによってスクリプトを中断した後に、再びスクリプトを走らせると、以下のエラーが出ます。
Traceback (most recent call last): File "<ipython-input-2-91bf2f9f639a>", line 1, in <module> runfile('***', wdir='***') File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/Users/arata/Documents/gunosynews/gunosynews/start_crawling.py", line 13, in <module> start_crawling() File "/Users/arata/Documents/gunosynews/gunosynews/start_crawling.py", line 9, in start_crawling process.start() File "/anaconda/lib/python3.6/site-packages/scrapy/crawler.py", line 285, in start reactor.run(installSignalHandlers=False) # blocking call File "/anaconda/lib/python3.6/site-packages/twisted/internet/base.py", line 1242, in run self.startRunning(installSignalHandlers=installSignalHandlers) File "/anaconda/lib/python3.6/site-packages/twisted/internet/base.py", line 1222, in startRunning ReactorBase.startRunning(self) File "/anaconda/lib/python3.6/site-packages/twisted/internet/base.py", line 730, in startRunning raise error.ReactorNotRestartable() ReactorNotRestartable
エラーについて調べてみたところ、どうやらCtrl-cを押した時にちゃんとtwistedのreactorを終了できていない?ようでした。
エラーが起きている箇所のスクリプトは下のような感じです。
Python
1def startRunning(self): 2 """ 3 Method called when reactor starts: do some initialization and fire 4 startup events. 5 6 Don't call this directly, call reactor.run() instead: it should take 7 care of calling this. 8 9 This method is somewhat misnamed. The reactor will not necessarily be 10 in the running state by the time this method returns. The only 11 guarantee is that it will be on its way to the running state. 12 """ 13 if self._started: 14 raise error.ReactorAlreadyRunning() 15 #エラー箇所 16 if self._startedBefore: 17 raise error.ReactorNotRestartable() 18 self._started = True 19 self._stopped = False 20 if self._registerAsIOThread: 21 threadable.registerAsIOThread() 22 self.fireSystemEvent('startup')
どうしたらKeyboardInterruptを押した時(スクリプトを中断した後再び正常に走らせることができれば、他の方法でも良いです)にtwistedのreactorを正常に終了させることができるでしょうか?
よろしくお願いいたします。
###環境
Python 3.6.0
Scrapy 1.4.0
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。