python自定义命令行
2025-07-23 18:59:25
发布于:浙江
命令行,如windows系统的cmd,powershell,都是非常强大的工具,他们不同于功能性软件那么局限性,而是多方面的。
命令行(Command Line)通常会有一个UI界面,且会有各种命令。
代码参考:
import subprocess
import tkinter as tk
from tkinter import ttk, messagebox
import sys
import os
import threading
messagebox.showinfo("PYTHON CUSTOM COMMAND LINE - WELCOME!","欢迎使用python自定义命令行!\nWelcome to use the 'PYTHON CUSTOM COMMAND LINE'!")
messagebox.showinfo("PYTHON CUSTOM COMMAND LINE - ANSSISTANCE","请键入‘help’来获得帮助。\nType 'help' for assistance.")
# 创建全局主窗口
root = tk.Tk()
root.withdraw() # 隐藏主窗口
# 创建一个事件用于线程间通信
stop_event = threading.Event()
def terminate_process(process_identifier):
"""终止指定进程,使用 tskill 命令"""
try:
if sys.platform.startswith('win'):
subprocess.run(
f'tskill {process_identifier}',
shell=True,
check=True
)
messagebox.showinfo("操作成功", f"已终止进程 (PID: {process_identifier})")
else:
messagebox.showerror("不支持的系统", "该命令仅在 Windows 系统下支持")
except subprocess.CalledProcessError as e:
messagebox.showerror("操作失败", f"终止进程时出错: {str(e)}")
def stop_command():
"""显示带终止功能的进程窗口(修复进程名称解析问题)"""
try:
# 初始化窗口
process_window = tk.Toplevel(root)
process_window.title("系统进程监控 - 可终止进程")
process_window.geometry("800x500")
# 创建搜索框
search_frame = ttk.Frame(process_window)
search_frame.pack(fill=tk.X, pady=5, padx=5)
search_entry = ttk.Entry(search_frame)
search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
def search_processes():
keyword = search_entry.get().lower()
for frame, name in process_frames:
if keyword in name.lower():
frame.pack(fill=tk.X, pady=2, padx=5)
else:
frame.pack_forget()
search_button = ttk.Button(search_frame, text="搜索", command=search_processes)
search_button.pack(side=tk.RIGHT, padx=5)
# 创建滚动框架
main_frame = ttk.Frame(process_window)
main_frame.pack(fill=tk.BOTH, expand=True)
canvas = tk.Canvas(main_frame)
scrollbar = ttk.Scrollbar(main_frame, orient=tk.VERTICAL, command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 获取系统进程(优化解析逻辑)
if sys.platform.startswith('win'):
process_cmd = ['tasklist', '/FO', 'CSV', '/NH'] # /NH 去除标题行
system_type = "windows"
elif sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
process_cmd = ['ps', 'aux', '--no-headers'] # 简洁格式,无标题
system_type = "unix"
else:
raise OSError("不支持的操作系统")
process_list = subprocess.check_output(
process_cmd, shell=(system_type == "windows"), text=True, stderr=subprocess.STDOUT
)
process_frames = []
# 解析并显示进程(修复名称提取错误)
for line in process_list.strip().split('\n'):
frame = ttk.Frame(scrollable_frame)
if system_type == "windows":
# 解析Windows的CSV格式:"Image Name","PID","Session Name"..."Mem Usage"
parts = [p.strip('"') for p in line.split(',')]
if len(parts) >= 2:
process_name = parts[0] # 正确提取第一个字段(Image Name)
identifier = parts[1] # 获取 PID
else:
continue # 跳过无效行
else:
# 解析Unix的ps aux格式:用户 PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
parts = line.split()
if len(parts) >= 8:
pid = parts[1]
process_name = ' '.join(parts[7:]) # 从第8列开始是完整命令行
identifier = pid
else:
continue # 跳过无效行
# 显示进程名称(明确宽度和对齐方式)
ttk.Label(frame, text=process_name, width=60, anchor=tk.W, wraplength=400).pack(side=tk.LEFT, padx=5)
# 终止按钮
def create_terminate_btn(ident=identifier):
btn = ttk.Button(frame, text="终止进程", style="危险.TButton")
btn.pack(side=tk.RIGHT, padx=5)
btn.bind("<Button-1>", lambda e: on_terminate_click(ident))
create_terminate_btn()
process_frames.append((frame, process_name))
frame.pack(fill=tk.X, pady=2, padx=5)
# 样式设置
style = ttk.Style()
style.configure("危险.TButton", foreground="red", borderwidth=1)
except subprocess.CalledProcessError as e:
messagebox.showerror("进程获取失败", f"命令执行错误:\n{e.output}")
except OSError as e:
messagebox.showerror("系统错误", f"不支持的操作系统:{str(e)}")
def on_terminate_click(identifier):
"""终止按钮点击事件处理(显示具体进程名)"""
result = messagebox.askyesno(
"确认终止",
f"是否真的要终止以下进程?\n标识符: {identifier}",
icon=messagebox.WARNING
)
if result:
terminate_process(identifier)
# 其他命令保持不变(start/echo/while/for/help/exit)
def start_command(process_name):
try:
if sys.platform.startswith('win'):
if process_name.lower() in ['cmd', 'powershell']:
subprocess.Popen(f'start {process_name}', shell=True)
else:
subprocess.Popen(process_name, shell=True)
else:
subprocess.Popen(process_name.split())
print(f"已启动:{process_name}")
except FileNotFoundError:
messagebox.showerror("启动失败", f"未找到程序:{process_name}")
except Exception as e:
messagebox.showerror("启动失败", f"启动程序时出错:{str(e)}")
def echo_command(content):
print(content)
def while_command(command):
global stop_event
try:
# 处理单行格式(while 条件: 代码)
if ':' in command:
# 拆分条件和循环体(只拆分第一个冒号)
prefix, body = command.split(':', 1)
condition = prefix.strip().lstrip('while').strip()
# 确保条件不为空
if not condition:
raise ValueError("缺少循环条件")
# 替换 echo 为 print
if body.strip().startswith('echo '):
body = 'print(' + body.strip()[len('echo '):] + ')'
# 构建带缩进的循环体(替换换行符为带缩进的换行)
indented_body = " " + body.strip().replace('\n', '\n ')
full_code = f"while {condition}:\n{indented_body}"
else:
# 处理多行输入(原逻辑,输入end结束)
condition = command.lstrip('while').strip()
print("请输入循环体代码(每行一条语句,输入 'end' 结束):")
indented_body = []
while True:
line = input()
if line.strip() == 'end':
break
# 替换 echo 为 print
if line.strip().startswith('echo '):
line = ' print(' + line.strip()[len('echo '):] + ')'
indented_body.append(line)
full_code = f"while {condition}:\n" + "\n".join(indented_body)
# 定义一个函数来执行代码
def run_loop():
try:
exec(full_code)
except SystemExit:
pass
# 创建一个线程来执行循环
loop_thread = threading.Thread(target=run_loop)
loop_thread.start()
# 等待循环线程结束或停止事件被设置
while loop_thread.is_alive():
if stop_event.is_set():
print("\n检测到键盘中断,停止循环...")
stop_event.clear()
break
loop_thread.join(timeout=0.1)
except ValueError as e:
print(f"格式错误:{e},示例:while True: echo 你好")
except Exception as e:
print(f"循环执行错误:{str(e)}")
def for_command(command):
global stop_event
try:
print("请输入循环体代码(输入 'end' 结束输入):")
loop_body = ""
while True:
line = input()
if line.strip() == "end":
break
# 替换 echo 为 print
if line.strip().startswith('echo '):
line = 'print(' + line.strip()[len('echo '):] + ')'
loop_body += line + "\n"
full_command = f"{command}:\n"
for line in loop_body.splitlines():
full_command += f" {line}\n"
# 定义一个函数来执行代码
def run_loop():
try:
exec(full_command)
except SystemExit:
pass
# 创建一个线程来执行循环
loop_thread = threading.Thread(target=run_loop)
loop_thread.start()
# 等待循环线程结束或停止事件被设置
while loop_thread.is_alive():
if stop_event.is_set():
print("\n检测到键盘中断,停止循环...")
stop_event.clear()
break
loop_thread.join(timeout=0.1)
except Exception as e:
print(f"循环执行错误:{str(e)}")
def help_command():
print("\n".join([
"=== 自定义命令行工具 ===",
"stop - 显示可终止的进程列表(每个进程后有终止按钮),支持搜索进程",
"start 程序 - 启动指定程序(Windows支持程序名,Linux需完整命令)",
"exit - 退出程序",
"echo 内容 - 输出文本内容",
"while 条件: 代码 - 执行Python风格while循环,支持单行和多行输入(多行输入以end结束)",
"for 变量 in 序列 - 执行Python风格for循环,需输入循环体(输入end结束)",
"killprocess 进程名 - 根据进程名终止进程(Windows 下使用 tskill)",
"pop_up_window(x,y,title='',message='',ico='',button='确定') - 弹出指定大小和配置的弹窗",
"** 注释 - 忽略注释",
"help - 显示帮助"
]))
def killprocess_command(process_name):
if sys.platform.startswith('win'):
try:
process_list = subprocess.check_output(
['tasklist', '/FO', 'CSV', '/NH'],
shell=True,
text=True,
stderr=subprocess.STDOUT
)
for line in process_list.strip().split('\n'):
parts = [p.strip('"') for p in line.split(',')]
if len(parts) >= 2 and parts[0].lower() == process_name.lower():
pid = parts[1]
terminate_process(pid)
return
messagebox.showerror("未找到进程", f"未找到名为 {process_name} 的进程")
except subprocess.CalledProcessError as e:
messagebox.showerror("获取进程列表失败", f"命令执行错误:\n{e.output}")
else:
messagebox.showerror("不支持的系统", "该命令仅在 Windows 系统下支持")
def pop_up_window(x, y, title='', message='', ico='', button='确定'):
try:
# 创建弹窗
popup = tk.Toplevel(root)
popup.title(title)
popup.geometry(f"{x}x{y}")
# 处理图标
ico_mapping = {
'info': messagebox.INFO,
'warning': messagebox.WARNING,
'error': messagebox.ERROR
}
if ico in ico_mapping:
ico_image = tk.Label(popup, text=ico_mapping[ico])
ico_image.pack(side=tk.LEFT, padx=10, pady=10)
# 显示消息
message_label = tk.Label(popup, text=message)
message_label.pack(padx=10, pady=10)
# 显示按钮
def close_popup():
popup.destroy()
button_widget = tk.Button(popup, text=button, command=close_popup)
button_widget.pack(side=tk.RIGHT, padx=10, pady=10)
except Exception as e:
print(f"弹出窗口时出错: {str(e)}")
if __name__ == "__main__":
# 分离命令行线程和GUI线程
def command_loop():
while True:
try:
command = input(">>> ").strip()
if command == "exit":
root.quit()
break
elif command == "stop":
stop_command()
elif command.startswith("start "):
start_command(command.split(" ", 1)[1])
elif command.startswith("echo "):
echo_command(command.split(" ", 1)[1])
elif command.startswith("while "):
while_command(command)
elif command.startswith("for "):
for_command(command)
elif command.startswith("killprocess "):
process_name = command.split(" ", 1)[1]
killprocess_command(process_name)
elif command.startswith("pop_up_window"):
try:
exec(command)
except Exception as e:
print(f"执行 pop_up_window 命令时出错: {str(e)}")
elif command.startswith("**"):
continue
elif command == "help":
help_command()
else:
print("未知命令,输入'help'获取帮助")
except KeyboardInterrupt:
print("\n检测到键盘中断,正在退出...")
stop_event.set()
root.quit()
break
command_thread = threading.Thread(target=command_loop)
command_thread.start()
root.mainloop()
root.destroy()
这个python自定义命令行可实现以下功能:
while循环
for循环
弹出弹窗
打开程序
结束某个程序
启动自制任务管理器
输出文本内容
以及最最最没用的注释
python的tkinter库。
messagebox函数可以弹出弹窗,包含于tkinter库。
但是导入不能这样导入:
import tkinter
必须这么导入:
from tkinter import messagebox
作者也这么错过
没有python编译器的点击链接下载即可。
https://secure.mydown.com/soft/351/717178351.shtml?f=bdj_975335
一定要记得点普通下载!!!
这里空空如也
有帮助,赞一个