日常整理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实现的阳历转阴历(农历)算法
Apr 25 Python
Python下载指定页面上图片的方法
May 12 Python
Python subprocess模块功能与常见用法实例详解
Jun 28 Python
ubuntu上安装python的实例方法
Sep 30 Python
python继承threading.Thread实现有返回值的子类实例
May 02 Python
Pymysql实现往表中插入数据过程解析
Jun 02 Python
PyCharm 2020.2.2 x64 下载并安装的详细教程
Oct 15 Python
Python APScheduler执行使用方法详解
Dec 10 Python
python 实现客户端与服务端的通信
Dec 23 Python
Python入门基础之数字字符串与列表
Feb 01 Python
Python爬取你好李焕英豆瓣短评生成词云的示例代码
Feb 24 Python
pyqt5蒙版遮罩mask,setmask的使用
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 mysql与mysqli事务使用说明 分享
2013/08/17 PHP
Drupal读取Excel并导入数据库实例
2014/03/02 PHP
ThinkPHP实现将SESSION存入MYSQL的方法
2014/07/22 PHP
javascript+php实现根据用户时区显示当地时间的方法
2015/03/11 PHP
PHP性能优化大全(php.ini)
2016/05/20 PHP
PHP云打印类完整示例
2016/10/15 PHP
php的常量和变量实例详解
2017/06/27 PHP
PHP性能测试工具xhprof安装与使用方法详解
2018/04/29 PHP
关于文本限制字数的js代码
2007/04/02 Javascript
js的.innerHTML = &quot;&quot;IE9下显示有错误的解决方法
2013/09/16 Javascript
node.js学习总结之调式代码的方法
2014/06/25 Javascript
上传图片预览JS脚本 Input file图片预览的实现示例
2014/10/23 Javascript
JavaScript对象数组排序实例方法浅析
2016/06/15 Javascript
javascript正则表达式模糊匹配IP地址功能示例
2017/01/06 Javascript
nodejs个人博客开发第六步 数据分页
2017/04/12 NodeJs
Vue.js使用$.ajax和vue-resource实现OAuth的注册、登录、注销和API调用
2017/05/10 Javascript
Mint UI 基于 Vue.js 移动端组件库
2017/11/07 Javascript
详解vue 单页应用(spa)前端路由实现原理
2018/04/04 Javascript
基于vue.js组件实现分页效果
2018/12/29 Javascript
JavaScript This指向问题详解
2019/11/25 Javascript
原生js实现下拉选项卡
2019/11/27 Javascript
python中的for循环
2018/09/28 Python
python3的输入方式及多组输入方法
2018/10/17 Python
tensorflow 实现打印pb模型的所有节点
2020/01/23 Python
Django ModelForm操作及验证方式
2020/03/30 Python
解决启动django,浏览器显示“服务器拒绝访问”的问题
2020/05/13 Python
Python web如何在IIS发布应用过程解析
2020/05/27 Python
windows10在visual studio2019下配置使用openCV4.3.0
2020/07/14 Python
python 基于DDT实现数据驱动测试
2021/02/18 Python
html5 拖拽上传图片实例演示
2013/04/01 HTML / CSS
canvas如何实现多张图片编辑的图片编辑器
2020/03/10 HTML / CSS
文员个人的求职信范文
2013/09/26 职场文书
商务英语专业自荐信
2013/10/14 职场文书
动漫专业高职生职业生涯规划书
2014/02/15 职场文书
2015年护士医德医风自我评价
2015/03/03 职场文书
Python列表删除重复元素与图像相似度判断及删除实例代码
2021/05/07 Python