一种简洁的python指令处理脚本

基本代码

如果想增加功能,可以在功能区直接声明新的函数,然后改一下大纲和入口。

python3 复制代码
import re

# 大纲 

def print_help():
     print("""[help
     输入指令以执行。
     输入"."以退出。
     hello : 示例功能,输出"Hello World"
     in [str] [str] : 示例功能,接收两个字符串
     """)

# 功能区

def f1():
    print("Hello World")

def f2(s1, s2):
    print(f"收到字符串{s1}和{s2}")

#入口

while True:
    cmd = input("\n_ ")
    if cmd == ".":
        break
    elif cmd == "hello":
        f1()
    elif s := re.match(r"in (\S+) (\S+)", cmd):
        f2(s.group(1), s.group(2))
    else:
        print_help()

静态化

增加一个设计,可以在执行之前决定一定要执行哪些指令。

python 复制代码
import re

# 大纲 

def print_help():
     print("""[help]
     输入指令以执行。
     输入"."以退出。
     hello : 示例功能,输出"Hello World"
     in [str] [str] : 示例功能,接收两个字符串
     """)

# 功能区

def f1():
    print("Hello World")

def f2(s1, s2):
    print(f"收到字符串{s1}和{s2}")

#入口

def process(cmd):
    if cmd == ".":
        return False
    elif cmd == "hello":
        f1()
    elif s := re.match(r"in (\S+) (\S+)", cmd):
        f2(s.group(1), s.group(2))
    else:
        print_help()
    return True

def run_script():
    while True:
        cmd = input("_")
        if not process(cmd)
            break

# 静态测试

process("hello")

# 启用脚本

run_script()
相关推荐
ZhengEnCi3 小时前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风8 小时前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风9 小时前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling1 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook1 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风1 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风1 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei2 天前
python 抽象基类
python
用户8356290780512 天前
Python 实现 PPT 转 HTML
后端·python