推荐学习书目
› 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 · Nov 20, 2018 · 2852 views
    This topic created in 2878 days ago, the information mentioned may be changed or developed.
    为了学习 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 replies  •  2018-11-22 10:44:50 +08:00
    julyclyde
        1
    julyclyde  
    OP
       Nov 20, 2018
    排版乱了……还好只有一层缩紧,大家努力想象一下
    lanqing
        2
    lanqing  
       Nov 22, 2018
    @julyclyde 编辑的时候右下有个 default ,选择 makedown 就行了哦~
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   741 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 21:22 · PVG 05:22 · LAX 14:22 · JFK 17:22
    ♥ Do have faith in what you're doing.