python 获取 shell 命令行执行结果

# -*- coding: utf-8 -*-
import subprocess as sp

# windows
windows = "gbk"

# linux
linux = "utf-8"

def exec(cmd: str, agent: str) -> None:
    p = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, shell=True)
    out, err = p.communicate()
    if p.returncode:
        print("code: {}, response:{} ".format(p.returncode, out.decode(agent)))


if __name__ == '__main__':
    exec("ls -l", windows)
posted @ 2021-08-23 15:16  tt_贝塔  阅读(354)  评论(0)    收藏  举报