日常整理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基础教程之popen函数操作其它程序的输入和输出示例
Feb 10 Python
python实现ping的方法
Jul 06 Python
关于Python中异常(Exception)的汇总
Jan 18 Python
基于并发服务器几种实现方法(总结)
Dec 29 Python
对python使用http、https代理的实例讲解
May 07 Python
Python画柱状统计图操作示例【基于matplotlib库】
Jul 04 Python
Python OOP类中的几种函数或方法总结
Feb 22 Python
python2和python3在处理字符串上的区别详解
May 29 Python
python 定义类时,实现内部方法的互相调用
Dec 25 Python
JAVA SWT事件四种写法实例解析
Jun 05 Python
python3字符串输出常见面试题总结
Dec 01 Python
Python带你从浅入深探究Tuple(基础篇)
May 15 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程序中的常见漏洞进行攻击(下)
2006/10/09 PHP
PHP运行出现Notice : Use of undefined constant 的完美解决方案分享
2012/03/05 PHP
ThinkPHP有变量的where条件分页实例
2014/11/03 PHP
浅谈laravel 5.6 安装 windows上使用composer的安装过程
2019/10/18 PHP
js 鼠标点击事件及其它捕获
2009/06/04 Javascript
js在IE与firefox的差异集锦
2014/11/11 Javascript
jQuery实现菜单感应鼠标滑动动画效果的方法
2015/02/28 Javascript
JavaScript通过字典进行字符串翻译转换的方法
2015/03/19 Javascript
jQuery+css实现的换页标签栏效果
2016/01/27 Javascript
AngularJS入门教程之ng-checked 指令详解
2016/08/01 Javascript
jQuery插件EasyUI实现Layout框架页面中弹出窗体到最顶层效果(穿越iframe)
2016/08/05 Javascript
微信小程序中子页面向父页面传值实例详解
2017/03/20 Javascript
vue响应式更新机制及不使用框架实现简单的数据双向绑定问题
2019/06/27 Javascript
[05:45]Ti4观战指南(下)
2014/07/07 DOTA
Python编程之列表操作实例详解【创建、使用、更新、删除】
2017/07/22 Python
Python模拟百度自动输入搜索功能的实例
2019/02/14 Python
使用python进行波形及频谱绘制的方法
2019/06/17 Python
Python中那些 Pythonic的写法详解
2019/07/02 Python
简单了解python关系(比较)运算符
2019/07/08 Python
浅谈OpenCV中的新函数connectedComponentsWithStats用法
2020/07/05 Python
Python如何输出百分比
2020/07/31 Python
详解Pytorch显存动态分配规律探索
2020/11/17 Python
python抢购软件/插件/脚本附完整源码
2021/03/04 Python
phonegap常用事件总结(必看篇)
2017/03/31 HTML / CSS
美国本地交易和折扣网站:LocalFlavor.com
2017/10/26 全球购物
印度最大的时尚购物网站:Myntra
2018/09/13 全球购物
小学教师学期末自我评价
2013/09/25 职场文书
力学专业毕业生自荐信
2013/11/17 职场文书
教师自荐信范文
2013/12/09 职场文书
新文化运动的基本口号
2014/06/21 职场文书
关于读书的演讲稿600字
2014/08/27 职场文书
2014年体育教学工作总结
2014/12/09 职场文书
党员民主生活会材料
2014/12/15 职场文书
2015年公司工作总结
2015/04/25 职场文书
全民创业工作总结
2015/08/13 职场文书
你离财务总监还有多远?速览CFO的岗位职责
2019/11/18 职场文书