python学习——python中执行shell命令

简介:

这里介绍一下python执行shell命令的四种方法:

1、os模块中的os.system()这个函数来执行shell命令

1
2
3
>>> os.system( 'ls' )
anaconda - ks.cfg  install.log  install.log.syslog  send_sms_service.py  sms.py
0

注,这个方法得不到shell命令的输出。


2、popen()#这个方法能得到命令执行后的结果是一个字符串,要自行处理才能得到想要的信息。

1
2
3
4
5
>>>  import  os
>>>  str  =  os.popen( "ls" ).read()
>>> a  =  str .split( "\n" )
>>>  for  in  a:
         print  b

这样得到的结果与第一个方法是一样的。

3、commands模块#可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位

1
2
3
4
5
6
7
8
9
10
11
12
import  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.syslog

commands.getstatusoutput(cmd)返回(status,output)

commands.getoutput(cmd)只返回输出结果

commands.getstatus(file)返回ls -ld file 的执行结果字符串,调用了getoutput,不建议使用这个方法。


4、subprocess模块


使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。

import subprocess

1、subprocess.call(command, shell=True)

#会直接打印出结果。

2、subprocess.Popen(command, shell=True) 也可以是subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) 这样就可以输出结果了。

如果command不是一个可执行文件,shell=True是不可省略的。

shell=True意思是shell下执行command


这四种方法都可以执行shell命令。



本文转自 ZhouLS 51CTO博客,原文链接:http://blog.51cto.com/zhou123/1312791

相关文章
|
8天前
|
Python
python函数的参数学习
学习Python函数参数涉及五个方面:1) 位置参数按顺序传递,如`func(1, 2, 3)`;2) 关键字参数通过名称传值,如`func(a=1, b=2, c=3)`;3) 默认参数设定默认值,如`func(a, b, c=0)`;4) 可变参数用*和**接收任意数量的位置和关键字参数,如`func(1, 2, 3, a=4, b=5, c=6)`;5) 参数组合结合不同类型的参数,如`func(1, 2, 3, a=4, b=5, c=6)`。
13 1
|
11天前
|
Web App开发 Java Linux
Linux之Shell基本命令篇
Linux之Shell基本命令篇
Linux之Shell基本命令篇
|
12天前
|
Python
Python文件操作学习应用案例详解
【4月更文挑战第7天】Python文件操作包括打开、读取、写入和关闭文件。使用`open()`函数以指定模式(如'r'、'w'、'a'或'r+')打开文件,然后用`read()`读取全部内容,`readline()`逐行读取,`write()`写入字符串。最后,别忘了用`close()`关闭文件,确保资源释放。
17 1
|
4天前
|
Python
python学习3-选择结构、bool值、pass语句
python学习3-选择结构、bool值、pass语句
|
2天前
|
机器学习/深度学习 算法 Python
使用Python实现集成学习算法:Bagging与Boosting
使用Python实现集成学习算法:Bagging与Boosting
14 0
|
4天前
|
Python
python学习14-模块与包
python学习14-模块与包
|
4天前
|
Python
python学习12-类对象和实例对象
python学习12-类对象和实例对象
|
4天前
|
数据采集 Python
python学习9-字符串
python学习9-字符串
|
4天前
|
Python
python学习10-函数
python学习10-函数
|
4天前
|
存储 索引 Python
python学习7-元组
python学习7-元组