【发布时间】:2016-01-19 13:13:26
【问题描述】:
我正在学习 Python,尽管我正在编写自己的脚本,该脚本允许我检查程序运行时提供的参数。下面是我想要实现的示例:
python file.py -v -h anotherfile.py
或./file.py -v -h anotherfile.py
在这两种情况下,-v 和-h 参数打印出模块版本和基本帮助文件。我已经有了区分参数和文件的代码,除了我想创建一个关于这个问题的通用模块。
以下用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();
-将成功运行 Lambda 表达式(至少这是我在研究该主题时读到的)。但是我不知道 Lambda 表达式是如何工作的,并且只有基本的使用知识。
这个问题的重点是,如何在 Python 中实现类似于 Java 示例的功能,将任何类型的代码存储在数组中?
问题在于Java示例,如果我在执行addArgument的类中定义了int i = 0;并以某种方式使用i,则包含addArgument的类知道使用i调用它的一个。我担心 Python 的情况可能不一样......
我希望能够将它们存储在字典或其他某种基于键的数组中,因此我可以按以下方式存储它们:
# Very rough example on the latter argument, showing what I'm after.
addoption("-v", print("version 1.0"))
编辑:我想要的示例:(不按原样工作)(请忽略 ;'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();
【问题讨论】:
标签: python function dictionary lambda