簡體   English   中英

當我在子進程中使用python-requests時,我的Python程序意外退出

[英]My Python program unexpectedly quit when I use python-requests in sub process

在我的蜘蛛項目中,我有一個代碼段落,用於抓取“新浪微博”這個最熱門的主題鏈接,它將為我的蜘蛛提供食物。 當我單獨測試它時它完美地工作。但是,當我在Process中使用它時,代碼段導致python意外退出。 我發現失敗的原因是我在代碼段中使用python-requests。所以,當我用urllib3重寫它時,它正常工作。

這段代碼在我的macOS Mojava中運行。 Python版本為“3.7”,python-requests版本為“2.21.0”。

"""
The run_spider function periodically crawls the link and feed to the spiders
"""
@staticmethod
def run_spider():
    try:
        cs = CoreScheduler()
        while True:
            cs.feed_spider()
            first_time = 3 * 60
            while not cs.is_finish():
                time.sleep(first_time)
                first_time = max(10, first_time // 2)
            cs.crawl_done()
            time.sleep(SPIDER_INTERVAL)
    except Exception as e:
        print(e)
"""
The cs.feed_spider() just crawl and parse the page, it will return a generator of links. The code is shown below.
"""
def get_page(self):
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'zh-cn',
        'Host': 's.weibo.com',
        'Accept-Encoding': 'br, gzip, deflate',
        "User-Agent": 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_3) AppleWebKit/605.1.15\
         (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1',

        }
    # res = requests.get(self.TARGET_URL, headers=headers)
    http = urllib3.PoolManager()
    res = http.request("GET", self.TARGET_URL, headers=headers)
    if 200 == res.status:
        return res.data
    else:
        return None
"""
The crawler will become a child process. like below.
"""
def run(self):
    spider_process = Process(target=Scheduler.run_spider)
    spider_process.start()

我希望使用python-requests可以工作,但它導致程序意外退出。 當我使用urllib3重寫代碼時,程序運行正常。 我不明白為什么。

你開始了這個過程,但我看不到你在等它。 join()函數將導致主線程暫停執行,直到spider_process線程完成其執行。

def run(self):
    spider_process = Process(target=Scheduler.run_spider)
    spider_process.start()
    spider_process.join()

這是官方join()文檔的鏈接: https//docs.python.org/3/library/threading.html#threading.Thread.join

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM