在Python中执行DOS命令,你可以使用`subprocess`模块或`os`模块。以下是使用`subprocess`模块执行DOS命令的示例:
import subprocess
def run_dos_command(command):
try:
使用 subprocess.run 执行命令
result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
打印命令执行结果
print(result.stdout.decode('utf-8'))
except Exception as e:
print(f"命令执行出错:{e}")
示例:执行 dir 命令
run_dos_command("dir")
如果你想指定一个特定的目录来执行命令,可以使用`os.system`函数,如下所示:
import os
def run_dos_command_with_directory(command, directory):
full_command = os.path.join(directory, command)
try:
使用 os.system 执行命令
os.system(full_command)
except Exception as e:
print(f"命令执行出错:{e}")
示例:在 C:\Users 目录下执行 dir 命令
run_dos_command_with_directory("dir", "C:\\Users")
请注意,使用`shell=True`参数时要格外小心,因为它可能会导致安全漏洞。确保你信任你传递给命令的参数,避免执行恶意代码。