在Python中执行命令行命令(CMD)可以通过多种方式实现,以下是使用`os`模块和`subprocess`模块的几种常见方法:
使用`os.system()`方法
`os.system()`方法可以直接调用系统shell来运行命令,并返回命令的退出状态码。
import os
os.system('dir') 运行dir命令并显示结果
使用`os.popen()`方法
`os.popen()`方法可以从一个命令打开一个管道,返回一个文件对象,可以读取命令的输出。
import os
with os.popen('dir', 'r') as f:
output = f.read()
print(output) 将输出打印出来
使用`subprocess.Popen()`方法
`subprocess.Popen()`提供了更丰富的功能,可以控制子进程的输入、输出和错误。
import subprocess
cmd = 'dir'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output = process.communicate()
print(output.decode()) 将输出解码为字符串并打印
使用`shutil.which()`函数
`shutil.which()`函数可以查找命令的可执行文件路径,避免因环境变量设置不同而导致命令找不到的问题。
import shutil
cmd = 'dir'
path = shutil.which(cmd)
if path:
print(f"Command '{cmd}' found at path: {path}")
else:
print(f"Command '{cmd}' not found")
异步执行CMD命令
使用`asyncio`和`subprocess`可以异步执行CMD命令。
import asyncio
import subprocess
async def run_cmd(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
print(f"[{cmd!r} exited with {proc.returncode}]")
if stdout:
print(f"[stdout]\n{stdout.decode()}")
if stderr:
print(f"[stderr]\n{stderr.decode()}")
运行异步命令
asyncio.run(run_cmd('dir'))
以上方法都可以用来在Python中执行CMD命令。选择哪种方法取决于你的具体需求,例如是否需要捕获命令输出、是否需要异步执行等