我们写习惯了C代码,都知道了解析输入参数argc argv,获取环境变量env,常见的C语言main函数有:
-
int main(int argc,char* argv[],char** envp)
我们首先给出C语言的获取命令行参数和环境变量的代码:
-
manu@manu-hacks:~/code/c/self/env$ cat env.c
-
-
#include<stdio.h>
-
#include<stdlib.h>
-
-
-
int main(int argc,char* argv[],char** envp)
-
{
-
int i;
-
printf("there are %d input param\n",argc);
-
printf("they are :\n");
-
for(i = 0 ; i < argc ; i++)
-
{
-
printf("%s\n",argv[i]);
-
}
-
-
printf("env LIST--------------------------------------\n");
-
char **p = envp;
-
for(;*p != NULL;p++)
-
{
-
printf("%s\n",*p);
-
}
-
return 0;
-
}
golang自然也可以做到,获取命令行参数,获取环境变量。
-
manu@manu-hacks:~/code/go/self$ godoc os Args
-
PACKAGE DOCUMENTATION
-
-
package os
-
import "os"
-
-
-
-
VARIABLES
-
-
var Args []string
-
Args hold the command-line arguments, starting with the program name.
我们先写一个简单的获取命令行参数的go 程序:
-
manu@manu-hacks:~/code/go/self$ cat sum.go
-
package main
-
import "fmt"
-
import "os"
-
import "strconv"
-
-
-
func main() int{
-
arg_num := len(os.Args)
-
fmt.Printf("the num of input is %d\n",arg_num)
-
-
fmt.Printf("they are :\n")
-
for i := 0 ; i < arg_num ;i++{
-
fmt.Println(os.Args[i])
-
}
-
-
sum := 0
-
for i := 1 ; i < arg_num; i++{
-
curr,err := strconv.Atoi(os.Args[i])
-
if(err != nil){
-
fmt.Println("error happened ,exit")
-
return 1
-
}
-
sum += curr
-
}
-
-
fmt.Printf("sum of Args is %d\n",sum)
-
return 0
-
}
输出如下:
-
manu@manu-hacks:~/code/go/self$ ./sum 1 2 4
-
the num of input is 4
-
they are :
-
./sum
-
1
-
2
-
4
-
sum of Args is 7
-
manu@manu-hacks:~/code/go/self$ ./sum 1 2 4 f 5
-
the num of input is 6
-
they are :
-
./sum
-
1
-
2
-
4
-
f
-
5
-
error happened ,exit
另外一个方面是如何获取环境变量。对于C而言,直接就是 之际而言os中也有获取环境变量的函数:
-
FUNCTIONS
-
-
func Environ() []string
-
Environ returns a copy of strings representing the environment, in the
-
form "key=value".
-
-
func Getenv(key string) string
-
Getenv retrieves the value of the environment variable named by the key.
-
It returns the value, which will be empty if the variable is not
-
present.
有了这个,就简单了。写了个简单的例子:
-
manu@manu-hacks:~/code/go/self$ cat env.go
-
package main
-
import "fmt"
-
import "os"
-
-
func main(){
-
-
environ := os.Environ()
-
for i := range environ {
-
fmt.Println(environ[i])
-
}
-
fmt.Println("------------------------------------------------------------\n")
-
logname := os.Getenv("LOGNAME")
-
fmt.Printf("logname is %s\n",logname)
-
}
输出如下:
-
manu@manu-hacks:~/code/go/self$ go run env.go
-
SSH_AGENT_PID=2331
-
GPG_AGENT_INFO=/tmp/keyring-5CkALe/gpg:0:1
-
TERM=xterm
-
SHELL=/bin/bash
-
。。。
-
-
------------------------------------------------------------
-
-
logname is manu
参考文献
1 Package os
阅读(561) | 评论(0) | 转发(0) |