【问题标题】:Python get stdout as a listPython将标准输出作为列表
【发布时间】:2015-06-04 13:19:15
【问题描述】:

这是我的代码:

rows = subprocess.check_output("ls -1t | grep 'syslogdmz'", shell=True)

我得到的结果是 2 个文件名,但我不明白为什么它没有将它们放在列表中。有什么办法吗?

谢谢

【问题讨论】:

  • 您可以使用rows.splitlines() 来获取字节字符串列表,而不是一个包含一些\n 的字符串。

标签: python linux operating-system


【解决方案1】:

您可能想使用os.popen

from os import popen
rows = popen("ls -1t | grep 'syslogdmz'","r").readlines()

rows 将结果包含在一个列表中。

【讨论】:

  • 这似乎有效,你不知道如何避免使用 \n 而不必为每一行重新剥离它。谢谢
【解决方案2】:

来自文档https://docs.python.org/2/library/subprocess.html#subprocess.check_output

“使用参数运行命令并将其输出作为字节字符串返回。”

不知道你为什么希望得到一份清单。

【讨论】:

    【解决方案3】:

    请参阅手册页。

    >>> import subprocess
    >>> help(subprocess.check_output)
    Help on function check_output in module subprocess:
    
    check_output(*popenargs, **kwargs)
        Run command with arguments and return its output as a byte string.
    
        If the exit code was non-zero it raises a CalledProcessError.  The
        CalledProcessError object will have the return code in the returncode
        attribute and output in the output attribute.
    
        The arguments are the same as for the Popen constructor.  Example:
    
        >>> check_output(["ls", "-l", "/dev/null"])
        'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
    
        The stdout argument is not allowed as it is used internally.
        To capture standard error in the result, use stderr=STDOUT.
    
        >>> check_output(["/bin/sh", "-c",
        ...               "ls -l non_existent_file ; exit 0"],
        ...              stderr=STDOUT)
        'ls: non_existent_file: No such file or directory\n'
    
    >>>
    

    尝试使用os.popen 来获取列表中的输出。 或者交替使用 split() 进入列表。

    x = os.popen('ls -1t | grep syslogdmz').readlines()
    print x
    

    【讨论】:

      猜你喜欢
      • 2013-05-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 2011-12-04
      • 2011-09-04
      • 2021-12-13
      相关资源
      最近更新 更多