[英]Keep script running after entering a CLI command
I'm working on a CLI for my project.我正在为我的项目开发 CLI。 I want it to work in a way similar to an interpreter.
我希望它以类似于解释器的方式工作。 For example, once I initialise, I can proceed with other commands.
例如,一旦我初始化,我可以继续执行其他命令。
Consider a sandbox examble:考虑一个沙盒示例:
import typer
app = typer.Typer()
@app.command()
def init():
global x
x = 5
@app.command()
def print_():
print(x)
if __name__ == "__main__":
app()
This works if I replace app()
with init(); print_()
如果我将
app()
替换为init(); print_()
这将有效init(); print_()
. init(); print_()
。 However, if I use a CLI (in my case it is Windows Command Prompt), the script terminates after the first command, so after script init
(let the script be named as script.py
) I cannot run script print-
as the variable x
is not defined anymore.但是,如果我使用 CLI(在我的情况下是 Windows 命令提示符),脚本会在第一个命令之后终止,因此在
script init
之后(让脚本命名为script.py
)我无法运行script print-
作为变量x
不再定义。
How can I make it work?我怎样才能让它工作? Is it possible for a CLI to keep script running and waiting for further commands?
CLI 是否可以保持脚本运行并等待进一步的命令? Other instruments apart from
typer
can also be put forward.也可以提出除
typer
以外的其他工具。
Anything you save in a Python variable will be forgotten when that Python process exits.当 Python 进程退出时,您保存在 Python 变量中的任何内容都将被遗忘。
You should probably implement a simple REPL and get rid of the command-line arguments.您可能应该实现一个简单的 REPL 并摆脱命令行参数。
commands = {}
x = 5
def _print(*args):
print(x)
commands["print"] = _print
def _set(*args):
global x
x = int(*args[0])
commands["set"] = _set
def repl():
while True:
raw_input = input("> ").split()
command = raw_input[0]
args = raw_input[1:]
try:
commands[command](args)
except KeyError:
print(f"syntax error: {command}")
# should probably handle exception from _set somehow too
if __name__ == "__main__":
repl()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.