Python If语句语法无效但缩进是正确的

时间:2015-12-07 20:34:42

标签: python python-2.7 python-3.x

我正在尝试使用此script来设置秘密圣诞老人。我修改了几行,所以它符合python 3,但是当我运行它(在python2和python3下)时,我得到一个语法错误。

以下是我的一些代码:

def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "shc", ["send", "help"])
        except getopt.error:
            raise Usage(msg)

        # option processing
        send = False
        for option, value in opts:
            if option in ("-s", "--send"):
                send = True
            if option in ("-h", "--help"):
                raise Usage(help_message)

        config = parse_yaml()
        for key in REQRD:
            if key not in config.keys():
                raise Exception(
                    'Required parameter %s not in yaml config file!' % (key,))

        participants = config['PARTICIPANTS']
        dont_pair = config['DONT-PAIR']
        if len(participants) < 2:
            raise Exception('Not enough participants specified.')

        givers = []
        for person in participants:
            name, email = re.match(r'([^<]*)<([^>]*)>', person).groups()
            name = name.strip()
            invalid_matches = []
            for pair in dont_pair:
                names = [n.strip() for n in pair.split(',')]
                if name in names:
                    # is part of this pair
                    for member in names:
                        if name != member:
                            invalid_matches.append(member)
            person = Person(name, email, invalid_matches)
            givers.append(person)

        recievers = givers[:]
        pairs = create_pairs(givers, recievers)
        if not send:
            print("""
Test pairings:

%s

To send out emails with new pairings,
call with the --send argument:
    $ python secret_santa.py --send

            """ % ("\n".join([str(p) for p in pairs]))

        if send:
            server = smtplib.SMTP(config['SMTP_SERVER'], config['SMTP_PORT'])
            server.starttls()
            server.login(config['USERNAME'], config['PASSWORD'])
        for pair in pairs:
            zone = pytz.timezone(config['TIMEZONE'])
            now = zone.localize(datetime.datetime.now())
            date = now.strftime('%a, %d %b %Y %T %Z') # Sun, 21 Dec 2008 06:25:23 +0000
            message_id = '<%s@%s>' % (str(time.time())+str(random.random()), socket.gethostname())
            frm = config['FROM']
            to = pair.giver.email
            subject = config['SUBJECT'].format(santa=pair.giver.name, santee=pair.reciever.name)
            body = (HEADER+config['MESSAGE']).format(
                date=date, 
                message_id=message_id, 
                frm=frm, 
                to=to, 
                subject=subject,
                santa=pair.giver.name,
                santee=pair.reciever.name,
            )
            if send:
                result = server.sendmail(frm, [to], body)
                print "Emailed %s <%s>" % (pair.giver.name, to)

        if send:
            server.quit()

    except Usage, err:
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >> sys.stderr, "\t for help use --help"
        return 2


if __name__ == "__main__":
    sys.exit(main())

错误出现在第153行(以if send开头并且紧跟在那个大块打印语句之后的行)并且它表示

  File "secretSanta.py", line 153
    if send:
           ^
SyntaxError: invalid syntax

但是我有理由相信错误是由它上方的print语句引起的,因为当我在print语句下面注释掉每个部分时,错误会转移到下一行代码。

编辑:我收到堆栈溢出导致中止陷阱6.它跟踪到这段代码:

def create_pairs(g, r):
    givers = g[:]
    recievers = r[:]
    pairs = []
    for giver in givers:
        try:
            reciever = choose_reciever(giver, recievers)
            recievers.remove(reciever)
            pairs.append(Pair(giver, reciever))
        except:
            return create_pairs(g, r)
    return pairs

具体是`return create_pairs(g,r)行。我不确定为什么脚本使用这一行是诚实的。

1 个答案:

答案 0 :(得分:1)

问题出在第153行之前的行(错误消息中显示的行)。通常语法错误实际上是由错误消息中显示的另一行引起的。您在第152行缺少右括号。