nim-lang - 最终从 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 系统移植到另一个系统,或者是否有“正确”的方法(我想用更好的词来表达这个问题)。
解决方案
将代码粘贴到此处以确保完整性:
# 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"]
推荐阅读
- apache-spark - Spark:如何将 pairRdd 的值转换为 Rdd?
- nginx - 是否可以使用 openresty 和 docker 实时重新加载 lua 脚本?
- c++ - Qt:如何使不兼容的发送方/接收方参数兼容?
- c++ - thread_local unordered_map 加上 AccessibleObjectFromWindow 不在 WinXP 中运行
- ios - 裁剪为形状的 SwiftUI 图像在上下文菜单中具有透明填充
- go - 类型定义 - 即使基本类型是自定义类型的来源,也不能将基本类型用作自定义类型
- python - ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型浮点数)
- php - 分解源自 CURL 响应的数组
- git - 无法通过使用 push {remote} {src branch}:{dst branch} 更新分支中的拉取请求文件
- r - 将矩阵转换为R中的对称矩阵