问题描述
我希望能够从可以压缩的文本文件中读取,并且可以作为来自标准输入的流。
import zip/gzipfiles # Import zip package
# get "inputFile" being a string with the filename or "-" to read from STDIN?
if inputFile == "-":
inputFile = "/dev/stdin"
let file = newGzFileStream(inputFile)
defer: file.close()
var line: string # Declare line variable
while not file.atEnd():
line = file.readLine()
echo line
我实现它的方式 cat file.txt(.gz) | my_prog
导致检查第一个参数,如果没有提供,或者如果等于“-”,程序将 inputFile
设置为“/dev/stdin”。>
我不知道这是否是一种正确的方法,例如,可以从一个 POSIX 系统移植到另一个系统,或者是否有“正确”的方法(我想用更好的词来表述问题).
解决方法
为了完整起见,将代码粘贴到此处:
# Figuring out if input is coming from a pipe and if output is going to a pipe.
import std/[terminal,strutils]
if isatty(stdin):
# ./stdin_stdout foo
# ./stdin_stdout foo | cat
echo "--> Input from terminal"
else:
# echo bar | ./stdin_stdout
# echo bar | ./stdin_stdout | cat
echo "--> Input from a PIPE/FILE: `" & readAll(stdin).strip() & "'"
if isatty(stdout):
# ./stdin_stdout foo
# echo bar | ./stdin_stdout foo
echo " Output to terminal -->"
else:
# ./stdin_stdout | cat
# echo bar | ./stdin_stdout | cat
echo " Output to a PIPE -->"
另一个例子
import std/[terminal,strutils,os]
# Assuming space-separated file names.
let
inputFiles = if isatty(stdin):
commandLineParams()
else:
readAll(stdin).strip().split()
echo "inputFiles = ",inputFiles
通过上面的代码,我们得到了这样的结果:
> ./BINARY abc.txt def.txt
inputFiles = @["abc.txt","def.txt"]
> echo "abc.txt def.txt" | ./BINARY
inputFiles = @["abc.txt","def.txt"]
> echo "abc.txt\n def.txt" | ./BINARY
inputFiles = @["abc.txt","def.txt"]