连接到子进程stdin到管道

时间:2011-06-07 18:27:00

标签: python subprocess pipe stdin

我有一个创建子进程并将STDIN连接到匿名管道的方法;这是行不通的。它没有引发任何异常,子进程似乎永远不会读取数据。 (子流程是'zenity'可执行文件,用于在GUI中显示进度条)

class Screen(object):
    def __init__(self, display = ":0", bin = '/usr/bin/zenity'):
        self.bin = bin
        os.environ['DISPLAY'] = display
        self.dis = display

    def displayProgress(self, text, pulse = True, title = 'Progess'):
    '''Method to represent the 'zenity --progress' command
    '''
        readp, writep = os.pipe()
        reade, writee = os.pipe()

        rfd = os.fdopen(readp, 'r')
        wfd = os.fdopen(writep, 'w')


        if pulse:
            zenhandle = Popen([self.bin, '--progress',
                                         '--title=%s' % title,
                                         '--auto-close',
                                         '--pulsate'],
                              stdin = rfd)
        else:
            zenhandle = Popen([self.bin, '--progress',
                                         '--title=%s' % title,
                                         '--auto-close'],
                              stdin = rfd)

        self.progress = wfd

这个想法是调用该方法将是非阻塞的,我可以write()Screen.progress并且必须写入子(zenity)进程的STDIN。 (zenity绘制完成条形图,从STDIN读取值)

框会在屏幕上绘制,但Screen.progress.write('50')永远不会更新栏。

我做错了什么?

修改

如果以交互方式运行,只要退出python shell,该栏就会开始移动。 (pulsing)这意味着只有在python进程退出后它才会读取内容。

2 个答案:

答案 0 :(得分:1)

您可能需要刷新文件缓冲区。每次写作后尝试self.progress.flush()

答案 1 :(得分:1)

os.fdopen()的缓冲区大小应为0.使用rfd = os.fdopen(readp, 'r', 0)

相关问题