详解在Python中执行系统命令的方法


本文摘自php中文网,作者巴扎黑,侵删。

最近在做那个测试框架的时候发现对python执行系统命令不太熟悉,所以想着总结下,下面这篇文章主要给大家介绍了关于在Python中执行系统命令的方法,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库。在Python/wxPython环境下,执行外部命令或者说在Python程序中启动另一个程序的方法。

本文将详细介绍关于Python中如何执行系统命令的相关资料,下面话不多说了,来一起看看详细的介绍吧。

(1) os.system()

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


1

2

3

4

5

6

7

8

>>> 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()

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


1

2

3

4

5

6

7

8

9

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

>>> output

<open file 'cat /proc/cpuinfo', mode 'r' at 0x7ff52d831540>

>>> print output.read()

processor : 0

vendor_id : AuthenticAMD

cpu family : 21

... ...

>>><span style="font-size:14px;">

(3) commands模块


1

2

3

4

5

6

7

8

9

>>> 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*等方法的一个模块。


1

2

3

4

5

6

7

8

9

10

11

>>> import subprocess

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

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

<subprocess.Popen object at 0x7ff52d7ee490>

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

... ...

>>>

以上就是详解在Python中执行系统命令的方法的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python中关于四种字典合并方法的总结

Python安装流程指南

比较讲解Python中的*args和 **kwargs用法

Python如何初始化列表?

Python工作好找吗

Python全栈要学什么

Python中numpy的广播原则的代码解析

Python实现购物车的简单实例分享

Python爬虫任务接单渠道

使用Python将数组的元素导出到变量中(unpacking)

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...