现在的位置: 首页 > 综合 > 正文

在python中执行shell命令,并以字符串形式返回命令执行结果

2017年08月26日 ⁄ 综合 ⁄ 共 360字 ⁄ 字号 评论关闭
def run_cmd(cmd):
    try:
        import subprocess
    except ImportError:
        _, result_f, error_f = os.popen3(cmd)
    else:
        process = subprocess.Popen(cmd, shell = True,
        stdout = subprocess.PIPE, stderr = subprocess.PIPE)
        result_f, error_f = process.stdout, process.stderr

    errors = error_f.read()
    if errors:  pass
    result_str = result_f.read().strip()
    if result_f :   result_f.close()
    if error_f  :    error_f.close()

    return result_str

【上篇】
【下篇】

抱歉!评论已关闭.