Parse command-line arguments: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 11:
=={{header|AutoHotkey}}==
For AutoHotkey v1.1+
<langsyntaxhighlight AutoHotkeylang="autohotkey">;Get Arguments as an array
if 0 > 0
{
Line 41:
}
 
MsgBox % "Parsed Arguments :`n" msg</langsyntaxhighlight>
'''Output (MsgBox):'''
<pre>Parsed Arguments :
Line 52:
=={{header|AWK}}==
{{works with|gawk}}
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -E
# -E instead of -f so program arguments don't conflict with Gawk arguments
@include "getopt.awk"
Line 70:
if(tval) print "-t = " tval
if(uval) print "-u = " uval
}</langsyntaxhighlight>
 
=={{header|Bracmat}}==
Line 80:
=={{header|C}}==
The man page for getopt (man 3 getopt) provides better option handling with examples. But if you just want to parse one argument... (adapted from simple database task):
<langsyntaxhighlight lang="c">#include <stdio.h>
int main(int argc, char **argv){
int i;
Line 109:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 116:
=={{header|D}}==
The [http://dlang.org/phobos/std_getopt.html getopt module] in D's standard library is inspired by Perl's Getopt::Long module. The syntax of Phobos getopt infers the expected parameter types from the static types of the passed-in pointers.
<langsyntaxhighlight lang="d">import std.stdio, std.getopt;
 
void main(string[] args) {
Line 134:
writeln("verbose: ", verbose);
writeln("color: ", color);
}</langsyntaxhighlight>
{{out|Usage example}}
<pre>C:\getopt_test --verbose --length 12
Line 143:
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Parse_command_line_argument;
 
Line 179:
 
Readln;
end.</langsyntaxhighlight>
{{out}}
Parse_command_line_argument.exe
Line 198:
Elixir provides an option parser in a library module called <tt>OptionParser</tt>.
 
<langsyntaxhighlight lang="elixir">#!/usr/bin/env elixir
IO.puts 'Arguments:'
IO.inspect OptionParser.parse(System.argv())</langsyntaxhighlight>
 
<langsyntaxhighlight lang="bash">$ ./parse-args.exs --a --b --c=yes --no-flag --verbose -V -a=1 -b=t -- apple banana
Arguments:
{[a: true, b: true, c: "yes", no_flag: true, verbose: true],
["apple", "banana"], [{"-V", nil}, {"-a", "1"}, {"-b", "t"}]}</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Program (commandline.exe) invoked like this:
Line 225:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 244:
=={{header|Go}}==
Most simply, implementing the suggested example from the talk page:
<langsyntaxhighlight lang="go">package main
 
import (
Line 259:
fmt.Println("s:", *s)
fmt.Println("n:", *n)
}</langsyntaxhighlight>
Example runs:
<pre>
Line 281:
The Icon Programming Library provides a procedure for processing command line options. See the library reference for detailed documentation. The code below is an example.
 
<langsyntaxhighlight Iconlang="icon">link options
 
procedure main(ARGLIST)
Line 294:
i := opttable(i) # assign an integer
...
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 309:
:Test if an argument is present:
 
::<langsyntaxhighlight lang="j"> (<'-b') e. ARGV</langsyntaxhighlight>
 
::This is true if the argument is present and false, if it is not.
Line 315:
:Or, find the name of an optional file:
 
::<langsyntaxhighlight lang="j"> (ARGV i.<'-f') {:: }.ARGV,a:</langsyntaxhighlight>
 
::This is the name of the first file named after the first -f argument, or empty if there was no such file.
Line 326:
Example taken from the official documentation of [https://carlobaldassi.github.io/ArgParse.jl/stable/ ArgParse docs].
 
<langsyntaxhighlight lang="julia">using ArgParse
 
function parse_commandline()
Line 357:
end
 
main()</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6 (packaged as parse_cla.jar)
 
fun main(args: Array<String>) = println(args.asList())</langsyntaxhighlight>
 
{{out}}
Line 372:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The command line is parsed and stored into a list of strings to ease manual handling by list processing functions.
<langsyntaxhighlight Mathematicalang="mathematica">$CommandLine
-> {math, -v, -n, -z, -w, 1, 192.168.1.2, 1-1000}</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import os
import parseopt
 
Line 409:
 
main()
</syntaxhighlight>
</lang>
 
Sample command line:
Line 445:
=={{header|PARI/GP}}==
GP exists in a REPL and so it doesn't make sense to parse command-line arguments. But PARI can parse them just like [[#C|C]]:
<langsyntaxhighlight lang="c">#include <pari/pari.h>
#include <stdio.h>
 
Line 452:
pari_printf("8 + 1 = %Ps\n", addii(int2u(3), gen_1));
return 0;
}</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 458:
Use the <tt>Getopt::Long</tt> module:
 
<langsyntaxhighlight lang="perl"># Copyright Shlomi Fish, 2013 under the MIT/X11 License.
 
use strict;
Line 477:
($verbose ? "Verbosity" : "No verbosity"),
" and a length of $length.\n";
</syntaxhighlight>
</lang>
 
The output from it is:
Line 495:
{{libheader|Phix/basics}}
 
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">res</span>
<!--</langsyntaxhighlight>-->
 
{{out}}
Line 529:
 
 
<langsyntaxhighlight Picatlang="picat">main(ARGS) =>
Opts = new_map(),
process_args(ARGS,Opts),
Line 562:
process_args([Opt|As],Pos,Map) :-
Map.put(Pos,[Opt,'']),
process_args(As,Pos+1,Map).</langsyntaxhighlight>
 
Note: The parameters to the program should not be one of Picat's own parameters, since they will be parsed (and consumed) by Picat before starting to run the user's program. Here are Picat's parameters:
Line 588:
=={{header|PicoLisp}}==
PicoLisp doesn't have a library to get options. Instead, the command line is parsed at startup and handled in the following way: Each command line argument is executed (interpreted) as a Lisp source file, except that if the first character is a hypen '-', then that arguments is taken as a Lisp function call (without the surrounding parentheses). For example, the command line
<langsyntaxhighlight lang="shell">$ ./pil abc.l -foo def.l -"bar 3 4" -'mumble "hello"' -bye</langsyntaxhighlight>
has the effect that
# The file "abc.l" is executed
Line 602:
=={{header|PowerShell}}==
Powershell functions and filters handle options organically, with advanced .NET support to handle complex and advanced options including aliases, ranges, sets, datatypes, and more. [https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.core/about/about_parsing See] [https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Core/about/about_Functions more] [https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.core/about/about_functions_advanced here]. However, to parse options 'classically', you can write a custom parser. A slightly messy version (inspired by ruby optparse) that can only handle switches and relies on RegEx:
<syntaxhighlight lang="powershell">
<lang Powershell>
$options = @{
opt1 = [bool] 0
Line 654:
return [array]$argv,$options
}#fn
</syntaxhighlight>
</lang>
Usage (in some function or script):
<syntaxhighlight lang="powershell">
<lang Powershell>
 
$argv,$options = parseOptions $args $options
Line 664:
$bar = $argv | SomeOtherFilter | Baz
}
</syntaxhighlight>
</lang>
Usage in shell:
<langsyntaxhighlight lang="shell">
$> function -c --wxx arg1 arg2
</syntaxhighlight>
</lang>
Note that this works in Powershell. All of the arguments after the function name will be passed as strings to the function, which then calls them as an array with the automatic variable, $args. The custom parser/function does the work from there, turning the strings into flags and typed arguments. WARNING: This is reinventing the wheel to an extreme degree.
 
Line 674:
Works in SWI-Prolog.
 
<langsyntaxhighlight Prologlang="prolog">:- initialization(main, main).
 
main(Argv) :-
Line 718:
longflags([port]),
help('The server port.')]
]).</langsyntaxhighlight>
 
{{out}}
<syntaxhighlight lang="powershell">
<lang Powershell>
# no options set (use defaults)
$ swipl .\opts.pl
Line 744:
--server -s atom=www.google.com The server address.
--port -p integer=5000 The server port.
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
Version 2.3+
<syntaxhighlight lang="python">
<lang Python>
from optparse import OptionParser
[...]
Line 763:
 
<yourscript> --file=outfile -q
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 769:
Racket has a good command-line parsing library, the following demonstrates some of its features:
 
<langsyntaxhighlight lang="racket">
#!/usr/bin/env racket
#lang racket
Line 799:
(printf "Log level: ~s\n" loglevel)
(printf "Operations: ~a\n" (string-join ops ", ")))
</syntaxhighlight>
</lang>
 
Sample runs:
Line 834:
(formerly Perl 6)
At the end of running any top-level code (which can preprocess the arguments if it likes), Raku automatically examines any remaining arguments and transforms them into a call to a <tt>MAIN</tt> routine, if one is defined. The arguments are parsed based on the signature of the routine, so that options are mapped to named arguments.
<syntaxhighlight lang="raku" line>
<lang perl6>
sub MAIN (Bool :$b, Str :$s = '', Int :$n = 0, *@rest) {
say "Bool: $b";
Line 841:
say "Rest: @rest[]";
}
</syntaxhighlight>
</lang>
{{out}}
<pre>$ ./main -h
Line 878:
╚═════════════════════════════════════════════════════════════════════════════╝
</pre>
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates one method to parse options for a command (entered on the CL*/
parse arg opts /*this preserves the case of options. */
opts=space(opts) /*elide superfluous blanks in options. */
Line 917:
isInt: return datatype(arg(1), 'W') /*return 1 if argument is an integer*/
isNum: return datatype(arg(1), 'N') /*return 1 if argument is a number.*/
sayer: say; say '***error***' arg(1); exit 13</langsyntaxhighlight>
<pre>
╔═══════════════════════════════════════════════════════════════════════╗
Line 934:
 
=== Ruby with 'getoptlong' ===
<langsyntaxhighlight lang="ruby">#!/usr/bin/env ruby
 
# == Synopsis
Line 1,015:
nil
end
end</langsyntaxhighlight>
 
<pre>$ ./pargs.rb -h
Line 1,049:
 
=== Ruby with 'optparse' ===
<langsyntaxhighlight lang="ruby">require 'optparse'
 
sflag = false
Line 1,100:
Fruit: #{fruit}
Arguments: #{ARGV.inspect}
EOF</langsyntaxhighlight>
 
<pre>$ ruby takeopts.rb -h
Line 1,132:
Using the [https://docs.rs/structopt StructOpt]:
 
<langsyntaxhighlight lang="rust">use structopt::StructOpt;
 
#[derive(StructOpt)]
Line 1,149:
println!("s: {}", opt.s);
println!("n: {}", opt.n);
}</langsyntaxhighlight>
 
Examples:
Line 1,172:
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">object CommandLineArguments extends App {
println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}")
}</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Line 1,180:
{{works with|MLton}}
The following code listing can be compiled with both [[SML/NJ]] and [[MLton]]:
<langsyntaxhighlight lang="sml">structure Test = struct
 
exception FatalError of string
Line 1,211:
 
(* MLton *)
val _ = Test.main (CommandLine.name(), CommandLine.arguments())</langsyntaxhighlight>
 
=== SML/NJ ===
[[SML/NJ]] can compile source code to a "heap file", witch can than be executed by the interpreter with arguments given (see [http://stackoverflow.com/questions/5053149/sml-nj-how-to-compile-standalone-executable this entry on stackowerflow.com] for more information).
The <code>source.cm</code> file should lock like this:
<syntaxhighlight lang="text">Group
is
SOURCE_FILE.sml
$/basis.cm</langsyntaxhighlight>
To compile the program, use <code>ml-build sources.cm</code>. This should create a "heap file" <code>sources.x86-linux</code>, depending on your architecture.
The heap file can be executed with <code>sml @SMLload=sources.x86-linux ARGUMENTS</code>, or the script [http://www.smlnj.org/doc/heap2exec/index.html <code>heap2exec</code>] can be used to make a single executable.
Line 1,228:
=={{header|Tcl}}==
The following proc detects and removes argument-less (-b) and one-argument options from the argument vector.
<langsyntaxhighlight Tcllang="tcl">proc getopt {_argv name {_var ""} {default ""}} {
upvar 1 $_argv argv $_var var
set pos [lsearch -regexp $argv ^$name]
Line 1,240:
return 0
}
}</langsyntaxhighlight>
Usage examples:
getopt argv -sep sep ";" ;# possibly override default with user preference
Line 1,250:
=={{header|Wren}}==
Any command line arguments passed to a Wren CLI script are collected in the same order into a list of strings. If individual arguments require any further parsing, this can then be done using normal Wren code.
<langsyntaxhighlight lang="ecmascript">import "os" for Process
 
var args = Process.arguments
Line 1,259:
var end = Num.fromString(sp[1])
var r = start..end
System.print("The final argument expressed as a Range object is %(r)")</langsyntaxhighlight>
 
{{out}}
Line 1,273:
 
File myprogram.zkl:
<langsyntaxhighlight lang="zkl">var ip;
argh := Utils.Argh(
T("v","v","print version",fcn{println("Version stub")}),
Line 1,288:
case("z") { println("zazzle") }
}
}</langsyntaxhighlight>
<pre>zkl myprogram nc -v -n -z --ip 192.168.1.2 1-1000</pre>
{{out}}
10,327

edits