Equivalent of os.Args but on custom input

107 views
Skip to first unread message

Michał Łowicki

unread,
Apr 20, 2020, 12:27:41 PM4/20/20
to golang-nuts
Hi,

I'm working on a program which will have a prompt to enter commands like:

    add "foo bar"

I need what os.Args provides but on custom input so to above input I would like to get:

    []string{"add", "foo bar"}

Package os uses runtime_args(), and it isn't exported nor accepts input. Any idea what can I use instead? As a fallback, I can always implement something like https://stackoverflow.com/a/46973603, but maybe there is a smarter way to do it.

--
BR,
Michał Łowicki

Kurtis Rader

unread,
Apr 20, 2020, 1:24:16 PM4/20/20
to Michał Łowicki, golang-nuts
os.Args simply exposes the arguments passed to the program by the operating system. On UNIX this is typically called "argv" in C/C++ programs. The parsing of those strings into two arguments is done by the shell that runs your elvish program. It is not done by os.Args. I'm not aware of any functionality in the standard Go runtime that does what you want. There are probably third-party packages which do it that you could import. Or, roll your own CLI parser as shown in the stackoverflow question.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAKu9hcexcyMdjPaWUNd84q0Yhs_PoHCe-jczvhC04vqiU7LPwQ%40mail.gmail.com.


--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

Raffaele Sena

unread,
Apr 20, 2020, 2:14:28 PM4/20/20
to Kurtis Rader, Michał Łowicki, golang-nuts
I do something similar for some of my interactive tools and ended up
writing this: https://github.com/gobs/args.
If interested the command parser is here: https://github.com/gobs/cmd.

-- Raffaele
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CABx2%3DD8yDKak6DR7-7wrm-W40PFEKXTFv-Hn45OqKicft%2BvMVw%40mail.gmail.com.

ben....@compass.com

unread,
Apr 21, 2020, 5:09:08 PM4/21/20
to golang-nuts
There's also Google's shlex package: https://pkg.go.dev/github.com/google/shlex?tab=doc

Incidentally, on Windows Go has to do this manually on startup. See commandLineToArgv in https://golang.org/src/os/exec_windows.go

-Ben
Reply all
Reply to author
Forward
0 new messages