python subprocess proc.stderr.read() 引入额外的行?

标签 python subprocess

我想运行一些命令并获取输出到 stderr 的任何内容。我有两个版本的功能可以做到这一点 版本 1。

def Getstatusoutput(cmd):
    """Return (status, output) of executing cmd in a shell."""

    import sys
    mswindows = (sys.platform == "win32")

    import os
    if not mswindows:
        cmd = '{ ' + cmd + '; }'

    pipe = os.popen(cmd + ' 2>&1', 'r')
    text = pipe.read()
    sts = pipe.close()
    if sts is None: sts = 0
    if text[-1:] == '\n': text = text[:-1]
    return sts, text  

和 版本 2

def Getstatusoutput2(cmd):
    proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    return_code = proc.wait()
    return return_code, proc.stdout.read(), proc.stderr.read()

第一个版本如我所料打印 stderr 输出。第二个版本在每一行之后打印一个空行。我怀疑这是由于版本 1 中的 text[-1:] 行造成的......但我似乎无法在第二个版本中做类似的事情。任何人都可以解释我需要做什么才能使第二个函数生成与第一个函数相同的输出而中间(和最后)没有额外的行吗?

更新:这是我打印输出的方式 这是我打印的方式

      status, output, error = Getstatusoutput2(cmd)
      s, oldOutput = Getstatusoutput(cmd)
      print "oldOutput = <<%s>>" % (oldOutput)
      print "error = <<%s>>" % (error)

最佳答案

你可以添加.strip():

def Getstatusoutput2(cmd):
    proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    return_code = proc.wait()
    return return_code, proc.stdout.read().strip(), proc.stderr.read().strip()

Python string Docs :

string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

string.whitespace

A string containing all characters that are considered whitespace. On most systems this includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

关于python subprocess proc.stderr.read() 引入额外的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7985334/

相关文章:

python - 如何使用 Python 连接来自不同元组但位于同一索引中的两个字符串?

communication - 与子进程多次通信

python - PyQt4 python 中的 "RuntimeError: maximum recursion depth exceeded while calling a Python object"错误

python - pychef中的ssl证书验证

python - Matplotlib 在所有 Jupyter 笔记本中显示空白数字(无错误)

python - Popen subprocess.PIPE 及其用途

java - 为什么 Java Processbuilder 运行命令比 Python Subprocess.check_output 慢 4000 倍

python - (Python) 阻塞子进程

python - 无法在python中通过名称获取进程的PID

python - 从 Sanic 应用程序的蓝图中检索配置