Python 运行 shell 获取输出结果的实例
作者:zhipeng-python 发布时间:2023-08-02 16:51:18
标签: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
来源:https://blog.csdn.net/u012731379/article/details/78856318
0
投稿
猜你喜欢
- 最近在使用Python开发系统,需连接mysql数据库,我用的是Python3连接MySQL8.0,其中老是报错以下问题:网上给了各种各样的
- 最近项目中需要与管易云erp做对接,看了他的接口文档,php的示例代码,于是用python仿写。其中传的参数data中前面几个json数据是
- <?php $link=mysql_connect("localhost",&
- 上一篇自动在Windows中运行Python脚本并定时触发功能实现传送门链接运行Python脚本:.bat文件在Windows中,.bat文
- 输入:数字m mm,n nn输出:m mm行n nn列的数字蛇形方阵1. 从方阵最左上角开始,顺时针向内填充。初始化一个m mm行n nn列
- 类的代码: define('QR_MODE_NUL', -1); define('QR_MODE_NUM',
- 1、为什么要设置headers?在请求网页爬取的时候,输出的text信息中会出现抱歉,无法访问等字眼,这就是禁止爬取,需要通过反爬机制去解决
- 计算Python Numpy向量之间的欧氏距离,已知vec1和vec2是两个Numpy向量,欧氏距离计算如下:import numpydis
- python实现猫捉老鼠小游戏首界面开始游戏界面然后键盘操作小老鼠上下左右移动,猫自己去追,当猫追上老鼠则游戏结束这里用时3.2秒,最后将游
- 用css属性选择器可以有选择性地对链接样式进行控制,如让所有的外部链接都加一个小图标来标识其是一外部链接。但用css有弊端: 1、只支持Fi
- Python自带一个轻量级的关系型数据库SQLite。这一数据库使用SQL语言。SQLite作为后端数据库,可以搭配Python建网站,或者
- SQL Server Extended Events(下面简称XEvent)是SQL Server 2008里新加的事件处理系统,用来取代S
- 如下所示:def getWordPattern(word): pattern = [] usedLetter={} count=0 for
- 本文实例为大家分享了PyQt5实现暗黑风格的计时器的具体代码,供大家参考,具体内容如下主要是学习多线程知识,使用的是QTime(),但是似乎
- 本文实例讲述了php7 图形用户界面GUI 开发。分享给大家供大家参考,具体如下:一、下载指定系统扩展http://pecl.php.net
- 简介memory_profiler是第三方模块,用于监视进程的内存消耗以及python程序内存消耗的逐行分析。它是一个纯python模块,依
- CSS Hack是在标准CSS没办法兼容各浏览器显示效果时才会用上的补救方法,在各浏览器厂商解析CSS没有达成一致前,我们只能用这样的方法来
- 如果你想进一步了解如何用JavaScript来为网页添加交互性的话,你也许已经听过JavaScript的事件代理(event delegat
- 一、什么是NumPyNumpy--Numerical Python,是一个基于Python的可以存储和处理大型矩阵的库。几乎是Python
- Nocalhost是一种开发者工具,支持针对Kubernetes应用程序进行调试和部署。使用Nocalhost进行Python开发需要完成以