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的更多相关文章

  1. Testing shell commands from Python

    如何测试shell命令?最近,我遇到了一些情况,我想运行shell命令进行测试,Python称为万能胶水语言,一些自动化测试都可以完成,目前手头的工作都是用python完成的.但是无法从Python中 ...

  2. 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 ...

  3. 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 ...

  4. linux下Tab及shell 补全python

    Python自动补全 Python自动补全有vim编辑下和python交互模式下,下面分别介绍如何在这2种情况下实现Tab键自动补全. vim python自动补全插件:pydiction 可以实现下 ...

  5. shell如何向python传递参数,shell如何接受python的返回值

    1.shell如何向python传递参数 shell脚本 python $sendmailCommandPath $optDate python脚本 lastDateFormat = sys.argv ...

  6. Frequently Used Shell Commands

    [Common Use Shell Commands] 1.ps aux:查看当前所有进程 ,以用户名为主键.可以查看到 USER.PID.COMMAND(binary所有位置) 2.netstat ...

  7. shell脚本安装python、pip--这种写法是错误的---每一个命令执行完都要判断是否执行成功,否则无法进行下一步

    shell脚本安装python.pip--不需要选择安装项目--不管用总报错,必须带上判断符号,while没有这种用法,写在这里为了以后少走弯路,所以不要用下面的执行了 首先把pip-.tgz 安装包 ...

  8. 用户添加到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 ...

  9. shell脚本调用python模块

    python helloworld.py代码为 # coding:utf-8 from __future__ import print_function import sys print(sys.pa ...

随机推荐

  1. Linux云计算-01_介绍以及Linux操作系统安装

    1 学习目的 兴趣爱好 技能提升 找到满意的工作 2 什么是云计算 云计算(cloud computing)是分布式计算的一种,指的是通过网络"云"将巨大的数据计算处理程序分解成无 ...

  2. Ant Design Blazor 组件库的路由复用多标签页介绍

    最近,在 Ant Design Blazor 组件库中实现多标签页组件的呼声日益高涨.于是,我利用周末时间,结合 Blazor 内置路由组件实现了基于 Tabs 组件的 ReuseTabs 组件. 前 ...

  3. 利用C语言判别用户输入数的奇偶性和正负性

    要求:利用C语言判别用户输入数的奇偶性和正负性 提示:可以利用%求余数来判别 由题可知 我们需要if..else的结构来实现区分奇偶和正负 区分奇偶我们可以用: if (a % 2 == 0) { p ...

  4. codeforces 830E dp

    大致题意: n场比赛,k个钱币.赢一场获得一个钱币,输一场失去一个钱币,一旦钱币数量为2k个或者0个,就马上离开比赛.给出n个长度字符串,由W,D,L,?四个字符组成,W表示赢,L表示输,D表示平局, ...

  5. Linux 3.16 release 贡献度

    内核 3.16 release 的贡献度可以在下面网页看到: http://www.remword.com/kps_result/3.16_whole.html 一共发布了 12802 个补丁, 18 ...

  6. XCTF Normal_RSA

    这题本来算是很常规的rsa了,下载附件 发现有个公钥文件,还有一个加密文件,这种题之前有遇到一次,做法和这个类似,上次那个是用rsa的库,直接解的,这次直接用常规的,好像更简单,记录下模板 记事本打开 ...

  7. 如何用jmeter监控内存,CPU(1)

    要jmeter的运行环境配置好就可以: 打开这个小工具的步骤很简单,如果你已经配置好了Jmeter运行的环境,那么你也就不用去做其他的配置,直接 点击:开始-->运行-->输入cmd--& ...

  8. npm run start失败&Node.js 查询指定端口运行情况及终止占用端口办法

    缘由: node.js项目中运行npm run start命令脚本报错,No such file or directory 最开始以为是命令脚本找不到所谓的执行路径,但后面发现不是,是package. ...

  9. pxe+kickstart部署多个版本的Linux操作系统(下)---实践篇

        我们在企业运维环境中,难免会遇到使用多个Linux操作系统的情况,如果每天都需要安装不同版本的Linux系统的话,那么使用Kickstart只能安装一种版本的Linux系统的方法则显得有些捉襟 ...

  10. 刚刚进公司不会SVN 菜鸟感觉好蛋疼-----------SVN学习记

    这篇文章源于6月份给公司新人作的关于SVN使用的培训,转眼已经过了几个月的时间,丢了也怪可惜的,于是整理出来希望能够帮助后来人快速入门. 转载:https://blog.csdn.net/maplej ...