How do I access argv / command line options in Dart?
Asked Answered
O

5

13

And does Dart have a getopt library?

Overdress answered 14/2, 2012 at 15:27 Comment(0)
A
35

Using Options is no longer an option, use:

void main(List<String> args) {
   print(args);
}

To get executable, use Platform.executable (Platform comes from dart:io)

For parsing arguments passed to main, use this cool package

Axum answered 25/11, 2013 at 12:41 Comment(0)
I
4

Edit: This is no longer valid, see accepted answer above.

See Options.

http://api.dartlang.org/dart_io/Options.html

List<String> argv = (new Options()).arguments;
Ineducation answered 14/2, 2012 at 15:35 Comment(4)
I see that Dart omits the script name from the arguments. Do you know how to retrieve it? Ruby and Perl do it with $0.Overdress
Ah, Options has a script accessor. rosettacode.org/wiki/Program_name#DartOverdress
Small additional comment: as of March 2013 the Options class is in dart:io.Backbreaking
The Options class does no longer exist in dart:io. Use package:args instead.Sporades
V
4
// dart 1.0 
import 'dart:io';

void main(List<String> args) {
  String exec = Platform.executable;
  List<String> flags = Platform.executableArguments;
  Uri    script = Platform.script;

  print("exec=$exec");
  print("flags=$flags");
  print("script=$script");

  print("script arguments:");
  for(String arg in args)
    print(arg);
}
Vitrify answered 19/11, 2013 at 10:20 Comment(0)
O
1
#!/usr/bin/env dart

main() {
    print("Args: " + new Options().arguments);
}
Overdress answered 14/2, 2012 at 16:9 Comment(2)
Some comments: (1) You do not need to import the core library, (2) the + operator cannot be used as String concatenation, so use "Args: ${new Options().arguments}"Wicketkeeper
I think for the version of Dart/Mac OS X I'm using, you do actually have to import dart:core. Thank you for the Dart tips. Obviously + can be used for string concatenation, because it works in this snippet. Perhaps string interpolation is preferred in Dart, but it is not the only option.Overdress
U
1

I use this library for defining and parsing command line args http://pub.dartlang.org/packages/args

Uncivilized answered 21/12, 2012 at 2:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.