I need to write a command line application, like a shell. So it will include commands etc. The thing is I don’t know how to pass parameters to the funcions in a module. For example:
User writes: function1 folder1
Program should now pass the ‘folder1’ parameter to the function1 function, and run it. But also it has to support other functions with different parameters ex:
User input: function2 folder2 –exampleparam
How to make this to work? I mean, I could just write a module, import it in python and just use the python console, but this is not the case. I need a script that takes command input and runs it.
I tried to use eval(), but that doesn’t solve the problem with params. Or maybe it does but I don’t see it?
The first part of your problem — parsing the command line — can be solved with argparse.
The second part — converting the string name of a function into a function call — can be done with exec or a dispatching dict which maps from strings to function objects.
I would recommend NOT using
execfor this, sinceallowing a user to call arbitrary Python functions from the command line might be dangerous. Instead, make a whitelist of allowable functions:
The above works when the command is typed into the command-line itself. If the command is being typed into
stdin, then we’ll need to do something a bit different.A simple way would be to call
raw_inputto grab the string fromstdin. We could then parse the string with argparse, as we did above:shmod.py:
main.py:
Another, more sophisticated way to handle this is to use the cmd module, as @chepner mentioned in the comments.
For more information on how to use the cmd module, see Doug Hellman’s excellent tutorial.
Running the code above yields a result like this: