I'm getting into Python, and though of writing my own script which allows me to check arguments provided when a program is run. An example below of what I'm trying to achieve:
python file.py -v -h anotherfile.py
or
./file.py -v -h anotherfile.py
In these two cases, the -v
and -h
arguments, print out the module version, and a basic help file. I already have the code to differentiate between arguments and files, except I want to create a generalised module on the matter.
The following code written in Java-
// Somewhere.
public static HashMap<String, Runnable> args = new HashMap<String, Runnable>();
public void addArgument(String argument, Runnable command) {
if (argument.length() > 0) {
if (args.get(argument) == null) {
args.put(argument, command);
} else {
System.err.println("Cannot add argument: " + argument + " to HashMap as the mapping already exists.");
// Recover.
}
}
}
// Somewhere else.
foo.addArgument("-v", () -> {System.out.println("version 1.0");});
foo.args.get("-v").run();
-will run the Lambda Expressions (atleast that's what I read they were when researching the topic) successfully. I have no idea how Lambda Expressions work however, and have only basic knowledge of using them.
The point of this question, is how can I implement something like the Java example, in Python, storing any type of code inside of an array?
The thing is with the Java example though, if I have int i = 0;
defined in the class which executes addArgument
and uses i
somehow or rather, the class containing addArgument
knows to use i
from the one that invoked it. I'm worried that this may not be the same case for Python...
I want to be able to store them in dictionaries, or some other sort of key-based array, so I can store them in the following manner:
# Very rough example on the latter argument, showing what I'm after.
addoption("-v", print("version 1.0"))
EDIT: Example of what I want: (not working as is) (please ignore the ;'s)
args = {};
def add(argument, command):
args[argument] = lambda: command; # Same problem when removing 'lambda:'
def run():
for arg in args:
arg(); # Causing problems.
def prnt():
print("test");
add("-v", prnt);
run();