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编程中对线程锁的使用
Jul 12 Python
简单谈谈Python中的几种常见的数据类型
Feb 10 Python
python学习笔记之列表(list)与元组(tuple)详解
Nov 23 Python
python的staticmethod与classmethod实现实例代码
Feb 11 Python
django请求返回不同的类型图片json,xml,html的实例
May 22 Python
PyTorch学习笔记之回归实战
May 28 Python
Python3用tkinter和PIL实现看图工具
Jun 21 Python
Python3的介绍、安装和命令行的认识(推荐)
Oct 20 Python
基于python修改srt字幕的时间轴
Feb 03 Python
Sentry错误日志监控使用方法解析
Nov 12 Python
python爬虫多次请求超时的几种重试方法(6种)
Dec 01 Python
django项目中使用云片网发送短信验证码的实现
Jan 19 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
substr()函数中文版
2006/10/09 PHP
Admin generator, filters and I18n
2011/10/06 PHP
Uncaught exception com_exception with message Failed to create COM object
2012/01/11 PHP
php定义一个参数带有默认值的函数实例分析
2015/03/16 PHP
php检查字符串中是否有外链的方法
2015/07/29 PHP
PHP获取数组中单列值的方法
2017/06/10 PHP
Ajax请求PHP后台接口返回信息的实例代码
2018/08/21 PHP
PHP 对象接口简单实现方法示例
2020/04/13 PHP
jQuery实现切换页面布局使用介绍
2011/10/09 Javascript
nodejs win7下安装方法
2012/05/24 NodeJs
JQuery EasyUI 日期控件如何控制日期选择区间
2014/05/05 Javascript
详细解密jsonp跨域请求
2015/04/15 Javascript
js实现跨域的4种实用方法原理分析
2015/10/29 Javascript
百度多文件异步上传控件webuploader基本用法解析
2016/11/07 Javascript
从零开始学习Node.js系列教程四:多页面实现数学运算的client端和server端示例
2017/04/13 Javascript
BootStrap模态框和select2合用时input无法获取焦点的解决方法
2017/09/01 Javascript
js删除数组中的元素delete和splice的区别详解
2018/02/03 Javascript
Express进阶之log4js实用入门指南
2018/02/10 Javascript
Vue 路由间跳转和新开窗口的方式(query、params)
2019/12/25 Javascript
关于javascript中的promise的用法和注意事项(推荐)
2021/01/15 Javascript
详解Python的Django框架中的templates设置
2015/05/11 Python
Python开发之Nginx+uWSGI+virtualenv多项目部署教程
2019/05/13 Python
浅谈pytorch池化maxpool2D注意事项
2020/02/18 Python
jupyter notebook 多环境conda kernel配置方式
2020/04/10 Python
在matplotlib中改变figure的布局和大小实例
2020/04/23 Python
浅谈keras通过model.fit_generator训练模型(节省内存)
2020/06/17 Python
python中使用np.delete()的实例方法
2021/02/01 Python
Html5剪切板功能的实现代码
2018/06/29 HTML / CSS
英国最大的天然和有机产品在线零售商之一:Big Green Smile
2020/05/06 全球购物
护士实习自我鉴定
2013/10/22 职场文书
留学推荐信怎么写
2014/01/25 职场文书
汉语言文学职业规划
2014/02/14 职场文书
群众路线个人剖析材料及整改措施
2014/11/04 职场文书
2015年度对口支援工作总结
2015/07/22 职场文书
幼儿园科学课教学反思
2016/03/03 职场文书
关于Nginx中虚拟主机的一些冷门知识小结
2022/03/03 Servers