首页 > 解决方案 > 最终从 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 导致检查第一个参数,如果没有提供,或者如果等于“-”,程序设置inputFile为“/dev/stdin”。

我不知道这是否是正确的方法,例如可以从一个 POSIX 系统移植到另一个系统,或者是否有“正确”的方法(我想用更好的词来表达这个问题)。

标签: nim-lang

解决方案


查看https://scripter.co/nim-check-if-stdin-stdout-are-associated-with-terminal-or-pipe/#stdin-stdout-isatty

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

# 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"]

推荐阅读