Python If语句语法无效但缩进

2024-09-25 08:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用这个script来设置秘密圣诞老人。我修改了几行代码,使之符合python3,但是当我运行它(在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开头的行,就在大块print语句之后),它说

^{pr2}$

但是我有理由相信错误是由它上面的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)行。我不知道为什么剧本要用这句话来诚实。在


Tags: nameinsendconfigforifsyshelp
1条回答
网友
1楼 · 发布于 2024-09-25 08:28:05

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

相关问题 更多 >