Python之系统交互(subprocess)
参考: https://www.cnblogs.com/yyds/p/7288916.html
https://www.jb51.net/article/133941.htm
https://www.aliyun.com/jiaocheng/454213.html
例子: subprocess执行ansible 命令.
#subprocess 调用ansible命令,没有shell=True要写成列表格式,并且第一个元素是一个可执行的文件 child=subprocess.Popen(["ansible","all","-i","./hosts","-m","command","-a","ls /mnt/"], stdout=subprocess.PIPE,stderr=subprocess.PIPE) child.stdout.read() #带了shell=True,可以直接像在shell在执行命令一样书写要执行的命令 child=subprocess.Popen(["ansible all -i ./hosts -m command -a 'ls -alh /mnt/'"], stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
child=subprocess.Popen("ansible all -i ./hosts -m command -a 'ls -alh /mnt/'", stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
1. communicate()方法:发送data到stdin
下面的例子演示了如何在Python代码中运行命令nslookup www.python.org
,这和命令行直接运行的效果是一样的:
import subprocess print('$ nslookup www.python.org') r = subprocess.call(['nslookup', 'www.python.org']) print('Exit code:', r)
如果子进程还需要输入,则可以通过communicate()
方法输入,:
import subprocess print('$ nslookup') p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = p.communicate(b'set q=mx\npython.org\nexit\n') print(output.decode('utf-8')) print('Exit code:', p.returncode)
上面的代码相当于在命令行执行命令nslookup
,然后手动输入:
set q=mx
python.org
exit
一搭搭
二搭搭
三搭搭