【问题标题】:reading a os.popen(command) into a string将 os.popen(command) 读入字符串
【发布时间】:2011-01-21 07:41:40
【问题描述】:

我不确定我的标题是否正确。 我正在做的是编写一个 python 脚本来自动化我的一些代码编写。 所以我正在解析一个 .h 文件。 但我想在开始之前展开所有宏。 所以我想调用 shell 来:

gcc -E myHeader.h

应该将 myHeader.h 的后预处理版本输出到标准输出。 现在我想将所有输出直接读入一个字符串以进行进一步处理。 我读过我可以用 popen 做到这一点,但我从未使用过管道对象。

我该怎么做?

【问题讨论】:

标签: python string popen


【解决方案1】:

os.popen 函数只返回一个类似文件的对象。你可以这样使用它:

import os

process = os.popen('gcc -E myHeader.h')
preprocessed = process.read()
process.close()

正如其他人所说,您应该使用subprocess.Popen。它被设计为safer versionos.popen。 Python 文档有一个section describing how to switch over

【讨论】:

  • 我不认为将os.popen 替换为subprocess.Popen 的建议现在仍然有效。我认为这可以追溯到从 Python 2 到 Python 3 的过渡,当时 popenpopen2popen3popen4 已被弃用。截至 2021 年 12 月,the Python documentation for os.popen 声明“这是使用 subprocess.Popen 实现的;有关管理子流程和与子流程通信的更强大方法,请参阅该类的文档。”
【解决方案2】:
import subprocess

p = subprocess.popen('gcc -E myHeader.h'.split(),
                     stdout=subprocess.PIPE)
preprocessed, _ = p.communicate()

String preprocessed 现在拥有您需要的预处理源 - 并且您使用了“正确”(现代)方式来壳到子进程,而不是旧的不再那么喜欢 os.popen

【讨论】:

  • 非常好的例子。有没有办法分离 stdout 和 stderr 流?
  • 现在.split() 是发生在外壳中并使其使用不安全的事情之一。 (考虑subprocess.open(cmd.split()),以及有人将'gcc "My Program.c"' 传递给cmd 的情况...)
【解决方案3】:

你应该使用subprocess.Popen() SO上有很多例子

How to get output from subprocess.Popen()

【讨论】:

  • 请包含数据库的摘录以防止链接损坏。
【解决方案4】:

os.popen() 自 Python 2.6 起已被弃用。您现在应该使用 subprocess 模块:http://docs.python.org/2/library/subprocess.html#subprocess.Popen

import subprocess

command = "gcc -E myHeader.h"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)

#Launch the shell command:
output = process.communicate()

print output[0]

在 Popen 构造函数中,如果 shellTrue,则应将命令作为字符串而不是序列传递。否则,只需将命令拆分为一个列表:

command = ["gcc", "-E", "myHeader.h"]  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)

如果您还需要读取标准错误,进入 Popen 初始化,您可以将 stderr 设置为 subprocess.PIPEsubprocess.STDOUT em>:

import subprocess

command = "gcc -E myHeader.h"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

#Launch the shell command:
output, error = process.communicate()

【讨论】:

    【解决方案5】:

    这是另一种捕获常规输出和错误输出的方法:

    com_str = 'uname -a'
    command = subprocess.Popen([com_str], stdout=subprocess.PIPE, shell=True)
    (output, error) = command.communicate()
    print output
    
    Linux 3.11.0-20-generic  Fri May 2 21:32:55 UTC 2014 GNU/Linux
    

    com_str = 'id'
    command = subprocess.Popen([com_str], stdout=subprocess.PIPE, shell=True)
    (output, error) = command.communicate()
    print output
    
    uid=1000(myname) gid=1000(myGID) groups=1000(mygrp),0(root)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 2016-12-03
      相关资源
      最近更新 更多