Python是一门非常不错的编程语言,语法清晰、功能强大、内置丰富的库,那么你知道如何使用Python执行系统命令吗?我们来看看详细的方法吧。

  1. os.system()

  这个方法直接调用标准C的system()函数,仅仅在一个子终端运行系统命令,而不能获取执行返回的信息。

  >>> import os

  >>> output = os.system('cat /proc/cpuinfo')

  processor : 0

  vendor_id : AuthenticAMD

  cpu family : 21

  ... ...

  >>> output # doesn't capture output

  0

  2. os.popen()

  这个方法执行命令并返回执行后的信息对象,是通过一个管道文件将结果返回。

  >>> output = os.popen('cat /proc/cpuinfo')

  >>> output

  >>> print output.read()

  processor : 0

  vendor_id : AuthenticAMD

  cpu family : 21

  ... ...

  >>>

  3. commands模块

  >>> import commands

  >>> (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')

  >>> print output

  processor : 0

  vendor_id : AuthenticAMD

  cpu family : 21

  ... ...

  >>> print status

  0

  注意1:在类unix的系统下使用此方法返回的返回值(status)与脚本或命令执行之后的返回值不等,这是因为调用了os.wait()的缘故,具体原因就得去了解下系统wait()的实现了。需要正确的返回值(status),只需要对返回值进行右移8位操作就可以了。

  注意2:当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess。

  4. subprocess模块

  该模块是一个功能强大的子进程管理模块,是替换os.system, os.spawn*等方法的一个模块。

  >>> import subprocess

  >>> subprocess.Popen(["ls", "-l"]) # python2.x doesn't capture output

  >>> subprocess.run(["ls", "-l"]) # python3.x doesn't capture output

  >>> total 68

  drwxrwxr-x 3 xl xl 4096 Feb 8 05:00 com

  drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Desktop

  drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Documents

  drwxr-xr-x 2 xl xl 4096 Jan 21 07:44 Downloads

  ... ...

  >>>

©著作权归作者所有:来自51CTO博客作者mb5fd1925b5d585的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. 推荐一种Python安装的方法
  2. 如何找到属于自己高效学习方法?
  3. Pyecharts制作地图的几种方法评析
  4. 词云图的几种制作方法评测,你pick哪款
  5. 上班摸鱼系列|Python开发命令行斗地主
  6. Python一行命令生成数据分析报告
  7. 便捷搭建 Zookeeper 服务器的方法,好用,收藏~
  8. 自学系列 | 就谈自学方法!
  9. Linux学习之linux的find命令如何使用?

随机推荐

  1. 图解 Class 文件结构
  2. 《深入理解 Java 虚拟机·第三版》读书笔
  3. 常见 JVM dump 指令整理
  4. 抽点时间写篇文章都是享受
  5. 学C Day-2
  6. 翻一翻 Java 的发展史,闻一闻那浓厚的咖啡
  7. 【Demo见真章】投稿赢HarmonyOS手机Beta
  8. 《MyBatis从入门到精通》读书笔记
  9. JVM 面试题解答(40道全)
  10. 到底什么是脏读和幻读?为啥网上答案不一?