python调用shell命令-python调用shell命令小结
在写python脚本的时候,经常需要调用系统命令,常用的python调用系统命令的方法主要有subprocess.call和os.popen。默认情况下subprocess.call的方法结果是返回值,即1或0,而os.popen则是命令运行的结果,可以用readlines(读取所有行,返回数组)或者read(读读取所有行,返回str)来读取。
subprocess类总主要的方法有:
subprocess.call:开启子进程,开启子进程,运行命令,默认结果是返回值,不能try
subprocess.check_call:运行命令,默认结果是返回值,可以try
subprocess.check_out(2.7中才有这个方法) 开启子进程,运行命令,可以获取命令结果,可以try
subprocess.Popen 开启子进程,运行命令,没有返回值,不能try,可以获取命令结果
subprocess.PIPE 初始化stdin,stdout,stderr,表示与子进程通信的标准流
Popen.poll 检查子进程是否结束,并返回returncode
Popen.wait等待子进程是否结束,并返回retrurncode
比如check_call的sample:
import subprocess
import traceback
cmd='hadoop fs -ls hdfs://xxxxx'
try:
e=subprocess.check_call(cmd,shell=True,stdout=subprocess.PIPE)
print "return code is: %s"%(str(e))
#print stdout.read()
except Exception,re:
print "message is:%s" %(str(re))
traceback.print_exc()
分析subprocess的源码:
class CalledProcessError(Exception): #首先定义了一个exception,用来在check_call和 check_output中raise exception
def __init__(self, returncode, cmd, output=None):
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
..........
def call(*popenargs, **kwargs):
return Popen(*popenargs, **kwargs).wait() #call方法调用wait
def check_call(*popenargs, **kwargs):
retcode = call(*popenargs, **kwargs) #调用call,返回返回值
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd) #可以抛出异常
return 0
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate() #获取标准输出和标准错误输出
retcode = process.poll() #检查子进程是否结束,并返回returncode
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output
有时候我们需要在运行命令时可以获取返回值,获取结果,并且能够try。
可以对上面的代码进行组合
# -*- coding: utf8 -*-
import exceptions
import subprocess
import traceback
class CalledCommandError(Exception):
def __init__(self, returncode, cmd, errorlog,output):
self.returncode = returncode
self.cmd = cmd
self.output = output
self.errorlog = errorlog
def __str__(self):
return "命令运行错误:'%s',返回值: %s,错误信息: %s" % (self.cmd, str(self.returncode) ,self.errorlog)
def run_command_all(*popenargs, **kwargs):
allresult = {}
cmd = popenargs[0]
if 'stdout' in kwargs or 'stderr' in kwargs :
raise ValueError('标准输出和标准错误输出已经定义,不需设置。')
process = subprocess.Popen(stdout=subprocess.PIPE,shell=True,stderr = subprocess.PIPE,*popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
#print retcode,cmd,unused_err,output
raise CalledCommandError(cmd,retcode,errorlog=unused_err,output=output)
allresult['cmd'] = cmd
allresult['returncode'] = retcode
allresult['errorlog'] = unused_err
allresult['outdata'] = output
return allresult
if __name__ == '__main__':
cmd = 'hadoop fs -ls xxxx|wc -l'
try:
e=run_command_all(cmd)
print "ok"
except Exception,re:
print (str(re))
print "failed"
traceback.print_exc()
©著作权归作者所有:来自51CTO博客作者菜菜光的原创作品,如需转载,请注明出处,否则将追究法律责任
调用python shell命令dev
python调用shell命令-python调用shell命令小结相关推荐
- python调用shell命令-「Python」6种python中执行shell命令方法
用Python调用Shell命令有如下几种方式: 第一种: os.system("The command you want"). 这个调用相当直接,且是同步进行的,程序需要阻塞并等 ...
- Python语言学习:利用python语言实现调用内部命令(python调用Shell脚本)—命令提示符cmd的几种方法
Python语言学习:利用python语言实现调用内部命令(python调用Shell脚本)-命令提示符cmd的几种方法 目录 利用python语言实现调用内部命令-命令提示符cmd的几种方法 T1. ...
- python 执行shell_用Python调用Shell命令
Python经常被称作"胶水语言",因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库,也当然可以用Python调用Shell命令. 用Python调用Shell命令有如 ...
- python调用adb shell命令_如何在python脚本里面连续执行adb shell后面的各种命令
如何在python脚本里面连续执行adb shell后面的各种命令 adb shell "cd /data/local && mkdir tmp" adb shel ...
- 在beeline中执行Linux命令,python - 从python脚本执行beeline命令时出现“找不到beeline命令”错误(从oozie shell操作调用) - 堆栈内存溢出...
我有一个要使用oozie计划的python脚本. 我正在使用Oozie shell动作来调用脚本. 脚本中有一条直线指令. 运行oozie工作流程时,出现错误" sh:beeline:命令未 ...
- python调用shell命令-python中执行shell命令的几个方法小结
最近有个需求就是页面上执行shell命令,第一想到的就是os.system, 复制代码 代码如下: os.system('cat /proc/cpuinfo') 但是发现页面上打印的命令执行结果 0或 ...
- python调用php命令行,python调用php函数 python怎样调用php文件中的函数详解
前言 python调用php代码实现思路:php文件可通过在terminal中使用php命令行进行调用,因此可使用python开启子进程执行命令行代码.函数所需的参数可通过命令行传递. 测试环境 1. ...
- python 调用linux命令-Python 执行Linux系统命令的N种方法
前言: 很多时候我们会用到python去调用外部工具/命令去实现某种功能. I. os https://docs.python.org/2/library/os.html os.system 执行流程 ...
- python调用shell该引用到什么类_python调用shell, shell 引用python
标签: python 调用 shell get_line_num="wc -l as_uniq_info | awk '{print $1}'" ###get the lines ...
最新文章
- matplotlib画图绘制辅助线
- java juc包多线程编程案例:Executor入门示例
- 开篇词丨这样学Redis,才能技高一筹
- 贪心 Codeforces Round #273 (Div. 2) C. Table Decorations
- idea使用svn拉取项目代码_使用 IDEA 搭建 Hadoop3.1.1 项目
- 我与“顶级工程师”距离有多远?
- 企业级实际性能测试案例与经验分享
- C# 类与对象(面向对象的编程)
- 当知识图谱遇上预训练语言模型
- 177.第N高的薪水
- Chrome浏览器安装Axure插件教程
- TCP/UDP 协议格式
- IE疑难杂症之已取消网页导航--该站点安全证书的吊销信息不可用
- 韦小宝是咱IT人!理由有8!!
- cocos2d实现语音_【Cocos Creator与C++知识分享】Creator接入呀呀语音SDK
- Javamail使用IMAP同步QQ自定义文件夹问题
- BigBrother的大数据之旅 Day 4 Linux(4)
- 信息学奥赛一本通|1309:【例1.6】回文数(Noip1999)
- 三星java世界x108_三星 X108:其他
- VScode报错内容:Already included file name