Python本身没有内置的DOS命令,但可以通过调用系统命令的方式实现类似的功能。在Windows系统中,可以使用os.system()
或subprocess
模块来执行DOS命令。以下是一些关于如何在Python中执行DOS命令的操作指南:
使用os模块执行DOS命令
import os # 执行简单的DOS命令 os.system('dir')
使用subprocess模块执行DOS命令
import subprocess # 执行简单的DOS命令,并获取输出 result = subprocess.run(['dir'], shell=True, capture_output=True, text=True) print(result.stdout)
调用外部批处理脚本
创建一个名为script.bat
的批处理文件,内容如下:
@echo off echo Hello from the batch script!
然后在Python代码中调用这个脚本:
import subprocess # 调用外部批处理脚本 result = subprocess.run(['script.bat'], shell=True, capture_output=True, text=True) print(result.stdout)
通过上述方法,你可以在Python中执行DOS命令,并根据需要选择合适的方法来处理命令输出或执行更复杂的命令链。