【问题标题】:how can I start a new input() instance after breaking the initial input() with EOF exception?如何在使用 EOF 异常中断初始 input() 后启动新的 input() 实例?
【发布时间】:2019-07-08 19:43:33
【问题描述】:

我需要从用户那里获取多行输入 - 使用 while 循环,但是在启动另一个 input() 时遇到问题,因为 EOF 被“传递”到新的 input()

我尝试过使用 sys stdin 和 func() 的组合,但不知道为什么会这样。

while True: try: list = input() except EOFError: break input('input2:')

【问题讨论】:

    标签: python-3.x input stdin


    【解决方案1】:

    1) 不要使用list 作为变量名。这是python中的保留字。
    2)您可以捕获 KeyboardInterrupt ,这将在 Ctrl + CEOFError 捕获 Ctrl + D 之后停止循环:

    while True:
        try:
            list = input()
        except (EOFError, KeyboardInterrupt):
            break
    input('input2:')
    

    或者,您可以启动循环并让循环在设定的条件下退出:

    my_input = input()
    
    while my_input: # Break if nothing was inputted
        print(f"Inputed: {my_input}")
        my_input = input()
    
    input('input2:')
    

    【讨论】:

    • 嗨,感谢您的建议 - 看起来 KeyboardInterrupt 已被捕获,但仍会传递到 input('input2') 嗯..
    • @Vvega 你是什么意思它将被传递给input2? except 捕获KeyboardInterrupt 并将丢弃它,除非添加raise。你使用什么输入,你期望什么输出?
    • 当我执行 command+D(我在 macOS 上)时,中断也会中断输入('input2')。所以它会在让我实际输入任何内容之前关闭。
    • @Vvega for Ctrl+D 那么你是对的,EOFError 仍然有效。查看我的更新。
    • 谢谢!似乎问题出在 Pycharm 上,但编译成 exec 似乎现在可以工作了:D
    猜你喜欢
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    相关资源
    最近更新 更多