无效语法(<unknown>,第 21 行)

当我尝试调试时收到此错误消息我不知道这是怎么回事这是自动 Reddit 海报


第 21 行是例外,e:


这行代码看起来不错,我不知道为什么会出现错误。



import praw

import json

import urllib


import settingslocal


REDDIT_USERNAME = ''

REDDIT_PASSWORD = ''


try:

    from settingslocal import *

except ImportError:

    pass


def main():

    print ('starting')


    url = "http://api.ihackernews.com/page"

    try:

        result = json.load(urllib.urlopen(url))

    except Exception, e:

    return


    items = result['items'][:-1]


    reddit = praw.Reddit(user_agent='HackerNews bot by /u/mpdavis')

    reddit.login(REDDIT_USERNAME, REDDIT_PASSWORD)

    link_submitted = False

    for link in items:

        if link_submitted:

            return

        try:

            #Check to make sure the post is a link and not a post to another HN page. 

            if not 'item?id=' in link['url'] and not '/comments/' in link['url']:

                submission = list(reddit.get_info(url=str(link['url'])))

                if not submission:

                    subreddit = get_subreddit(str(link['title']))

                    print "Submitting link to %s: %s" % (subreddit, link['url'])

                    resp = reddit.submit(subreddit, str(link['title']), url=str(link['url']))

                    link_submitted = True


        except Exception, e:

            print e

            pass


手掌心
浏览 185回答 2
2回答

四季花海

我假设您正在运行 Python 3。如果是这样,这些行有两个问题:try:&nbsp; &nbsp; result = json.load(urllib.urlopen(url))except Exception, e:returnexcept Exception, e:语法仅适用于 Python 2;Python 3 的等价物是except Exception as e:你return没有缩进,except块的内容必须缩进。固定代码是:try:&nbsp; &nbsp; result = json.load(urllib.urlopen(url))except Exception as e:&nbsp; &nbsp; return要不就:try:&nbsp; &nbsp; result = json.load(urllib.urlopen(url))except Exception:&nbsp; &nbsp; returne由于您从未使用过它,因此不会费心捕获异常。同样,进一步向下,您需要更改:except Exception, e:&nbsp; &nbsp; print e到:except Exception as e:&nbsp; &nbsp; print(e)在 Python 3 上运行。您可能只想使用该2to3工具自动执行这些更改(以及我错过的任何其他 2/3 相关更改),或者只是安装 Python 2.7 以未经修改地运行此脚本(尽管 Python 2 不再支持)完全在明年年初,所以这不是一个长期的解决方案)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python