日常整理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处理PHP数组文本文件实例
Sep 18 Python
Python中使用Beautiful Soup库的超详细教程
Apr 30 Python
Python抓取百度查询结果的方法
Jul 08 Python
在Python的while循环中使用else以及循环嵌套的用法
Oct 14 Python
使用Python保存网页上的图片或者保存页面为截图
Mar 05 Python
Python使用遗传算法解决最大流问题
Jan 29 Python
用Python实现筛选文件脚本的方法
Oct 27 Python
Python Flask框架模板操作实例分析
May 03 Python
Django model.py表单设置默认值允许为空的操作
May 19 Python
python调用私有属性的方法总结
Jul 24 Python
mac安装python3后使用pip和pip3的区别说明
Sep 01 Python
python 爬取华为应用市场评论
May 29 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循环输出指定目录下的所有文件和文件夹路径例子(简单实用)
2014/05/10 PHP
php学习笔记之面向对象
2014/11/08 PHP
PHP读取大文件的多种方法介绍
2016/04/04 PHP
tp5(thinkPHP5)框架连接数据库的方法示例
2018/12/24 PHP
解决Laravel 使用insert插入数据,字段created_at为0000的问题
2019/10/11 PHP
discuz论坛更换域名,详细文件修改步骤
2020/12/09 PHP
firefox下frameset取不到值的解决方法
2010/09/06 Javascript
jquery.qrcode在线生成二维码使用示例
2013/08/21 Javascript
JavaScript动态创建div属性和样式示例代码
2013/10/09 Javascript
jquery如何获取复选框的值
2013/12/12 Javascript
jQuery中:submit选择器用法实例
2015/01/03 Javascript
Javascript编写2048小游戏
2015/07/07 Javascript
使用js复制链接中的部分文字的方法
2015/07/30 Javascript
详解如何在vue项目中引入elementUI组件
2018/02/11 Javascript
nodejs微信扫码支付功能实现
2018/02/17 NodeJs
vue 解决遍历对象显示的顺序不对问题
2019/11/07 Javascript
javascript实现异形滚动轮播
2019/11/28 Javascript
JS获取当前时间的年月日时分秒及时间的格式化的方法
2019/12/18 Javascript
JavaScript实现简易聊天对话框(加滚动条)
2020/02/10 Javascript
[02:41]《西雅图我们来了》2015国际邀请赛出征全记录
2015/07/23 DOTA
简单介绍Python中的JSON模块
2015/04/08 Python
Python下rrdtool模块的基本使用方法
2015/11/13 Python
对Tensorflow中的变量初始化函数详解
2018/07/27 Python
Django模型序列化返回自然主键值示例代码
2019/06/12 Python
matplotlib 画双轴子图无法显示x轴的解决方法
2020/07/27 Python
世界领先的豪华床上用品供应商之一:Bedeck Home
2019/03/18 全球购物
Charles&Keith美国官方网站:新加坡快时尚鞋类和配饰零售商
2019/11/27 全球购物
Shell脚本如何向终端输出信息
2014/04/25 面试题
工商企业管理专业自荐信范文
2014/04/12 职场文书
产品发布会策划方案
2014/05/12 职场文书
幼儿园端午节活动方案
2014/08/25 职场文书
迎国庆演讲稿
2014/09/15 职场文书
母亲节感言
2015/08/03 职场文书
销售人员管理制度
2015/08/06 职场文书
HTML5 语义化标签(移动端必备)
2021/08/23 HTML / CSS
win11开机发生死循环重启怎么办?win11开机发生死循环重启解决方法
2022/08/05 数码科技