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

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

你可能感兴趣的:(在python中执行shell命令,并以字符串形式返回命令执行结果)