日常整理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 第一步 hello world
Sep 25 Python
利用Python读取文件的四种不同方法比对
May 18 Python
python 3.0 模拟用户登录功能并实现三次错误锁定
Nov 01 Python
Django + Uwsgi + Nginx 实现生产环境部署的方法
Jun 20 Python
Python实现的建造者模式示例
Aug 06 Python
解决pycharm工程启动卡住没反应的问题
Jan 19 Python
python pytest进阶之fixture详解
Jun 27 Python
pandas进行时间数据的转换和计算时间差并提取年月日
Jul 06 Python
tesserocr与pytesseract模块的使用方法解析
Aug 30 Python
基于python的BP神经网络及异或实现过程解析
Sep 30 Python
解决jupyter notebook import error但是命令提示符import正常的问题
Apr 15 Python
Django 解决阿里云部署同步数据库报错的问题
May 14 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
从零开始学YII2框架(四)扩展插件yii2-kartikgii
2014/08/20 PHP
PHP永久登录、记住我功能实现方法和安全做法
2015/04/27 PHP
8个PHP数组面试题
2015/06/23 PHP
PHP动态地创建属性和方法, 对象的复制, 对象的比较,加载指定的文件,自动加载类文件,命名空间
2016/05/06 PHP
基于jquery的内容循环滚动小模块(仿新浪微博未登录首页滚动微博显示)
2011/03/28 Javascript
js拖拽一些常见的思路方法整理
2014/03/19 Javascript
JavaScript节点及列表操作实例小结
2015/08/05 Javascript
jquery+CSS3实现淘宝移动网页菜单效果
2015/08/31 Javascript
详解AngularJS实现表单验证
2015/12/10 Javascript
JavaScript编程学习技巧汇总
2016/02/21 Javascript
JS实现的RGB网页颜色在线取色器完整实例
2016/12/21 Javascript
JS一个简单的注册页面实例
2017/09/05 Javascript
AngularJS实现的输入框字数限制提醒功能示例
2017/10/26 Javascript
10行原生JS实现文字无缝滚动(超简单)
2018/01/02 Javascript
Mac下通过brew安装指定版本的nodejs教程
2018/05/17 NodeJs
layui 优化button按钮和弹出框的方法
2018/08/15 Javascript
vue 通过绑定事件获取当前行的id操作
2020/07/27 Javascript
[01:03:51]2018DOTA2亚洲邀请赛 4.7 淘汰赛 VP vs LGD 第三场
2018/04/09 DOTA
Python with用法实例
2015/04/14 Python
python实现SMTP邮件发送功能
2020/06/16 Python
python模块简介之有序字典(OrderedDict)
2016/12/01 Python
使用XML库的方式,实现RPC通信的方法(推荐)
2017/06/14 Python
完美解决python中ndarray 默认用科学计数法显示的问题
2018/07/14 Python
python批量下载网站马拉松照片的完整步骤
2018/12/05 Python
Python编程学习之如何判断3个数的大小
2019/08/07 Python
python 字典 setdefault()和get()方法比较详解
2019/08/07 Python
Python scrapy增量爬取实例及实现过程解析
2019/12/24 Python
Python中BeautifulSoup通过查找Id获取元素信息
2020/12/07 Python
详解python第三方库的安装、PyInstaller库、random库
2021/03/03 Python
毕业生找工作推荐信
2013/11/21 职场文书
管理建议书范文
2014/05/13 职场文书
乡镇干部个人对照检查材料思想汇报
2014/10/04 职场文书
2015年专项整治工作总结
2015/04/03 职场文书
公务员的复习计划书,请收下!
2019/07/15 职场文书
详解python中[-1]、[:-1]、[::-1]、[n::-1]使用方法
2021/04/25 Python
基于Redis位图实现用户签到功能
2021/05/08 Redis