简体   繁体   English

Python,为什么我不能覆盖Popen.stdout

[英]Python, why can't i override Popen.stdout

Why is possibile to override sys.stdout but not subprocess.Popen.stdout, with my own class. 为什么可能使用我自己的类覆盖sys.stdout但不覆盖subprocess.Popen.stdout。 If it is possibile to override please show me how ... 如果有可能覆盖请告诉我如何...

I'm working on some GUI project, and i want to print output of some other program on text_view in "real_time", not when everything is done. 我正在研究一些GUI项目,我想在“real_time”中打印text_view上的其他程序的输出,而不是在一切都完成时。

when i am overriding sys.stdout i do somthing like this : 当我覆盖sys.stdout时,我会做这样的事情:

class MyStdOut :
  def __init__(self) : self.text = ""
  def write(self, string) : self.text += string

here is some program 'pyscript.py' 这是一些程序'pyscript.py'

import os

def main() :
  for i in range(10) :
    print i
    os.system('sleep 0.1') ## this is just to make some delay, i did also 3 loops

if __name__ == '__main__' : main()

and here is main program : 这是主程序:

import subprocess as sub

def main() :
  popen = sub.Popen('./pyscript.py', stdout=sub.PIPE)
  for line in popen.stdout : print 'Line :', line
  print 'Main done'

if __name__ == '__main__' : main()

Still it is not 'real time', i get everything when it ends. 仍然不是'实时',我在结束时得到一切。

I also tried communicate, but get same result. 我也尝试过沟通,但得到的结果相同。

In my real program i have to print output of other program on text_view (GUI GTK+). 在我的真实程序中,我必须在text_view(GUI GTK +)上打印其他程序的输出。 I suspect that subprocess.stdout must be file, but when i tried to make some class that inherits from IOBase i got errors too. 我怀疑subprocess.stdout必须是文件,但是当我试图创建一个继承自IOBase的类时,我也遇到了错误。

Everybody say that it is possible, but still I tried many different ways with no success. 每个人都说这是可能的,但我仍然尝试了许多不同的方法而没有成功。

You can achieve the same by using: 您可以通过以下方式实现相同目的:

p = Popen(args, ..., stdout=subprocess.PIPE)
for line in p.stdout:
   print line

where p.stdout behaves like PIPE, so you can read data from it as soon as it arrives. 其中p.stdout行为类似于PIPE,因此您可以在它到达时立即从中读取数据。 It is not strict realtime, because some buffering comes in play, but still this is a viable alternative. 它不是严格的实时,因为一些缓冲起作用,但这仍然是一个可行的替代方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM