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

pty 咋用?

  •  
  •   julyclyde ·
    julyclyde · 2018-11-20 14:21:53 +08:00 · 1733 次点击
    这是一个创建于 1955 天前的主题,其中的信息可能已经有所发展或是发生改变。
    为了学习 pty.fork(),尝试写了下面的程序:
    import os
    import pty
    import sys

    (pid, fd)=os.forkpty()

    if pid==0: #child
    sys.stdout.write(sys.stdin.read(1024)[::-1])
    else: #parent
    print "parent running"
    os.write(fd, "msg from parent to child")
    print os.read(fd,1024)


    结果发现,最后一行 os.read 读入的居然是刚刚 write 出去的字符串
    也就是子进程并没有读到主进程发来的字符串
    这是什么原因呢?

    改进的程序如下:
    import os
    import pty
    import sys
    import time

    (pid, fd)=os.forkpty()

    if pid==0: #child
    sys.stderr.write(sys.stdin.read(10)[::-1])
    sys.stderr.flush()
    else: #parent
    print "parent running"
    print os.read(fd,0)
    os.write(fd, "msg from parent to child\n")
    time.sleep(1)
    print os.read(fd,1024)

    主进程写过之后 sleep 一下再读;子进程读取较短的字节数,就可以成功了
    经过多次尝试,主进程写之后、读之前的 sleep 只能算“对整体结果有改善”但不是因果关系,偶尔还是会失败。所以看起来这个是操作系统调度多进程方面的问题

    但子进程如果不缩短读取长度,在我的尝试里是全部失败的,这个我就想不明白了
    2 条回复    2018-11-22 10:44:50 +08:00
    julyclyde
        1
    julyclyde  
    OP
       2018-11-20 14:23:46 +08:00
    排版乱了……还好只有一层缩紧,大家努力想象一下
    lanqing
        2
    lanqing  
       2018-11-22 10:44:50 +08:00
    @julyclyde 编辑的时候右下有个 default ,选择 makedown 就行了哦~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3169 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:29 · PVG 20:29 · LAX 05:29 · JFK 08:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.