前言:

很多时候我们会用到python去调用外部工具/命令去实现某种功能。

I. os

https://docs.python.org/2/library/os.html

os.system

执行流程

system(command) -> exit_status

Execute the command (a string) in a subshell.

# os.system() 是新起一个shell去干活的,对系统的开销比较大

# 仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息

# 无法控制,(如果调用的外部命令,挂死或者执行时间很长),主进程无法控制os.system(), 因为调用os.system(cmd) 调用进程会block, until os.system() 自己退出

In [30]: import os

In [31]: os.system('ls *.py')

check_drive_usage.py diff_file.py fcSpider.py fedspider.py get_host_list.py test.py while.py

Out[31]: 0

os.popen

执行流程

popen(command [, mode='r' [, bufsize]]) -> pipe

Open a pipe to/from a command returning a file object.

# 该方法不但执行命令还返回执行后的信息对象

# 好处在于:将返回的结果赋于一变量,便于程序的处理

In [32]: py = os.popen('ls *py').readlines()

In [33]: print py

['check_drive_usage.py ', 'diff_file.py ', 'fcSpider.py ', 'fedspider.py ', 'get_host_list.py ', 'test.py ', 'while.py ']

II. commands

https://docs.python.org/2/library/commands.html

常用的主要有两个方法:getoutput和getstatusoutput

In [40]: import commands

In [41]: commands.getoutput('ls *.py')

Out[41]: 'check_drive_usage.py diff_file.py fcSpider.py fedspider.py get_host_list.py test.py while.py'

In [41]: commands.getstatusoutput('ls *py')

Out[41]:

(0,

'check_drive_usage.py diff_file.py fcSpider.py fedspider.py get_host_list.py test.py while.py')

III. subprocess [ 推荐使用 ]

https://docs.python.org/2/library/subprocess.html

http://python.usyiyi.cn/python_278/library/subprocess.html

# 运用对线程的控制和监控,将返回的结果赋于一变量,便于程序的处理

# 会自动地加载系统环境变量。

subprocess模块主要用于替代以下几个模块函数

os.system

os.spawn*

os.popen*

popen2.*

commands.*

相对应的subprocess 模块里有 call 函数和 popen 函数 。

1、subprocess.call

call 函数的用法如下:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

可以看出,相对于os模块中的函数,这里可以指定的选项更多。

In [64]: import subprocess

In [65]: subprocess.call('ls *py ',shell=False)

check_drive_usage.py diff_file.py fcSpider.py fedspider.py get_host_list.py test.py while.py

Out[65]: 0

交互式模式下,call 也会有returncode 0 输出,不过在py文件里执行时,ruturn的结果并不会将最后的 0 输出。不过在使用call 函数时,需要注意后面的几个参数:

开启shell=True是不安全的

Using shell=True can be a security hazard. See the warning under Frequently Used Arguments for details.

Note:

尽量不要启用标准输出和标准错误输出需要管道,call有可能会导致子进程死锁。如需管道时,请使用Popen函数

Do not use stdout=PIPE or stderr=PIPE with this function as that can deadlock based on the child process output volume. Use Popen with the communicate() method when you need pipes.

subprocess.call 主要用于替换 os.system ,具体如下:

In [66]: subprocess.call('date')

Thu Oct 29 16:02:24 CST 2015

Out[66]: 0

sub.process.Popen的用法如下:

subprocess.Popen(args, bufsize=0, 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)

eg:

In [67]: import subprocess

In [68]: p = subprocess.Popen('ls *.py', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

In [69]: print p.stdout.readlines()

['check_drive_usage.py ', 'diff_file.py ', 'fcSpider.py ', 'fedspider.py ', 'get_host_list.py ', 'test.py ', 'while.py ']

python 调用linux命令-Python 执行Linux系统命令的N种方法相关推荐

  1. 在Linux命令行发送电子邮件附件的两种方法

    需 求 本文使用Centos7操作系统. 需要有一个工作正常的邮件系统.本文将不介绍如何配置邮件服务器. 1.使用mail命令 安装mailx安装包 [root@localhost ~]# yum - ...

  2. python调用shell命令-Python调用shell命令常用方法(4种)

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

  3. java代码执行linux命令_java执行Linux命令的方法

    本文实例讲述了java执行Linux命令的方法.分享给大家供大家参考.具体实现方法如下: public class StreamGobbler extends Thread { InputStream ...

  4. python调用shell命令-python调用shell命令小结

    在写python脚本的时候,经常需要调用系统命令,常用的python调用系统命令的方法主要有subprocess.call和os.popen.默认情况下subprocess.call的方法结果是返回值 ...

  5. cuda安装linux命令,ubuntu下安装cuda的两种方法

    1. 安装方法1 对.其实底部已经有安装说明了,这里再详细说明一下. 首先肯定是将.deb安装包下载到本地. 然后使用ctrl+alt+F1进入终端,使用如下命令关掉图形用户界面: sudo serv ...

  6. python调用shell命令-python中执行shell命令的几个方法小结

    最近有个需求就是页面上执行shell命令,第一想到的就是os.system, 复制代码 代码如下: os.system('cat /proc/cpuinfo') 但是发现页面上打印的命令执行结果 0或 ...

  7. python调用shell命令-Python怎么运行shell脚本

    Python作为一门脚本语言,有时候需要与shell命令交互式使用,在Python中提供了很多的方法可以调用并执行shell脚本,本文介绍几个简单的方法. Python怎么运行shell脚本 一.os ...

  8. execl执行linux命令,execl执行Linux命令

    相关函数:execle, execlp, execv, execve, execvp 1.表头文件: #include 2.函数定义: int execl(const char *path, cons ...

  9. linux命令history作用,Linux命令:history命令历史的管理及用法

    bash可以保存的过去曾经执行过的命令.当某个用户登录到shell中,会读取该用户家目录中的~/.bash_history文件,并将历史命令列表保存到内存中.当用户退出当前shell时,会将内存中的历 ...

  10. Linux系统中运行.sh文件的几种方法

    在Linux系统中执行.sh文件的几种方法: 1. cd到.sh文件所在的目录,然后执行./xxx.sh   [前提:该./sh文件要有可执行的权限,chmod u+x xxx.sh]  2. 在任何 ...

最新文章

  1. 找对业务G点, 体验酸爽 - PostgreSQL内核扩展指南
  2. css中颜色的表示方法
  3. 一种新的图像清晰度评价函数,数字图像清晰度评价函数的研究与改进
  4. .net 怎么使用github_如何正确的使用ncnn的Extractor
  5. java模拟器百度_Java模拟实现百度文档在线浏览
  6. 马斯克脑机接口_如何看待“马斯克:脑机接口或一年内植入人脑,可修复任何大脑问题”?...
  7. C/C++基础面试-Const的全面理解(C部分)
  8. iPhone 12不附赠耳机!代工厂股份大跌5%,负责人:无线耳机销量将上涨
  9. java manager 模式_java设计模式之装饰器模式(Decorator)
  10. 使用汉化版srvinstw.exe安装/卸载Windows系统服务
  11. C#使用ITextSharp操作pdf
  12. 机器人的分类、发展史、现状及国内外发展趋势
  13. 使用面包板的一点小注意
  14. 统计推断——假设检验中 p 值的含义具体是什么?
  15. Python—遇到的问题,使用PyPDF2转化pdf时候遇到的各种问题。
  16. 循环闹钟c语言,闹钟设置四天一个循环,自定义周期循环提醒便签
  17. 电阻、电容及电感的高频等效电路及特性曲线
  18. python中最小公倍数函数_python求最大公约数和最小公倍数的简单方法
  19. 插件!crx插件包下载网址与安装方法!!
  20. 前端知识总结汇总!(HTML、CSS、JS、jQuery、vue、微信小程序)

热门文章

  1. C++编程练习(5)----“实现简单的循环队列的顺序存储结构“
  2. Go-ethereum源码解析-Part I
  3. word文档内容如何防止被复制
  4. MultiBinding的StringFormat参数问题
  5. vim编辑器高级应用
  6. Java多线程Socket在控制台输出的多人聊天室编程
  7. redis搭建与安装2
  8. 《怎样解题》-波利亚
  9. Tomcat+Apache 负载均衡
  10. UnityVS(Visual Studio Tools For Unity)的安装与使用