stdout - 如果在 Nim 中未检测到控制台,如何将输出重定向到文件
问题描述
如果有控制台,我希望我的 Nim 程序写入控制台,如果没有则重定向echo
到写入文件。是否有与Environment.UserInteractive
.NET 中的属性等效的东西,我可以用它来检测是否没有可用的控制台并在这种情况下重定向标准输出?
解决方案
这是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.
推荐阅读
- angular - 切换路线时防止角动画
- python - 有人可以建议为什么第二个玩家没有被授权吗?
- netlogo - 如何在 NetLogo 中的框中打印输出
- c++ - 浅拷贝不会崩溃
- ruby-on-rails - API Rails:如何在控制器中呈现模型的自定义属性?
- centos7 - 关于隧道问题 IKEv2 的 strongswan 配置和流量
- google-sheets - 如何根据国家/地区显示货币符号
- angular - JHipster 应用程序中的功能标志
- json - HttpFoundation JsonResponse 在 PhpUnit 测试中返回 Null
- oracle-cloud-infrastructure - 如何使用 mobaxterm 连接到 oracle 免费云?