Python,为什么不能覆盖 Popen.stdout
为什么可以用我自己的类覆盖 sys.stdout 而不是 subprocess.Popen.stdout。 如果可以覆盖,请告诉我如何...
我正在开发一些 GUI 项目,并且我想以“实时”方式在 text_view 上打印其他程序的输出,而不是在一切完成后打印。
当我覆盖 sys.stdout 时,我会做这样的事情:
class MyStdOut :
def __init__(self) : self.text = ""
def write(self, string) : self.text += string
这是一些程序“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()
,这是主程序:
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()
仍然不是“实时”,当它结束时我得到了一切。
我也尝试过沟通,但得到相同的结果。
在我的真实程序中,我必须在 text_view (GUI GTK+) 上打印其他程序的输出。我怀疑 subprocess.stdout 必须是文件,但是当我尝试创建一些继承自 IOBase 的类时,我也遇到了错误。
大家都说可以,但我还是尝试了很多方法都没有成功。
Why is possibile to override sys.stdout but not subprocess.Popen.stdout, with my own class.
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.
when i am overriding sys.stdout i do somthing like this :
class MyStdOut :
def __init__(self) : self.text = ""
def write(self, string) : self.text += string
here is some program '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+). I suspect that subprocess.stdout must be file, but when i tried to make some class that inherits from IOBase i got errors too.
Everybody say that it is possible, but still I tried many different ways with no success.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过使用以下方法实现相同的目的:
其中
p.stdout
的行为类似于 PIPE,因此您可以在数据到达时立即从中读取数据。它不是严格的实时,因为一些缓冲起作用,但这仍然是一个可行的替代方案。You can achieve the same by using:
where
p.stdout
behaves like PIPE, so you can read data from it as soon as it arrives. It is not strict realtime, because some buffering comes in play, but still this is a viable alternative.