代码之家  ›  专栏  ›  技术社区  ›  Fire Crow

检测tty输出端

  •  1
  • Fire Crow  · 技术社区  · 16 年前

    我现在正在用python编写它,生成第二个tty,读写都很容易

    但是当我阅读时,阅读并没有结束,它会等待更多的输入。

    import subprocess
    
    pfd = subprocess.Popen(['/bin/sh'], shell=True, 
        stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    
    cmd = "ls" 
    
    pfd.stdin.write(cmd + '\n')
    
    out = ''
    while 1: 
        c = pfd.stdout.read(1)
        if not c: # if end of output (this never happends)
            break 
        if c == '\n': # print line when found
            print repr(out)
            out = ''
        else:
            out += c
    

    -----------------------------输出------------------------

    intty $ python intty.py 
    'intty.py'
    'testA_blank'
    'testB_blank'
    (hangs here does not return)
    

    它看起来已经到达了缓冲区的末尾,它没有返回None或“”,而是挂起等待更多的输入。

    我应该寻找什么来查看输出是否已完成?缓冲区的尽头?不可打印的字符?

    ----------------编辑-------------

    2 回复  |  直到 16 年前
        1
  •  1
  •   Crast    16 年前

    /bin/sh ,shell在“ls”完成后仍在运行。没有EOF指示器,因为它仍在运行。

    /bin/ls ?

    你可以这样做

    pfd = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    
    out, err_output = pfd.communicate()
    

    subprocess.communicate ,这是从单个程序运行中获取输出(无论如何,对于适合内存的输出)的更安全的方法。仅当程序完成运行时,才会返回此消息。

    或者,您可以从shell中逐行读取,但您需要寻找一个特殊的shell序列,如 sh~# 可以很容易地显示在程序输出中的行。因此,运行shell可能是一个坏主意。


    编辑 这就是我所指的,但它仍然不是最好的解决方案,因为它有很多警告:

    while 1: 
        c = pfd.stdout.read(1)
        if not c:
            break
        elif c == '\n': # print line when found
            print repr(out)
            out = ''
        else:
            out += c
            if out.strip() == 'sh#':
                break
    

        2
  •  0
  •   Ignacio Vazquez-Abrams    16 年前

    对于像shell这样的应用程序,直到shell结束,输出才会结束。任用 select.select()

    推荐文章