subprocess模块是
os.system作用os.system(cmd)的返回值只会有0(成功)
os.spawn* 产生一个新进程
这两个模块的替换。上面这两个模块会慢慢被替换掉,逐步不使用了。
#执行命令,返回命令执行状态 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"])
#执行命令,如果命令结果为0,就正常返回,否则抛异常
>>> subprocess.check_call(["ls", "-l"])
0
#接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
>>> 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 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n‘
#上面那些方法,底层都是封装的subprocess.Popen
poll()
Check if child process has terminated. Returns returncode
wait()
Wait for child process to terminate. Returns returncode attribute.
terminate() 杀掉所启动进程
communicate() 等待任务结束
stdin 标准输入
stdout 标准输出
stderr 标准错误
pid
The process ID of the child process.
#例子
>>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
>>> p.stdout.read()
b‘/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /\n‘
调用subprocess.run(...)是推荐的常用方法,在大多数情况下能满足需求,但如果你可能需要进行一些复杂的与系统的交互的话,你还可以用subprocess.Popen(),语法如下:
可用参数:
终端输入的命令分为两种:
需要交互的命令示例
import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) obj.stdin.write(‘print 1 \n ‘) obj.stdin.write(‘print 2 \n ‘) obj.stdin.write(‘print 3 \n ‘) obj.stdin.write(‘print 4 \n ‘) out_error_list = obj.communicate(timeout=10) print out_error_list
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 \n Iptables Chains %s" % end_of_pipe.read()
原文:http://www.cnblogs.com/itfat/p/7499780.html