背景:
- linux机器上有个写好的sh脚本,这个sh可以输入参数,我要执行它。
- 用Python去执行这个sh脚本,通过组合不同的参数。来查看它的结果。
需求:
- Python如何执行本地命令?
解决方式:基于subprocess实现
-
import subprocess def local_ssh(command): p = subprocess.Popen([command], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out = p.stdout.read().decode('utf-8') err = p.stderr.read().decode('utf-8') print("标准输出:", out, "错误输出:", err) if __name__ == '__main__': local_ssh("ls")
-
参考资料:
https://blog.51cto.com/u_10941874/5331599