Python 运行 shell 获取输出结果的实例


Posted in Python onJanuary 07, 2019

首先使用内置模块os.

>>> import os
>>> code = os.system("pwd && sleep 2")
# /User/zhipeng
>>> print code
# 0

问题是 os.system 只能获取到结束状态

使用内置模块 subprocess

>>> import subprocess
>>> subprocess.Popen("pwd && sleep 2", shell=True, cwd="/home")
# <subprocess.Popen object at 0x106498310>
# /home

>>> sub = subprocess.Popen("pwd && sleep 2", shell=True, stdout=subprcess.PIPE)
>>> sub.wait()
>>> print sub.stdout.read()
# /User/zhipeng
subprocess.Popen还支持一些别的参数 
bufsize,executable=None, stdin=None, stdout=None, stderr=None 
preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None 
universal_newlines=False, startupinfo=None, creationflags=0

使用第三方模块 sh

# pip install sh
>>> from sh import ifconfig
>>> print ifconfig("eth0")

>>> from sh import bash
>>> bash("pwd")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/Library/Python/2.7/site-packages/sh.py", line 1021, in __call__
 return RunningCommand(cmd, call_args, stdin, stdout, stderr)
 File "/Library/Python/2.7/site-packages/sh.py", line 486, in __init__
 self.wait()
 File "/Library/Python/2.7/site-packages/sh.py", line 500, in wait
 self.handle_command_exit_code(exit_code)
 File "/Library/Python/2.7/site-packages/sh.py", line 516, in handle_command_exit_code
 raise exc(self.ran, self.process.stdout, self.process.stderr)
sh.ErrorReturnCode_126: 
 RAN: '/bin/bash ls'
 STDOUT:
 STDERR:
/bin/ls: /bin/ls: cannot execute binary file

# 不能这么用
>>> from sh import ls
>>> ls()
# hello.txt 1.txt
# ls -al
>>> ls(a=True, l=True)
# ls(al=True) 是不可以的

这操作太复杂了, 项目中使用也太糟心了, 也没有办法多个命令同时用.不过可以用别的方式代替

# bash -c command 可以很好的解决这个问题
# bash -c "sleep 1 && pwd"
>>> result = bash(c="pwd", _timeout=1, _cwd="/home")
>>> print result
# -rw-r--r--@ 1 zhipeng staff 0 10 13 18:30 hello.txt
# -rw-r--r--@ 1 zhipeng staff 0 10 13 18:30 1.txt

>>> result = bash(c="pwd", _timeout=1, _cwd="/")
>>> print result
# /
>>> bash(c="pwd && sleep 2", _timeout=1)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/Library/Python/2.7/site-packages/sh.py", line 1021, in __call__
 return RunningCommand(cmd, call_args, stdin, stdout, stderr)
 File "/Library/Python/2.7/site-packages/sh.py", line 486, in __init__
 self.wait()
 File "/Library/Python/2.7/site-packages/sh.py", line 498, in wait
 raise TimeoutException(-exit_code)
sh.TimeoutException
参数里面可以添加非命令参数. 需要以_开头, 例如上面的_timeout, _cwd. 详见sh.py 源码 

还支持以下参数 

internal_bufsize, err_bufsize, tee, done, in, decode_errors, tty_in, 
out, cwd, timeout_signal, bg, timeout, with, ok_code, err, env, no_out,

参考:

https://github.com/amoffat/sh/blob/master/sh.py
https://github.com/amoffat/sh

以上这篇Python 运行 shell 获取输出结果的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python根据出生日期获得年龄的方法
Mar 31 Python
完美解决python遍历删除字典里值为空的元素报错问题
Sep 11 Python
Django1.7+python 2.78+pycharm配置mysql数据库
Oct 09 Python
解决python3 urllib中urlopen报错的问题
Mar 25 Python
Python3 中文文件读写方法
Jan 23 Python
python中for循环输出列表索引与对应的值方法
Nov 07 Python
Python图像滤波处理操作示例【基于ImageFilter类】
Jan 03 Python
使用Python检测文章抄袭及去重算法原理解析
Jun 14 Python
Pandas+Matplotlib 箱式图异常值分析示例
Dec 09 Python
Python模块_PyLibTiff读取tif文件的实例
Jan 13 Python
浅析Django 接收所有文件,前端展示文件(包括视频,文件,图片)ajax请求
Mar 09 Python
Python csv文件记录流程代码解析
Jul 16 Python
在python 中实现运行多条shell命令
Jan 07 #Python
Python之使用adb shell命令启动应用的方法详解
Jan 07 #Python
python 对多个csv文件分别进行处理的方法
Jan 07 #Python
python 同时运行多个程序的实例
Jan 07 #Python
python实现将多个文件分配到多个文件夹的方法
Jan 07 #Python
在python中使用with打开多个文件的方法
Jan 07 #Python
python读取文件名并改名字的实例
Jan 07 #Python
You might like
php 随机数的产生、页面跳转、件读写、文件重命名、switch语句
2009/08/07 PHP
php使用mkdir创建多级目录入门例子
2014/05/10 PHP
使用PHP json_decode可能遇到的坑与解决方法
2017/08/03 PHP
CodeIgniter框架钩子机制实现方法【hooks类】
2018/08/21 PHP
jQuery.extend 函数的详细用法
2012/06/27 Javascript
ko knockoutjs动态属性绑定技巧应用
2012/11/14 Javascript
Jquery 模板数据绑定插件的使用方法详解
2013/07/08 Javascript
jquery next nextAll nextUntil siblings的区别介绍
2013/10/05 Javascript
Jquery实现兼容各大浏览器的Enter回车切换输入焦点的方法
2014/09/01 Javascript
js读取cookie方法总结
2014/10/31 Javascript
微信WeixinJSBridge API使用实例
2015/05/25 Javascript
javascript实现的字符串与十六进制表示字符串相互转换方法
2015/07/17 Javascript
thinkphp实现无限分类(使用递归)
2015/12/19 Javascript
Node.js+Express配置入门教程
2016/05/19 Javascript
第三篇Bootstrap网格基础
2016/06/21 Javascript
JS回调函数简单用法示例
2017/02/09 Javascript
JS拉起或下载app的实现代码
2017/02/22 Javascript
Bootstrap Table使用整理(二)
2017/06/09 Javascript
详解JS实现系统登录页的登录和验证
2019/04/29 Javascript
vue路由权限校验功能的实现代码
2020/06/07 Javascript
python使用Tkinter显示网络图片的方法
2015/04/24 Python
Python中使用插入排序算法的简单分析与代码示例
2016/05/04 Python
浅谈Python NLP入门教程
2017/12/25 Python
详解python 拆包可迭代数据如tuple, list
2017/12/29 Python
Python字典循环添加一键多值的用法实例
2019/01/20 Python
Python八皇后问题解答过程详解
2019/07/29 Python
Numpy将二维数组添加到空数组的实现
2019/12/05 Python
解决pycharm中导入自己写的.py函数出错问题
2020/02/12 Python
python绘制封闭多边形教程
2020/02/18 Python
JD Sports马来西亚:英国领先的运动鞋和运动服饰零售商
2018/03/13 全球购物
精灵市场:Pixie Market
2019/06/18 全球购物
银行实习鉴定
2013/12/13 职场文书
图书室管理制度
2014/01/19 职场文书
财务管理职业生涯规划书
2014/02/26 职场文书
单位租房协议范本
2014/12/03 职场文书
党员进社区活动总结
2015/05/07 职场文书