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

首先使用内置模块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 获取输出结果的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • python 执行shell命令并将结果保存的实例

    方法1: 将shell执行的结果保存到字符串 def run_cmd(cmd): result_str='' process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result_f = process.stdout error_f = process.stderr errors = error_f.read() if errors: pass result_str =

  • python中执行shell命令的几个方法小结

    最近有个需求就是页面上执行shell命令,第一想到的就是os.system, 复制代码 代码如下: os.system('cat /proc/cpuinfo') 但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了. 尝试第二种方案 os.popen() 复制代码 代码如下: output = os.popen('cat /proc/cpuinfo') print output.read() 通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的

  • Python实现获取命令行输出结果的方法

    本文实例讲述了Python实现获取命令行输出结果的方法.分享给大家供大家参考,具体如下: Python获取命令行输出结果,并对结果进行过滤找到自己需要的! 这里以获取本机MAC地址和IP地址为例! # coding: GB2312 import os, re # execute command, and return the output def execCmd(cmd): r = os.popen(cmd) text = r.read() r.close() return text # wri

  • python 捕获 shell/bash 脚本的输出结果实例

    #!/usr/bin/python ## get subprocess module import subprocess   ## call date command ## p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True)   ## Talk with date command i.e. read data from stdout and stderr. Store this info in tuple #

  • python中执行shell的两种方法总结

    一.使用python内置commands模块执行shell commands对Python的os.popen()进行了封装,使用SHELL命令字符串作为其参数,返回命令的结果数据以及命令执行的状态: 该命令目前已经废弃,被subprocess所替代: # coding=utf-8 ''' Created on 2013年11月22日 @author: crazyant.net ''' import commands import pprint def cmd_exe(cmd_String): p

  • python执行使用shell命令方法分享

    1. os.system(shell_command) 直接在终端输出执行结果,返回执行状态0,1 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出状态,如果command有执行内容,会在标准输出显示.这实际上是使用C标准库函数system()实现的. 缺点:这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果. os.system('cat /etc/passwdqc.conf') 2. os.popen()

  • Python下调用Linux的Shell命令的方法

    有时候难免需要直接调用Shell命令来完成一些比较简单的操作,比如mount一个文件系统之类的.那么我们使用Python如何调用Linux的Shell命令?下面来介绍几种常用的方法: 1. os 模块 1.1. os模块的exec方法族 Python的exec系统方法同Unix的exec系统调用是一致的.这些方法适用于在子进程中调用外部程序的情况,因为外部程序会替换当前进程的代码,不会返回.( 这个看了点 help(os)  --> search "exec" 的相关介绍,但是没

  • python 捕获shell脚本的输出结果实例

    import subprocess output =Popen(["mycmd","myarg"], stdout=PIPE).communicate()[0] import subprocess p = subprocess.Popen(['ls','-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() print out # work on Unix/Li

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

    首先使用内置模块os. >>> import os >>> code = os.system("pwd && sleep 2") # /User/zhipeng >>> print code # 0 问题是 os.system 只能获取到结束状态 使用内置模块 subprocess >>> import subprocess >>> subprocess.Popen("p

  • python执行shell获取硬件参数写入mysql的方法

    本文实例讲述了python执行shell获取硬件参数写入mysql的方法.分享给大家供大家参考.具体分析如下: 最近要获取服务器各种参数,包括cpu.内存.磁盘.型号等信息.试用了Hyperic HQ.Nagios和Snmp,它们功能都挺强大的,但是于需求不是太符,亦或者太heavy. 于是乎想到用python执行shell获取这些信息,python执行shell脚本有以下三种方法: 1. os.system() 复制代码 代码如下: os.system('ls') #返回结果0或者1,不能得到

  • Python之自动获取公网IP的实例讲解

    0.预备知识 0.1 SQL基础 ubuntu.Debian系列安装: root@raspberrypi:~/python-script# apt-get install mysql-server Redhat.Centos 系列安装: [root@localhost ~]# yum install mysql-server 登录数据库 pi@raspberrypi:~ $ mysql -uroot -p -hlocalhost Enter password: Welcome to the Ma

  • python和shell获取文本内容的方法

    这两天搞脚本,花费不少时间. Python和Shell都可以获取文本内容,网上许多资料介绍的都不具体.简单的使用Python和Shell写了脚本. 做一些笔记沉淀一下. 1.Python实现: #-*- encoding:UTF-8 -*- filehandler = open('f.txt','r') #以读方式打开文件,rb为二进制方式(如图片或可执行文件等) print filehandler.read() #读取整个文件 filehandler.close() #关闭文件句柄 2.She

  • python 爬虫 批量获取代理ip的实例代码

    实例如下所示: import urllib.request import os, re,sys,time try: from StringIO import StringIO except ImportError: from io import StringIO loca = re.compile(r"""ion":"\D+", "ti""") #伪装成浏览器 header = {'User-Agent':

  • python根据时间获取周数代码实例

    时间 时间和周数 import time import datetime # 获取今天是第几周 print(time.strftime('%W')) # 获取当前是周几(0-6,0代表周一) today=datetime.datetime.now().weekday() # 获取指定日期属于当年的第几周 week=datetime.datetime.strptime('20190825','%Y%m%d').strftime('%W') 获取下周的时间范围 import datetime,cal

  • 获取python运行输出的数据并解析存为dataFrame实例

    在学习xg的 时候,想画学习曲线,但无奈没有没有这个 evals_result_ AttributeError: 'Booster' object has no attribute 'evals_result_' 因为不是用的分类器或者回归器,而且是使用的train而不是fit进行训练的,看过源码fit才有evals_result_这个,导致训练后没有这个,但是又想获取学习曲线,因此肯定还需要获取训练数据. 运行的结果 上面有数据,于是就想自己解析屏幕的数据试一下,屏幕可以看到有我们迭代过程的数

  • Python 从subprocess运行的子进程中实时获取输出的例子

    有些时候,我们需要将某些程序放到子进程中去运行,以达到整合系统的目的.在Python中,一个非常好的选择就是使用subprocess模块,本模块为开辟子进程去执行子程序提供了统一的接口,更加便于学习和使用. 同时,对于在子进程里的程序,我们希望能够实时获取其输出,以在主进程中打印相关信息,使我们能够了解当前子程序的执行进度.对此,subprocess模块也提供了相应的参数,能够将子程序的标准输出和标准错误输出返回给主程序. 下面,我们就通过一个例子来说明这个功能.首先,我们需要一个用于模拟标准输

  • shell获取目录下所有文件夹的名称并输出的实例

    获取指定目录/usr/下所有文件夹的名称并输出: shell代码: #!/bin/bash #方法一 dir=$(ls -l /usr/ |awk '/^d/ {print $NF}') for i in $dir do echo $i done ####### #方法二 for dir in $(ls /usr/) do [ -d $dir ] && echo $dir done ##方法三 ls -l /usr/ |awk '/^d/ {print $NF}' ## 其实同方法一,直接

随机推荐