如何使 Ruby C 扩展中调用的 printf 静音?

发布于 2024-12-29 00:24:42 字数 271 浏览 3 评论 0原文

  • 我正在运行一个 Ruby gem,它依赖于 C 扩展(而不是对系统的调用)。
  • C 代码多次调用 printf。
  • 我想使这些调用的输出静音。
  • 更改 Ruby 的 STDOUT(示例)或 STDERR 不会阻止输出文本。

是否可以在不修改C代码的情况下做到这一点?如果是这样,怎么办?

  • I am running a Ruby gem which relies on a C extension (not a call to system).
  • The C code makes several calls to printf.
  • I want to silence the output of these calls.
  • Changing Ruby's STDOUT (example) or STDERR does not prevent the text from being output.

Is it possible to do this without modifying the C code? If so, how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

没︽人懂的悲伤 2025-01-05 00:24:42

有人最初评论我的帖子建议使用 IO.reopen< /a>.这对我有用。不幸的是,这个人已经删除了他/她的评论,所以我发布了我最后使用的更详细的功能:

def silence_stdout(log = '/dev/null')
  old = $stdout.dup
  $stdout.reopen(File.new(log, 'w'))
  yield
  $stdout = old
end

用法:

silence_stdout { foo }              # Won't be displayed, won't be logged.
silence_stdout('log.txt') { bar }   # Won't be displayed, logged in log.txt.

Someone originally commented on my post suggesting to use IO.reopen. This worked for me. The person has unfortunately since deleted his/her comment, so I'm posting the more detailed function I used in the end:

def silence_stdout(log = '/dev/null')
  old = $stdout.dup
  $stdout.reopen(File.new(log, 'w'))
  yield
  $stdout = old
end

Usage:

silence_stdout { foo }              # Won't be displayed, won't be logged.
silence_stdout('log.txt') { bar }   # Won't be displayed, logged in log.txt.
世界如花海般美丽 2025-01-05 00:24:42

Ruby 可能会打印到 stderr 而不是 stdout,这就是为什么更改 Ruby 的 stdout 无法解决您的问题。
stderrstdout 通常都会转到控制台。)

尝试重定向 stderr。我记得它是: myprogram 2> /dev/null

It is possible that Ruby is printing to stderr instead of stdout, which is why changing Ruby's stdout doesn't fix your problem.
(Both stderr and stdout typically go to the console.)

Try redirecting stderr. As I recall it'd be: myprogram 2> /dev/null

友谊不毕业 2025-01-05 00:24:42

如果您有权访问 C 源代码:

#define printf(...)

该宏形式是 C99 可变参数宏。

If you have access to the C source code:

#define printf(...)

This macro form is a C99 variadic macro.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文