在 main.py 中优化自动补全功能,支持路径补全并添加异常处理;更新退出命令逻辑,增加确认提示;新增对 Python 和 pip 命令的支持

This commit is contained in:
2025-04-17 15:00:40 +08:00
Unverified
parent 97eb1d992a
commit 12e26fefc8

60
main.py
View File

@@ -10,12 +10,25 @@ def get_simple_system_info():
# 自动补全功能,基于系统命令和当前目录的文件
def completer(text, state):
# 获取系统命令
commands = os.listdir('/bin') + os.listdir('/usr/bin') + os.listdir('/usr/local/bin')
# 获取当前目录的文件和文件夹
local_files = os.listdir(os.getcwd())
# 合并系统命令和当前目录的文件
matches = [cmd for cmd in commands + local_files if cmd.startswith(text)]
# 如果输入包含路径分隔符,则补全路径
if '/' in text:
dir_path, partial_file = os.path.split(text)
if not dir_path: # 如果路径为空,使用当前目录
dir_path = '.'
try:
# 获取指定路径下的文件和文件夹
entries = os.listdir(dir_path)
matches = [os.path.join(dir_path, entry) for entry in entries if entry.startswith(partial_file)]
except FileNotFoundError:
matches = []
else:
# 获取系统命令
commands = os.listdir('/bin') + os.listdir('/usr/bin') + os.listdir('/usr/local/bin')
# 获取当前目录的文件和文件夹
local_files = os.listdir(os.getcwd())
# 合并系统命令和当前目录的文件
matches = [cmd for cmd in commands + local_files if cmd.startswith(text)]
return matches[state] if state < len(matches) else None
# # 获取真正的 Last login 信息
@@ -43,12 +56,7 @@ def pseudo_zsh():
hostname = platform.node()
username = os.getlogin()
# 获取 IP 地址
try:
hostname = socket.gethostname()
ip_address = socket.gethostbyname_ex(hostname)[2][0] # 获取第一个 IP 地址
except (socket.gaierror, IndexError):
ip_address = "127.0.0.1" # 默认回环地址
# 获取内存信息
memory = psutil.virtual_memory()
@@ -68,34 +76,39 @@ def pseudo_zsh():
print(f"系统: {system_name}")
print(f"主机名: {hostname}")
print(f"用户: {username}")
print(f"IP 地址: {ip_address}")
print(f"内存: {used_memory}GB / {total_memory}GB ({memory_usage}%)")
print(f"CPU 使用率: {cpu_usage}%")
print(f"存储: {used_disk}GB / {total_disk}GB ({disk_usage}%)")
print("-" * 40)
subprocess.run("cd /", shell=True) # 切换到用户目录
subprocess.run(f"cd /{username}/", shell=True) # 切换到用户目录
while True:
try:
dir = os.getcwd()
if dir == '/':
CmdDir = '/'
elif re.match(dir, "/home/*"): # 用户目录下的任意文件夹
elif dir == f'/Users/{username}':
CmdDir = '~'
else:
CmdDir = dir
if dir.split('/')[-1] == 'PyShell':
CmdDir = 'Shell/'
# 显示提示符并获取用户输入
cmd = input(f"{CmdDir} > ")
# 如果输入特定命令 "exit",退出程序
if cmd.strip() == "exit":
print("zsh: 未找到命令: exit")
break
# 闻讯是否退出
confirm = input("退出PyShell (y/n): ").lower()
if confirm == 'y':
print("退出...")
exit(0)
else:
print("取消。")
continue
# 使用 shlex 分割用户输入为命令和参数
args = shlex.split(cmd)
@@ -145,6 +158,17 @@ def pseudo_zsh():
if args[0] == 'ping1':
subprocess.run(['ping','10.147.17.161'])
continue
if args[0] == 'python':
subprocess.run(['python3',args[1]])
continue
if args[0] == 'pip':
subprocess.run(['pip3',args[1]])
continue
if args[0] == 'py':
subprocess.run(['python3',args[1]])
continue
# if args[0] == 'sudo':
# flight1 = True
# a = 0