首页 > 解决方案 > Python while循环不等待用户输入

问题描述

我还在学习python,所以请记住,因为我不是专家,我正在尝试创建一个小程序,它将根据用户输入创建一个文件,

第一个菜单将包含设备的一些条码,每次条码扫描仪扫描时,设备都会自动发送一个输入,因此为什么我while True:为了允许多个输入而做了一个,一旦扫描完成,用户就会去按 CTRL+D 下一个菜单

下面的代码工作,直到它调用下一个菜单但停止(它应该要求用户输入下一个值)

def netmap_mac():
    clear()
    header_function()
    print('Start by scanning the mac address of the device: ')
    print('When finish press <CTRL+D>')
    mac = []
    while True:
        try:
            line = input()
        except EOFError:
            return netmap_ip()
        mac.append(line)
    print(mac)

def netmap_ip():
    clear()
    header_function()
    print('Enter the mangement IP for each MAC you scanned: ')
    print('When finish press <CTRL+D>')
    ip = input()
    print ('This is netmap_ip()')

我了解我的问题,while 循环仍然存在True,但我不知道如何关闭它

我相信 while 循环将是我唯一简单的选择,因为条形码扫描仪会在每个条形码的扫描完成后自动发送 Enter

我正在运行 python3

标签: python-3.x

解决方案


按照您描述的流程,这里是代码。1.你应该打破while 2.你应该在netmap_ip函数中添加一个while

def netmap_mac():
    # clear()
    # header_function()
    print('Start by scanning the mac address of the device: ')
    print('When finish press <CTRL+D>')
    mac = []
    while True:
        try:
            line = input()
            mac.append(line)
        except EOFError:
            break

    print(mac)
    netmap_ip()

def netmap_ip():
    # clear()
    # header_function()
    print('Enter the mangement IP for each MAC you scanned: ')
    print('When finish press <CTRL+D>')
    ips = []
    while True:
        try:
            line = input()
            ips.append(line)
        except EOFError:
            break

    print ('This is netmap_ip()')
    print(ips)

if __name__ == '__main__':
  netmap_mac()

更新:

输出:

Start by scanning the mac address of the device:
When finish press <CTRL+D>
mac1
mac2  # -> press Ctrl-D
['mac1', 'mac2']
Enter the mangement IP for each MAC you scanned:
When finish press <CTRL+D>
ip1
ip2  # -> press Ctrl-D
This is netmap_ip()
['ip1', 'ip2']

推荐阅读