最终从STDIN读取一个gzip文件:正确的方法是什么



我希望能够从一个可以进行gzip映射的文本文件中读取,该文件可以作为stdin的流。

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导致检查第一个参数,如果没有提供,或者如果等于"0"-&";,程序将CCD_ 2设置为"0"/dev/stdin";。

我不知道这是否是一种正确的方式,并且可以从一个POSIX系统移植到另一个,例如;适当的";方式(我想用更好的词语来表述这个问题(。

退房https://scripter.co/nim-check-if-stdin-stdout-are-associated-with-terminal-or-pipe/#stdin-标准输出是

将代码粘贴在此处以确保完整性:

# 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.txtn def.txt" | ./BINARY
inputFiles = @["abc.txt", "def.txt"]

最新更新