【问题标题】:Python subprocess module usePython子流程模块使用
【发布时间】:2012-07-10 18:32:43
【问题描述】:

如何指定python模块子进程用来执行命令的目录?我想运行一个 C 程序并在 Python 中近乎实时地处理它的输出。

我想执行命令(这将为我的 C 程序运行我的 makefile:

make run_pci

在:

/home/ecorbett/hello_world_pthread

我还想用 Python 处理 C 程序的输出。我是 Python 新手,因此将不胜感激示例代码!

谢谢, 爱德华

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    Popencallcheck_callcheck_output 使用cwd 参数。例如

    subprocess.check_output(["make", "run_pci"],
                            cwd="/home/ecorbett/hello_world_pthread")
    

    编辑:好的,现在我明白您所说的“近实时”是什么意思了。试试

    p = subprocess.Popen(["make", "run_pci"],
                         stdout=subprocess.PIPE,
                         cwd="/home/ecorbett/hello_world_pthread")
    for ln in p.stdout:
        # do processing
    

    【讨论】:

    • 谢谢!现在我将如何捕获 c 程序的输出?它只是简单地 printfs 多行文本?
    • 如果您阅读文档,您会看到 check_output 返回命令的输出。 docs.python.org/library/subprocess.html#subprocess.check_output
    • 我明白了。所以做这样的事情: process = subprocess.check_output(["make","run_pci"],cwd="/home/ecorbett/hello_world_pthread") print process.communicate() 是不必要的/不正确的?
    • 但回到我原来的问题。如果我的 C 程序将运行,处理数据并产生我需要与我的 python 程序同时处理的输出,这种方法是否仍然有效?
    • @NASAIntern: 不,那你需要使用Popen 而不是check_output。将其传递给stdout=subprocess.PIPE,然后从其stdout 成员中读取。
    【解决方案2】:

    阅读the documentation。您可以使用cwd 参数指定它,否则它使用父进程的当前目录(即运行子进程的脚本)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      相关资源
      最近更新 更多