【问题标题】:python - how to pipe the output using popen?python - 如何使用popen管道输出?
【发布时间】:2010-12-27 07:39:09
【问题描述】:

我想使用popen 输出我的文件的pipe,我该怎么做?

test.py

while True:
  print"hello"

a.py

import os  
os.popen('python test.py')

我想使用os.popen 管道输出。 我该怎么做?

【问题讨论】:

    标签: python popen


    【解决方案1】:

    这将只打印输出的第一行:

    a.py:

    import os
    pipe = os.popen('python test.py')
    a = pipe.readline()
    print a
    

    ...这将打印所有这些

    import os
    pipe = os.popen('python test.py')
    while True:
        a = pipe.readline()
        print a
    

    (我将 test.py 更改为这个,以便更容易看到发生了什么:

    #!/usr/bin/python
    x = 0
    while True:
        x = x + 1
        print "hello",x
    

    )

    【讨论】:

      【解决方案2】:

      首先,不推荐使用 os.popen(),改用 subprocess 模块。

      你可以这样使用它:

      from subprocess import Popen, PIPE
      
      output = Popen(['command-to-run', 'some-argument'], stdout=PIPE)
      print output.stdout.read()
      

      【讨论】:

      • 示例显示了这一点。你应该使用:Popen(['python', 'test.py'], stdout=PIPE)
      • 根据子流程文档Here 和另一个答案,应该使用 proc.communicate()[0] 而不是 stdout.read() 以避免死锁
      【解决方案3】:

      使用subprocess 模块,这里是一个例子:

      from subprocess import Popen, PIPE
      
      proc = Popen(["python","test.py"], stdout=PIPE)
      output = proc.communicate()[0]
      

      【讨论】:

      猜你喜欢
      • 2018-03-11
      • 2019-07-26
      • 2023-03-24
      • 2010-12-10
      • 2013-11-09
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      相关资源
      最近更新 更多