简体   繁体   中英

Go obtain a directory name as an argument

Go obtain a directory name from the сyrillic as an argument

How to get the full path, not cut garbage. Example: The path as a program argument /home/spouk/spouk.download/torrent/Сергей Лукьяненко, Собрание сочинений/

I get in the trimmed version of the program, how to fix? /Home/spouk/spouk.download/torrent/Сергей

example simple code

package main

import (
    "flag"
    "fmt"
)

func main() {
    wordPtr := flag.String("path", "foo", "a string")
    flag.Parse()
    fmt.Printf("Flag: -path=`%v`\nflag.Args: %v\n", *wordPtr, flag.Args())
    fmt.Printf("Rune: %v\n", []rune(*wordPtr))
}

This is not a matter of the Go code but how you pass it into your program, try passing the path in double quotes "…"

./main -path="/home/spouk/spouk.download/torrent/Сергей Лукьяненко, Собрание сочинений/"
> Flag: -path=`/home/spouk/spouk.download/torrent/Сергей Лукьяненко, Собрание сочинений/`
> flag.Args: []
> Rune: [47 104 111 109 101 47 115 112 111 117 107 47 115 112 111 117 107 46 100 111 119 110 108 111 97 100 47 116 111 114 114 101 110 116 47 1057 1077 1088 1075 1077 1081 32 1051 1091 1082 1100 1103 1085 1077 1085 1082 1086 44 32 1057 1086 1073 1088 1072 1085 1080 1077 32 1089 1086 1095 1080 1085 1077 1085 1080 1081 47]

This has nothing to do with Go. This has nothing to do with cyrillic. It is how the shell parses the command line. It is using spaces to separate arguments. Enclose the argument in double quotes (") to override. For example,

package main

import (
    "flag"
    "fmt"
    "os"
)

func main() {
    fmt.Printf("os.Args:   %q\n", os.Args[1:])
    wordPtr := flag.String("path", "foo", "a string")
    flag.Parse()
    fmt.Printf("flag.path: %q\n", *wordPtr)
    fmt.Printf("flag.Args: %q\n", flag.Args())
}

Output:

$ go run path.go -path=/home/spouk/Сергей Лукьяненко, Собрание сочинений/
os.Args:   ["-path=/home/spouk/Сергей" "Лукьяненко," "Собрание" "сочинений/"]
flag.path: "/home/spouk/Сергей"
flag.Args: ["Лукьяненко," "Собрание" "сочинений/"]

$ go run path.go -path="/home/spouk/Сергей Лукьяненко, Собрание сочинений/"
os.Args:   ["-path=/home/spouk/Сергей Лукьяненко, Собрание сочинений/"]
flag.path: "/home/spouk/Сергей Лукьяненко, Собрание сочинений/"
flag.Args: []

Bash Reference Manual

3.1.2.3 Double Quotes

Enclosing characters in double quotes ('"') preserves the literal value of all characters within the quotes [with some exceptions].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM