英文:
Go analogue of Python's fileinput.input()?
问题
有没有Go语言的类似于Python的fileinput.input的函数?
import fileinput
for line in fileinput.input():
process(line)
这样可以让你的程序像grep
一样工作,即可以从命令行指定的文件中读取program input.txt
,也可以从标准输入中读取cat input.txt | program
。
Perl的钻石操作符<>
和Ruby的ARGF类似。
英文:
Is there a Go analogue of Python's fileinput.input?
import fileinput
for line in fileinput.input():
process(line)
That lets your program work likegrep
, ie. it can read either from a files specified from the commald line program input.txt
or from standard input cat input.txt | program
.
Perl's diamond operator <>
and Ruby's ARGF are similar.
答案1
得分: 2
你有几个选择。虽然fileinput.input()
函数也会检查sys.args[1:]
中的任何文件名,但我将专注于从stdin读取。
使用Scanner
。以下是文档中的示例(http://play.golang.org/p/_Nar8-uBDs):
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text()) // Println会添加回最后的'\n'
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}
更低级的替代方法是使用bufio.Reader
及其ReadString()
方法(http://play.golang.org/p/h2sobrWNYd):
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
rbuf := bufio.NewReader(os.Stdin)
for {
line, err := rbuf.ReadString('\n')
fmt.Print(line)
if err != nil {
// line包含最后剩余的字符或为空
// 如果'\n'是输入中的最后一个字符,则为空
break
}
}
}
对于最低级的替代方法,请参阅ReadLine()
。
英文:
You have a couple of options. Although the fileinput.input()
function will also check sys.args[1:]
for any file names, I'm going to focus on reading from stdin here.
Use Scanner
. Example from the docs (http://play.golang.org/p/_Nar8-uBDs):
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text()) // Println will add back the final '\n'
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}
A lower-level alternative would be bufio.Reader
with its ReadString()
method (http://play.golang.org/p/h2sobrWNYd):
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
rbuf := bufio.NewReader(os.Stdin)
for {
line, err := rbuf.ReadString('\n')
fmt.Print(line)
if err != nil {
// line contains the last remaining characters or is empty
// it is only empty if '\n' was the last character in the input
break
}
}
}
For the lowest-level alternative, see ReadLine()
.
答案2
得分: 0
不,标准库中没有Go的类似功能。然而,读取标准输入或命名文件只需要几行代码(示例)。
英文:
No, there's no Go analogue of that in the standard library. However, reading stding or a named file is only a handful of lines (example)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论