加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python子进程proc.stderr.read()引入额外的行?

发布时间:2020-12-16 22:14:26 所属栏目:Python 来源:网络整理
导读:我想运行一些命令并抓取输出到stderr的任何内容.我有两个版本的功能来做到这一点 版本1. def Getstatusoutput(cmd): """Return (status,output) of executing cmd in a shell.""" import sys mswindows = (sys.platform == "win32") import os if not mswind

我想运行一些命令并抓取输出到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中的文本[-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,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读