- Dart Cookbook
- Ivo Balbaert
- 376字
- 2021-08-05 17:42:47
Parsing command-line arguments
A server app that runs a batch job often takes parameter values from the command line. How can we get these values in our program?
How to do it...
The obvious way to parse command-line arguments is as follows (see command_line_arguments.dart
):
void main(List<String> args) { print("script arguments:"); for(String arg in args) print(arg); }
Now, the command dart command_line_arguments.dart param1 param2 param3
gives you the following output:
script arguments:
param1
param2
param3
However, you can also test this from within Dart Editor, open the menu Run, and select Manage Launches (Ctrl + Shift + M). Fill in the parameters in the Script arguments window:

Script arguments
What if your parameters are in the key:value
form, as shown in the following code?
par1:value1 par2:value2 par3:value3
In this case, use the following code snippet:
for(String arg in args) { List<String> par = arg.split(':'); var key = par[0]; var value = par[1]; print('Key is: $key - Value is: $value'); }
The previous code snippet gives you the following output:
Key is: par1 - Value is: value1
Key is: par2 - Value is: value2
Key is: par3 - Value is: value3
The split
method returned List<String>
with a key and value for each parameter. A more sophisticated way to parse the parameters can be done as follows:
final parser = new ArgParser(); argResults = parser.parse(args); List<String> pars = argResults.rest; print(pars); // [par1:value1, par2:value2, par3:value3]
Again, use split
to get the keys and values.
How it works...
The main()
function can take an optional argument List<String> args
to get parameters from the command line. It only takes a split of the parameter strings to get the keys and values.
The second option uses the args
package from the pub repository, authored by the Dart team. Include args:any
in the dependencies section of the pubspec.yaml
file. Then, you can use the package by including import 'package:args/args.dart';
at the top of the script. The args
package can be applied both in client and server apps. It can be used more specifically for the parsing of GNU and POSIX style options and is documented at https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/args/args.
See also
- Refer to the Searching in files recipe in Chapter 6, Working with Files and Streams, for an example of how to use the args package with a flag
- 物聯(lián)網(wǎng)安全:理論、實(shí)踐與創(chuàng)新
- JBoss EAP6 High Availability
- 計(jì)算機(jī)網(wǎng)絡(luò)安全實(shí)訓(xùn)教程(第二版)
- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- 射頻通信系統(tǒng)
- 區(qū)塊鏈輕松上手:原理、源碼、搭建與應(yīng)用
- Kong網(wǎng)關(guān):入門、實(shí)戰(zhàn)與進(jìn)階
- 光纖通信系統(tǒng)與網(wǎng)絡(luò)(修訂版)
- 計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)及應(yīng)用
- Scala Design Patterns.
- AIoT應(yīng)用開發(fā)與實(shí)踐
- 物聯(lián)網(wǎng)與智慧農(nóng)業(yè)
- 圖解物聯(lián)網(wǎng)
- 移動互聯(lián)網(wǎng)新思維
- ReasonML Quick Start Guide