Python 缩进不直观

Python indentation not intuitive

我正在尝试遵循 Python 缩进的正确协议,但 python 仍然会引发错误。我确信 python 有充分的理由,我的代码很糟糕,但我没有看到根本原因。

当运行错误指向最后一行

~/python $ ./hover_api_v1.0.py
  File "./hover_api_v1.0.py", line 139
    time.sleep(60.0)
    ^
IndentationError: expected an indented block

下面是我的代码。有一些headers与缩进无关。

在time命令的最后一行抛出错误。但是我没有在代码中看到我的错误。时间 cmd 是顶部 while 循环的一部分并正确缩进。

while True:
    ip_now = get_asus_wan_ip()
    if (ip_now == ip_last):
        day = datetime.datetime.now().day
        if day != last_day:
            last_day = day
            with open(logfile, "a") as lf:
                lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " WAN IP still the same " + str(ip_last) +"\n")

    else:
        # We need to do something
        #print('WAN IP changed from ' + str(ip_last) + " to " + str(ip_now))
        with open(logfile, "a") as lf:
            lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " WAN IP changed from " + str(ip_last) + " to " + str(ip_now) + "\n")
        ip_last= ip_now

        # connect to API
        client = HoverAPI('XXXXXXX','YYYYYYY')
        for dnsname in ['*.zzzzz.zzz', '@.zzzzz.zzz']:
            #print('Testing: ' + dnsname)
            dns_name, domain_name = dnsname.split('.', 1)

            # get all DNS records
            result = client.call("get", "dns")
            assert result['succeeded'], result

            # discover existing dns record, if any
            dns_record = None
            domain_record = None
            for dns_domain in result['domains']:
                if dns_domain['domain_name'] == domain_name:
                    domain_record = dns_domain
                    for dns_entry in dns_domain['entries']:
                        if dns_entry['name'] == dns_name:
                            dns_record = dns_entry
                            break
                if dns_record is not None and domain_record is not None:
                    break

            if dns_record is not None and domain_record is not None:
                #print('Hover-IP for ' + dnsname + ' = ' + str(dns_entry['content'].encode('ascii','ignore')))
                #print('Current IP= ' + str(ip_now))
                if str(dns_entry['content']) == str(ip_now):
                    #print('Hover-IP for ' + dnsname + ' = ' + str(dns_entry['content'].encode('ascii','ignore')) + ' same as Current IP = ' + str(ip_now) + '. No action.')
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Hover-IP for " + dnsname + " = " + str(dns_entry['content'].encode('ascii','ignore')) + " same as Current IP = " + str(ip_now) + ". No action." + "\n")
                else:
                    #print(" Deleting entry for {0}.{1} ... ".format(dns_name, domain_name), end="")
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Deleting entry for " + dnsname + "\n")
                    result = client.call("delete", "dns/{0}".format(dns_record['id']))
                    assert result['succeeded'], result
                    #print("OK")
                    ## create a new A record:
                    #print("Creating A record {0}.{1} => {2} ... ".format(dns_name, domain_name, ip_now), end="")
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Creating A record " + dnsname + " => " + ip_now + "\n")
                    record = {"name": dns_name, "type": "A", "content": ip_now}
                    post_id = "domains/{0}/dns".format(domain_record['id'])
                    #print("post", post_id, record)
                    result = client.call("post", post_id, record)
                    assert result['succeeded'], result
                    #print("OK")
            else:
                #print("No record exists for {0}".format(dnsname))

    # Sleep at end of loop.
    time.sleep(60.0)

非常感谢您提供反馈。 格特

问题就在这里;

else:
    #print("No record exists for {0}".format(dnsname))

就缩进而言,注释不算作代码。 所以你需要在那个地方有真正的代码。

解决这个问题的方法是 python 的 pass 关键字。

else:
    #print("No record exists for {0}".format(dnsname))
    pass

这向 python 表明您有意将缩进级别所需的代码留空。

或者,简单地取消注释你那里的代码也可以解决这个问题,当然假设你真的想在那里打印。

最后的 else 块需要一个有效的语句。使用 pass.

Python 正在寻找 time.sleep(60.0) 语句上方 else 子句之后的语句(在您评论的 "No record exists" print() 调用上方);当 Python 没有看到具有正确缩进的行被归类在 else 子句下时,它会抛出一个错误。

我倾向于做的(这可能不是最好的方法)绕过这个问题是参考 None 或使用 pass 并可选择添加评论来绕过这个问题。 else 子句附近的代码看起来类似于:

# ...
        else:
            # TODO
            # print("No record exists for {0}".format(dnsname))
            pass

    # Sleep at end of loop.
    time.sleep(60.0)

希望对您有所帮助!