import os
status = os.system("ls -l")
os.system 创建子进程在系统上执行命令,只能获取命令的返回状态,命令的输出结果会直接打到 console 上
比如 status = os.system("ls -l")
如果执行成功 status 的值就是 0,但是 list 的内容是直接打到 console 而无法取到值
import os
f = os.popen("ls -l")
f.read() ## 返回所有输出
f.readline() ## 返回输出的下一行
f.readlines() ## 返回输出的剩下的所有行
popen 无法得到命令的返回状态,只能获取命令的输出
os.popen 实际是对 subprocess.Popen 的封装,可以直接使用 subprocess.Popen
import subprocess
f = subprocess.Popen("ls -l",
shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
f.stdout.read()
f.stdout.readline()
f.stdout.readlines()
f = subprocess.Popen("python", shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
f.stdin.write("print(\"test\")") ## 可以和命令进行交互
f.stdin.close()
f.stdout.read()
subprocess 在 python2 和 python3 提供的函数有区别,但 Popen 的功能是一样的
只用在 python2,在 python3 会被 subprocess 替代
import commands
commands.getoutput("ls -l") ## 只获得输出
commands.getstatusoutput("ls -l") ## 获得输出,还有返回状态
有 getstatus 命令,但似乎用不了,并不是获取返回状态
python3 的 subprocess 添加了一些函数,用以取代 commands
import subprocess
subprocess.getoutput("ls -l") ## 获得输出
subprocess.getstatusoutput("ls /") ## 获得输出,还有返回状态
原文:https://www.cnblogs.com/moonlight-lin/p/13694112.html