當前位置: 首頁>>代碼示例>>Golang>>正文


Golang pflag.Parse函數代碼示例

本文整理匯總了Golang中github.com/ogier/pflag.Parse函數的典型用法代碼示例。如果您正苦於以下問題:Golang Parse函數的具體用法?Golang Parse怎麽用?Golang Parse使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Parse函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: main

func main() {
	var profile, version bool
	flag.BoolVarP(&version, "version", "v", false, "\tShow version")
	flag.BoolVar(&profile, "profile", false, "\tEnable profiler")
	flag.Parse()

	InitConfig()
	Config.MaxResults = 20

	if profile {
		f, err := os.Create("alexandria.prof")
		if err != nil {
			panic(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	// TODO run GenerateIndex() when there is something new

	if version {
		fmt.Println(NAME, VERSION)
		return
	}

	http.HandleFunc("/", mainHandler)
	http.HandleFunc("/stats", statsHandler)
	http.HandleFunc("/search", queryHandler)
	http.HandleFunc("/alexandria.edit", editHandler)
	serveDirectory("/images/", Config.CacheDirectory)
	serveDirectory("/static/", Config.TemplateDirectory+"static")
	http.ListenAndServe("127.0.0.1:41665", nil)
}
開發者ID:yzhs,項目名稱:alexandria,代碼行數:33,代碼來源:Web.go

示例2: main

func main() {
	logmgr.SetOutput(os.Stderr)
	if flagVerbose {
		logmgr.SetLevel(logrus.DebugLevel)
	} else {
		logmgr.SetLevel(logrus.InfoLevel)
	}

	flag.Parse()
	conf := &config.BuildConfig{
		BuildDir:  flagBuildDir,
		OutputDir: flag.Arg(0),
		Platform:  flagPlatform,
		Arch:      flagArch,
	}

	recipes := flag.Args()[1:]

	// Special case - passing a single 'all' means build all binaries.
	if len(recipes) == 1 && recipes[0] == "all" {
		recipes = builder.AllBinaries()
	}

	log.WithField("recipes", recipes).Info("Starting build")
	err := builder.Build(recipes, conf)
	if err != nil {
		log.WithField("err", err).Error("Error building")
	} else {
		log.Info("Successfully built")
	}
}
開發者ID:andrew-d,項目名稱:sbuild,代碼行數:31,代碼來源:main.go

示例3: parseFlags

func parseFlags() (*cmdConfig, *busltee.Config, error) {
	publisherConf := &busltee.Config{}
	cmdConf := &cmdConfig{}

	cmdConf.RollbarEnvironment = os.Getenv("ROLLBAR_ENVIRONMENT")
	cmdConf.RollbarToken = os.Getenv("ROLLBAR_TOKEN")

	// Connection related flags
	flag.BoolVarP(&publisherConf.Insecure, "insecure", "k", false, "allows insecure SSL connections")
	flag.IntVar(&publisherConf.Retry, "retry", 5, "max retries for connect timeout errors")
	flag.IntVar(&publisherConf.StreamRetry, "stream-retry", 60, "max retries for streamer disconnections")
	flag.Float64Var(&publisherConf.Timeout, "connect-timeout", 1, "max number of seconds to connect to busl URL")

	// Logging related flags
	flag.StringVar(&publisherConf.LogPrefix, "log-prefix", "", "log prefix")
	flag.StringVar(&publisherConf.LogFile, "log-file", "", "log file")
	flag.StringVar(&publisherConf.RequestID, "request-id", "", "request id")

	if flag.Parse(); len(flag.Args()) < 2 {
		return nil, nil, errors.New("insufficient args")
	}

	publisherConf.URL = flag.Arg(0)
	publisherConf.Args = flag.Args()[1:]

	return cmdConf, publisherConf, nil
}
開發者ID:heroku,項目名稱:busl,代碼行數:27,代碼來源:main.go

示例4: parseFlags

func (cm *ConfigManager) parseFlags() {
	pflag.StringVarP(&cm.Flags.ConfigFile, "configfile", "c", DefaultConfigFile, "Path to config")
	pflag.StringVarP(&cm.Flags.DestHost, "dest-host", "d", "", "Destination syslog hostname or IP")
	pflag.IntVarP(&cm.Flags.DestPort, "dest-port", "p", 0, "Destination syslog port")
	if utils.CanDaemonize {
		pflag.BoolVarP(&cm.Flags.NoDaemonize, "no-detach", "D", false, "Don't daemonize and detach from the terminal")
	} else {
		cm.Flags.NoDaemonize = true
	}
	pflag.StringVarP(&cm.Flags.Facility, "facility", "f", "user", "Facility")
	pflag.StringVar(&cm.Flags.Hostname, "hostname", "", "Local hostname to send from")
	pflag.StringVar(&cm.Flags.PidFile, "pid-file", "", "Location of the PID file")
	// --parse-syslog
	pflag.StringVarP(&cm.Flags.Severity, "severity", "s", "notice", "Severity")
	// --strip-color
	pflag.BoolVar(&cm.Flags.UseTCP, "tcp", false, "Connect via TCP (no TLS)")
	pflag.BoolVar(&cm.Flags.UseTLS, "tls", false, "Connect via TCP with TLS")
	pflag.BoolVar(&cm.Flags.Poll, "poll", false, "Detect changes by polling instead of inotify")
	pflag.Var(&cm.Flags.RefreshInterval, "new-file-check-interval", "How often to check for new files")
	_ = pflag.Bool("no-eventmachine-tail", false, "No action, provided for backwards compatibility")
	_ = pflag.Bool("eventmachine-tail", false, "No action, provided for backwards compatibility")
	pflag.StringVar(&cm.Flags.DebugLogFile, "debug-log-cfg", "", "the debug log file")
	pflag.StringVar(&cm.Flags.LogLevels, "log", "<root>=INFO", "\"logging configuration <root>=INFO;first=TRACE\"")
	pflag.Parse()
	cm.FlagFiles = pflag.Args()
}
開發者ID:ecorvo,項目名稱:remote_syslog2,代碼行數:26,代碼來源:config_manager.go

示例5: main

func main() {
	pflag.Usage = func() {
		fmt.Printf(`usage: tuplespaced [flags]

Run tuplespace server.

Flags:
`)
		pflag.PrintDefaults()
	}
	pflag.Parse()
	runtime.GOMAXPROCS(*ncpuFlag)

	log.AddFilter("stdout", logLevels[*logLevelFlag], log.NewConsoleLogWriter())
	debug := logLevels[*logLevelFlag] <= log.DEBUG

	log.Info("Starting server on http://%s/tuplespace/", *bindFlag)

	ts := tuplespace.NewTupleSpace(store.NewMemoryStore())

	srv := &http.Server{
		Addr:         *bindFlag,
		Handler:      makeService(ts, debug),
		ReadTimeout:  *readTimeoutFlag,
		WriteTimeout: *writeTimeoutFlag,
	}
	err := srv.ListenAndServe()
	if err != nil {
		fatalf("error: %s\n", err)
	}
}
開發者ID:pombredanne,項目名稱:tuplespace,代碼行數:31,代碼來源:tuplespaced.go

示例6: main

func main() {
	flag.Usage = func() {
		fmt.Fprint(os.Stderr, Usage)
	}

	flag.IntVarP(&options.Port, "port", "p", 9080, "")

	flag.Parse()

	// Parse base template
	var err error
	options.template, err = template.New("base").Parse(Template)
	if err != nil {
		log.Fatalln("Error parsing HTML template:", err)
	}
	options.Dir = "apidoc"
	// Verify that the wiki folder exists
	_, err = os.Stat(options.Dir)
	if os.IsNotExist(err) {
		log.Fatalln("Directory not found")
	}

	http.Handle("/apidoc/view", commonHandler(WikiHandler))
	http.Handle("/", commonHandler(WikiHandler))

	log.Println("Listening on:", options.Port)
	http.ListenAndServe(fmt.Sprintf(":%d", options.Port), nil)
}
開發者ID:yamingd,項目名稱:argo-script,代碼行數:28,代碼來源:main.go

示例7: main

func main() {
	flag.Usage = func() {
		// This is a little weird because I want to insert the correct
		// UTMP/WTMP file names into the Help output, but usually my
		// Help constants are raw string literals, so I had to
		// break it up into a couple chunks and move around some formatting.
		fmt.Fprintf(os.Stderr, "%s %s.  %s %s",
			Help1, utmp.UtmpFile, utmp.WtmpFile, Help2)
		os.Exit(1)
	}
	flag.Parse()

	if *version {
		fmt.Printf("%s\n", Version)
		os.Exit(0)
	}

	switch flag.NArg() {
	case 0:
		uptime(utmp.UtmpFile, utmp.CheckPIDs)
	case 1:
		uptime(flag.Arg(0), 0)
	default:
		fatal.Fatalf("extra operand %s\n", flag.Arg(1))
	}
}
開發者ID:patrickToca,項目名稱:go-coreutils,代碼行數:26,代碼來源:uptime.go

示例8: main

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s", Help)
		os.Exit(1)
	}
	flag.Parse()

	dir, err := os.Getwd()
	if err != nil {
		fatal.Fatalln(err)
	}

	// "To flush all open files on a volume, call FlushFileBuffers with a handle to the volume.
	// The caller must have administrative privileges. For more information, see Running with Special Privileges."
	// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364439(v=vs.85).aspx
	fp := filepath.VolumeName(dir)
	file, err := os.Open(fp)
	if err != nil {
		fatal.Fatalln(err)
	}

	err = syscall.Fsync(syscall.Handle(file.Fd()))
	if err != nil {
		fatal.Fatalln(err)
	}
}
開發者ID:patrickToca,項目名稱:go-coreutils,代碼行數:26,代碼來源:sync_windows.go

示例9: init

func init() {
	flag.Parse()

	log.PrintDebug = *debug
	log.Fileformat = func(now string, i int) string { return fmt.Sprintf("logs/%[1]s-%02[2]d.log", now, i) }
	log.Init()
	lang.Load()
	config.IndentConfig = *debug
	config.Load()

	if !*disableSafeShutdown {
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt, syscall.SIGTERM)
		go func() {
			<-c
			Shutdown("Interrupt/SIGTERM")
		}()
	}

	data, err := ioutil.ReadFile("/etc/hostname")
	if err != nil {
		log.Fatalln("Failed to read hostname: %s", err)
		return
	}
	hostname = strings.TrimSpace(string(data))
}
開發者ID:tulir293,項目名稱:ranssibot,代碼行數:26,代碼來源:ranssibot.go

示例10: main

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s", Help)
		os.Exit(1)
	}
	flag.Parse()

	if *version {
		fmt.Fprintf(os.Stdout, "%s", Version)
		os.Exit(0)
	}

	if len(flag.Args()) > 0 {
		for i := 0; i < len(flag.Args()); i++ {
			filename := flag.Arg(i)
			_, err := os.Stat(filename)
			if err == nil {
				now := time.Now()
				os.Chtimes(filename, now, now)
			} else if !(*nocreate) {
				f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0644)
				f.Close()
				if err != nil {
					log.Fatal(err)
				}
			}
		}
	}
}
開發者ID:patrickToca,項目名稱:go-coreutils,代碼行數:29,代碼來源:touch.go

示例11: main

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s", Help)
		os.Exit(1)
	}

	flag.Parse()

	has_error := false

	switch {
	case *show_version:
		fmt.Fprintf(os.Stdout, "%s", Version)
		os.Exit(0)
	case *check_sum:
		if !check_md5sum() {
			has_error = true
		}
	default:
		if !gen_md5sum() {
			has_error = true
		}
	}

	if has_error {
		os.Exit(1)
	}

	os.Exit(0)
}
開發者ID:fangdingjun,項目名稱:go-coreutils,代碼行數:30,代碼來源:md5sum.go

示例12: main

// Start the game and then, based on command line input, start up client
// interface listeners. Finally, wait for ^C before exiting.
func main() {
	var local, serve bool
	var endpoint string
	pflag.BoolVarP(&local, "local", "l", true, "run a local interactive REPL")
	pflag.BoolVarP(&serve, "serve", "s", false, "run a networked multiuser server")
	pflag.StringVarP(&endpoint, "endpoint", "e", ":4000", "where to run the networked server")
	pflag.Parse()

	done, events, spellbook := StartGame()

	if serve {
		go ListenTCP(endpoint, events, spellbook)
	}
	if local {
		go ListenLocal(events, spellbook)
	}

	interrupt := make(chan os.Signal)
	signal.Notify(interrupt, os.Interrupt)

	quitting := false
	for !quitting {
		select {
		case <-interrupt:
			events <- &ShutdownEvent{}
		case err := <-done:
			log.Print("main() stopping: ", err)
			quitting = true
		}
	}
}
開發者ID:zuwiki,項目名稱:hellas,代碼行數:33,代碼來源:hellas.go

示例13: main

func main() {
	var port uint
	var etcdAddr, logLevel string

	flag.UintVarP(&port, "port", "p", 19000, "listen port")
	flag.StringVarP(&etcdAddr, "etcd", "e", defaultEtcdAddr, "address of etcd machine")
	flag.StringVarP(&logLevel, "log-level", "l", "warn", "log level")
	flag.Parse()

	if err := logx.DefaultSetup(logLevel); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"level": logLevel,
		}).Fatal("failed to set up logging")
	}

	etcdClient := etcd.NewClient([]string{etcdAddr})

	if !etcdClient.SyncCluster() {
		log.WithFields(log.Fields{
			"addr": etcdAddr,
		}).Fatal("unable to sync etcd cluster")
	}

	ctx := lochness.NewContext(etcdClient)

	_ = Run(port, ctx)
}
開發者ID:joshie,項目名稱:lochness,代碼行數:28,代碼來源:main.go

示例14: main

func main() {
	flag.Usage = usage
	flag.Parse()

	if *help {
		usage()
	}

	// Read the configuration
	c, err := config.ReadConfigFromFile(cfgfile, source)
	if err != nil {
		fmt.Printf("Error:: %v\n", err)
		os.Exit(0)
	}

	// Create a Process
	process := &Process{Done: make(chan bool),
		Source:         *source,
		Started:        true,
		PagesFileInfo:  make(map[string]*os.FileInfo),
		AssetsFileInfo: make(map[string]*os.FileInfo),
	}

	// Create output directory if it does not exist
	err = os.Mkdir(c.OutputDirectory, 0755)

	// Generate whole book
	GenerateWholeBook(process)

	// Go into watch mode
	if *watchMode {
		WatchMode(*interval, process)
	}
}
開發者ID:nikoloz-pachuashvili,項目名稱:learn-node-mongo-the-hard-way,代碼行數:34,代碼來源:main.go

示例15: main

func main() {
	adaptflag.AdaptWithFunc(func(info adaptflag.Info) {
		flag.Var(info.Value, info.Name, info.Usage)
	})

	flag.Parse()
}
開發者ID:hlandau,項目名稱:easyconfig,代碼行數:7,代碼來源:exampleapp.go


注:本文中的github.com/ogier/pflag.Parse函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。