日常整理python执行系统命令的常见方法(全)


Posted in Python onOctober 22, 2015

具体内容如下:

1 os.system

例如 ipython中运行如下命令,返回运行状态status

os.system('cat /etc/passwdqc.conf')
min=disabled,24,11,8,7
max=40
passphrase=3
match=4
similar=deny
random=47
enforce=everyone
retry=3
Out[6]: 0

2 os.popen()

popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.

运行返回结果

In [20]: output = os.popen('cat /proc/cpuinfo')
In [21]: lineLen = []
In [22]: for line in output.readlines():
    lineLen.append(len(line))
   ....:    
In [23]: line
line     lineLen 
In [23]: lineLen
Out[23]:
[14,
 25,
...

3 如何同时返回结果和运行状态,commands模块:

#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'>
File: /usr/lib64/python2.7/commands.py
Docstring:
Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is removed from the output string.
Encapsulates the basic operation:
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()

commands示例如下:

In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
In [25]: status
Out[25]: 0
In [26]: len(output)
Out[26]: 3859

4 使用模块subprocess

ipython 中运行"?subprocess"可以发现subprocess是python用来替换os.popen()等管道操作命令的新模块

A more real-world example would look like this:

try:
 retcode = call("mycmd" + " myarg", shell=True)
 if retcode < 0:
  print >>sys.stderr, "Child was terminated by signal", -retcode
 else:
  print >>sys.stderr, "Child returned", retcode
except OSError, e:
 print >>sys.stderr, "Execution failed:", e

相对于上面几种方式,subprocess便于控制和监控进程运行结果,subprocess提供多种函数便于应对父进程对子进程不同要求:

4.1.1 subprocess.call()

父进程父进程等待子进程完成,返回exit code

4.1.2 subprocess.check_call()

父进程等待子进程完成,返回0,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try...except...来检查

4.1.3 subprocess.check_output()

父进程等待子进程完成

返回子进程向标准输出的输出结果

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try...except...来检查

例如:

In [32]: out = subprocess.call("ls -l", shell=True)
total 42244
-rw-rw-r--.  1 *** ***     366 May 26 09:10 ChangeLog

4.2.1

上面三个函数都是源于Popen()函数的wapper(封装),如果需要更加个性化应用,那么就需要使用popen()函数

Popen对象创建后,主程序不会自动等待子进程完成。我们必须调用对象的wait()方法,父进程才会等待 (也就是阻塞block)

[wenwt@localhost syntax]$ rm subprocess.pyc 
[wenwt@localhost syntax]$ python process.py 
parent process
[wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data.
^C
[wenwt@localhost syntax]$ 
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms

加上wait方法:

[wenwt@localhost syntax]$ python process.py 
PING www.google.com (173.194.219.103) 56(84) bytes of data.
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms
parent process

补充介绍:Python 执行终端命令的方法

import os
import subprocess
'''
os.system模块
os.system("ls -hl") 执行命令并返回状态码,当返回0表示成功;返回256表示失败,痛点是无法返回output
os.popen模块
os.popen("ls -hl") 执行命令,之后通过.read()方法获取output返回值
subprocess模块
subprocess.getstatusoutput("ls -hl") 执行命令,并返回状态status、输出output
subprocess.getoutput("ls -hl")    执行命令,只返回输出结果output
subprocess.call("ls -hl")      执行命令并返回状态码 和os.system("ls -hl")类似
'''
def test_system(cmd):
  status = os.system(cmd) # 会自动输出output到控制台 但是无法接收,status为0表示成功、status为256表示失败
  print(status)
def test_popen(cmd):
  output = os.popen(cmd).read() # 只会获取到命令的output,如果是有output的错误命令 会输出output,否则输出空白
  print(output)
def test_getoutput(cmd):
  output = subprocess.getoutput(cmd) # 和os.popen(cmd)类似
  print(output)
def test_getstatusoutput(cmd):
  status, output = subprocess.getstatusoutput(cmd) # 执行命令,并返回状态status、输出output
  print(status)
  print(output)
def test_call(cmd):
  status = subprocess.call(cmd) # 和os.system(cmd)类似
  print(status)
if __name__ == '__main__':
  # test_system('ls -lh') # test_system('test')
  # test_popen('pwd') # test_popen('test')
  # test_getoutput('pwd')
  # test_getstatusoutput('pwd')
  test_call('pwd')

以上内容就是本文的全部叙述,希望大家喜欢。

Python 相关文章推荐
Python中使用PyHook监听鼠标和键盘事件实例
Jul 18 Python
Python实现3行代码解简单的一元一次方程
Aug 18 Python
Python判断Abundant Number的方法
Jun 15 Python
Python简单实现子网掩码转换的方法
Apr 13 Python
Python与人工神经网络:使用神经网络识别手写图像介绍
Dec 19 Python
python PyTorch预训练示例
Feb 11 Python
Pycharm更换python解释器的方法
Oct 29 Python
在Python文件中指定Python解释器的方法
Feb 18 Python
Django Rest framework认证组件详细用法
Jul 25 Python
Python使用scrapy爬取阳光热线问政平台过程解析
Aug 14 Python
python tkinter图形界面代码统计工具
Sep 18 Python
pandas中ix的使用详细讲解
Mar 09 Python
Python六大开源框架对比
Oct 19 #Python
Python脚本暴力破解栅栏密码
Oct 19 #Python
python学习笔记之调用eval函数出现invalid syntax错误问题
Oct 18 #Python
在arcgis使用python脚本进行字段计算时是如何解决中文问题的
Oct 18 #Python
详解使用Python处理文件目录的相关方法
Oct 16 #Python
详解在Python程序中自定义异常的方法
Oct 16 #Python
Python编程中的文件操作攻略
Oct 16 #Python
You might like
比较全的PHP 会话(session 时间设定)使用入门代码
2008/06/05 PHP
php Memcache 中实现消息队列
2009/11/24 PHP
PHP开发负载均衡指南
2010/07/17 PHP
php数据库连接时容易出错的特殊符号问题
2010/09/01 PHP
PHP+FFMPEG实现将视频自动转码成H264标准Mp4文件
2014/09/24 PHP
新浪微博OAuth认证和储存的主要过程详解
2015/03/27 PHP
weiphp微信公众平台授权设置
2016/01/04 PHP
php实现推荐功能的简单实例
2019/09/29 PHP
符合W3C网页标准的iframe标签的使用方法
2007/07/19 Javascript
如何实现修改密码时密码框显示保存到cookie的密码
2013/12/10 Javascript
Express.JS使用详解
2014/07/17 Javascript
angularjs在ng-repeat中使用ng-model遇到的问题
2016/01/21 Javascript
javascript中eval解析JSON字符串
2016/02/27 Javascript
详解JavaScript基础知识(JSON、Function对象、原型、引用类型)
2018/01/16 Javascript
vue项目webpack中Npm传递参数配置不同域名接口
2018/06/15 Javascript
echarts实现词云自定义形状的示例代码
2019/02/20 Javascript
关于layui的下拉搜索框异步加载数据的解决方法
2019/09/28 Javascript
vue 解决数组赋值无法渲染在页面的问题
2019/10/28 Javascript
[02:37]2018DOTA2亚洲邀请赛赛前采访 VP.no[o]ne心中最强SOLO是谁
2018/04/04 DOTA
[01:14:30]TNC vs VG 2019国际邀请赛淘汰赛 胜者组赛BO3 第二场 8.20.mp4
2019/08/22 DOTA
Python创建文件和追加文件内容实例
2014/10/21 Python
Python面向对象编程中的类和对象学习教程
2015/03/30 Python
python select.select模块通信全过程解析
2017/09/20 Python
windows下搭建python scrapy爬虫框架步骤
2018/12/23 Python
Python ADF 单位根检验 如何查看结果的实现
2020/06/03 Python
完美解决python针对hdfs上传和下载的问题
2020/06/05 Python
Python实现一个论文下载器的过程
2021/01/18 Python
css3学习之2D转换功能详解
2016/12/23 HTML / CSS
突破canvas语法限制 让他支持链式语法
2012/12/24 HTML / CSS
澳大利亚拥有最好的家具和家居用品在线目的地:Nestz
2019/02/23 全球购物
Myprotein西班牙官网:欧洲第一大运动营养品牌
2020/02/24 全球购物
土地转让协议书
2014/04/15 职场文书
个人承诺书怎么写
2014/05/24 职场文书
医院护士工作检讨书
2014/10/26 职场文书
创业计划书之奶茶店开店方案范本!
2019/08/06 职场文书
Java 死锁解决方案
2022/05/11 Java/Android