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


Golang os.Getwd函數代碼示例

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


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

示例1: initOSVars

func initOSVars() {
	var err error

	switch runtime.GOOS {
	case "darwin":
		if dbg {
			workingDir, err = os.Getwd()
		} else {
			workingDir = "/Applications/5DPrint.app/Contents/MacOS"
		}

		launchBrowserArgs = []string{"open"}
	case "windows":
		workingDir, err = os.Getwd()
		launchBrowserArgs = []string{"cmd", "/c", "start"}
	default:
		workingDir, err = os.Getwd()
		launchBrowserArgs = []string{"xdg-open"}
	}

	if err != nil {
		log.Println("initOSVars: ", err)
		os.Exit(1)
	}
}
開發者ID:shotantan,項目名稱:5DPrint,代碼行數:25,代碼來源:main.go

示例2: ConstructFileLocations

// Construct file locations of of scanner resources based on the operating system.
//
// Example:
//
// 	fileLocations := goNessus.ConstructFileLocations()
func ConstructFileLocations() FileLocations {
	if runtime.GOOS == "linux" {
		fileLocations := FileLocations{Base_directory: "/opt/scanner"}
		fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
		fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
		fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
		fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
		return fileLocations
	} else if runtime.GOOS == "darwin" {
		// Use PWD since don't really know where to put this type of thing
		pwd, err := os.Getwd()
		CheckErr(err)

		fileLocations := FileLocations{Base_directory: pwd}
		fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
		fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
		fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
		fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
		return fileLocations
	} else {
		// Use PWD since don't really know where to put this type of thing
		pwd, err := os.Getwd()
		CheckErr(err)

		fileLocations := FileLocations{Base_directory: pwd}
		fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
		fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
		fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
		fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
		return fileLocations
	}
}
開發者ID:kkirsche,項目名稱:go-nessus,代碼行數:37,代碼來源:process_files.go

示例3: TestdirectoryContents

func TestdirectoryContents(t *testing.T) {
	// setup
	save_pwd, _ := os.Getwd()
	if err := os.MkdirAll("test/artifacts/.amber", 0700); err != nil {
		t.Error("Error creating artifacts: ", err)
	}
	defer os.RemoveAll("test/artifacts")
	defer os.Chdir(save_pwd)

	// test
	actual, err := directoryContents("test/artifacts")
	if err != nil {
		t.Error(err)
	}

	// verify pwd same
	if pwd, _ := os.Getwd(); save_pwd != pwd {
		t.Errorf("Expected: %v, actual: %v", save_pwd, pwd)
	}

	// verify
	expected := []string{".amber"}
	if !stringSlicesEqual(expected, actual) {
		t.Errorf("Expected: %v, actual: %v", expected, actual)
	}
}
開發者ID:karrick,項目名稱:amber,代碼行數:26,代碼來源:retired_test.go

示例4: TestPushdPopd

func TestPushdPopd(t *testing.T) {
	sh := gosh.NewShell(t)
	defer sh.Cleanup()

	startDir, err := os.Getwd()
	ok(t, err)
	parentDir := filepath.Dir(startDir)
	neq(t, startDir, parentDir)
	sh.Pushd(parentDir)
	cwd, err := os.Getwd()
	ok(t, err)
	eq(t, cwd, parentDir)
	sh.Pushd(startDir)
	cwd, err = os.Getwd()
	ok(t, err)
	eq(t, cwd, startDir)
	sh.Popd()
	cwd, err = os.Getwd()
	ok(t, err)
	eq(t, cwd, parentDir)
	sh.Popd()
	cwd, err = os.Getwd()
	ok(t, err)
	eq(t, cwd, startDir)
	// The next sh.Popd() will fail.
	setsErr(t, sh, func() { sh.Popd() })
}
開發者ID:asadovsky,項目名稱:gosh,代碼行數:27,代碼來源:shell_test.go

示例5: testGetwd

func testGetwd() {
	// 獲取程序當前目錄,main go文件的目錄
	dir, err := os.Getwd()
	olddir := dir
	if err != nil {
		fmt.Println("Error : ", err)
		return
	}
	fmt.Println("當前 dir = ", dir)

	// 係統的目錄分隔符
	ps := os.PathSeparator
	fmt.Println("PathSeparator : ", string(ps))

	// 切換目錄
	os.Chdir(dir + "/mytest")

	dir, err = os.Getwd()
	if err != nil {
		fmt.Println("Error : ", err)
		return
	}
	fmt.Println("切換後 dir = ", dir)

	// 切換目錄
	os.Chdir(olddir)

}
開發者ID:shawnpan,項目名稱:learnGo,代碼行數:28,代碼來源:testOS.go

示例6: main

func main() {
	file, _ := os.Getwd()
	//	log.Println("current path:", file)
	//	fmt.Println(os.Args[0])
	//	file, _ = exec.LookPath(os.Args[0])
	abs := fmt.Sprintf(`%s/metronic/templates/admin/extra_profile.html`, file)
	//	fmt.Println(abs)
	file, _ = exec.LookPath(fmt.Sprintf(`%smetronic/templates/admin/extra_profile.html`, file))
	//	fmt.Printf("%T", os.Args[0])
	//	fmt.Println(file)
	log.Println("exec path:", file)
	filename := path.Dir(abs)
	os.MkdirAll(filename, 0777)
	dir, _ := path.Split(file)
	log.Println("exec folder relative path:", dir)
	os.OpenFile(file, os.O_CREATE, 0777)
	os.Chdir(dir)
	wd, _ := os.Getwd()
	log.Println("exec folder absolute path:", wd)

	fmt.Println("\n")
	m := map[string]map[string]string{}
	m["dasdfsdf"]["dfsadfasf"] = "sdfdsfsfsfddsfww"
	if m["dasdfsssdf"] == "" {
		fmt.Println(m["dasdfsdf"])
	}

}
開發者ID:hxangel,項目名稱:golang,代碼行數:28,代碼來源:path.go

示例7: TestAbs

func TestAbs(t *testing.T) {
	oldwd, err := os.Getwd()
	if err != nil {
		t.Fatal("Getwd failed: ", err)
	}
	defer os.Chdir(oldwd)

	root, err := ioutil.TempDir("", "TestAbs")
	if err != nil {
		t.Fatal("TempDir failed: ", err)
	}
	defer os.RemoveAll(root)

	wd, err := os.Getwd()
	if err != nil {
		t.Fatal("getwd failed: ", err)
	}
	err = os.Chdir(root)
	if err != nil {
		t.Fatal("chdir failed: ", err)
	}
	defer os.Chdir(wd)

	for _, dir := range absTestDirs {
		err = os.Mkdir(dir, 0777)
		if err != nil {
			t.Fatal("Mkdir failed: ", err)
		}
	}

	err = os.Chdir(absTestDirs[0])
	if err != nil {
		t.Fatal("chdir failed: ", err)
	}

	for _, path := range absTests {
		path = strings.Replace(path, "$", root, -1)
		info, err := os.Stat(path)
		if err != nil {
			t.Errorf("%s: %s", path, err)
			continue
		}

		abspath, err := filepath.Abs(path)
		if err != nil {
			t.Errorf("Abs(%q) error: %v", path, err)
			continue
		}
		absinfo, err := os.Stat(abspath)
		if err != nil || !os.SameFile(absinfo, info) {
			t.Errorf("Abs(%q)=%q, not the same file", path, abspath)
		}
		if !filepath.IsAbs(abspath) {
			t.Errorf("Abs(%q)=%q, not an absolute path", path, abspath)
		}
		if filepath.IsAbs(path) && abspath != filepath.Clean(path) {
			t.Errorf("Abs(%q)=%q, isn't clean", path, abspath)
		}
	}
}
開發者ID:TomHoenderdos,項目名稱:go-sunos,代碼行數:60,代碼來源:path_test.go

示例8: ReadComposeVolumes

// ReadComposeVolumes reads a docker-compose.yml and return a slice of
// directories to sync into the Docker Host
//
// "." and "./." is converted to the current directory parity is running from.
// Any volume starting with "/" will be treated as an absolute path.
// All other volumes (e.g. starting with "./" or without a prefix "/") will be treated as
// relative paths.
func ReadComposeVolumes() []string {
	var volumes []string

	files := FindDockerComposeFiles()
	for i, file := range files {
		if _, err := os.Stat(file); err == nil {
			project, err := docker.NewProject(&docker.Context{
				Context: project.Context{
					ComposeFiles: []string{file},
					ProjectName:  fmt.Sprintf("parity-%d", i),
				},
			})

			if err != nil {
				log.Info("Could not parse compose file")
			}

			for _, c := range project.Configs {
				for _, v := range c.Volumes {
					v = strings.SplitN(v, ":", 2)[0]

					if v == "." || v == "./." {
						v, _ = os.Getwd()
					} else if strings.Index(v, "/") != 0 {
						cwd, _ := os.Getwd()
						v = fmt.Sprintf("%s/%s", cwd, v)
					}
					volumes = append(volumes, mutils.LinuxPath(v))
				}
			}
		}
	}

	return volumes
}
開發者ID:mefellows,項目名稱:parity,代碼行數:42,代碼來源:utils.go

示例9: loadConfig

func loadConfig() {
	var temp Config

	if err := decodeConfig(bytes.NewBufferString(defaultConfig), &temp); err != nil {
		log.Fatal(err)
	}

	//Look for a configuration file in the following order:
	// Environment:  MAPWRAP_CONFIG
	// Current Directory: mapwrap.json
	configFile := os.Getenv("MAPWRAP_CONFIG")
	if configFile == "" {
		cwd, err := os.Getwd()
		if err != nil {
			log.Fatal(err)
		}
		configFile = filepath.Join(cwd, "mapwrap.json")
	}

	f, err := os.Open(configFile)
	defer f.Close()

	if err != nil {
		log.Printf("Error opening configuration file: %s\n", configFile)
		log.Fatal(err)
	}

	if err := decodeConfig(f, &temp); err != nil {
		log.Printf("Error loading configuration file: %s\n", configFile)
		log.Fatal(err)
	}
	//Set the working directory if it's not already set
	if temp.Directory == "" {
		temp.Directory, err = os.Getwd()
		if err != nil {
			log.Fatal(err)
		}
	}
	//Make sure the directory exists
	_, err = os.Stat(temp.Directory)
	if err != nil {
		log.Fatal(err)
	}

	if temp.Mapserv == "" {
		out, err := exec.Command("which", "mapserv").Output()

		if err != nil {
			log.Fatal("Error attempting to find mapserv: ", err)
		}
		temp.Mapserv = string(out)
	}
	_, err = exec.Command(temp.Mapserv).Output()
	if err != nil {
		log.Fatal("Error attempting to run mapserv: ", err)
	}

	config = &temp

}
開發者ID:escribano,項目名稱:mapwrap-go,代碼行數:60,代碼來源:config.go

示例10: findEntomon

func findEntomon() os.Error {
	origd, err := os.Getwd()
	if err != nil {
		// If we can't read our working directory, let's just fail!
		return err
	}
	oldd := origd
	for !isEntomonHere() {
		err = os.Chdir("..")
		if err != nil {
			// If we can't cd .. then we'll just use the original directory.
			goto giveup
		}
		newd, err := os.Getwd()
		if err != nil || newd == oldd {
			// Either something weird happened or we're at the root
			// directory.  In either case, we'll just go with the original
			// directory.
			goto giveup
		}
		oldd = newd
	}
	return nil
giveup:
	// If nothing else works we'll just use the original directory.
	err = os.Chdir(origd)
	if err != nil {
		return err
	}
	return os.MkdirAll(".entomon", 0777)
}
開發者ID:droundy,項目名稱:entomonitor,代碼行數:31,代碼來源:έντομο.go

示例11: GetExeDir

// TODO(urgent): don't rely on os.Args[0]
func GetExeDir() (string, error) {
	// Path with which the exe was ran.
	arg := os.Args[0]

	// This is the absolute path.
	if arg[0] == '/' {
		return path.Dir(arg), nil
	}

	// Running from within directory.
	if arg[0] == '.' && arg[1] == '/' {
		curDir, err := os.Getwd()
		if err != nil {
			return "", err
		}

		return curDir, nil
	}

	if existsIn('/', arg) {
		curDir, err := os.Getwd()
		if err != nil {
			return "", err
		}

		return path.Dir(path.Join(curDir, arg)), nil
	}

	return "", errors.New("Could not find exe path.")
}
開發者ID:vFense,項目名稱:vFenseAgent-nix,代碼行數:31,代碼來源:paths.go

示例12: main

func main() {
	if len(os.Args) > 1 {
		var err error
		if port, err = strconv.Atoi(os.Args[1]); err != nil {
			printUsage()
			return
		} else {
			if len(os.Args) > 2 {
				rootPath = os.Args[2]
				if rootStat, err := os.Stat(rootPath); err != nil || !rootStat.IsDir() {
					printUsage()
					return
				}
			} else {
				rootPath, _ = os.Getwd()
			}
		}
	} else {
		port = 80
		rootPath, _ = os.Getwd()
	}
	cacheFile = make(map[string]*FileRecord)
	go PeriodUpdate(periodSec)
	server := http.NewServeMux()
	server.HandleFunc("/", service)
	if err := http.ListenAndServe(":"+strconv.Itoa(port), server); err != nil {
		fmt.Println(err)
	}
}
開發者ID:andrewlee302,項目名稱:static-server,代碼行數:29,代碼來源:main.go

示例13: TestDirUnix

func TestDirUnix(t *testing.T) {
	check(t)
	if runtime.GOOS == "windows" {
		t.Skipf("skipping test on %q", runtime.GOOS)
	}
	cwd, _ := os.Getwd()
	h := &Handler{
		Path: "testdata/test.cgi",
		Root: "/test.cgi",
		Dir:  cwd,
	}
	expectedMap := map[string]string{
		"cwd": cwd,
	}
	runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)

	cwd, _ = os.Getwd()
	cwd = filepath.Join(cwd, "testdata")
	h = &Handler{
		Path: "testdata/test.cgi",
		Root: "/test.cgi",
	}
	expectedMap = map[string]string{
		"cwd": cwd,
	}
	runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
}
開發者ID:achanda,項目名稱:go,代碼行數:27,代碼來源:host_test.go

示例14: main

func main() {
	mypath, _ := os.Getwd()
	println(mypath + ":" + os.Args[0])
	d, _ := path.Split(os.Args[0])
	os.Chdir(d)
	fmt.Println(os.Getwd())
	mypath, _ = os.Getwd()
	println(mypath + ":" + os.Args[0])
	mybytes := make(TestBytes, 100)
	println(mybytes)
	processMap["server"] = &Command{name: "server", command: "mhive", dir: mypath, args: []string{"mhive", "-r"}}
	processMap["client"] = &Command{name: "client", command: "mhive", dir: mypath, args: []string{"mhive", "-i"}}
	processMap["web"] = &Command{name: "web", command: "mhive", dir: mypath, args: []string{"mhive", "-w"}}

	flag.Parse()
	if flag.Arg(0) == "s" {
		fmt.Println("starting server")
		//go processListener(processMap)
		server()
		<-make(chan int)
	} else if flag.Arg(0) == "stop" {
		fmt.Println("stopping client")
		stopclient("localhost", 1234)
	} else {
		fmt.Println("starting client")
		client(flag.Arg(0), 1234)
	}
}
開發者ID:psychobob666,項目名稱:MediaEncodingCluster,代碼行數:28,代碼來源:mainrpc.go

示例15: LoadConfig

func LoadConfig(cfgfile string) (*Config, error) {
	var (
		cfg *Config
		err error
		wd  string
	)

	if cfg, err = loadJsonConfig(cfgfile); err != nil {
		return cfg, err
	}

	if cfg.Http.Webroot != "" && !strings.HasPrefix(cfg.Http.Webroot, "/") {
		if wd, err = os.Getwd(); err == nil {
			cfg.Http.Webroot = wd + "/" + cfg.Http.Webroot
		} else {
			return cfg, err
		}
	}

	if !strings.HasPrefix(cfg.Http.ClientConf, "/") {
		if wd, err = os.Getwd(); err == nil {
			cfg.Http.ClientConf = wd + "/" + cfg.Http.ClientConf
		} else {
			return cfg, err
		}
	}

	return cfg, nil
}
開發者ID:metrilyx,項目名稱:metrilyx-dashboarder,代碼行數:29,代碼來源:common.go


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