简体   繁体   English

如果发生错误,则重新运行 Python 脚本

[英]rerun Python script if error occured

I am scraping twitter data using their Streaming API, sometimes, I will get我正在使用他们的 Streaming API 抓取 twitter 数据,有时,我会得到

  File "//swigel_local/Shared/Resources/Tools/Twitter/Streaming/StreamingTwitter.py", line 68, in <module>
    stream.filter(track=TRACK_TERMS)

  File "C:\Users\SwigelUser\Anaconda3\lib\site-packages\tweepy\streaming.py", line 445, in filter
    self._start(async)

  File "C:\Users\SwigelUser\Anaconda3\lib\site-packages\tweepy\streaming.py", line 361, in _start
    self._run()

  File "C:\Users\SwigelUser\Anaconda3\lib\site-packages\tweepy\streaming.py", line 294, in _run
    raise exception

  File "C:\Users\SwigelUser\Anaconda3\lib\site-packages\tweepy\streaming.py", line 263, in _run
    self._read_loop(resp)

  File "C:\Users\SwigelUser\Anaconda3\lib\site-packages\tweepy\streaming.py", line 313, in _read_loop
    line = buf.read_line().strip()

AttributeError: 'NoneType' object has no attribute 'strip'

And this will stop my program.这将停止我的程序。 Is there a way that I can rerun my program automatically when this error occurs?有没有办法在发生此错误时自动重新运行我的程序?

My code is :我的代码是:

class StreamListener(tweepy.StreamListener):

    def on_status(self, status):
        if status.retweeted:
            return

        text = status.text
        created = status.created_at
        id_str = status.id_str
        retweets = status.retweet_count
        blob = TextBlob(text)
        sent = blob.sentiment

        table = db[settings.TABLE_NAME]
        try:
            table.insert(dict(
                text = text,
                created = created,
                id_str = id_str,
                retweet_count = retweets,
                polarity = sent.polarity,
                subjectivity = sent.subjectivity,
            ))
        except ProgrammingError as err:
            print(err)


    def on_error(self, status_code):
        if status_code == 420:
            #returning False in on_data disconnects the stream
            return False
stream.filter(track=TRACK_TERMS)

I don't know why the error happens.我不知道为什么会发生错误。 But I think it has something to do with the change I made recently.但我想这与我最近所做的改变有关。

Before, my table in MySQL has utf8 collation, but this will cause warning, then I read articles, and changed my table to utf8mb4 unicode.之前,我在MySQL中的表有utf8 collat​​ion,但是这会引起警告,然后我阅读了文章,将我的表更改为utf8mb4 unicode。 The warning disappeared and the program runs fine.警告消失,程序运行正常。 But sometimes, the above error would occur when the program is running.但有时,程序运行时会出现上述错误。

def _read_loop(self, resp):
    charset = resp.headers.get('content-type', default='')
    enc_search = re.search('charset=(?P<enc>\S*)', charset)
    if enc_search is not None:
        encoding = enc_search.group('enc')
    else:
        encoding = 'utf-8'

    buf = ReadBuffer(resp.raw, self.chunk_size, encoding=encoding)

    while self.running and not resp.raw.closed:
        length = 0
        while not resp.raw.closed:
            line = buf.read_line().strip()
            if not line:
                self.listener.keep_alive()  # keep-alive new lines are expected
            elif line.isdigit():
                length = int(line)
                break
            else:
                raise TweepError('Expecting length, unexpected value found')

Is there a way that I can rerun my program automatically when this error occurs?有没有办法在发生此错误时自动重新运行我的程序?

You could write an external application that monitors the system, detects crashes of your application and restarts it.您可以编写一个外部应用程序来监视系统、检测应用程序的崩溃并重新启动它。

BUT I wouldn't recommend it!我不会推荐它!

The right solution is:正确的解决办法是:

  • Identify the cause of this issue and fix it!找出此问题的原因并修复它!
  • Wrap problematic code segments using try .. except , catch such errors (eg AttributeError ) and handle them accordingly使用try .. except包装有问题的代码段,捕获此类错误(例如AttributeError )并相应地处理它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM