Python中执行Shell命令的两种方法:commands与subprocess

小满
小满
发布时间:2026-10-11 | 2人浏览过
原创

本文总结了Python中执行Shell命令的两种主要方法:已废弃的commands模块和官方推荐的subprocess模块。commands模块封装了os.popen(),返回结果与状态;subprocess模块功能更强大,支持多进程、标准输入输出及错误处理,并可通过Popen指定参数。文章提供了两种方法的代码示例及注意事项。

Python执行Shell命令的方法演进

在Python中执行外部Shell命令,早期版本主要依赖commands模块,而现代Python开发则推荐使用subprocess模块。了解这两者的区别与用法,有助于编写更稳定、高效的脚本。

方法一:使用commands模块(已废弃)

commands模块是对os.popen()函数的封装,它接收Shell命令字符串作为参数,并返回命令的执行结果及执行状态。尽管该模块简单易用,但它目前已被Python官方标记为废弃(deprecated)。

以下是使用commands模块执行命令的示例代码:

# coding=utf-8
'''
Created on 2013年11月22日
 
@author: crazyant.net
'''
import commands
import pprint
 
def cmd_exe(cmd_String):
  print "will exe cmd,cmd:"+cmd_String
  return commands.getstatusoutput(cmd_String)
 
if __name__=="__main__":
  pprint.pprint(cmd_exe("ls -la"))

方法二:使用subprocess模块(推荐)

subprocess模块是Python官方推荐的执行外部命令的方式,它替代了commands模块以及os.system、os.spawn*、os.popen*和popen2.*等旧方法。该模块功能强大,支持创建多个子进程,并可指定子进程的标准输入、标准输出和错误输出管道,从而获取详细的输出结果和执行状态。

通过Popen类,可以灵活地指定stdin和stdout为变量,直接接收输出值。以下是封装subprocess模块的示例代码,支持路径切换、超时判断及标准输出/错误读取:

# coding=utf-8
'''
Created on 2013年11月22日
 
@author: crazyant.net
'''
import shlex
import datetime
import subprocess
import time
 
def execute_command(cmdstring, cwd=None, timeout=None, shell=False):
  """执行一个SHELL命令
      封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr
      参数:
    cwd: 运行命令时更改路径,如果被设定,子进程会直接先更改当前路径到cwd
    timeout: 超时时间,秒,支持小数,精度0.1秒
    shell: 是否通过shell运行
  Returns: return_code
  Raises: Exception: 执行超时
  """
  if shell:
    cmdstring_list = cmdstring
  else:
    cmdstring_list = shlex.split(cmdstring)
  if timeout:
    end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
  
  #没有指定标准输出和错误输出的管道,因此会打印到屏幕上;
  sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)
  
  #subprocess.poll()方法:检查子进程是否结束了,如果结束了,设定并返回码,放在subprocess.returncode变量中 
  while sub.poll() is None:
    time.sleep(0.1)
    if timeout:
      if end_time <= datetime.datetime.now():
        raise Exception("Timeout:%s"%cmdstring)
      
  return str(sub.returncode)
 
if __name__=="__main__":
  print execute_command("ls")

总结

虽然commands模块使用简单,但由于其已被废弃,建议在新的Python项目中使用subprocess模块。它提供了更丰富的功能,如多进程支持、标准输入输出处理以及超时控制,能够满足更复杂的脚本需求。

以上就是Python中执行Shell命令的两种方法总结的详细内容,更多关于Python Shell命令的资料请关注本站其它相关文章!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表