【问题标题】:Python while loop is not waiting for user inputPython while循环不等待用户输入
【发布时间】:2019-10-27 14:21:42
【问题描述】:

我还在学习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

【问题讨论】:

  • 请描述您的程序所需的流程。你想什么时候输入。单身的时候。 netmap_ip() 应该返回什么?
  • 我的程序主要是一堆用户输入和引导用户的菜单,最后会将用户输入保存到一个文件中,netmap_ip()是我程序的下一个用户输入,用户应提供在 netmap_mac() 期间扫描的每个条形码的 IP
  • 在第一个 Ctrl-D 之后,您是否希望添加另一个用户输入的 ip 然后退出?还是几个?
  • 所以ip需要和已经扫描的MAC数量相匹配,即:如果用户扫描了10个mac地址,则需要输入10个IP,我没有足够的经验做一个验证机制,所以我现在相信用户输入。回答你的问题,我期待几个

标签: python-3.x


【解决方案1】:

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

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']

【讨论】:

  • 感谢 Lior,我已经测试了代码 - 它不允许我在 netmap_ip() 上输入任何内容它实际上停止了代码:进程以退出代码 0 完成,我之前也遇到过同样的问题
  • 很奇怪。我添加了程序的控制台输出。它似乎正在工作。这是你所期望的吗?
  • 正是我要找的东西,不知道为什么我的不一样,这是我的完整代码:pastebin.com/gWkVmVnR - 我正在使用 python 3.7
  • 它正在工作。检查:repl.it/@liorcohen/ColossalAccurateMention
  • 正确我在windows上开发脚本,但是一旦完成就会在linux服务器上执行
猜你喜欢
  • 2012-10-13
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 2016-05-03
  • 2017-02-25
  • 2021-12-08
相关资源
最近更新 更多