一种简洁的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()
相关推荐
码农小韩4 分钟前
基于Linux的C++学习——动态数组容器vector
linux·c语言·开发语言·数据结构·c++·单片机·学习
木风小助理5 分钟前
`mapfile`命令详解:Bash中高效的文本至数组转换工具
开发语言·chrome·bash
彼岸花开了吗12 分钟前
构建AI智能体:八十、SVD知识整理与降维:从数据混沌到语义秩序的智能转换
人工智能·python·llm
yyy(十一月限定版)14 分钟前
初始matlab
开发语言·matlab
LawrenceLan15 分钟前
Flutter 零基础入门(九):构造函数、命名构造函数与 this 关键字
开发语言·flutter·dart
listhi52015 分钟前
基于MATLAB的支持向量机(SVM)医学图像分割方法
开发语言·matlab
hui函数21 分钟前
如何解决 pip install 编译报错 g++: command not found(缺少 C++ 编译器)问题
开发语言·c++·pip
山土成旧客25 分钟前
【Python学习打卡-Day40】从“能跑就行”到“工程标准”:PyTorch训练与测试的规范化写法
pytorch·python·学习
Tisfy29 分钟前
网站访问耗时优化 - 从数十秒到几百毫秒的“零成本”优化过程
服务器·开发语言·性能优化·php·网站·建站
济61736 分钟前
嵌入式C语言(第一期)
c语言·开发语言