方式一:os.system(command)
1、会将执行结果显示在控制台上
2、方法返回执行结果的状态码,默认情况下,执行成功返回0,执行失败返回1
3、参数command为字符串
4、该命令会开启一个子进程(subshell)去执行
脚本:
# -*- coding:utf-8 -*-
import os
s=os.system("dir")
#因为文件是以utf-8编码,所以对字符串做了一个转码操作
print("返回结果:".decode("UTF-8").encode("GBK"))
print(s)
执行结果:
驱动器 D 中的卷没有标签。
卷的序列号是 A25B-3CEA
D:\abc 的目录
2018/01/15 14:45 <DIR> .
2018/01/15 14:45 <DIR> ..
2018/01/15 14:43 202 free.py
2017/12/01 10:58 <DIR> logs
1 个文件 202 字节
3 个目录 154,370,527,232 可用字节
返回结果:
0
此处返回结果为:0
如果将命令改为一个无法执行的命令,例如nv,则执行结果为:
'nv' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
返回结果:
1
此处返回结果为1
方式二:os.popen()
格式:popen(command [, mode=’r’ [, bufsize]])
作用:该方法在执行命令的同时会打开一个管道流将输出内容返回给一个文件对象。(Open a pipe to/from a command returning a file object.)
脚本:
# -*- coding:utf-8 -*-
import os
s=os.popen("dir /b")
print("返回值:")
print(s)
print("\n返回值类型:")
print(type(s))
print("\n返回值内容:")
for line in s:
print(line)
执行结果:
返回值:
<open file 'dir /b', mode 'r' at 0x01E2D1D8>
返回值类型:
<type 'file'>
返回值内容:
free.py
logs
从上面的执行结果可知,os.popen()将命令的执行结果传输给了一个只读的文件对象。
方式三:commands模块
commands模块只针对于unix的操作系统,windows操作系统执行会报异常。
'{' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
具体用法:http://blog.youkuaiyun.com/sky6even/article/details/79064272