Python,subprocess模块(补充)

1.subprocess模块,前戏
res = os.system('dir') 打印到屏幕,res为0或非0
os.popen('dir') 返回一个内存对象,相当于文件流
a = os.popen('dir').read() a中就存的是执行结果输出了

Python2.7 commands模块 commands.getstatusoutput('dir')返回元祖,第一个元素为状态0为成功,第二个为结果
windows上不好用,只是Linux好用




subprocess模块,替换os.system等

subprocess.run(['df','-h']) 当参数传,Python解析,如果有管道符就不行了
subprocess.run('df -h | grep sda1', shell=True) shell=True是指不需要Python解析,直接把字符串给shell
Python3.5才出现subprocess.run
终端输入的命令分为两种:
输入即可得到输出,如:ifconfig
输入进行某环境,依赖再输入,如:Python

常用subprocess

没有管道
retcode = subprocess.call(['ls','-l']) 成功返回0,不成功返回非0
subprocess.check_call(['ls','-l']) 执行成功返回0,执行错误抛异常
subprocess.getoutput('ls /bin/ls')接收字符串格式命令,只返回结果
res = subprocess.check_output(['ls','-l'])执行成功返回执行结果,不成功出错
subprocess.getstatsoutput('ls /bin/ls') 返回元祖(1,'/bin/ls'),第一个状态,第二个结果

上面的方法,底层都是封装subprocess.popen
例子
res = subprocess.popen('ifconfig | grep 192',shell=True)
res
<subprocess.popen object at ox7f2131a>
res.stdout.read()读不出来
要读出来要先输出到标准输出里,先存到管道PIPE 再给stdout python和shell是两个进程不能独立通信,必须通过操作系统提供的管道
用管道可以把结果存到stdin stdout stderr
subprocess.popen('ifconfig | grep 192',shell=True,stdout=subprocess.PIPE)
res.stdout.read()就可以读出来了
subprocess.popen('ifconfig | gr1111ep 192',shell=True,stdout=subprocess.PIPE)
出错会直接打印错误。想不打印错误可以stderr保存stderr=subprocess.PIPE


poll() check if child process has terminated. returns returncode
---------
res=subprocess.popen("sleep 10;echo 'hello'", shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
执行的时候没反应,不知道是卡主了还是执行完了
每次调subprocess执行Linux命令,都相当于启动了一个新的shell,启动新的进程,执行一次命令等结果
如果该命令要花半小时,不知道是卡主了还是执行完了,可以res.poll()返回none表示还没有执行完,返回0表示执行完了
res.wait()等待结束然后返回0
----------
terminate()杀掉该进程,res.terminate()
wait() wait for child process to terminate. returns returncode attribute
communicate()等待任务结束 没什么用,用Python当参数,输Python进入环境
stdin 标准输入
stdout 标准输出
stderr 标准错误
pid the process ID of the child process


-----可用参数
args: shell命令,可以是字符串或者序列类型
bufsize:指定缓冲,0无缓冲,1 行缓冲,其他 缓冲区大小 负值 系统缓冲
stdin,stdout,stderr:标准输入,输出,错误句柄
preexec_fn:只在Unix平台下有效,用于指定一个可执行对象,它将在子进程运行之前被调用
close_sfs:在Windows平台下,如果close_sfs被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道
所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误

shell:同上
cod:用于设置子进程的当前目录
env:用于指定子进程的环境变量。如果env=None,子进程的环境变量将从父进程中继承
universal_newlines:不同系统的换行符不同,True->同意使用
startupinfo与createionflags只在Windows下有效
将被传递给底层的createprocess()函数,用于设置子进程的一些属性,
如:主窗口的外观,进程的优先级等


subprocess实现sudo自动输入密码
例如Python里面执行sudo apt-get install vim (Linux里面要输入密码)
linux中应该echo '123' | sudo -S iptables -L
python直接 subprocess.popen("echo '123' | sudo -S iptables -L",shell=True)