Files
PyShell/main.py

60 lines
2.0 KiB
Python
Raw Normal View History

2025-04-02 10:53:37 +08:00
import subprocess
import readline
2025-04-02 10:56:24 +08:00
import os
import shlex
2025-04-02 08:01:33 +08:00
2025-04-02 10:56:24 +08:00
# 自动补全功能的实现
2025-04-02 10:53:37 +08:00
def completer(text, state):
2025-04-02 10:56:24 +08:00
# 获取系统中可执行命令的列表
2025-04-02 10:53:37 +08:00
commands = os.listdir('/bin') + os.listdir('/usr/bin') + os.listdir('/usr/local/bin')
2025-04-02 10:56:24 +08:00
# 根据用户输入的前缀匹配命令
2025-04-02 10:53:37 +08:00
matches = [cmd for cmd in commands if cmd.startswith(text)]
2025-04-02 10:56:24 +08:00
# 返回匹配的命令
2025-04-02 10:53:37 +08:00
return matches[state] if state < len(matches) else None
2025-04-02 08:01:33 +08:00
2025-04-02 10:56:24 +08:00
# 模拟一个简单的 zsh 终端
2025-04-02 10:53:37 +08:00
def pseudo_zsh():
2025-04-02 10:56:24 +08:00
# 配置 readline 的自动补全功能
2025-04-02 10:53:37 +08:00
readline.parse_and_bind("tab: complete")
readline.set_completer(completer)
while True:
try:
2025-04-02 10:56:24 +08:00
# 显示提示符并获取用户输入
2025-04-02 10:53:37 +08:00
cmd = input("20240915786@\u9648\u5764\u9633 ~ % ")
2025-04-02 10:56:24 +08:00
# 如果输入特定命令 "hexianglong",退出程序
2025-04-02 10:53:37 +08:00
if cmd.strip() == "hexianglong":
print("Exiting secret mode...")
break
2025-04-02 10:56:24 +08:00
# 使用 shlex 分割用户输入为命令和参数
2025-04-02 10:53:37 +08:00
args = shlex.split(cmd)
2025-04-02 10:56:24 +08:00
if not args: # 如果输入为空,跳过本次循环
2025-04-02 10:53:37 +08:00
continue
2025-04-02 10:56:24 +08:00
# 实现简单的 cd 命令
2025-04-02 10:53:37 +08:00
if args[0] == 'cd':
try:
2025-04-02 10:56:24 +08:00
os.chdir(args[1]) # 切换到指定目录
2025-04-02 10:53:37 +08:00
except IndexError:
2025-04-02 10:56:24 +08:00
print("cd: missing argument") # 缺少参数
2025-04-02 10:53:37 +08:00
except FileNotFoundError:
2025-04-02 10:56:24 +08:00
print(f"cd: no such file or directory: {args[1]}") # 目录不存在
2025-04-02 10:53:37 +08:00
continue
2025-04-02 10:56:24 +08:00
# 执行其他命令
2025-04-02 10:53:37 +08:00
try:
2025-04-02 10:56:24 +08:00
subprocess.run(args) # 调用系统命令
2025-04-02 10:53:37 +08:00
except FileNotFoundError:
2025-04-02 10:56:24 +08:00
print(f"zsh: command not found: {args[0]}") # 命令未找到
2025-04-02 10:53:37 +08:00
except KeyboardInterrupt:
2025-04-02 10:56:24 +08:00
# 捕获 Ctrl+C忽略中断
2025-04-02 10:53:37 +08:00
pass
except EOFError:
2025-04-02 10:56:24 +08:00
# 捕获 Ctrl+D忽略结束输入
2025-04-02 10:53:37 +08:00
pass
2025-04-02 08:01:33 +08:00
2025-04-02 10:56:24 +08:00
# 程序入口
2025-04-02 10:53:37 +08:00
if __name__ == "__main__":
pseudo_zsh()