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正则表达式中的括号匹配问题
Dec 14 Python
在Linux系统上部署Apache+Python+Django+MySQL环境
Dec 24 Python
详解Python如何获取列表(List)的中位数
Aug 12 Python
python获取多线程及子线程的返回值
Nov 15 Python
Tensorflow 自带可视化Tensorboard使用方法(附项目代码)
Feb 10 Python
python使用Pycharm创建一个Django项目
Mar 05 Python
PyQt5每天必学之切换按钮
Aug 20 Python
pyqt5 comboBox获得下标、文本和事件选中函数的方法
Jun 14 Python
python的mysql数据库建立表与插入数据操作示例
Sep 30 Python
python循环输出三角形图案的例子
Nov 22 Python
django中url映射规则和服务端响应顺序的实现
Apr 02 Python
python执行js代码的方法
May 13 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使用SOAP调用.net的WebService数据
2013/11/12 PHP
PHP下载远程文件到本地存储的方法
2015/03/24 PHP
自己编写的类似JS的trim方法
2013/10/09 Javascript
解析JavaScript中的不可见数据类型
2013/12/02 Javascript
jQuery结合HTML5制作的爱心树表白动画
2015/02/01 Javascript
分享五个有用的jquery小技巧
2015/10/08 Javascript
微信小程序 教程之小程序配置
2016/10/17 Javascript
JavaScript 轮播图和自定义滚动条配合鼠标滚轮分享代码贴
2016/10/28 Javascript
使用jQuery的ajax方法向服务器发出get和post请求的方法
2017/01/13 Javascript
基于JQuery的购物车添加删除以及结算功能示例
2017/03/08 Javascript
JS验证input输入框(字母,数字,符号,中文)
2017/03/23 Javascript
javascript实现二叉树遍历的代码
2017/06/08 Javascript
JS作用域链详解
2017/06/26 Javascript
Vue.js实现实例搜索应用功能详细代码
2017/08/24 Javascript
Vue中mintui的field实现blur和focus事件的方法
2018/08/25 Javascript
解决vue props 拿不到值的问题
2018/09/11 Javascript
小程序server请求微信服务器超时的解决方法
2019/05/21 Javascript
简单介绍Python中用于求最小值的min()方法
2015/05/15 Python
python 实现对文件夹内的文件排序编号
2018/04/12 Python
pycharm 将django中多个app放到同个文件夹apps的处理方法
2018/05/30 Python
PyQT5 QTableView显示绑定数据的实例详解
2019/06/25 Python
TensorFlow通过文件名/文件夹名获取标签,并加入队列的实现
2020/02/17 Python
QML实现钟表效果
2020/06/02 Python
学习Python需要哪些工具
2020/09/04 Python
SneakerStudio英国:最佳运动鞋商店
2019/05/22 全球购物
李维斯牛仔裤荷兰官方网站:Levi’s NL
2020/08/23 全球购物
英语专业毕业生自荐信范文
2013/12/31 职场文书
医药工作岗位求职信分享
2013/12/31 职场文书
西安交大自主招生自荐信
2014/01/27 职场文书
大学自我评价
2014/02/12 职场文书
本科生就业推荐信
2014/05/19 职场文书
自我查摆剖析材料
2014/10/11 职场文书
2015年部门工作总结范文
2015/03/31 职场文书
被告答辩状范文
2015/05/22 职场文书
python爬虫请求库httpx和parsel解析库的使用测评
2021/05/10 Python
一文读懂navicat for mysql基础知识
2021/05/31 MySQL