Home > Blockchain >  Is it possible to call a python function in a terminal?
Is it possible to call a python function in a terminal?

Time:04-29

I want to be able to run a python program and type a function in the terminal and have the function execute. For example:

I define a function in the python script

def hi():
   print('hello')

and while program is running, I type "hi()" or "hi" in the terminal and "hello" is returned.

My end goal is to have many different functions that can be called any time. I understand I could hard-code this with a ton of if/elif statements but that is a messy and seemingly impractical solution.

An example of this in use is with discord bots that can look for a prefix and command following it and run the function that was called

Is there any way I can do this in a way that is clean looking to the user?

#sorry for bad formatting, I am pretty new to Stack Overflow

CodePudding user response:

This can get complicated. A basic solution is to get the function object from the global namespace.

def hi():
    print("Hello")

def bye():
    print("Sorry, I'm staying")

while True:
    try:
        cmd = input("what up? ")
        globals()[cmd.strip()]()
    except KeyError:
        print("Invalid")

You could use your own dictionary instead of the global namespace, at the cost of the need to initialize it. That can aid in implementing something like a help system. You could even put all of your commands in their own module, use its namespace instead of your own dict.

Then there is the question of supplying parameters. If you want to do something like that, you could split the string on commas, or something like that.

You could even explore "Domaim Specific Languages in Python" for more complicated but expressive solutions.

  • Related