当前位置: 首页>>代码示例>>Golang>>正文


Golang pflag.String函数代码示例

本文整理汇总了Golang中github.com/spf13/pflag.String函数的典型用法代码示例。如果您正苦于以下问题:Golang String函数的具体用法?Golang String怎么用?Golang String使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了String函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	var token = flag.String("token", "nil", "log token")
	var logfile = flag.String("logfile", "/tmp/foo.txt", "log file to follow")
	var seekInfoOnStart = &tail.SeekInfo{Offset: 0, Whence: os.SEEK_END}

	flag.Parse()

	fmt.Println("using token: ", *token)

	if _, err := os.Stat(*logfile); os.IsNotExist(err) {
		fmt.Printf("no such file or directory: %s\n", *logfile)
		return
	}

	le, err := le_go.Connect(*token) // replace with token
	if err != nil {
		panic(err)
	}

	defer le.Close()
	t, err := tail.TailFile(*logfile, tail.Config{Follow: true, ReOpen: true, Location: seekInfoOnStart, Logger: tail.DiscardingLogger})
	if err == nil {
		for line := range t.Lines {
			le.Println(line.Text)
		}
	}
}
开发者ID:jcftang,项目名称:logentries-go,代码行数:27,代码来源:follower-single-token.go

示例2: processVars

func processVars() {
	flag.String("targetDirs", "", "Local directories  to back up.")
	flag.String("s3Host", "", "S3 host.")
	flag.String("s3AccessKey", "", "S3 access key.")
	flag.String("s3SecretKey", "", "S3 secret key.")
	flag.String("s3BucketName", "", "S3 Bucket Name.")
	flag.Int("remoteWorkerCount", 5, "Number of workers performing actions against S3 host.")
	flag.Bool("dryRun", false, "Flag to indicate that this should be a dry run.")
	flag.Parse()

	viper.BindPFlag("targetDirs", flag.CommandLine.Lookup("targetDirs"))
	viper.BindPFlag("s3Host", flag.CommandLine.Lookup("s3Host"))
	viper.BindPFlag("s3AccessKey", flag.CommandLine.Lookup("s3AccessKey"))
	viper.BindPFlag("s3SecretKey", flag.CommandLine.Lookup("s3SecretKey"))
	viper.BindPFlag("s3BucketName", flag.CommandLine.Lookup("s3BucketName"))
	viper.BindPFlag("remoteWorkerCount", flag.CommandLine.Lookup("remoteWorkerCount"))
	viper.BindPFlag("dryRun", flag.CommandLine.Lookup("dryRun"))

	viper.AutomaticEnv()
	viper.SetEnvPrefix("PERSONAL_BACKUP")
	viper.BindEnv("targetDirs")
	viper.BindEnv("s3Host")
	viper.BindEnv("s3AccessKey")
	viper.BindEnv("s3SecretKey")
	viper.BindEnv("s3BucketName")
	viper.BindEnv("remoteWorkerCount")

	viper.SetDefault("remoteWorkerCount", 5)
}
开发者ID:ptrimble,项目名称:dreamhost-personal-backup,代码行数:29,代码来源:main.go

示例3: parseFlags

// parseFlags sets up the flags and parses them, this needs to be called before any other operation
func parseFlags() {
	flag.String("workdir", "", "Working directory for GlusterD. (default: current directory)")
	flag.String("localstatedir", "", "Directory to store local state information. (default: workdir)")
	flag.String("rundir", "", "Directory to store runtime data. (default: workdir/run)")
	flag.String("logdir", "", "Directory to store logs. (default: workdir/log)")
	flag.String("config", "", "Configuration file for GlusterD. By default looks for glusterd.(yaml|toml|json) in /etc/glusterd and current working directory.")
	flag.String("loglevel", defaultLogLevel, "Severity of messages to be logged.")

	flag.String("restaddress", defaultRestAddress, "Address to bind the REST service.")
	flag.String("rpcaddress", defaultRPCAddress, "Address to bind the RPC service.")
	flag.String("etcdclientaddress", defaultEtcdClientAddress, "Address which etcd server will use for peer to peer communication.")
	flag.String("etcdpeeraddress", defaultEtcdPeerAddress, "Address which etcd server will use to receive etcd client requests.")

	flag.Parse()
}
开发者ID:kshlm,项目名称:glusterd2,代码行数:16,代码来源:config.go

示例4: String

// String creates a new entry in the flag set with String value.
// The environment value used as a default, if it exists
func String(flagName, envName, value, usage string) *string {
	verifyNames(flagName, envName)
	envVal := lookupEnv(envName)
	if envVal != "" {
		value = envVal
	}

	flag.String(flagName, value, usage)
	return pflag.String(flagName, value, usage)
}
开发者ID:NirmataOSS,项目名称:go-envflag,代码行数:12,代码来源:envflag.go

示例5: main

func main() {
	var wg sync.WaitGroup
	var config = flag.String("config", "logs.csv", "CSV file containing a list of 'tokens,/file/to/follow'")
	flag.Parse()

	if _, err := os.Stat(*config); os.IsNotExist(err) {
		fmt.Printf("no such file or directory: %s\n", *config)
		return
	}

	f, err := os.Open(*config)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	reader := csv.NewReader(f)
	reader.FieldsPerRecord = 2
	rawCSVdata, err := reader.ReadAll()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	for _, each := range rawCSVdata {
		// first column is the token, the second is the path to the log to follow
		fmt.Println("Following : ", each[1], each[0])
		t, err := multi.NewTailer(each[1], each[0])
		if err != nil {
			log.Fatal(err)
		}
		wg.Add(1)
		go func(t *multi.Tailer) {
			t.Do()
			wg.Done()
		}(t)
	}
	wg.Wait()
}
开发者ID:jcftang,项目名称:logentries-go,代码行数:38,代码来源:follower-multi-token.go

示例6: versionToPath

	test          = flag.BoolP("test", "t", false, "set this flag to generate the client code for the testdata")
	inputVersions = flag.StringSlice("input", []string{
		"api/",
		"authentication/",
		"authorization/",
		"autoscaling/",
		"batch/",
		"certificates/",
		"extensions/",
		"rbac/",
		"storage/",
		"apps/",
		"policy/",
	}, "group/versions that client-gen will generate clients for. At most one version per group is allowed. Specified in the format \"group1/version1,group2/version2...\". Default to \"api/,extensions/,autoscaling/,batch/,rbac/\"")
	includedTypesOverrides = flag.StringSlice("included-types-overrides", []string{}, "list of group/version/type for which client should be generated. By default, client is generated for all types which have genclient=true in types.go. This overrides that. For each groupVersion in this list, only the types mentioned here will be included. The default check of genclient=true will be used for other group versions.")
	basePath               = flag.String("input-base", "k8s.io/kubernetes/pkg/apis", "base path to look for the api group. Default to \"k8s.io/kubernetes/pkg/apis\"")
	clientsetName          = flag.StringP("clientset-name", "n", "internalclientset", "the name of the generated clientset package.")
	clientsetPath          = flag.String("clientset-path", "k8s.io/kubernetes/pkg/client/clientset_generated/", "the generated clientset will be output to <clientset-path>/<clientset-name>. Default to \"k8s.io/kubernetes/pkg/client/clientset_generated/\"")
	clientsetOnly          = flag.Bool("clientset-only", false, "when set, client-gen only generates the clientset shell, without generating the individual typed clients")
	fakeClient             = flag.Bool("fake-clientset", true, "when set, client-gen will generate the fake clientset that can be used in tests")
)

func versionToPath(gvPath string, group string, version string) (path string) {
	// special case for the core group
	if group == "api" {
		path = filepath.Join(*basePath, "../api", version)
	} else {
		path = filepath.Join(*basePath, gvPath, group, version)
	}
	return
}
开发者ID:ncdc,项目名称:kubernetes,代码行数:31,代码来源:main.go

示例7: downloadUrl

	"github.com/boltdb/bolt"
	flag "github.com/spf13/pflag"
	"github.com/ungerik/go-rss"

	"../data"
)

type updatedTitleMessage struct {
	Name  string
	Title string
}

// Flag specifications.
var (
	dbFilename         = flag.String("database", "feeds.db", "database to use")
	target             = flag.String("target", "", "target directory to download to")
	checkInterval      = flag.Int("check_interval", 3600, "seconds between checks during normal operation")
	rapidCheckInterval = flag.Int("rapid_check_interval", 60, "seconds between checks when we suspect there will be a new item")
	rapidCheckDuration = flag.Int("rapid_check_duration", 3600, "seconds that we suspect there will be a new item")
	downloadDelay      = flag.Int("download_delay", 30, "seconds to wait before downloading the file")
	requestDelay       = flag.Int("request_delay", 5, "seconds to wait between requests")
	checkImmediate     = flag.Bool("check_immediately", false, "if set, check immediately on startup")
	updateCommand      = flag.String("update_command", "", "command to run after an update is noticed")
	download           = flag.Bool("download", true, "if unset, do not actually download files")
)

var requestDelayTicker <-chan time.Time

func downloadUrl(url string) error {
	if !*download {
开发者ID:BranLwyd,项目名称:rss-download,代码行数:30,代码来源:rssd.go

示例8:

	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"

	flag "github.com/spf13/pflag"
)

// This needs to be updated when we cut a new release series.
const latestReleaseBranch = "release-1.1"

var (
	verbose = flag.Bool("verbose", false, "On verification failure, emit pre-munge and post-munge versions.")
	verify  = flag.Bool("verify", false, "Exit with status 1 if files would have needed changes but do not change.")
	rootDir = flag.String("root-dir", "", "Root directory containing documents to be processed.")
	// "repo-root" seems like a dumb name, this is the relative path (from rootDir) to get to the repoRoot
	relRoot = flag.String("repo-root", "..", `Appended to --root-dir to get the repository root.
It's done this way so that generally you just have to set --root-dir.
Examples:
 * --root-dir=docs/ --repo-root=.. means the repository root is ./
 * --root-dir=/usr/local/long/path/repo/docs/ --repo-root=.. means the repository root is /usr/local/long/path/repo/
 * --root-dir=/usr/local/long/path/repo/docs/admin --repo-root=../.. means the repository root is /usr/local/long/path/repo/`)
	skipMunges = flag.String("skip-munges", "", "Comma-separated list of munges to *not* run. Available munges are: "+availableMungeList)
	repoRoot   string

	ErrChangesNeeded = errors.New("mungedocs: changes required")

	// This records the files in the rootDir in upstream/latest-release
	filesInLatestRelease string
	// This indicates if the munger is running inside Jenkins
开发者ID:johndmulhausen,项目名称:kubernetes,代码行数:31,代码来源:mungedocs.go

示例9:

	"path"
	"runtime"
	"runtime/pprof"
	"time"

	"github.com/spf13/cobra"
	"github.com/spf13/pflag"

	"github.com/ncw/rclone/fs"
)

// Globals
var (
	// Flags
	cpuProfile    = pflag.StringP("cpuprofile", "", "", "Write cpu profile to file")
	memProfile    = pflag.String("memprofile", "", "Write memory profile to file")
	statsInterval = pflag.DurationP("stats", "", time.Minute*1, "Interval to print stats (0 to disable)")
	version       bool
	logFile       = pflag.StringP("log-file", "", "", "Log everything to this file")
	retries       = pflag.IntP("retries", "", 3, "Retry operations this many times if they fail")
)

// Root is the main rclone command
var Root = &cobra.Command{
	Use:   "rclone",
	Short: "Sync files and directories to and from local and remote object stores - " + fs.Version,
	Long: `
Rclone is a command line program to sync files and directories to and
from various cloud storage systems, such as:

  * Google Drive
开发者ID:marcopaganini,项目名称:rclone,代码行数:31,代码来源:cmd.go

示例10:

	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/cadvisor"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/dockertools"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/master"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/service"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/tools"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler"
	_ "github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler/algorithmprovider"
	"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler/factory"

	"github.com/golang/glog"
	flag "github.com/spf13/pflag"
)

var (
	addr           = flag.String("addr", "127.0.0.1", "The address to use for the apiserver.")
	port           = flag.Int("port", 8080, "The port for the apiserver to use.")
	dockerEndpoint = flag.String("docker_endpoint", "", "If non-empty, use this for the docker endpoint to communicate with")
	etcdServer     = flag.String("etcd_server", "http://localhost:4001", "If non-empty, path to the set of etcd server to use")
	// TODO: Discover these by pinging the host machines, and rip out these flags.
	nodeMilliCPU           = flag.Int64("node_milli_cpu", 1000, "The amount of MilliCPU provisioned on each node")
	nodeMemory             = flag.Int64("node_memory", 3*1024*1024*1024, "The amount of memory (in bytes) provisioned on each node")
	masterServiceNamespace = flag.String("master_service_namespace", api.NamespaceDefault, "The namespace from which the kubernetes master services should be injected into pods")
	enableProfiling        = flag.Bool("profiling", false, "Enable profiling via web interface host:port/debug/pprof/")
	deletingPodsQps        = flag.Float32("deleting_pods_qps", 0.1, "")
	deletingPodsBurst      = flag.Int("deleting_pods_burst", 10, "")
)

type delegateHandler struct {
	delegate http.Handler
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:31,代码来源:kubernetes.go

示例11: main

	"github.com/GoogleCloudPlatform/kubernetes/pkg/proxy/config"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"

	"github.com/golang/glog"
	flag "github.com/spf13/pflag"
)

const (
	configPath   = "/etc/haproxy/haproxy.cfg"
	templatePath = "/etc/k8s-haproxy/haproxy.cfg.gotemplate"
)

var clientConfig = &client.Config{}
var (
	keyPath = flag.String("key", "", "")
	caPath  = flag.String("ca", "", "")
	crtPath = flag.String("crt", "", "crt")
)

func main() {
	client.BindClientConfigFlags(flag.CommandLine, clientConfig)
	flag.Set("logtostderr", "true")
	flag.Parse()

	cmd := exec.Command("haproxy", "-f", configPath, "-p", "/var/run/haproxy.pid")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		if o, err := cmd.CombinedOutput(); err != nil {
开发者ID:porchdotcom,项目名称:k8s-haproxy,代码行数:31,代码来源:main.go

示例12:

	"github.com/spf13/pflag"
)

type parseGenData struct {
	PackageName    string
	InterpFunc     string
	InterpFuncName string
	OpCodeT        string
	InstructT      string
	FuncName       string
	NumCaptures    int
	Instructions   []Inst
}

var packageName = pflag.String("package", "main", "package name for generated code")
var regexPattern = pflag.String("pattern", "", "regex to generate code for")
var funcName = pflag.String("func", "RegexMatch",
	"function name for regex matching function")
var outFile = pflag.String("out", "", "output file for generated code")

const instruct = `
type Inst struct {
	Op     OpCode
	Char   rune
	Label1 int64
	Label2 int64
}`

const opcode = `
type OpCode uint
开发者ID:ezrosent,项目名称:regen,代码行数:30,代码来源:render.go

示例13: main

func main() {
	options := &gbuild.Options{CreateMapFile: true}
	var pkgObj string

	pflag.BoolVarP(&options.Verbose, "verbose", "v", false, "print the names of packages as they are compiled")
	flagVerbose := pflag.Lookup("verbose")
	pflag.BoolVarP(&options.Watch, "watch", "w", false, "watch for changes to the source files")
	flagWatch := pflag.Lookup("watch")
	pflag.BoolVarP(&options.Minify, "minify", "m", false, "minify generated code")
	flagMinify := pflag.Lookup("minify")
	pflag.BoolVar(&options.Color, "color", terminal.IsTerminal(int(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb", "colored output")
	flagColor := pflag.Lookup("color")
	tags := pflag.String("tags", "", "a list of build tags to consider satisfied during the build")
	flagTags := pflag.Lookup("tags")

	cmdBuild := &cobra.Command{
		Use:   "build [packages]",
		Short: "compile packages and dependencies",
	}
	cmdBuild.Flags().StringVarP(&pkgObj, "output", "o", "", "output file")
	cmdBuild.Flags().AddFlag(flagVerbose)
	cmdBuild.Flags().AddFlag(flagWatch)
	cmdBuild.Flags().AddFlag(flagMinify)
	cmdBuild.Flags().AddFlag(flagColor)
	cmdBuild.Flags().AddFlag(flagTags)
	cmdBuild.Run = func(cmd *cobra.Command, args []string) {
		options.BuildTags = strings.Fields(*tags)
		for {
			s := gbuild.NewSession(options)

			exitCode := handleError(func() error {
				if len(args) == 0 {
					return s.BuildDir(currentDirectory, currentDirectory, pkgObj)
				}

				if strings.HasSuffix(args[0], ".go") || strings.HasSuffix(args[0], ".inc.js") {
					for _, arg := range args {
						if !strings.HasSuffix(arg, ".go") && !strings.HasSuffix(arg, ".inc.js") {
							return fmt.Errorf("named files must be .go or .inc.js files")
						}
					}
					if pkgObj == "" {
						basename := filepath.Base(args[0])
						pkgObj = basename[:len(basename)-3] + ".js"
					}
					names := make([]string, len(args))
					for i, name := range args {
						name = filepath.ToSlash(name)
						names[i] = name
						if s.Watcher != nil {
							s.Watcher.Add(name)
						}
					}
					if err := s.BuildFiles(args, pkgObj, currentDirectory); err != nil {
						return err
					}
					return nil
				}

				for _, pkgPath := range args {
					pkgPath = filepath.ToSlash(pkgPath)
					if s.Watcher != nil {
						s.Watcher.Add(pkgPath)
					}
					buildPkg, err := gbuild.Import(pkgPath, 0, s.InstallSuffix(), options.BuildTags)
					if err != nil {
						return err
					}
					pkg := &gbuild.PackageData{Package: buildPkg}
					if err := s.BuildPackage(pkg); err != nil {
						return err
					}
					if pkgObj == "" {
						pkgObj = filepath.Base(args[0]) + ".js"
					}
					if err := s.WriteCommandPackage(pkg, pkgObj); err != nil {
						return err
					}
				}
				return nil
			}, options, nil)

			if s.Watcher == nil {
				os.Exit(exitCode)
			}
			s.WaitForChange()
		}
	}

	cmdInstall := &cobra.Command{
		Use:   "install [packages]",
		Short: "compile and install packages and dependencies",
	}
	cmdInstall.Flags().AddFlag(flagVerbose)
	cmdInstall.Flags().AddFlag(flagWatch)
	cmdInstall.Flags().AddFlag(flagMinify)
	cmdInstall.Flags().AddFlag(flagColor)
	cmdInstall.Flags().AddFlag(flagTags)
	cmdInstall.Run = func(cmd *cobra.Command, args []string) {
		options.BuildTags = strings.Fields(*tags)
//.........这里部分代码省略.........
开发者ID:wmydz1,项目名称:gopherjs,代码行数:101,代码来源:tool.go

示例14: init

	replicationControllerPkg "github.com/GoogleCloudPlatform/kubernetes/pkg/controller"
	_ "github.com/GoogleCloudPlatform/kubernetes/pkg/healthz"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/master/ports"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/service"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/version/verflag"

	"github.com/golang/glog"
	flag "github.com/spf13/pflag"
)

var (
	port            = flag.Int("port", ports.ControllerManagerPort, "The port that the controller-manager's http service runs on")
	address         = util.IP(net.ParseIP("127.0.0.1"))
	clientConfig    = &client.Config{}
	cloudProvider   = flag.String("cloud_provider", "", "The provider for cloud services.  Empty string for no provider.")
	cloudConfigFile = flag.String("cloud_config", "", "The path to the cloud provider configuration file.  Empty string for no configuration file.")
	minionRegexp    = flag.String("minion_regexp", "", "If non empty, and -cloud_provider is specified, a regular expression for matching minion VMs.")
	machineList     util.StringList
	// TODO: Discover these by pinging the host machines, and rip out these flags.
	// TODO: in the meantime, use resource.QuantityFlag() instead of these
	nodeMilliCPU = flag.Int64("node_milli_cpu", 1000, "The amount of MilliCPU provisioned on each node")
	nodeMemory   = resource.QuantityFlag("node_memory", "3Gi", "The amount of memory (in bytes) provisioned on each node")
)

func init() {
	flag.Var(&address, "address", "The IP address to serve on (set to 0.0.0.0 for all interfaces)")
	flag.Var(&machineList, "machines", "List of machines to schedule onto, comma separated.")
	client.BindClientConfigFlags(flag.CommandLine, clientConfig)
}
开发者ID:hortonworks,项目名称:kubernetes-yarn,代码行数:30,代码来源:controller-manager.go

示例15: init

package main

import (
	"os"
	goruntime "runtime"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/client/clientcmd"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/GoogleCloudPlatform/kubernetes/test/e2e"
	"github.com/golang/glog"
	flag "github.com/spf13/pflag"
)

var (
	kubeConfig = flag.String(clientcmd.RecommendedConfigPathFlag, "", "Path to kubeconfig containing embeded authinfo. Will use cluster/user info from 'current-context'")
	authConfig = flag.String("auth_config", "", "Path to the auth info file.")
	certDir    = flag.String("cert_dir", "", "Path to the directory containing the certs. Default is empty, which doesn't use certs.")
	gceProject = flag.String("gce_project", "", "The GCE project being used, if applicable")
	gceZone    = flag.String("gce_zone", "", "GCE zone being used, if applicable")
	host       = flag.String("host", "", "The host to connect to")
	masterName = flag.String("kube_master", "", "Name of the kubernetes master. Only required if provider is gce or gke")
	provider   = flag.String("provider", "", "The name of the Kubernetes provider")
	orderseed  = flag.Int64("orderseed", 0, "If non-zero, seed of random test shuffle order. (Otherwise random.)")
	repoRoot   = flag.String("repo_root", "./", "Root directory of kubernetes repository, for finding test files. Default assumes working directory is repository root")
	reportDir  = flag.String("report_dir", "", "Path to the directory where the JUnit XML reports should be saved. Default is empty, which doesn't generate these reports.")
	times      = flag.Int("times", 1, "Number of times each test is eligible to be run. Individual order is determined by shuffling --times instances of each test using --orderseed (like a multi-deck shoe of cards).")
	testList   util.StringList
)

func init() {
开发者ID:vrosnet,项目名称:kubernetes,代码行数:30,代码来源:e2e.go


注:本文中的github.com/spf13/pflag.String函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。