使用Python执行系统命令方法

lnh2017 · 2018-11-02 16:30:45 · 2086 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2018-11-02 16:30:45 的主题,其中的信息可能已经有所发展或是发生改变。

Python是一款操作简单的编程语言,内置丰富的库,能够很容易的实现强大的功能,在使用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

... ...

>

以上是列举的python执行系统命令的方法,如果需要这方面的操作,可以参考一下!


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2086 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传