drqvr26084 2013-10-27 10:51 采纳率: 100%
浏览 241
已采纳

Golang标志被解释为第一个os.Args参数

I would like to run my program like this:

go run launch.go http://example.com --m=2 --strat=par

"http://example.com" gets interpreted as the first command line argument, which is ok, but the flags are not parsed after that and stay at the default value. If I put it like this:

go run launch.go --m=2 --strat=par http://example.com

then "--m=2" is interpreted as the first argument (which should be the URL).

I could also just remove the os.Args completely, but then I would have only optional flags and I want one (the URL) to be mandatory.

Here's my code:

package main

import (
    "fmt"
    "webcrawler/crawler"
    "webcrawler/model"
    "webcrawler/urlutils"
    "os"
    "flag"
)

func main() {
    if len(os.Args) < 2 {
        log.Fatal("Url must be provided as first argument")
    }

    strategy := flag.String("strat", "par", "par for parallel OR seq for sequential crawling strategy")
    routineMultiplier := flag.Int("m", 1, "Goroutine multiplier. Default 1x logical CPUs. Only works in parallel strategy")

    page := model.NewBasePage(os.Args[1])
    urlutils.BASE_URL = os.Args[1]
    flag.Parse()
    pages := crawler.Crawl(&page, *strategy, *routineMultiplier)
    fmt.Printf("Crawled: %d
", len(pages))
}

I am pretty sure that this should be possible, but I can't figure out how.

EDIT: Thanks justinas for the hint with the flag.Args(). I now adapted it like this and it works:

...
flag.Parse()

args := flag.Args()
    if len(args) != 1 {
        log.Fatal("Only one argument (URL) allowed.")
    }

page := model.NewBasePage(args[0])
...
  • 写回答

4条回答 默认 最新

  • dsvbtgo639708 2013-10-27 11:13
    关注

    os.Args doesn't really know anything about the flag package and contains all command-line arguments. Try flag.Args() (after calling flag.Parse(), of course).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面