Keep script running after entering a CLI command

Viewed 56

I'm working on a CLI for my project. 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_(). 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.

How can I make it work? Is it possible for a CLI to keep script running and waiting for further commands? Other instruments apart from typer can also be put forward.

1 Answers

Anything you save in a Python variable will be forgotten when that Python process exits.

You should probably implement a simple REPL and get rid of the command-line arguments.

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()
Related