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

发布于 2024-10-27 05:15:07 字数 990 浏览 2 评论 0原文

为什么可以用我自己的类覆盖 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云醉月微眠 2024-11-03 05:15:07

您可以通过使用以下方法实现相同的目的:

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

其中 p.stdout 的行为类似于 PIPE,因此您可以在数据到达时立即从中读取数据。它不是严格的实时,因为一些缓冲起作用,但这仍然是一个可行的替代方案。

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. It is not strict realtime, because some buffering comes in play, but still this is a viable alternative.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文