Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access command line parameters?

People also ask

Where are command line parameters stored?

All the command line arguments are stored in a character pointer array called argv[ ].

What are command line parameters?

Command line arguments are nothing but simply arguments that are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution.


You can access the command line arguments by using the std::env::args or std::env::args_os functions. Both functions return an iterator over the arguments. The former iterates over Strings (that are easy to work with) but panics if one of the arguments is not valid unicode. The latter iterates over OsStrings and never panics.

Note that the first element of the iterator is the name of the program itself (this is a convention in all major OSes), so the first argument is actually the second iterated element.

An easy way to deal with the result of args is to convert it to a Vec:

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() > 1 {
        println!("The first argument is {}", args[1]);
    }
}

You can use the whole standard iterator toolbox to work with these arguments. For example, to retrieve only the first argument:

use std::env;

fn main() {
    if let Some(arg1) = env::args().nth(1) {
        println!("The first argument is {}", arg1);
    }
}

You can find libraries on crates.io for parsing command line arguments:

  • docopt: you just write the help message, and the parsing code is generated for you.
  • clap: you describe the options you want to parse using a fluent API. Faster than docopt and gives you more control.
  • getopts: port of the popular C library. Lower-level and even more control.
  • structopt: built on top of clap, it is even more ergonomic to use.

Docopt is also available for Rust, which generates a parser for you from a usage string. As a bonus in Rust, a macro can be used to automatically generate the struct and do type based decoding:

docopt!(Args, "
Usage: cp [-a] SOURCE DEST
       cp [-a] SOURCE... DIR

Options:
    -a, --archive  Copy everything.
")

And you can get the arguments with:

let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());

The README and documentation have plenty of full working examples.

Disclaimer: I am one of the authors of this library.


Rust has getopt-style CLI argument parsing in the getopts crate.


For me, getopts always felt too low-level and docopt.rs was too much magic. I want something explicit and straightforward that still provides all the features if I need them.

This is where clap-rs comes in handy.
It feels a bit like argparse from Python. Here is an example of how it looks like:

let matches = App::new("myapp")
                      .version("1.0")
                      .author("Kevin K. <[email protected]>")
                      .about("Does awesome things")
                      .arg(Arg::with_name("CONFIG")
                           .short("c")
                           .long("config")
                           .help("Sets a custom config file")
                           .takes_value(true))
                      .arg(Arg::with_name("INPUT")
                           .help("Sets the input file to use")
                           .required(true)
                           .index(1))
                      .arg(Arg::with_name("debug")
                           .short("d")
                           .multiple(true)
                           .help("Sets the level of debugging information"))
                      .get_matches();

You can access your parameters like so:

println!("Using input file: {}", matches.value_of("INPUT").unwrap());

// Gets a value for config if supplied by user, or defaults to "default.conf"
let config = matches.value_of("CONFIG").unwrap_or("default.conf");
println!("Value for config: {}", config);

(Copied from the official documentation)


As of version 0.8/0.9, the correct path to the function args() would be ::std::os::args, i.e.:

fn main() {
  let args: ~[~str] = ::std::os::args();
  println(args[0]);
}

It seems that Rust is still pretty volatile right now with even standard I/O, so this may become out of date fairly quickly.


Rust changed again. os::args() is deprecated in favor of std::args(). But std::args() is not an array, it returns an iterator. You can iterate over the command line arguments, but cannot access them with subscripts.

http://doc.rust-lang.org/std/env/fn.args.html

If you want the command line arguments as a vector of strings, this will work now:

use std::env;
...
let args: Vec<String> = env::args().map(|s| s.into_string().unwrap()).collect();

Rust - learn to embrace the pain of change.


Also check out structopt:

extern crate structopt;
#[macro_use]
extern crate structopt_derive;

use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "example", about = "An example of StructOpt usage.")]
struct Opt {
    /// A flag, true if used in the command line.
    #[structopt(short = "d", long = "debug", help = "Activate debug mode")]
    debug: bool,

    /// An argument of type float, with a default value.
    #[structopt(short = "s", long = "speed", help = "Set speed", default_value = "42")]
    speed: f64,

    /// Needed parameter, the first on the command line.
    #[structopt(help = "Input file")]
    input: String,

    /// An optional parameter, will be `None` if not present on the
    /// command line.
    #[structopt(help = "Output file, stdout if not present")]
    output: Option<String>,
}

fn main() {
    let opt = Opt::from_args();
    println!("{:?}", opt);
}

https://github.com/TeXitoi/structopt