python运行系统(Linux)命令的四种做法

os.system

示例:

cmd = 'ls -l'
os.system(cmd)

os.system会在命令行上显示具体的命令结果

os.popen

有时我们需要获取到具体的命令输出结果进行处理,而os.system很难做到这种情况,因此我们需要使用os.popen,
示例:

import os
cmd = 'ls -l'
result = os.popen(cmd)
for o in result.readlines():
	print o

commands模块

commands不仅可以获取命令的运行结果内容,还可以获取命令的结果状态。
示例:

import commands
# 获取执行状态和执行结果
the_status, the_output = commands.getstatusoutput('ls -l') # the_status为0表示运行成功,the_status不为0表示运行失败
# 只获取执行结果
the_output2 = commands.getoutput('ls -l')

subprocess

subprocess模块会创建新的进程用来执行命令,还可以编辑系统输入输出流实现与程序段的交互。

示例:

# 在shell运行,并且将运行结果返回给result,result为0表示执行成功,result不为0表示执行失败
result = subprocess.call('ls -l aaabcdea.txt', shell=True)

# 执行命令并且获取执行结果
result = subprocess.Popen('ls -l', stdout=subprocess.PIPE, shell=True)
# 输出执行结果
print result.stdout.readlines()

# 执行命令并且在输入流中输入相关信息完成命令的执行
result = subprocess.Popen('python hello.py', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
result.stdin.write('hello world\n')
print result.stdout.read()
#