一、OS模块
(1) OS模块的system方法
用法:
① import os
② os.system("command")
返回值:命令的执行状态
缺点:无法获取命令的返回内容
二、commands模块
用法:
① import commands
② commands.getstatusoutput("command")
返回值:(执行状态, 输出内容)
要想分别获取执行状态和输出内容:
status = commands.getstatusoutput("command")[0]
output = commands.getstatusoutput("command")[1]
三、subprocess模块
用法:
① from subprocess import call
② call(["command"])
返回值:命令的执行状态
缺点:
① 无法获取命令的返回内容
② 命令和参数之间只要中间有空格就需要拆分开,例如:调用ls -al
call(["ls", "-al"])
总结:subprocess模块更像是system的替换,而commands模块调用shell命令更加全面。
本文详细介绍了在Python中使用OS模块、commands模块及subprocess模块调用Shell命令的方法,对比了各模块的优缺点,帮助读者理解如何在Python脚本中高效地执行外部命令。
2061

被折叠的 条评论
为什么被折叠?



