栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

管道Popen stderr和stdout

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

管道Popen stderr和stdout

授予http://docs.python.org/library/subprocess.html。

communication()返回一个元组(stdoutdata,stderrdata)。

子流程完成后,您可以从Popen实例获取返回代码:

Popen.returnpre:子返回码,由poll()和wait()设置(并由communication()间接设置)。

同样,您可以实现以下目标:

sp = subprocess.Popen([executable, arg1, arg2], stdout=subprocess.PIPE, stderr=subprocess.PIPE)out, err = sp.communicate()if out:    print "standard output of subprocess:"    print outif err:    print "standard error of subprocess:"    print errprint "returnpre of subprocess:"print sp.returnpre

顺便说一句,我会改变测试

    if script.endswith('.*~') or script == 'README':         continue

变成一个积极的:

if not filename.endswith(".sh"):    continue

明确声明要执行的内容比明确声明 执行的内容要好。

另外,您应该以更通用的方式命名变量,因此

script
应该
filename
放在首位。由于
listdir
还列出了目录,你可以明确地检查这些。
try/except
只要您不处理特定的异常,当前的块就不合适。取而代之的是
abspath
,您应该只连接
initdir
filename
,这是一个经常在上下文中应用的概念
os.listdir()
。出于安全原因,仅在绝对确定需要时才
shell=True
Popen
对象的构造函数中使用它。让我提出以下建议:

for filename in sorted(os.listdir(initdir), reverse=reverse):    if os.path.isdir(filename) or not filename.endswith(".sh"):         continue    if os.access(script, os.X_OK):        exepath = os.path.join(initdir, filename)        sp = subprocess.Popen( (exepath, 'stop' if reverse else 'start'), stderr=subprocess.PIPE, stdout=subprocess.PIPE)        out, err = sp.communicate()        print out, err, sp.returnpre


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651723.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号