Python中执行 Sehll 命令
在日常的使用中,会经常遇到需要执行 Shell 命令的情况,但是很多时候,在 Python 下执行也是很方便的。下面介绍四种方法以供参考。
OS模块中的
os.system()1
2>>>os.system('ls')
123.txtpopen()得到一个字符串,需要处理下。1
2
3
4
5import os
str = os.popen("ls").read()
a = str.split("\n")
for b in a:
print b
commands模块#可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位1
2
3
4
5
6
7
8
9
10
11
12import commands
a,b = commands.getstatusoutput('ls')
a#是退出状态
b#是输出的结果。
import commands
a,b = commands.getstatusoutput('ls')
print a
0
print b
anaconda-ks.cfg
install.log
install.log.syslogcommands.getstatusoutput(cmd)返回status,outputcommands.getoutput(cmd)只返回输出结果subprocess模块使用
subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用
subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。subprocess.call(command, shell=True)直接打印结果subprocess.Popen(command, shell=True)也可以是subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)这样就可以输出结果了。如果
command不是一个可执行文件,shell=True是不可省略的。
以上就是四种方法。