日常整理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的Django框架中的模版相关知识
Jul 15 Python
Python压缩解压缩zip文件及破解zip文件密码的方法
Nov 04 Python
python查看微信好友是否删除自己
Dec 19 Python
Python中创建字典的几种方法总结(推荐)
Apr 27 Python
python类的方法属性与方法属性的动态绑定代码详解
Dec 27 Python
python实现数据写入excel表格
Mar 25 Python
Python3之不使用第三方变量,实现交换两个变量的值
Jun 26 Python
对django的User模型和四种扩展/重写方法小结
Aug 17 Python
基于YUV 数据格式详解及python实现方式
Dec 09 Python
python 可视化库PyG2Plot的使用
Jan 21 Python
详解Python小数据池和代码块缓存机制
Apr 07 Python
Python下opencv库的安装过程及问题汇总
Jun 11 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中MVC模式的模板引擎开发经验分享
2011/03/23 PHP
ThinkPHP中pathinfo的访问模式、路径访问模式及URL重写总结
2014/08/23 PHP
PHP实现双链表删除与插入节点的方法示例
2017/11/11 PHP
PHP排序二叉树基本功能实现方法示例
2018/05/26 PHP
laravel5.6框架操作数据curd写法(查询构建器)实例分析
2020/01/26 PHP
js判断FCKeditor内容是否为空的两种形式
2013/05/14 Javascript
用于deeplink的js方法(判断手机是否安装app)
2014/04/02 Javascript
Bootstrap入门书籍之(五)导航条、分页导航
2016/02/17 Javascript
jQuery基于BootStrap样式实现无限极地区联动
2016/08/26 Javascript
详解VueJs异步动态加载块
2017/03/09 Javascript
使用Xcache缓存器加速PHP网站的配置方法
2017/04/22 Javascript
jQuery选择器之属性过滤选择器详解
2017/09/28 jQuery
Vuex 进阶之模块化组织详解
2018/01/12 Javascript
微信小程序模版渲染详解
2018/01/26 Javascript
Vue中的scoped实现原理及穿透方法
2018/05/15 Javascript
js监听html页面的上下滚动事件方法
2018/09/11 Javascript
nodejs实现获取本地文件夹下图片信息功能示例
2019/06/22 NodeJs
[26:40]DOTA2上海特级锦标赛A组资格赛#1 Secret VS MVP.Phx第一局
2016/02/25 DOTA
在Linux上安装Python的Flask框架和创建第一个app实例的教程
2015/03/30 Python
快速了解Python开发中的cookie及简单代码示例
2018/01/17 Python
python使用xlsxwriter实现有向无环图到Excel的转换
2018/12/12 Python
Python中logging实例讲解
2019/01/17 Python
Python mutiprocessing多线程池pool操作示例
2019/01/30 Python
python实现简单银行管理系统
2019/10/25 Python
Pandas时间序列重采样(resample)方法中closed、label的作用详解
2019/12/10 Python
Pyqt5 关于流式布局和滚动条的综合使用示例代码
2020/03/24 Python
python爬虫 requests-html的使用
2020/11/30 Python
传统HTML页面实现模块化加载的方法
2018/10/15 HTML / CSS
贝嫂喜欢的婴儿品牌,个性化的婴儿礼物:My 1st Years
2017/11/19 全球购物
在校大学生的职业生涯规划书
2014/03/14 职场文书
幼儿园户外活动总结
2014/07/04 职场文书
幼儿园园长新年寄语2015
2014/12/08 职场文书
Python数据可视化之基于pyecharts实现的地理图表的绘制
2021/06/10 Python
Github 使用python对copilot做些简单使用测试
2022/04/14 Python
美国运营商 T-Mobile 以 117.83Mb/s 的速度排第一位
2022/04/21 数码科技
全网非常详细的pytest配置文件
2022/07/15 Python