Search code examples
pythonfunctionterminalterminal-emulator

Can I call a Python function without brackets, like a shell command. If so, how?


First time posting here, so apologies if I don't follow formatting guidelines or anything.

I'm writing a terminal-like utility tool for, among other things, bulk file editing. My goal was to have every function be three letters ling, a bit like in Assembly. For example, mkd("yeet") makes a directory called yeet.
The basic way it works is as follows: I define a whole bunch of functions, and then I set up a while True loop, that prints the eval() of whatever I type. So far, everything's going pretty well, except for one thing. I want to be able to call functions without having to add the brackets. Any parameters should be added afterwards, like using sys.argscv[1].

Here is a link to the GitHub repo.

Is this possible in Python, if so, how?

Obviously, just typing the name of the function will return me <function pwd at 0x7f6c4d86f6a8> or something along those lines.

Thanks in advance,
Walrus Gumboot


Solution

  • Here's a simple example if you want to parse the string yourself, that's easily extendable.

    def mkd(*args):
        if len(args) == 1:
            print("Making", *args)
        else:
            print("mdk only takes 1 argument.")
    
    def pwd(*args):
        if len(args) == 0:
            print("You're here!")
        else:
            print("pwd doesn't take any arguments.")
    
    def add(*args):
        if len(args) == 2:
            if args[0].isdigit() and args[1].isdigit(): 
                print("Result:", int(args[0]) + int(args[1]))
            else:
                print("Can only add two numbers!")
        else:
            print("add takes exactly 2 arguments.")
    
    def exit(*args):
        quit()
    
    
    functions = {'mkd': mkd, 'pwd': pwd, 'add': add, 'exit': exit}  # The available functions.  
    
    while True:
        command, *arguments = input("> ").strip().split(' ')  # Take the user's input and split on spaces.
        if command not in functions:
            print("Couldn't find command", command)
        else:
            functions[command](*arguments)