subprocess |
subprocess模块介绍
subprocess模块是一个可以将系统内的命令结果赋值给变量并打印, 还可以输出命令执行状态,subprocess可以单独将
命令输出结果与执行状态,以及报错信息等。
模块使用
>>subprocess.run("df -h |grep sda1",shell=True)
注:输出命令内容,可用单个字符串,涉及到管道符可使用shell=True。
注:shell=True表示不需要python解析命令,让linux自己去解析。
屏幕输出类别
stdout(标准输出)
stdin(标准输入)
stdeerr(把错误单独分开)
注:如果需要存如错误打印,可以使用“stder=subprocess.PIPE”
常用subprocess方法
#执行命令,返回命令执行状态,0 or 非0
>>>retcode = subprocess.call("ls","-l")
0
#执行命令,如果命令结果为0,就正常返回,否则抛异常。
>>>subprocess.check_call(["ls","-l"])
0
#接受字符串格式命令,返回元组形式,第一个元素执行状态,第二个是命令结果。
>>>subprocess.getstatusoutput('ls /bin/ls')
(0,'/bin/ls')
#接收字符串格式命令,并返回结果
>>>subprocess.getoutput('ls /bin/ls')
'/bin/ls'
#执行命令,并返回结果,注意是返回结果,不是打印,下列结果返回给res。
>>>res=subprocess.check_output(['ls','-l'])
>>>res
b'total D drwxr -xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM '
#通过Popen打印结果的步骤,打印内存地址输出,需要通过stdout输出到标准输出内。
>>>res = subprocess.Popen("ifconfig|grep 192",shell=True,stdout=subprocess.PIPE)
>>>res.stdout.read()
注:stdout:标准输出。
stdout=subprocess.PIPE:先输出到标准输出内。
原理图(列1)
#上面哪些方法,底层都是封装的subprocess.Popen
poll()
Check if child process has terminated. Returns returncode
注:可以与执行结果长的结合使用。
res.poll():返回None,没执行完。
res.poll():返回0,执行完了。
wait()
Wait for child process to terminate. Returns returncode attribute
注:wait()执行后等待执行结果后才可继续操作终端。
terminate()
注:杀掉所启动进程。
使用:res.terminate() 创建变量后在杀掉进程。
communicate()
注:等待任务结束,可在命令等待过程中输入内容。
命令式列
import subprocess obj = subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) obj.stdin.write('print 1 ') obj.stdin.write('print 2 ') obj.stdin.write('print 3 ') obj.stdin.write('print 4 ') out_error_list = obj.communicate(timeout=10) print(out_error_list)
可用参数:
- args:shell命令,可以是字符串或者序列类型(如:list,元组)
- bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
- stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
- preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
- close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
- shell:同上
- cwd:用于设置子进程的当前目录
- env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
- universal_newlines:不同系统的换行符不同,True -> 同意使用
- startupinfo与createionflags只在windows下有效
将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
模块使用案例
subprocess实现sudo 自动输入密码
import subprocess def mypass(): mypass = '123' #or get the password from anywhere return mypass echo = subprocess.Popen(['echo',mypass()], stdout=subprocess.PIPE, ) sudo = subprocess.Popen(['sudo','-S','iptables','-L'], stdin=echo.stdout, stdout=subprocess.PIPE, ) end_of_pipe = sudo.stdout print "Password ok Iptables Chains %s" % end_of_pipe.read()