在Python中,你可以使用subprocess
模块来执行DOS命令
import subprocess # 使用subprocess.run()执行DOS命令并等待完成 result = subprocess.run(["dir"], capture_output=True, text=True) # 打印命令输出 print(result.stdout)
在这个例子中,我们使用subprocess.run()
函数执行了一个简单的dir
命令,该命令会列出当前目录下的所有文件和文件夹。capture_output=True
参数表示我们希望捕获命令的输出,而text=True
参数表示我们希望将输出作为文本处理。
如果你需要执行多个命令,可以将它们作为列表传递给subprocess.run()
函数:
import subprocess # 使用subprocess.run()执行多个DOS命令并等待完成 result1 = subprocess.run(["dir"], capture_output=True, text=True) result2 = subprocess.run(["ipconfig"], capture_output=True, text=True) # 打印命令输出 print("Output of dir command:") print(result1.stdout) print("\nOutput of ipconfig command:") print(result2.stdout)
这个例子中,我们分别执行了dir
和ipconfig
命令,并打印了它们的输出。
注意:在使用subprocess
模块时,请确保你了解要执行的命令及其潜在的安全风险。避免执行不受信任的命令,以防止潜在的安全问题。