python程序中调用shell命令,是件很酷且常用的事情
今天来总结一下

 
1.使用os模块 的  system
        此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出状态
如果command有执行内容,会在标准输出显示。这实际上是使用C标准库函数system()实现的。
      system方法会创建子进程运行外部程序,方法只返回外部程序的运行状态。这个方法比较适用于外部程序没有输出结果的情况
>>> import os
>>> os.system('ls')
1.py                   51.29.txt        dead.letter  error.txt      yue.csv
1.txt                  anaconda-ks.cfg  dengji.sh    kefuTongji.sh
0
>>> a=os.system('ls')
1.py                   51.29.txt        dead.letter  error.txt      yue.csv
1.txt                  anaconda-ks.cfg  dengji.sh    kefuTongji.sh
>>> print a
0
 
 

2.os模块的popen方法

        打开一个与command进程之间的管道。
这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。
       当需要得到外部程序的输出结果时,本方法非常有用,返回一个类文件对象,调用该对象的read()或readlines()方法可以读取输出内容。
>>> os.popen('ls')
<open file 'ls', mode 'r' at 0x7f365a5075d0>
 
>>> print os.popen('ls').read()
1.py
1.txt
 
>>>a=os.popen('ls').readlines()
>>>print a
['1.py\n', '1.txt\n', '2016_11_28_access_log\n', '51.29.txt\n', 'anaconda-ks.cfg\n']
 
 

3.commands模块的  getoutput 方法

      这种方法同popend的区别在于popen返回的是一个类文件对象,而本方法将外部程序的输出结果当作字符串返回,很多情况下用起来要更方便些。

主要方法:

*   commands.getstatusoutput(cmd)         返回(status, output)
*   commands.getoutput(cmd)                   只返回输出结果
*   commands.getstatus(file)                     返回ls -ld file的执行结果字符串,调用了getoutput,不建议

>>> import commands

>>> commands.getstatusoutput('ls')

(0, '1.py\n1.txt\n2016_11_28_access_log\n51.29.txt\nanaconda-ks.cfg\ndata.txt\ndead.letter\ndengji.sh\ndiskJK,sh')

>>> commands.getoutput('ls')

'1.py\n1.txt\n2016_11_28_access_log\n51.29.txt\nanaconda-ks.cfg'

 
>>> commands.getstatus('1.py')=ippi
'-rwxr-xr-x 1 root root 69 Jan 19 14:22 1.py'
 
 

4.模块subprocess

subprocess意在替代其他几个老的模块或者函数,
比如:os.system os.spawn*  os.popen*  popen2.* commands.*

       根据Python官方文档说明,subprocess模块用于取代上面这些模块。有一个用Python实现的并行ssh工具—mssh,代码很简短,不过很有意思,它在线程中调用subprocess启动子进程来干活
 
subprocess.Popen('脚本/shell', shell=True)        无阻塞、和主程序并行运行
subprocess.call('脚本/shell', shell=True)              必须等待命令执行完毕
 
>>> import subprocess

>>> subprocess.Popen("ls")
1.py                   anaconda-ks.cfg  diskJK,sh      yue.csv
<subprocess.Popen object at 0x7fda1a0fcc50>
 
>>> a=subprocess.Popen("ls")
1.py                   anaconda-ks.cfg  diskJK,sh      yue.csv
>>> print a
<subprocess.Popen object at 0x7fda1a0fcc90>

>>>subprocess.Popen('. xxx.sh', stdout = subprocess.PIPE, shell = True).stdout.read()
'1.py\n1.txt\n2016_11_28_access_log\n51.29.txt\n'
 
  1. p = subprocess.Popen("python stdTest.py",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  2. sout = p.stdout.readlines()
  3. serr = p.stderr.readlines()
  4. print sout
  5. print serr
 
 
 
>>> subprocess.call("ls")
1.py                   anaconda-ks.cfg  diskJK,sh      yue.csv
 
>>> a=subprocess.call("ls")
1.py                   anaconda-ks.cfg  diskJK,sh      yue.csv
>>> print a
0
 
 
>>> from subprocess import call
>>> call(["ls","-l"])
total 2972
-rwxr-xr-x 1 root root     220 Jan 17 22:33 1.sh
 
 
 
总结一下:
1.os.system            命令行可以输出运行内容,但只能返回运行状态
2.os.popen             返回一个类文件对象,可以从此文件读取输出内容
3.commands.get    既能返回输出内容,也能返回运行结果状态
4.subprocess          既能返回输出内容,也能返回运行结果状态

Python 调用 Shell命令的更多相关文章

  1. python 调用 shell 命令方法

    python调用shell命令方法 1.os.system(cmd) 缺点:不能获取返回值 2.os.popen(cmd) 要得到命令的输出内容,只需再调用下read()或readlines()等   ...

  2. python 调用shell命令三种方法

    #!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器: #!/usr/bin/env python这种用法是为了防止操作系统用户没有将pyth ...

  3. python 调用 shell 命令

    记录 python 调用 shell 命令的方法 加载 os 模块, 使用 os 类 import os; os.system("ls /");

  4. 用Python调用Shell命令

    Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库,也当然可以用Python调用Shell命令. 用Python调用Shell命令有如下几种方式: 第一种 ...

  5. python 调用shell命令的方法

    在python程序中调用shell命令,是件很酷且常用的事情…… 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出 ...

  6. python调用shell命令

    1.subprocess介绍 官方推荐 subprocess模块,os.system(command) 这个废弃了 亲测 os.system 使用sed需要进行字符转义,非常麻烦 python3 su ...

  7. Python调用shell命令常用方法

    Python调用shell指令 方法一.使用os模块的system方法:os.system(cmd),其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,256表示未 ...

  8. (转载)python调用shell命令之os 、commands、subprocess

    linux系统下进入python交互式环境: 一.os 模块 1.1.os模块的exec方法簇: python交互界面中: In [1]: import os In [2]: os.exec os.e ...

  9. python调用shell命令之三慷慨法

    preface: 忙于近期的任务,须要用到libsvm的一些命令.如在终端执行java svm_train train_file model_file. pythonsubset.py file tr ...

随机推荐

  1. 快速回顾MySQL:汇总和分组

    10.3 汇总数据 我们经常需要汇总数据而不用把它们实际检索处出来,为此MySQL提供了专门的函数.使用这些函数,MySQL查询可用于检索数据,以便分析和报表的生成.这种类型的检索例子有以下几种: 确 ...

  2. 跟着知识追寻者学BeautifulSoup,你学不会打不还口,骂不还手

    一 前言 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库:其强大的提取能力让知识追寻者放弃了使用正则匹配查找HTML节点:Beautifu Soup 其能直接 ...

  3. dp-最大连续子序列的和

    https://www.felix021.com/blog/read.php?1587 什么是最大连续子序列和呢 ? 最大连续子序列和是所有子序列中元素和最大的一个 . 问题 : 给定一个序列 { - ...

  4. scratch3.0二次开发scratch3.0基本介绍(第一章)

    为什么要自己开发而不使用官方版本? 这个问题要看我们的做少儿编程教育的需求是怎么样的. scratch本身提供了离线版本以及官网在线平台供我们使用,这足以满足我们对于编程教学模块的需求.但是对于一些教 ...

  5. Linux.cp命令总提示是否覆盖

    执行cp命令,其实是默认执行了cp -i命令的别名,因此总提示是否覆盖. 修改~/.bashrc,注释“alias cp='cp -i'”即可. [root@xxxx test]# vi ~/.bas ...

  6. Java入门 - 语言基础 - 14.String类

    原文地址:http://www.work100.net/training/java-string.html 更多教程:光束云 - 免费课程 String类 序号 文内章节 视频 1 概述 2 创建字符 ...

  7. c#数字图像处理(二)彩色图像灰度化,灰度图像二值化

    为加快处理速度,在图像处理算法中,往往需要把彩色图像转换为灰度图像,在灰度图像上得到验证的算法,很容易移植到彩色图像上.24位彩色图像每个像素用3个字节表示,每个字节对应着R.G.B分量的亮度(红.绿 ...

  8. 认识Class -- 终于不在怂

    引子     本是新年,怎奈新冠肆掠,路上行人,男女老少几乎是全副口罩,形色匆匆:偶尔有一两个裸露口鼻的,估计都是没囤到口罩的,这几天药店几乎都是贴上大字:口罩没货.看着网络上病毒消息满天飞,我也响应 ...

  9. CSS-10-内边距

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  10. shiro中ecache-core版本引起的异常

    ecache-core包版本不对引起的错误,将2.5.3换成2.4.5就好了 来源 WARN [RMI TCP Connection(3)-127.0.0.1] - Exception encount ...