Command line 如何访问命令行参数?

Command line 如何访问命令行参数?,command-line,rust,Command Line,Rust,没有解释如何从命令行获取参数fn main()在所有示例中仅显示空参数列表 从main访问命令行参数的正确方法是什么?您可以使用或函数访问命令行参数。这两个函数都返回参数的迭代器。前者迭代Strings(这很容易处理),但如果其中一个参数不是有效的unicode,则会出现恐慌。后者迭代OsStrings,从不惊慌 请注意,迭代器的第一个元素是程序本身的名称(这是所有主要操作系统中的约定),因此第一个参数实际上是第二个迭代元素 处理args结果的一种简单方法是将其转换为Vec: use std::

没有解释如何从命令行获取参数
fn main()
在所有示例中仅显示空参数列表


main
访问命令行参数的正确方法是什么?

您可以使用或函数访问命令行参数。这两个函数都返回参数的迭代器。前者迭代
String
s(这很容易处理),但如果其中一个参数不是有效的unicode,则会出现恐慌。后者迭代
OsString
s,从不惊慌

请注意,迭代器的第一个元素是程序本身的名称(这是所有主要操作系统中的约定),因此第一个参数实际上是第二个迭代元素

处理
args
结果的一种简单方法是将其转换为
Vec

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() > 1 {
        println!("The first argument is {}", args[1]);
    }
}
您可以在上找到用于分析命令行参数的库:

  • :您只需编写帮助消息,就会为您生成解析代码
  • :描述要使用fluent API解析的选项。比docopt更快,并为您提供更多控制
  • :流行C库的端口。更低的级别,甚至更多的控制
  • :建立在clap之上,使用更符合人体工程学
什么适用于字符串,但如果需要参数作为数字(在本例中为uint),则需要如下转换:

fn main() {
    let arg : ~[~str] = os::args();
    match uint::from_str(arg[1]){
         Some(x)=>io::println(fmt!("%u",someFunction(x))),
         None=>io::println("I need a real number")
    }
}

Rust在中具有
getopt
-style CLI参数解析。

自版本0.8/0.9起,函数args()的正确路径为
::std::os::args
,即:

fn main() {
  let args: ~[~str] = ::std::os::args();
  println(args[0]);
}
即使使用标准I/O,Rust现在似乎仍然非常不稳定,因此可能很快就会过时。

对于较新的Rust版本(Rust>0.10/11),数组语法将无法工作。您必须使用get方法

数组语法(同样)在夜间工作。因此,您可以在getter或数组索引之间进行选择

use std::os;

fn main() {
  let args = os::args();
  println!("{}", args.get(1));
}

// Compile
rustc args.rs && ./args hello-world // returns hello-world
自2013年5月起,锈菌开始进化。现在,我们将使用
作为\u slice()
解析命令行参数:

使用std::os;
fn见参数(x:uint)
{       
println!(“你超过了我{}”,x);
}
fn main(){
设args=os::args();
设args=args.as_slice();
让nitems={
如果args.len()==2{
from_str::(args[1]。as_slice()).unwrap()
}否则{
10000
}
};
seen_arg(nitems);
}
也可用于Rust,它从用法字符串为您生成解析器。作为Rust的一个额外功能,可以使用宏自动生成结构并执行基于类型的解码:

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

Options:
    -a, --archive  Copy everything.
")
您可以通过以下方式获取参数:

let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
自述文件和文档中有大量完整的工作示例

免责声明:我是此库的作者之一。

介绍了如何访问命令行参数(另一种方式)

现在,这个例子也有了
#![no_std]
我认为这意味着通常情况下,std库将拥有二进制文件的真正入口点,并调用名为
main()
的全局函数。另一个选项是用
#禁用
垫片![no_main]
。如果我没有弄错的话,这是对编译器说,你正在完全控制你的程序是如何启动的

#![no_std]
#![no_main]

#[no_mangle] // ensure that this symbol is called `main` in the output
pub extern fn main(argc: isize, argv: *const *const u8) -> isize {
    0
}


如果您只想读取命令行参数,我认为这不是一种“好”的方法。其他答案中提到的
std::os
模块似乎是一种更好的做事方式。为了完整起见,我发布了这个答案。

铁锈又变了
os::args()
被弃用,取而代之的是
std::args()
。但是
std::args()
不是数组,它返回一个迭代器。您可以迭代命令行参数,但不能使用下标访问它们

如果希望命令行参数作为字符串向量,现在可以使用:

use std::env;
...
let args: Vec<String> = env::args().map(|s| s.into_string().unwrap()).collect();
使用std::env;
...
让args:Vec=env::args().map(|s|s.进入_字符串().unwrap()).collect();

生锈-学会接受变化的痛苦。

对我来说,getopts总是感觉太低级,docopt.rs太神奇了。 我想要一些明确和直接的东西,如果我需要的话,它仍然提供所有的特性

这就是方便的地方。
感觉有点像Python中的argparse。 下面是一个示例,展示了它的外观:

let matches = App::new("myapp")
                      .version("1.0")
                      .author("Kevin K. <kbknapp@gmail.com>")
                      .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();

(从中复制)

还可以签出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);
}
extern板条箱结构;
#[宏_使用]
外部板条箱结构;
使用structopt::structopt;
#[派生(StructOpt,Debug)]
#[structopt(name=“example”,about=“structopt用法示例”)]
结构选项{
///一个标志,如果在命令行中使用,则为true。
#[structopt(short=“d”,long=“debug”,help=“激活调试模式”)]
调试:bool,
///float类型的参数,具有默认值。
#[structopt(short=“s”、long=“speed”、help=“Set speed”、default_value=“42”)]
速度:f64,
///所需参数,命令行上的第一个参数。
#[structopt(help=“输入文件”)]
输入:字符串,
///如果服务器上不存在可选参数,则该参数将为“None”
///命令行。
#[structopt(help=“输出文件,如果不存在标准输出”)]
输出:选项,
}
fn main(){
让opt=opt::from_args();
println!(“{:?}”,opt);
}

谢谢您的更新!我想在1.0发布后,我将不得不重新考虑接受的答案。这是过时的声明。最新的Rust nightlies确实支持
Vec
s上的索引语法。我想它会在那里呆上一个月左右。请参阅。您现在只需要执行
env::args().collect()
。请注意:
因为_slice()
不再存在,应该改用
&args
。我喜欢clap rs让您在yaml文件中定义接口。此外,它还生成了非常好看的使用说明。这帮助我快速设置CLI应用程序。非常感谢。
use std::env;
...
let args: Vec<String> = env::args().map(|s| s.into_string().unwrap()).collect();
let matches = App::new("myapp")
                      .version("1.0")
                      .author("Kevin K. <kbknapp@gmail.com>")
                      .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();
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);
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);
}