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中的super()方法使用简介
Aug 14 Python
python的random模块及加权随机算法的python实现方法
Jan 04 Python
Python中static相关知识小结
Jan 02 Python
python 不以科学计数法输出的方法
Jul 16 Python
Python在for循环中更改list值的方法【推荐】
Aug 17 Python
win10下tensorflow和matplotlib安装教程
Sep 19 Python
在pandas多重索引multiIndex中选定指定索引的行方法
Nov 16 Python
python f-string式格式化听语音流程讲解
Jun 18 Python
详解tensorflow2.x版本无法调用gpu的一种解决方法
May 25 Python
python删除某个目录文件夹的方法
May 26 Python
python 引用传递和值传递详解(实参,形参)
Jun 05 Python
Python OpenCV中的numpy与图像类型转换操作
Dec 11 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
根德Grundig S400/S500/S700电路分析
2021/03/02 无线电
推荐25款php中非常有用的类库
2014/09/29 PHP
Windows7下的php环境配置教程
2015/02/28 PHP
PHP内核探索之变量
2015/12/22 PHP
PHP框架自动加载类文件原理详解
2017/06/06 PHP
清除网页历史记录,屏蔽后退按钮!
2008/12/22 Javascript
Javascript 遍历对象中的子对象
2009/07/03 Javascript
js 居中漂浮广告
2010/03/21 Javascript
javascrip客户端验证文件大小及文件类型并重置上传
2011/01/12 Javascript
『jQuery』取指定url格式及分割函数应用
2013/04/22 Javascript
JS分页控件 可用于无刷新分页
2013/07/23 Javascript
Js实现当前点击a标签变色突出显示其他a标签回复原色
2013/11/27 Javascript
JavaScript中闭包的写法和作用详解
2016/06/29 Javascript
AngularJS优雅的自定义指令
2016/07/01 Javascript
标准的js无缝滚动效果
2016/08/30 Javascript
基于JS实现checkbox全选功能实例代码
2016/10/31 Javascript
详解前端自动化工具gulp自动添加版本号
2016/12/20 Javascript
Jquery获取radio选中的值
2017/05/05 jQuery
使用D3.js创建物流地图的示例代码
2018/01/27 Javascript
node.js部署之启动后台运行forever的方法
2018/05/23 Javascript
Nodejs监听日志文件的变化的过程解析
2019/08/04 NodeJs
基于jQuery拖拽事件的封装
2020/11/29 jQuery
VUE中鼠标滚轮使div左右滚动的方法详解
2020/12/14 Vue.js
Python Trie树实现字典排序
2014/03/28 Python
python实现zencart产品数据导入到magento(python导入数据)
2014/04/03 Python
python批量提交沙箱问题实例
2014/10/08 Python
python实现查找两个字符串中相同字符并输出的方法
2015/07/11 Python
Python Flask-web表单使用详解
2017/11/18 Python
python数据持久存储 pickle模块的基本使用方法解析
2019/08/30 Python
查看端口并杀进程python脚本代码
2019/12/17 Python
十佳护士获奖感言
2014/02/18 职场文书
新闻学专业大学生职业生涯规划范文
2014/03/02 职场文书
义和团口号
2014/06/17 职场文书
总经理司机岗位职责
2015/04/10 职场文书
2015年妇幼保健工作总结
2015/05/19 职场文书
2015年小学重阳节活动总结
2015/07/29 职场文书