Python execute external commands, such as the shell

Convenience functions subprocess module

call()

subprocess.call(args,stdin=None,stdout=None,stderr=None,shell=False)
"""
call函数 将运行由args参数指定的命令,知道命令结束
返回0 执行成功
非0   失败
"""
subprocess.call("cmd",shell=True)
"""
cmd 是想要在shell输入的命令
先启动shell,再执行cmd
"""

check_call()

subprocess.check_call(["ls","-l"])
"""
与call()区别在于
都是返回0成功,
但check_call()失败会 抛出异常
"""

check_output()

output = check_output(["ls","-l"])
print(output)

"""
可以获取 cmd 终端输出的值
异常也会被抛出,
如果想获取异常,将错误输出重定向到标准输出
output = check_output(["ls","-l"],stderr=subprocess.STDOUT)
"""
subprocess模块的Popen类,上面的便利函数都是对Popen类的封装。
当便利函数无法满足我们的时候,可以使用更为底层的Popen
https://docs.python.org/zh-cn/3/library/subprocess.html#popen-objects
https://www.cnblogs.com/zhoug2020/p/5079407.html

Guess you like

Origin blog.csdn.net/sunt2018/article/details/90639798