subprocess中的标准错误,得不到返回值

正在学 python 的 subprocess,我想 这样测试标准输出,和标准错误但是发现用错误的 shell 命令,函数里用 return,函数外用 print 就显示不出来函数里用 print,函数外直接调用函数就可以显示出来,哪位大哥帮忙解答一下小弟的困惑

Jason990420
最佳答案

没有提供文本的代码… 还要整过一遍原代码…

def result_sts(cmd):
    results = run(cmd)
    return ''.join(results)
    """
    results is a tuple of string,
    ('',
    "'ffff' is not recognized as an internal or external command,\n"
    'operable program or batch file.\n')
    If you put `return` statement in `for` loop,
    then it just return first element, empty string,
    and almost like nothing shown.
    """
    # Wrong code,
    # for result in results:
    #    return (result.strip())
4年前 评论
star_Zz (楼主) 4年前
star_Zz (楼主) 4年前
star_Zz (楼主) 4年前
讨论数量: 2
Jason990420

没有提供文本的代码… 还要整过一遍原代码…

def result_sts(cmd):
    results = run(cmd)
    return ''.join(results)
    """
    results is a tuple of string,
    ('',
    "'ffff' is not recognized as an internal or external command,\n"
    'operable program or batch file.\n')
    If you put `return` statement in `for` loop,
    then it just return first element, empty string,
    and almost like nothing shown.
    """
    # Wrong code,
    # for result in results:
    #    return (result.strip())
4年前 评论
star_Zz (楼主) 4年前
star_Zz (楼主) 4年前
star_Zz (楼主) 4年前

补上代码

#!/usr/bin/python3
#coding=utf-8
import subprocess
import sys

cmd=sys.argv[1]
def static_output(cmd):
        p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8")
        stdout,stderr=p.communicate()
        return stdout,stderr
def run(cmd):
        stdout,stderr=static_output(cmd)
        return stdout,stderr

print("为什么这个就不显示返回的标准错误")
def result_sts(cmd):
        results=run(cmd)
        for result in results:
                return(result.strip())
print(result_sts(cmd))
print("而这个就显示返回标准错误呢,而且为什么会有个空行")
def result_sta(cmd):
        results=run(cmd)
        for result in results:
                print(result.strip())
result_sta(cmd)
4年前 评论