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


Golang pflag.StringP函數代碼示例

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


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

示例1: main

func main() {
	interval := flag.IntP("interval", "i", 60, "update interval in seconds")
	ttl := flag.IntP("ttl", "t", 0, "heartbeat ttl in seconds")
	eaddr := flag.StringP("etcd", "e", "http://localhost:4001", "address of etcd machine")
	id := flag.StringP("id", "d", "", "hypervisor id")
	logLevel := flag.StringP("log-level", "l", "info", "log level")
	flag.Parse()

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

	if *ttl == 0 {
		*ttl = 2 * (*interval)
	}

	e := etcd.NewClient([]string{*eaddr})
	c := lochness.NewContext(e)

	hn, err := lochness.SetHypervisorID(*id)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "lochness.SetHypervisorID",
			"id":    id,
		}).Fatal("failed to set hypervisor id")
	}

	hv, err := c.Hypervisor(hn)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "context.Hypervisor",
			"id":    hn,
		}).Fatal("failed to instantiate hypervisor")
	}

	for {
		if err = hv.UpdateResources(); err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"func":  "hv.UpdateResources",
			}).Fatal("failed to update hypervisor resources")
		}
		if err = hv.Heartbeat(time.Duration(*ttl)); err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"func":  "hv.Heartbeat",
				"ttl":   *ttl,
			}).Fatal("failed to beat heart")
		}
		time.Sleep(time.Duration(*interval) * time.Second)
	}
}
開發者ID:joshie,項目名稱:lochness,代碼行數:58,代碼來源:main.go

示例2: main

func main() {

	cfg, err := ReadConfig()
	if err != nil {
		log.Fatalf("Coult not read config: %v", err)
	}

	pflag.Usage = func() {
		fmt.Fprintln(os.Stderr, "Usage: slackcat [-c #channel] [-n name] [message]")
	}

	channel := pflag.StringP("channel", "c", cfg.Channel, "channel")
	name := pflag.StringP("name", "n", username(), "name")
	pflag.Parse()

	// was there a message on the command line? If so use it.
	args := pflag.Args()
	if len(args) > 0 {
		msg := SlackMsg{
			Channel:  *channel,
			Username: *name,
			Parse:    "full",
			Text:     strings.Join(args, " "),
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
		os.Exit(0)
	}

	// ...Otherwise scan stdin
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		msg := SlackMsg{
			Channel:  *channel,
			Username: *name,
			Parse:    "full",
			Text:     scanner.Text(),
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
	}
	if err := scanner.Err(); err != nil {
		log.Fatalf("Error reading: %v", err)
	}
}
開發者ID:pborreli,項目名稱:slackcat,代碼行數:51,代碼來源:slackcat.go

示例3: main

func main() {
	var pathStrings pathSlice
	filePtr := flag.StringP("file", "f", "", "Path to json file")
	jsonPtr := flag.StringP("json", "j", "", "JSON text")
	flag.VarP(&pathStrings, "path", "p", "One or more paths to target in JSON")
	showKeysPtr := flag.BoolP("keys", "k", false, "Print keys & indexes that lead to value")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
		fmt.Fprintln(os.Stderr, "Pipe JSON to StdIn by not specifying --file or --json ")
	}
	flag.Parse()

	if len(pathStrings) == 0 {
		fmt.Println("Must specify one or more paths with the --path flag")
		os.Exit(1)
	}

	paths, err := jsonpath.ParsePaths(pathStrings...)
	if err != nil {
		fmt.Println(fmt.Errorf("Failed to parse paths: %q", err.Error()))
		os.Exit(1)
	}

	if filePtr != nil && *filePtr != "" {
		f, err := os.Open(*filePtr)
		if err != nil {
			fmt.Println(fmt.Errorf("Failed to open file: %q", err.Error()))
			os.Exit(1)
		}

		eval, err := jsonpath.EvalPathsInReader(f, paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
		f.Close()

	} else if jsonPtr != nil && *jsonPtr != "" {
		eval, err := jsonpath.EvalPathsInBytes([]byte(*jsonPtr), paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
	} else {
		reader := bufio.NewReader(os.Stdin)
		eval, err := jsonpath.EvalPathsInReader(reader, paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
	}
}
開發者ID:pyting,項目名稱:jsonpath-1,代碼行數:50,代碼來源:main.go

示例4: main

// Executes a file of SQL statements one statement at a time, stopping everything
// if one of them has an error
func main() {

	// -f (filename) is a required program argument
	var fileName = flag.StringP("file", "f", "", "path of the SQL file to run")
	dbInfo := pgutil.DbInfo{}
	verFlag, helpFlag := dbInfo.Populate()

	if verFlag {
		fmt.Fprintf(os.Stderr, "%s version %s\n", os.Args[0], version)
		fmt.Fprintln(os.Stderr, "Copyright (c) 2016 Jon Carlson.  All rights reserved.")
		fmt.Fprintln(os.Stderr, "Use of this source code is governed by the MIT license")
		fmt.Fprintln(os.Stderr, "that can be found here: http://opensource.org/licenses/MIT")
		os.Exit(1)
	}

	if helpFlag {
		usage()
	}

	if len(*fileName) == 0 {
		fmt.Fprintln(os.Stderr, "Missing required filename argument (-f)")
		usage()
	}

	exists, _ := fileutil.Exists(*fileName)
	if !exists {
		fmt.Fprintf(os.Stderr, "File does not exist: %s\n", *fileName)
		os.Exit(2)
	}

	runFile(*fileName, &dbInfo)
}
開發者ID:joncrlsn,項目名稱:pgrun,代碼行數:34,代碼來源:pgrun.go

示例5: main

func main() {
	var file *string = flag.StringP("config", "c", "", "Config file to use")
	flag.Parse()

	setupInflux()

	alerts := []Alert{}

	data, _ := ioutil.ReadFile(*file)
	err := yaml.Unmarshal(data, &alerts)
	if err != nil {
		panic(err)
	}

	if os.Getenv("DEBUG") == "true" {
		fmt.Printf("%+v\n", alerts)
	}

	setupSlack()
	setupHipchat()
	done := make(chan bool)
	for _, alert := range alerts {
		go func(alert Alert) {
			for {
				alert.Run()
				time.Sleep(time.Duration(alert.Interval) * time.Second)
			}
		}(alert)
	}
	<-done // wait
}
開發者ID:joock,項目名稱:influx-alert,代碼行數:31,代碼來源:main.go

示例6: main

func main() {
	var (
		// general options
		stateDir = pflag.String("statedir", "", "the server state directory")
		help     = pflag.BoolP("help", "h", false, "show this help")

		// server options
		server = pflag.BoolP("server", "s", false, "run the server in the foreground")
		port   = pflag.IntP("port", "p", 40000, "server port to listen on")

		// client options
		method  = pflag.StringP("method", "X", "GET", "client method")
		plugin  = pflag.String("plugin", "", "client plugin")
		data    = pflag.StringP("data", "d", "", "client body")
		headers = &repString{[]string{}}
		verbose = pflag.BoolP("verbose", "v", false, "show full http response")
	)

	pflag.VarP(headers, "header", "H", "client request header")

	pflag.Parse()

	if *help {
		os.Exit(runHelp())
	}

	if *server {
		os.Exit(runServer(*port, *stateDir))
	}

	if pflag.NArg() < 1 {
		fmt.Fprintln(os.Stderr, "must pass in path to make api call")
		runHelp()
		os.Exit(1)
	}

	os.Exit(runClient(*stateDir, *plugin, *method, pflag.Arg(0), *data, headers.strs, *verbose))
}
開發者ID:jonasi,項目名稱:project,代碼行數:38,代碼來源:main.go

示例7: main

func main() {
	pflag.Usage = func() {
		fmt.Fprintf(os.Stderr, USAGE)
	}

	var output = pflag.StringP("output", "o", ".", "output directory")
	pflag.Parse()

	if pflag.NArg() == 1 {
		genRoutes(pflag.Arg(0), *output)
	} else {
		pflag.Usage()
	}
}
開發者ID:qyfbq123,項目名稱:freedom-routes,代碼行數:14,代碼來源:main.go

示例8: main

func main() {
	pflag.Usage = func() {
		fmt.Fprintf(os.Stderr, USAGE)
	}

	var output = pflag.StringP("output", "o", ".", "output directory")
	var version = pflag.BoolP("version", "", false, "version")
	pflag.Parse()

	if *version {
		fmt.Println(VERSION)
	} else if pflag.NArg() == 1 {
		genRoutes(pflag.Arg(0), *output)
	} else {
		pflag.Usage()
	}
}
開發者ID:rainly,項目名稱:freedom-routes,代碼行數:17,代碼來源:main.go

示例9: main

func main() {
	configFile := flag.StringP("config", "c", "accounting.yml", "configuration file")
	flag.Parse()

	app := types.Application{}
	ReadConfig(*configFile, &app)

	var store types.Storage
	if app.StorageType == "xml" {
		store = storage.XMLStorage{app.XMLFilepath}
	}

	printHeader(&app)
	err := cli.MainLoop(&app, &store)
	if err != nil {
		panic(err.Error())
	}
}
開發者ID:meisterluk,項目名稱:personal-accounting-go,代碼行數:18,代碼來源:main.go

示例10: main

func main() {
	bFlag := flag.StringP("body-numbering", "b", "t", "style")
	flag.Parse()
	if len(flag.Args()) == 0 {
		bytes, _ := ioutil.ReadAll(os.Stdin)
		lines := strings.Split(string(bytes), "\n")
		linecount := 0
		for i := 0; i < len(lines)-1; i++ {
			if *bFlag == "t" {
				if len(strings.TrimSpace(lines[i])) > 0 {
					linecount++
					fmt.Printf("%6d  %s\n", linecount, lines[i])
				} else {
					fmt.Println(lines[i])
				}
			} else {
				linecount++
				fmt.Printf("%6d  %s\n", linecount, lines[i])
			}
		}
	} else if len(flag.Args()) > 0 {
		linecount := 0
		for j := 0; j < len(flag.Args()); j++ {
			bytes, _ := ioutil.ReadFile(flag.Arg(j))
			lines := strings.Split(string(bytes), "\n")
			for i := 0; i < len(lines)-1; i++ {
				if *bFlag == "t" {
					if len(strings.TrimSpace(lines[i])) > 0 {
						linecount++
						fmt.Printf("%6d  %s\n", linecount, lines[i])
					} else {
						fmt.Println(lines[i])
					}
				} else {
					linecount++
					fmt.Printf("%6d  %s\n", linecount, lines[i])
				}
			}
		}
	}
}
開發者ID:patrickToca,項目名稱:go-coreutils,代碼行數:41,代碼來源:nl.go

示例11: main

func main() {
	// Basic user configuration variables
	force := pflag.BoolP("force", "f", false, "Force output to terminal.")
	count := pflag.StringP("count", "n", "+Inf", "Number of random bytes to generate.")
	procs := pflag.IntP("procs", "p", runtime.NumCPU(), "Maximum number of concurrent workers.")
	pflag.Parse()

	if !(*force) && terminal.IsTerminal(int(os.Stdout.Fd())) {
		fmt.Fprintf(os.Stderr, "Random data not written to terminal.\n\n")
		pflag.Usage()
		os.Exit(1)
	}
	cnt, err := strconv.ParsePrefix(*count, strconv.AutoParse)
	if err != nil || math.IsNaN(cnt) {
		fmt.Fprintf(os.Stderr, "Number of bytes to generate is invalid.\n\n")
		pflag.Usage()
		os.Exit(1)
	}
	if (*procs) < 1 {
		fmt.Fprintf(os.Stderr, "Number of workers must be positive.\n\n")
		pflag.Usage()
		os.Exit(1)
	}

	runtime.GOMAXPROCS(*procs)
	rand.SetNumRoutines(*procs)

	// Copy random data to stdout
	if int64(cnt) < 0 || math.IsInf(cnt, 0) {
		_, err = io.Copy(os.Stdout, rand.Reader)
	} else {
		_, err = io.CopyN(os.Stdout, rand.Reader, int64(cnt))
	}
	if perr, ok := err.(*os.PathError); ok && perr.Err == syscall.EPIPE {
		err = nil // Expected error is for the sink to close the pipe
	} else if err != nil {
		panic(err)
	}
}
開發者ID:dsnet,項目名稱:crypto,代碼行數:39,代碼來源:main.go

示例12:

	gutenberg "gutenberg.org"
	"gutenberg.org/config"
	"gutenberg.org/plugins"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

var (
	cfgfile   = flag.String("config", "", "config file (default is path/config.json)")
	help      = flag.BoolP("help", "h", false, "show this help")
	source    = flag.StringP("source", "s", "", "filesystem path to read files relative from")
	watchMode = flag.BoolP("watch", "w", false, "watch filesystem for changes and recreate as needed")
	server    = flag.BoolP("server", "S", false, "run a (very) simple web server")
	port      = flag.String("port", "1313", "port to run web server on, default :1313")
	interval  = flag.Int64P("interval", "i", 1000, "pooling interval for watching")
	rebuild   = flag.BoolP("rebuild", "r", false, "rebuild entire book on restart")
)

type Process struct {
	// Process is done
	Done chan bool
	// Source directory for the book
	Source string
	// Started
	Started bool
開發者ID:HaiNguyen007,項目名稱:learn-node-mongo-the-hard-way,代碼行數:30,代碼來源:main.go

示例13: main

func main() {

	cfg, err := ReadConfig()
	if err != nil {
		log.Fatalf("Could not read config: %v", err)
	}

	// By default use "[email protected]", unless overridden by config. cfg.Username
	// can be "", implying Slack should use the default username, so we have
	// to check if the value was set, not just for a non-empty string.
	defaultName := username()
	if cfg.Username != nil {
		defaultName = *cfg.Username
	}

	pflag.Usage = func() {
		fmt.Fprintln(os.Stderr, "Usage: slackcat [-c #channel] [-n name] [-i icon] [message]")
	}

	channel := pflag.StringP("channel", "c", cfg.Channel, "channel")
	name := pflag.StringP("name", "n", defaultName, "name")
	icon := pflag.StringP("icon", "i", "", "icon")
	pflag.Parse()

	// was there a message on the command line? If so use it.
	args := pflag.Args()
	if len(args) > 0 {
		msg := SlackMsg{
			Channel:   *channel,
			Username:  *name,
			Parse:     "full",
			Text:      strings.Join(args, " "),
			IconEmoji: *icon,
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
		return
	}

	// ...Otherwise scan stdin
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		msg := SlackMsg{
			Channel:   *channel,
			Username:  *name,
			Parse:     "full",
			Text:      scanner.Text(),
			IconEmoji: *icon,
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
	}
	if err := scanner.Err(); err != nil {
		log.Fatalf("Error reading: %v", err)
	}
}
開發者ID:montanaflynn,項目名稱:slackcat,代碼行數:62,代碼來源:slackcat.go

示例14:

	noDereference     = flag.BoolP("no-dereference", "P", false, "")
	noPreserve        = flag.String("no-preserve", "", "")
	noTargetDir       = flag.BoolP("no-target-directory", "T", false, "")
	oneFS             = flag.BoolP("one-file-system", "x", false, "")
	parents           = flag.Bool("parents", false, "")
	path              = flag.Bool("path", false, "")
	pmot              = flag.Bool("p", false, "")
	preserve          = flag.String("preserve", "", "")
	recursive         = flag.BoolP("recursive", "R", false, "")
	recursive2        = flag.Bool("r", false, "")
	removeDestination = flag.Bool("remove-destination", false, "")
	sparse            = flag.String("sparse", "界", "")
	reflink           = flag.String("reflink", "世", "")
	selinux           = flag.Bool("Z", false, "")
	stripTrailSlash   = flag.Bool("strip-trailing-slashes", false, "")
	suffix            = flag.StringP("suffix", "S", "", "")
	symLink           = flag.BoolP("symbolic-link", "s", false, "")
	targetDir         = flag.StringP("target-directory", "t", "", "")
	update            = flag.BoolP("update", "u", false, "")
	verbose           = flag.BoolP("verbose", "v", false, "")
	version           = flag.Bool("version", false, "")
)

var (
	makeBackups      bool
	copyConts        bool
	parentsOpt       bool
	removeTrailSlash bool
	noTargDir        bool
	targDir          string
	versControl      string
開發者ID:patrickToca,項目名稱:go-coreutils,代碼行數:31,代碼來源:cp.go

示例15: main

func main() {

	var name *string = flag.StringP("name", "n", "", "Only run the instruction with this name")
	var project *string = flag.StringP("project", "p", "", "Only run the instruction that are apart of this project")
	var force_deploy *bool = flag.BoolP("force", "f", false, "Force a redeploy of everything in the conductor.yml file")
	flag.Parse()

	cd := []ConductorDirections{}

	data, _ := ioutil.ReadFile("conductor.yml")
	err := yaml.Unmarshal(data, &cd)
	if err != nil {
		panic(err)
	}

	for _, instr := range cd {
		if *name != "" {
			if instr.Name != *name {
				continue
			}
		}
		if *project != "" {
			if instr.Project != *project {
				continue
			}
		}
		// fmt.Printf("--- m:\n%v\n\n", instr)
		for _, host := range instr.Hosts {

			docker_ctrl := conductor.New(host)
			container := docker_ctrl.FindContainer(instr.Container.Name)
			host_log := log.New("\t\t\t\t[host]", host, "[container]", instr.Container.Name)

			if instr.Healthcheck != "" {
				health := healthcheck.New(host_log, instr.Healthcheck, host)
				health.Check()
			}

			host_log.Info("[ ] pulling image")
			pulled_image, err := docker_ctrl.PullImage(instr.Container.Image + ":latest")
			if err != nil {
				host_log.Error("Error pulling image: " + err.Error())
			}
			host_log.Info("[x] finished pulling image")

			if container.Container != nil {
				if pulled_image == container.Container.Image && *force_deploy == false {
					host_log.Info("skipping, container running latest image : " + pulled_image)
					continue
				}

				if container.ID() != "" {
					if err := docker_ctrl.RemoveContainer(container.ID()); err != nil {
						host_log.Error(err.Error())
					}
				}
			}

			host_log.Info("[ ] creating container")
			docker_ctrl.CreateAndStartContainer(conductor.ConductorContainerConfig{
				Name:        instr.Container.Name,
				Image:       instr.Container.Image,
				PortMap:     instr.Container.Ports,
				Environment: instr.Container.Environment,
				Volumes:     instr.Container.Volumes,
				Dns:         instr.Container.Dns,
			})
			host_log.Info("[x] finished creating container")
		}

	}

}
開發者ID:mehulsbhatt,項目名稱:docker-conductor,代碼行數:73,代碼來源:docker-conductor.go


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