python input()使用疑问

2016-10-25 14:51:01 +08:00
 wisefree

请大家帮忙看看,>_<

运行环境 虚拟机 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

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

请问是不是只有加 encode 这一种方法呢?
jimzhong
2016-10-25 16:25:40 +08:00
@wisefree 对于管道文件应该只能用 encode 把 str 编码成 byte
如果是以文本格式打开的文件是可以直接 write 的
wisefree
2016-10-25 19:30:29 +08:00
@jimzhong 十分感谢,:)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/315316

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX