首页 > 解决方案 > 如果在 Nim 中未检测到控制台,如何将输出重定向到文件

问题描述

如果有控制台,我希望我的 Nim 程序写入控制台,如果没有则重定向echo到写入文件。是否有与Environment.UserInteractive.NET 中的属性等效的东西,我可以用它来检测是否没有可用的控制台并在这种情况下重定向标准输出?

标签: stdoutio-redirectionnim-lang

解决方案


这是genotranceisatty()建议的使用和您找到的代码的组合:)

# stdout_to_file.nim 
import terminal, strformat, times

if isatty(stdout): # ./stdout_to_file
  echo "This is output to the terminal."
else:              # ./stdout_to_file | cat
  const
    logFileName = "log.txt"
  let
    # https://github.com/jasonrbriggs/nimwhistle/blob/183c19556d6f11013959d17dfafd43486e1109e5/tests/cgitests.nim#L15
    logFile = open(logFileName, fmWrite)
  stdout = logFile
  echo fmt"This is output to the {logFileName} file."
  echo fmt"- Run using nim {NimVersion} on {now()}."

将上述文件另存为stdout_to_file.nim.

运行时:

nim c stdout_to_file.nim && ./stdout_to_file | cat

我在 created 中得到了这个log.txt

This is output to the log.txt file.
- Run using nim 0.19.9 on 2019-01-23T22:42:27-05:00.

推荐阅读