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
wisefree
V2EX  ›  Python

python input()使用疑问

  •  
  •   wisefree · 2016-10-25 14:51:01 +08:00 · 1515 次点击
    这是一个创建于 2741 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请大家帮忙看看,>_<

    运行环境 虚拟机 ubuntu12.04 python3.5.1

    用 input() python3 运行失败 用 raw_input(), python2 运行成功

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    import os
    import time
    
    p = os.pipe()
    childpid = os.fork()
    
    if (childpid==0):
        os.close(p[1])
        while True:
            time.sleep(3)
            print('reading')
            msg = os.read(p[0],1024)
            print(msg)
            if msg == '':
                print('can not read anything')
                break
            if (msg == 'q'):
                os.close(p[0])#关闭管道
                break
    else:
        os.close(p[0])
        while True:
            
            #python3.5 中运行出错
            str1 = input()
    		#python2.7 中运行正确
            #str1 = raw_input('input anything:')
            os.write(p[1],str1)
            if(str1 == 'q'):
                os.close(p[1])#关闭管道
                os.wait()
                break
    
    

    出错信息如图:

    http://a3.topitme.com/b/09/bb/11773765731b5bb09bl.jpg

    4 条回复    2016-10-25 19:30:29 +08:00
    jimzhong
        1
    jimzhong  
       2016-10-25 15:00:38 +08:00
    python3 里面 input 返回的是 str,要 encode 之后才可以 os.write
    wisefree
        2
    wisefree  
    OP
       2016-10-25 15:06:49 +08:00
    @jimzhong 谢啦,一直将 python2 中的 raw_input 和 python3 中的 input 等效来用,>_<
    昨天 ubuntu python3.2 ,加上 encode 依然报错,今天安装了 python3.5.1 ,就没有尝试加 encode 了

    请问是不是只有加 encode 这一种方法呢?
    jimzhong
        3
    jimzhong  
       2016-10-25 16:25:40 +08:00   ❤️ 1
    @wisefree 对于管道文件应该只能用 encode 把 str 编码成 byte
    如果是以文本格式打开的文件是可以直接 write 的
    wisefree
        4
    wisefree  
    OP
       2016-10-25 19:30:29 +08:00
    @jimzhong 十分感谢,:)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1821 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:19 · PVG 00:19 · LAX 09:19 · JFK 12:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.