Python 在带有for循环的函数中正确定位if语句

Python 在带有for循环的函数中正确定位if语句,python,function,for-loop,if-statement,Python,Function,For Loop,If Statement,我正在尝试执行以下代码,在文本文件中搜索mac地址,如果找到,它会询问用户是否希望根据找到的IP和密码调用API来检索设备信息。此外,它还为用户提供了启动新搜索或退出的选项 如果搜索匹配,则此部分可以完美工作。搜索不匹配时出现的问题! 它在第一次试用中正确执行“未找到匹配项!”,然后再次检查该函数,但如果用户重新输入的mac地址不再匹配,则代码不会再次重新执行并结束程序 下面是代码 import http.client from base64 import b64encode import ss

我正在尝试执行以下代码,在文本文件中搜索mac地址,如果找到,它会询问用户是否希望根据找到的IP和密码调用API来检索设备信息。此外,它还为用户提供了启动新搜索或退出的选项

如果搜索匹配,则此部分可以完美工作。搜索不匹配时出现的问题! 它在第一次试用中正确执行“未找到匹配项!”,然后再次检查该函数,但如果用户重新输入的mac地址不再匹配,则代码不会再次重新执行并结束程序

下面是代码

import http.client
from base64 import b64encode
import ssl
import json


def search_mac():
    with open(r"C:\Users\afahmy\Desktop\final.txt", "r") as output_file:
        search = input("Enter mac-address: ")
        search = search.lower().replace(':', '')
        for line in output_file:
            ip = line.split(',')[0]
            # print(ip)
            password = line.split(',')[1]
            # print(password)
            mac = line.split(',')[2].rstrip()
            # print(mac)
            if search == mac:
                print(format("IP:" + ip + "\n" + "password:" + password))
                if input("Do you want to retrieve device information?[y/n]") == 'y':
                    ssl._create_default_https_context = ssl._create_unverified_context
                    auth_string = "Polycom:"
                    admin_password = auth_string + password
                    conn = http.client.HTTPSConnection(ip)
                    userandpass = b64encode(admin_password.encode('UTF-8')).decode('ascii')
                    headers = {'Authorization': 'Basic %s' % userandpass}
                    conn.request("GET", "/api/v1/mgmt/device/info", headers=headers)
                    res = conn.getresponse()
                    data = res.read()
                    json_format = json.loads(data)
                    dictionary = json_format["data"]
                    dictionary_new = {k: dictionary[k] for k in dictionary.keys() - {'IPV6Address', 'DeviceType', 'DeviceVendor', 'AttachedHardware'}}
                    for item in dictionary_new.items():
                        print(item)
                if input("Do you want to make another search?[y/n]:") == 'y':
                    search_mac()
                else:
                    print("Thank you!")
                    exit()


search_mac()
print("No Match!")
if input("Do you really want to make another search?[y/n]:") == 'y':
    search_mac()
else:
    print("Thank you for your time!")
这是我第一次输入不正确的mac地址(工作正常)和第二次输入不正确的mac地址(问题出在这里)时的输出


输入mac地址:64167f185bf30000代码工作正常

你在等一场没有对手的比赛,是吗?。您需要在
def search\u mac()内移动
print(“不匹配!”)

代码在de函数外部打印第一个“不匹配”,但从de函数内部看,没有“不匹配”。这是开发人员的一个逻辑错误,但代码正在完成他的工作

这里是完成您工作的快速实现。但此代码非常基本,可能存在逻辑错误,并且可以通过以下方式改进:

  • 处理重复的Mac
  • 而退出捕捉信号的真实循环
  • 只读取一次文件
  • 内存泄漏,你可以打开百万次的bilion
    search\u mac()
    ,而无需关闭密码

非常感谢@gilito!!代码的正确率为95%,除了打印不匹配!在新的提示之后

输出:

Enter mac-address: 64167f185bf3
IP:10.10.10.5
password:Password!
Do you want to retrieve device information?[y/n]n
No Match!    <<<<<<<<<<< unwanted line
Do you want to make another search?[y/n]:

感谢您的详细回复,实际上是我写的代码,但我仍然是python的初学者。当我运行代码时,如果我输入了正确的mac地址(不匹配!),则会进行修改,直到捕获匹配后代码中断。如果我输入了一个错误的mac,它会打印(不匹配!)和文本的行数一样多。在提示下一个问题之前。我不想要这种行为,若有匹配,我只想要打印出来的(IP,密码)。哦,你们是真的。。。好的,我将编辑响应。。。现在试试@吉利托谢谢你,伙计,这帮了大忙!我做了一点修改,现在所有的测试都成功通过了!再次感谢。
def search_mac():
    with open(r"C:\Users\afahmy\Desktop\final.txt", "r") as output_file:
        found = False
        search = input("Enter mac-address: ")
        search = search.lower().replace(':', '')
        for line in output_file:
            ip = line.split(',')[0]
            # print(ip)
            password = line.split(',')[1]
            # print(password)
            mac = line.split(',')[2].rstrip()
            # print(mac)
            if search == mac:
                print(format("IP:" + ip + "\n" + "password:" + password))
                if input("Do you want to retrieve device information?[y/n]") == 'y':
                    ssl._create_default_https_context = ssl._create_unverified_context
                    auth_string = "Polycom:"
                    admin_password = auth_string + password
                    conn = http.client.HTTPSConnection(ip)
                    userandpass = b64encode(admin_password.encode('UTF-8')).decode('ascii')
                    headers = {'Authorization': 'Basic %s' % userandpass}
                    conn.request("GET", "/api/v1/mgmt/device/info", headers=headers)
                    res = conn.getresponse()
                    data = res.read()
                    json_format = json.loads(data)
                    dictionary = json_format["data"]
                    dictionary_new = {k: dictionary[k] for k in dictionary.keys() - {'IPV6Address', 'DeviceType', 'DeviceVendor', 'AttachedHardware'}}
                    found = True
                    for item in dictionary_new.items():
                        print(item)
                    break
        if not found:
            print("No Match!")
        if input("Do you want to make another search?[y/n]:") == 'y':
            search_mac()
        else:
            print("Thank you for your time!")
            exit(0)

search_mac()```

Enter mac-address: 64167f185bf3
IP:10.10.10.5
password:Password!
Do you want to retrieve device information?[y/n]n
No Match!    <<<<<<<<<<< unwanted line
Do you want to make another search?[y/n]:
def search_mac():
    with open(r"C:\Users\afahmy\Desktop\final.txt", "r") as output_file:
        found = False
        search = input("Enter mac-address: ")
        search = search.lower().replace(':', '')
        for line in output_file:
            ip = line.split(',')[0]
            # print(ip)
            password = line.split(',')[1]
            # print(password)
            mac = line.split(',')[2].rstrip()
            # print(mac)
            if search == mac:
                print(format("IP:" + ip + "\n" + "password:" + password))
                entry = input("Do you want to retrieve device information?[y/n]")
                while entry == 'y':
                    ssl._create_default_https_context = ssl._create_unverified_context
                    auth_string = "Polycom:"
                    admin_password = auth_string + password
                    conn = http.client.HTTPSConnection(ip)
                    userandpass = b64encode(admin_password.encode('UTF-8')).decode('ascii')
                    headers = {'Authorization': 'Basic %s' % userandpass}
                    conn.request("GET", "/api/v1/mgmt/device/info", headers=headers)
                    res = conn.getresponse()
                    data = res.read()
                    json_format = json.loads(data)
                    dictionary = json_format["data"]
                    dictionary_new = {k: dictionary[k] for k in dictionary.keys() - {'IPV6Address', 'DeviceType', 'DeviceVendor', 'AttachedHardware'}}
                    found = True
                    for item in dictionary_new.items():
                        print(item)
                    break
                else:
                    if input("Do you want to make another search?[y/n]:") == 'y':
                        search_mac()
                    else:
                        print("Thank you for your time!")
                        exit(0)
        if not found:
            print("No Match!")
        if input("Do you want to make another search?[y/n]:") == 'y':
            search_mac()
        else:
            print("Thank you for your time!")
            exit(0)


search_mac()