A simple snippet to restart a Python CLI from within the CLI.

import os
import sys
import click

@click.command()
def cli():
    click.echo("CLI is running.")
    # Logic that determines when to restart
    if click.confirm("Do you want to restart the CLI?"):
        click.echo("Restarting CLI...")
        executable = sys.executable
        args = sys.argv
        os.execv(executable, [executable] + args)
    else:
        click.echo("Exiting CLI.")

if __name__ == '__main__':
    cli()

os.execv is the system call that can replace the current process with a new one. In this case we’re simply supplying the same executable and all the args that were passed in while starting the CLI to os.execv() thus effectively restarting the process.