输入CLI命令后保持脚本运行



我正在为我的项目使用CLI。我希望它以类似于解释器的方式工作。例如,一旦初始化,就可以继续执行其他命令。

考虑一个沙盒示例:

import typer
app = typer.Typer()
@app.command()
def init():
global x
x = 5
@app.command()
def print_():
print(x)

if __name__ == "__main__":
app()

如果我将app()替换为init(); print_(),则此工作。然而,如果我使用CLI(在我的情况下,它是Windows命令提示符),脚本在第一个命令后终止,所以在script init之后(让脚本命名为script.py),我不能运行script print-,因为变量x不再定义了。

我怎样才能使它工作?CLI是否有可能保持脚本运行并等待进一步的命令?除typer外,还可以提出其他工具。

当Python进程退出时,任何保存在Python变量中的内容都将被遗忘。

你可能应该实现一个简单的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()

最新更新