Run Shell Commands in Python
subprocess.call
This is the recommended way to run shell commands in Python compared with old-fashioned os module.
This is a realtime method, which means you can get the shell output on the fly, compared with following "subprocess.check_output" method, which collect all output in its return value.
This method return the return value of the command, for example:
ret = subprocess.call('ls -l')
where ret=0, while
ret = subprocess.call('cd aaa')
ret=2 when there isn't "aaa" subfolder under CWD.
For ease of use, write a shorthand function:
import subprocess
def run(cmd):
ret = subprocess.call(cmd, shell=True)
if ret != 0:
sys.exit('Exec cmd %s error, return value: %s' %(cmd, str(ret)))
Then you can simply use "run(cmd)" as a shell interface. "run" print command stdout stderr to console stdout, and if there's something wrong during execution, we interrupt it.
subprocess.check_output
A more safe way to run shell command is using "check_output" function. If the return value if not 0, a exception raised, otherwise return the command output.
$ cat myrun.py
import subprocess
def run(cmd):
return subprocess.check_output(cmd, shell=True)
$ python -i myrun.py
>>> ret = run('ls -l|grep donno')
>>> ret
'drwxr-xr-x 6 chad chad 4096 Jan 26 18:18 donno-0.1.10\n-rw-r--r-- 1 chad chad 8716 Jan 27 15:53 donno-0.1.10.tar.gz\n'
>>> ret = run('cd aaa')
/bin/sh: 1: cd: can't cd to aaa
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "shtest.py", line 3, in run
return subprocess.check_output(cmd, shell=True)
File "/usr/lib/python2.7/subprocess.py", line 544, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'cd aaa' returned non-zero exit status 2
subprocess.Popen
If you want some more powerful tools, use this. You can't use pipe directly in this form. Instead, You have to use subprocess.PIPE:
>>> import subprocess
>>> lsres = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
>>> grepres = subprocess.Popen(['grep', 'Do'], stdin=lsres.stdout, stdout=subprocess.PIPE)
>>> res = grepres.communicate()
communicate() interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. It returns a tuple (stdoutdata, stderrdata).
Full solution of running shell command
If you want realtime output, while saving output and return code in variables, you should use Popen:
from subprocess import Popen, PIPE, STDOUT
cmd = 'vmstat 2 3'
cmd2 = 'exit 3' p = Popen(cmd, close_fds=True, shell=True, stdout=PIPE, stderr=STDOUT) line = ''
while p.poll() is None:
out = p.stdout.read(1)
if out=='\n':
print(line)
line = ''
else:
line = line + out
print('--------\nret is: %d' % p.returncode)
The Popen.stdout is a file object, so its "read(size)" method here means read every 1 byte.
"close_fds=True" is maybe unnecessary, but I keep it for safe.
os.system
If it's unnecessary to save command output, this is most convenient way. The output will output to console. You can use space and pipe in command:
>>> import os
>>> ret = os.system('ls -l|grep D')
And it will return after the command complete:
>>> ret = os.system('vmstat 3 3')
os.popen
Use this form if you want to save command output.
>>> retfile = os.popen('pwd')
>>> ret = retfile.read()
>>> ret
'/home/lichao\n'
>>> retfile
<open file 'pwd', mode 'r' at 0xb74aad30>
or write it more compact:
>>> result = os.popen('ls|grep enex').read()
Deprecated
commands.getoutput()
commands.getstatusoutput()
Run Shell Commands in Python的更多相关文章
- Testing shell commands from Python
如何测试shell命令?最近,我遇到了一些情况,我想运行shell命令进行测试,Python称为万能胶水语言,一些自动化测试都可以完成,目前手头的工作都是用python完成的.但是无法从Python中 ...
- The Linux Mint 18.1:Eclipse Run The C++ And Python ConfigorationWhen You achieve above step,you can run the c++ and python! (Next OTL ,PYOTL is Project That Write By Ruimin Shen(ability man) )
# Copyright (c) 2016, 付刘伟 (Liuwei Fu)# All rights reserved.# 转载请注明出处 1.Install The Eclipse,g++ Use T ...
- The Linux Mint 17.1:Eclipse Run The C++ And Python Configoration
p { margin-bottom: 0.1in; line-height: 120% } # Copyright (c) 2016, 付刘伟 (Liuwei Fu)# All rights rese ...
- linux下Tab及shell 补全python
Python自动补全 Python自动补全有vim编辑下和python交互模式下,下面分别介绍如何在这2种情况下实现Tab键自动补全. vim python自动补全插件:pydiction 可以实现下 ...
- shell如何向python传递参数,shell如何接受python的返回值
1.shell如何向python传递参数 shell脚本 python $sendmailCommandPath $optDate python脚本 lastDateFormat = sys.argv ...
- Frequently Used Shell Commands
[Common Use Shell Commands] 1.ps aux:查看当前所有进程 ,以用户名为主键.可以查看到 USER.PID.COMMAND(binary所有位置) 2.netstat ...
- shell脚本安装python、pip--这种写法是错误的---每一个命令执行完都要判断是否执行成功,否则无法进行下一步
shell脚本安装python.pip--不需要选择安装项目--不管用总报错,必须带上判断符号,while没有这种用法,写在这里为了以后少走弯路,所以不要用下面的执行了 首先把pip-.tgz 安装包 ...
- 用户添加到sudoer列表## Allow root to run any commands anywhere root ALL=(ALL) ALL Iron ALL=(ALL) ALL
将用户添加到sudoer列表 李序锴关注 2017.12.20 15:03:25字数 605阅读 4,067 默认情况下,linux没有将当前用户列入到sudoer列表中(在redhat系列的linu ...
- shell脚本调用python模块
python helloworld.py代码为 # coding:utf-8 from __future__ import print_function import sys print(sys.pa ...
随机推荐
- Linux云计算-04_Linux用户及权限管理
Linux是一个多用户的操作系统,引入用户,可以更加方便管理Linux服务器,系统默认需要以一个用户的身份登录,而且在系统上启动进程也需要以一个用户身份器运行,用户可以限制某些进程对特定资源的权限控制 ...
- hdu 1556 Color the ball 线段树 区间更新
水一下 #include <bits/stdc++.h> #define lson l, m, rt<<1 #define rson m+1, r, rt<<1|1 ...
- MyBatis框架的使用解析!数据库相关API的基本介绍
动态SQL if 根据条件包含where子句的一部分 <select id="findActiveBlogLike" resultType="Blog"& ...
- Jenkins 进阶篇 - 权限配置
Jenkins的授权策略 Jenkins 默认的授权策略是[登录用户可以做任何事],也就是人人都是管理员,可以修改所有的设置以及构建所有的任务,不用做任何设置,有账号登录到 Jenkins 系统即可, ...
- TCP/UDP/HTTP的区别和联系(转载)
一.TPC/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据. 关于TCP/IP和HTTP协议的关系,网络有一段比较容易理解的介绍:"我们在传 ...
- bugkuCTF
这题说实话我一脸懵逼,计网还没学的我,瑟瑟发抖,赶紧去百度. 思路分析: 涉及到域名解析,也就是dns服务,看了看writeup,都是修改host文件,百度了下host文件的作用,才明白了 host文 ...
- buu 简单注册器
一.本身对安卓逆向这块不是很熟悉,为了看这题稍微了解了一下,原来安卓虚拟机解释运行的是dex文件,和java的字节码不一样,然后是smail语法,这块我不会,所以找个了个神器来反编译2333,然后这题 ...
- 华为高级研究员谢凌曦:下一代AI将走向何方?盘古大模型探路之旅
摘要:为了更深入理解千亿参数的盘古大模型,华为云社区采访到了华为云EI盘古团队高级研究员谢凌曦.谢博士以非常通俗的方式为我们娓娓道来了盘古大模型研发的"前世今生",以及它背后的艰难 ...
- Kotlin Coroutine(协程): 二、初识协程
@ 目录 前言 一.初识协程 1.runBlocking: 阻塞协程 2.launch: 创建协程 3.Job 4.coroutineScope 5.协程取消 6.协程超时 7.async 并行任务 ...
- Django基础010--ORM操作
orm返回的数据有两种,QuerySet,object 1.QuerySet支持链式编程,可以在all()后面继续.方法 teachers = models.Teacher.objects.all() ...