LoginSignup
48
40

More than 5 years have passed since last update.

コマンドライン引数

Last updated at Posted at 2013-11-04

Go言語でコマンドライン引数を取り扱う際のメモ。

flag - The Go Programming Language

結論から、flagパッケージをimportすれば万事解決。

os.Argsでコマンドラインの引数を取ることも可能だけど、
機能が全然違うのでちょっと凝ったことをしたいならflagを使うのがいい。

sample.go
package main

import (
        "fmt"
        "flag"
        "os"
)

func main(){
        f := flag.Int("flag1", 0, "flag 1")
        flag.Parse()

        fmt.Println("os.Args: ", os.Args)
        fmt.Println("compare")
        fmt.Println("flag.Args: ", flag.Args())
        if *f == 100 {
            fmt.Println("Hello")
        }
}
% go build sample.go 

% ./sample  a b c
os.Args:  [./sample a b c]
compare
flag.Args:  [a b c]

flagパッケージを使うと指定したオプションとそれ以外に指定したパラメータは分けて返してくれる機能が備わっている

% ./sample  -flag1=1 a  
os.Args:  [./sample -flag1=1 a]
compare
flag.Args:  [a]

あと、ヘルプも-hで表示してくれる。

% ./sample   -h   
Usage of ./sample:
  -flag1=0: flag 1

pythonのargparse, optparse よりかは柔軟性が落ちる印象だけど普通のコマンドラインツール作るにはこれでかなり間に合いそうな印象。

48
40
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48
40