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
You can use locals
or globals
depending the scope and and pass the string you get in the arguments:
>>> def foo():
... print("Hi from foo!")
...
>>> locals()["foo"]()
Hi from foo!
Where "foo"
would be the sys.args[1]
from the call to python script.py foo
Or you can define your own dictionary with the available commands, for example:
calc.py
commands = {
"add" : lambda x, y: x + y,
"mul" : lambda x, y: x * y,
}
if __name__ == __main__:
import sys
_, command, arg1, arg2, *_ = sys.args
f = commands.get(command, lambda *_: "Invalid command")
res = f(int(arg1), int(arg2))
print(res)
Calling python calc.py add 5 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With