在Python中控制CMD命令行,你可以使用`os`模块或`subprocess`模块。以下是使用这两种模块控制CMD命令行的方法:
使用`os`模块
`os`模块提供了`os.system()`函数,可以直接调用系统shell来运行命令。
import os
os.system('ping www.example.com') 运行ping命令
使用`subprocess`模块
`subprocess`模块提供了更丰富的功能,可以控制子进程的输入、输出和错误。
import subprocess
cmd = 'dir' 命令字符串
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) 创建子进程
output = process.communicate() 获取子进程的输出
print(output.decode()) 将输出解码为字符串并打印
使用`cmd`模块
`cmd`模块允许你创建一个命令行界面,可以自定义命令和交互。
from cmd import Cmd
class BingCmd(Cmd):
prompt = 'BingCmd> '
def print_log(self, argv):
print('la la la')
def do_bing(self, argv):
self.print_log(argv)
def help_bing(self):
print('just print la la la')
if __name__ == '__main__':
BingCmd().cmdloop() 运行交互式命令行界面
使用`shutil.which()`函数
`shutil.which()`函数可以查找命令的可执行文件路径,避免因环境变量设置不同而导致命令找不到的问题。
import shutil
cmd = 'dir'
path = shutil.which(cmd) 获取命令路径
if path:
os.system(f'{path} 运行命令')
else:
print('命令未找到')
以上是使用Python控制CMD命令行的一些方法。你可以根据具体需求选择合适的方法