日常整理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信息抽取之乱码解决办法
Jun 29 Python
基于Python __dict__与dir()的区别详解
Oct 30 Python
hmac模块生成加入了密钥的消息摘要详解
Jan 11 Python
python实现list由于numpy array的转换
Apr 04 Python
解决python3 urllib 链接中有中文的问题
Jul 16 Python
python 自定义异常和异常捕捉的方法
Oct 18 Python
Python推导式简单示例【列表推导式、字典推导式与集合推导式】
Dec 04 Python
python程序快速缩进多行代码方法总结
Jun 23 Python
python算法题 链表反转详解
Jul 02 Python
在linux下实现 python 监控usb设备信号
Jul 03 Python
使用 Python ssh 远程登陆服务器的最佳方案
Mar 06 Python
总结Python变量的相关知识
Jun 28 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
destoon二次开发常用数据库操作
2014/06/21 PHP
thinkphp的静态缓存用法分析
2014/11/29 PHP
thinkPHP3.1验证码的简单实现方法
2016/04/22 PHP
javascript或asp实现的判断身份证号码是否正确两种验证方法
2009/11/26 Javascript
jQuery Validation插件remote验证方式的Bug解决
2010/07/01 Javascript
javascript 进阶篇2 CSS XML学习
2012/03/14 Javascript
mailto的使用技巧分享
2012/12/21 Javascript
js弹出窗口之弹出层的小例子
2013/06/17 Javascript
使用Jquery获取带特殊符号的ID 标签的方法
2014/04/30 Javascript
jquery实现简单文字提示效果
2015/12/02 Javascript
Jquery attr()方法 属性赋值和属性获取详解
2016/04/15 Javascript
JS实现添加,替换,删除节点元素的方法
2016/06/30 Javascript
详解用vue编写弹出框组件
2017/07/04 Javascript
vue内置指令详解
2018/04/03 Javascript
React中如何引入Angular组件详解
2018/08/09 Javascript
vue模仿网易云音乐的单页面应用
2019/04/24 Javascript
Vue 设置axios请求格式为form-data的操作步骤
2019/10/29 Javascript
Vue+ElementUI使用vue-pdf实现预览功能
2019/11/26 Javascript
小程序如何写动态标签的实现方法
2020/02/05 Javascript
微信小程序实现搜索功能
2020/03/10 Javascript
JavaScript实现多球运动效果
2020/09/07 Javascript
Python读取文件内容的三种常用方式及效率比较
2017/10/07 Python
Python爬虫天气预报实例详解(小白入门)
2018/01/24 Python
Python中对数组集进行按行打乱shuffle的方法
2018/11/08 Python
Django 自定义分页器的实现代码
2019/11/24 Python
美国的Eastbay旗下的运动款子品牌:Final-Score
2018/01/01 全球购物
澳大利亚在线家具店:Luxo Living
2019/03/24 全球购物
英国No.1体育用品零售商:SportsDirect.com
2019/10/16 全球购物
幼儿园家长会欢迎词
2014/01/09 职场文书
高三地理教学反思
2014/01/11 职场文书
中专生自我鉴定范文
2014/02/02 职场文书
军训自我鉴定200字
2014/02/13 职场文书
求职意向书范文
2014/04/01 职场文书
歌舞青春观后感
2015/06/10 职场文书
golang elasticsearch Client的使用详解
2021/05/05 Golang
灵能百分百第三季什么时候来?
2022/03/15 日漫