我正在重新设计一个命令行应用程序,并正在寻找一种使其使用更直观的方法。传递到命令行应用程序的参数格式是否有任何约定?还是人们发现有用的任何其他方法?
17 回答
如果您使用 C# 试试Mono.GetOptions,它是一个非常强大且易于使用的命令行参数解析器。它适用于 Mono 环境和 Microsoft .NET Framework。
编辑:这里有一些功能
- 每个参数有 2 个 CLI 表示(1 个字符和字符串,例如 -a 或 --add)
- 默认值
- 强类型
- 自动生成带有说明的帮助屏幕
- 自动生成版本和版权屏幕
我喜欢某些 CLI 的一件事是快捷方式的使用。
即,以下所有行都在做同样的事情
myCli.exe describe someThing
myCli.exe descr someThing
myCli.exe desc someThing
这样,用户可能不必每次都键入 all 命令。
一个好的和有用的参考:
https://commandline.codeplex.com/
可通过 NuGet 获得的库:
- 最新稳定:
Install-Package CommandLineParser
. - 最新发布:
Install-Package CommandLineParser -pre
.
使用默认单例进行一行解析:CommandLine.Parser.Default.ParseArguments(...)
.
一行帮助屏幕生成器:HelpText.AutoBuild(...)
.
将命令行参数映射到IList<string>
、数组、枚举或标准标量类型。
插件友好的架构,如此处所述。
将动词命令定义为git commit -a
.
使用 lambda 表达式创建解析器实例。
快速入门:https ://commandline.codeplex.com/wikipage?title=Quickstart&referringTitle=Documentation
// Define a class to receive parsed values
class Options {
[Option('r', "read", Required = true,
HelpText = "Input file to be processed.")]
public string InputFile { get; set; }
[Option('v', "verbose", DefaultValue = true,
HelpText = "Prints all messages to standard output.")]
public bool Verbose { get; set; }
[ParserState]
public IParserState LastParserState { get; set; }
[HelpOption]
public string GetUsage() {
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
// Consume them
static void Main(string[] args) {
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options)) {
// Values are available here
if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile);
}
}
最好的办法是,如果可以的话,不要假设任何事情。当操作员键入要执行的应用程序名称并且没有任何参数时,请使用 USAGE 块或替代方法打开 Windows 窗体并允许他们输入您需要的所有内容。
c:\>FOO
FOO
USAGE FOO -{Option}{Value}
-A Do A stuff
-B Do B stuff
c:\>
参数定界我放在宗教主题的标题下:连字符(破折号)、双连字符、斜线、无、位置等。
您没有指明您的平台,但对于下一条评论,我将假设 Windows 和 .net
您可以在 .net 中创建一个基于控制台的应用程序,并允许它使用 Forms 与桌面交互,只需选择基于控制台的项目,然后添加 Windows.Forms、System.Drawing 等 DLL。
我们一直这样做。这确保了没有人会在黑暗的小巷中转弯。
这是一篇可能对您有所帮助的 CodeProject 文章...
如果 VB 是您的口味,这里有一篇单独的文章(包含更多指导相关内容)来查看...
命令行约定因操作系统而异,但可能得到最多使用和最公开审查的约定是 GNU getopt 包支持的约定。看http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html了解更多信息。
它允许您将单字母命令(例如 -nr)与更长的自文档选项(例如 --numeric --reverse)混合使用。友好一点,并实现一个 --help (-?) 选项,然后您的用户将能够弄清楚他们需要知道的所有内容。
补充@vonc 的答案,不要接受模棱两可的缩写。例如:
myCli.exe describe someThing
myCli.exe destroy someThing
myCli.exe des someThing ???
事实上,在那种情况下,我可能不会接受“破坏”的缩写......
我总是加 /? 参数来获得帮助,我总是尝试使用默认(即最常见的场景)实现。
否则,我倾向于将“/x”用于开关,将“/x:value”用于需要传递值的开关。使用正则表达式解析参数变得非常容易。
我开发了这个框架,也许它有帮助:
SysCommand 是一个强大的跨平台框架,用于在 .NET 中开发控制台应用程序。简单,类型安全,受 MVC 模式影响很大。
https://github.com/juniorgasparotto/SysCommand
namespace Example.Initialization.Simple
{
using SysCommand.ConsoleApp;
public class Program
{
public static int Main(string[] args)
{
return App.RunApplication();
}
}
// Classes inheriting from `Command` will be automatically found by the system
// and its public properties and methods will be available for use.
public class MyCommand : Command
{
public void Main(string arg1, int? arg2 = null)
{
if (arg1 != null)
this.App.Console.Write(string.Format("Main arg1='{0}'", arg1));
if (arg2 != null)
this.App.Console.Write(string.Format("Main arg2='{0}'", arg2));
}
public void MyAction(bool a)
{
this.App.Console.Write(string.Format("MyAction a='{0}'", a));
}
}
}
测试:
// auto-generate help
$ my-app.exe help
// method "Main" typed
$ my-app.exe --arg1 value --arg2 1000
// or without "--arg2"
$ my-app.exe --arg1 value
// actions support
$ my-app.exe my-action -a
-operation [参数] -command [你的命令] -anotherthings [otherparams]....
例如,
YourApp.exe -file %YourProject.prj% -Secure true
如果您使用生成命令行界面的标准工具之一,例如 getopts,那么您将自动符合要求。
您用于应用程序的约定取决于
1)它是什么类型的应用程序。
2)您使用的是什么操作系统。Linux?视窗?他们都有不同的约定。
我的建议是查看系统上其他命令的其他命令行界面,特别注意传递的参数。有不正确的参数应该给用户解决方案指示的错误消息。易于查找的帮助屏幕也有助于提高可用性。
在不知道您的应用程序究竟会做什么的情况下,很难给出具体的例子。
您用于应用程序的约定取决于
1)它是什么类型的应用程序。2)您使用的是什么操作系统。
这绝对是真的。我不确定 dos-prompt 约定,但在类 unix 系统上,一般约定大致是:
1)格式是
应用名称参数
2)单字符参数(如'x')作为-x传递 3)多字符参数(如'add-keys')作为--add-keys传递
如果您使用 Perl,我的CLI::Application框架可能正是您所需要的。它使您可以轻松地使用类似 SVN/CVS/GIT 的用户界面构建应用程序(“your-command -o --long-opt some-action-to-execute some parameters”)。
我创建了一个包含命令行解析器的 .Net C# 库。您只需要创建一个继承自 CmdLineObject 类的类,调用 Initialize,它就会自动填充属性。它可以处理不同类型的转换(使用项目中也包含的高级转换库)、数组、命令行别名、单击一次参数等。它甚至可以自动创建命令行帮助 (/?)。
如果您有兴趣,该项目的 URL 是http://bizark.codeplex.com。它目前仅作为源代码提供。
我刚刚发布了一个更好的命令行解析器。
https://github.com/gene-l-thomas/coptions
它在 nuget Install-Package coptions
using System;
using System.Collections.Generic;
using coptions;
[ApplicationInfo(Help = "This program does something useful.")]
public class Options
{
[Flag('s', "silent", Help = "Produce no output.")]
public bool Silent;
[Option('n', "name", "NAME", Help = "Name of user.")]
public string Name
{
get { return _name; }
set { if (String.IsNullOrWhiteSpace(value))
throw new InvalidOptionValueException("Name must not be blank");
_name = value;
}
}
private string _name;
[Option("size", Help = "Size to output.")]
public int Size = 3;
[Option('i', "ignore", "FILENAME", Help = "Files to ignore.")]
public List<string> Ignore;
[Flag('v', "verbose", Help = "Increase the amount of output.")]
public int Verbose = 1;
[Value("OUT", Help = "Output file.")]
public string OutputFile;
[Value("INPUT", Help = "Input files.")]
public List<string> InputFiles;
}
namespace coptions.ReadmeExample
{
class Program
{
static int Main(string[] args)
{
try
{
Options opt = CliParser.Parse<Options>(args);
Console.WriteLine(opt.Silent);
Console.WriteLine(opt.OutputFile);
return 0;
}
catch (CliParserExit)
{
// --help
return 0;
} catch (Exception e)
{
// unknown options etc...
Console.Error.WriteLine("Fatal Error: " + e.Message);
return 1;
}
}
}
}
支持自动 --help 生成,动词,例如 commmand.exe
享受。