Khepera III 工具箱/工具箱/模組/命令列
外觀
commandline 模組解析命令列值並提供一個簡單的介面來訪問這些值。該模組期望命令列引數由以下組成:
- 具有一個值的選項(鍵值對),例如:-s 10000或--speed 10000
- 沒有值的選項(只有鍵),例如:-h或--help
- 一個引數列表,包含所有沒有鍵提供的值
例如,命令列:
./my_program --white-floor --speed 15000 10 12 10
將導致一個鍵(--white-floor),一個鍵值對(--speed 15000)和三個引數(10, 12, 10).
// Initialize the module
commandline_init();
// Register an option without value (by default, options are considered key-value pairs)
struct sCommandLineOption *option_white_floor = commandline_option_register("-wf", "--white-floor", cCommandLine_Option);
// Parse the command line
commandline_parse(int argc, char *argv[]);
// Check if the -h --help option was provided
if (commandline_option_provided("-h", "--help")) {
...
}
// Read the -s --speed option
int value = commandline_option_value_int("-s", "--speed", int defaultvalue);
float value = commandline_option_value_float("-s", "--speed", float defaultvalue);
const char *value = commandline_option_value("-s", "--speed", const char *defaultvalue);
// Obtain the number of arguments provided
int count = commandline_argument_count();
// Read argument (the index counter starts with 0)
int value = commandline_argument_int(int index, int defaultvalue);
float value = commandline_argument_float(int index, float defaultvalue);
const char *value = commandline_argument(int index, const char *defaultvalue);
// The following two lines are equivalent, as the option "--white-floor" was registered above
white_floor = option_white_floor->provided;
white_floor = commandline_option_provided("-wf", "--white-floor");
commandline_register_option 註冊具有特定型別的選項。預設情況下(對於所有未明確註冊的選項),選項型別為cCommandLine_Option_Value並且會“吃掉”下一個命令列引數。例如,命令列
./my_program --white-floor 15
預設情況下會被解析為一個鍵值對(--white-floor 15)。如果--white-floor被註冊為cCommandLine_Option,但是,同一行將被解析為一個選項(--white-floor)和一個引數(15).
一旦所有必要的選項都被註冊,commandline_parse 就可以被呼叫來解析命令列。隨後,函式 commandline_option_value 及其 _int 和 _float 版本可用於訪問選項值,而 commandline_option_provided 返回該選項是否出現在命令列中。要訪問引數,可以使用 commandline_argument 及其 _int 和 _float 版本。index 必須小於 commandline_argument_count 返回的數字。
或者,程式可以在選項中註冊一個鉤子
// The function to process the --white-floor argument.
void white_floor_hook(struct sCommandLineOption *option) {
char *value = option->value;
}
int main(int argc, char *argv[]) {
...
commandline_init();
...
// Register a hook for --white-floor
commandline_option_register_hook("-wf", "--white-floor", cCommandLine_Option_Value, white_floor_hook);
...
commandline_parse(argc, argv);
...
}
每次相應選項出現在命令列中時,鉤子函式都會被呼叫。請注意,如果使用者多次提供同一個選項,該函式將被呼叫多次。