V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
mushuiyu
V2EX  ›  Python

求老哥们解决一下 Python 的输入问题

  •  
  •   mushuiyu · 2019-09-05 10:47:58 +08:00 · 1884 次点击
    这是一个创建于 1687 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如题,以前做多行输入的时候一直用的 while true 循环,通过 try 和 except 的报错机制控制连续的多行输入,也没什么问题,但是昨天用编译器的时候发现,不能跳出输入循环了……用 sys.stdin 的输入也不行,很纠结不知道是怎么回事,贴一个我的测试代码:
    import collections

    dict_sum = collections.OrderedDict()

    while True:
    try:
    key = input().split('\\')[-1]
    if key in dict_sum:
    dict_sum[key] += 1
    else:
    dict_sum[key] = 1
    except :
    break

    list1 = sorted(dict_sum.items(),key = lambda x:x[1],reverse = True)
    print(list1)
    n = 8
    for item in list1:
    if n>0:

    print(item[0].split()[0][-16:],item[0].split()[1],item[1])

    n += -1
    执行输入以后疯狂摁回车也不能跳出 while 循环,现在真的有点烦躁,不知道怎么回事,这个代码我以前用一模一样的运行是没问题的……
    5 条回复    2019-09-06 11:22:55 +08:00
    arrow8899
        1
    arrow8899  
       2019-09-05 13:45:06 +08:00
    if key == 'exit':
    break
    Vegetable
        2
    Vegetable  
       2019-09-05 14:36:07 +08:00
    你这哪有退出 while 的判断啊?根本没有退出条件,str.split("sth")返回的列表是永远不为空的,你那个 try 除了 ctrl+c 就不会捕捉到错误.
    mushuiyu
        3
    mushuiyu  
    OP
       2019-09-05 14:48:28 +08:00
    @Vegetable 就是在 try 下面就有一条 input ()的赋值语句啊,如果输入为空的话,就会报错然后跳到 except 那里去
    676529483
        4
    676529483  
       2019-09-05 15:08:37 +08:00
    是不是 py 版本的问题? py2 的 input 会报 EOF,py3 会返回空字符串,所以就退出不了了
    Vegetable
        5
    Vegetable  
       2019-09-06 11:22:55 +08:00
    @mushuiyu input()会得到一个空字符串
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3724 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 04:37 · PVG 12:37 · LAX 21:37 · JFK 00:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.