gpt4 book ai didi

ruby - 在已占用的端口上运行 Sinatra 时避免显示回溯

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:41 24 4
gpt4 key购买 nike

当 Sinatra 无法正确运行服务器时(例如,由于端口已被使用),阻止 Sinatra 显示完整回溯的正确方法是什么?

这是一个示例 sinatra 应用程序:

# test.rb
require 'sinatra'
require 'bundler/inline'

gemfile do
gem 'sinatra'
gem 'puma'
end

set :bind, "0.0.0.0"
set :port, 3000

get '/' do
"hello"
end

然后用ruby test.rb运行一次,占用端口。

然后,在另一个终端窗口中再次运行它,显示了这个完整的错误回溯:

$ ruby test.rb
== Sinatra (v2.0.4) has taken the stage on 3000 for development with backup from Puma
Puma starting in single mode...
* Version 3.12.0 (ruby 2.5.0-p0), codename: Llamas in Pajamas
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://0.0.0.0:3000
== Someone is already performing on port 3000!
Traceback (most recent call last):
5: from /store/gems/ruby-2.5.0/gems/sinatra-2.0.4/lib/sinatra/main.rb:26:in `block in <module:Sinatra>'
4: from /store/gems/ruby-2.5.0/gems/sinatra-2.0.4/lib/sinatra/base.rb:1464:in `run!'
3: from /store/gems/ruby-2.5.0/gems/sinatra-2.0.4/lib/sinatra/base.rb:1464:in `ensure in run!'
2: from /store/gems/ruby-2.5.0/gems/sinatra-2.0.4/lib/sinatra/base.rb:1439:in `quit!'
1: from /store/gems/ruby-2.5.0/gems/puma-3.12.0/lib/puma/launcher.rb:147:in `stop'
/store/gems/ruby-2.5.0/gems/puma-3.12.0/lib/puma/single.rb:27:in `stop': undefined method `stop' for nil:NilClass (NoMethodError)
Traceback (most recent call last):
3: from /store/gems/ruby-2.5.0/gems/sinatra-2.0.4/lib/sinatra/base.rb:1545:in `block in setup_traps'
2: from /store/gems/ruby-2.5.0/gems/sinatra-2.0.4/lib/sinatra/base.rb:1439:in `quit!'
1: from /store/gems/ruby-2.5.0/gems/puma-3.12.0/lib/puma/launcher.rb:147:in `stop'
/store/gems/ruby-2.5.0/gems/puma-3.12.0/lib/puma/single.rb:27:in `stop': undefined method `stop' for nil:NilClass (NoMethodError)

因为我将它用作嵌入式服务器,所以我希望输出简单并且带有 Sinatra 已经显示的友好错误:

== Someone is already performing on port 3000!

并避免显示回溯。

最佳答案

默认情况下,Ruby 将错误消息输出到 STDOUT。但是如果你在 *nix 系统上,你可以这样做:

ruby test.rb > /dev/null 2>&1

对于 Windows,你可能可以做到

ruby test.rb > NULL

Windows 电源外壳

ruby test.rb > $null

但对于 Windows 也请参见 Is there a /dev/null on Windows?

但是如果你想在服务器运行时以编程方式抑制输出,这应该适用于 *nix 但不确定是否适用于 windows

# test.rb
require 'sinatra'
require 'bundler/inline'

gemfile do
gem 'sinatra'
gem 'puma'
end

set :bind, "0.0.0.0"
set :port, 3000

get '/' do
"hello"
end

unless `ps aux | grep sinatra`.match('tcp://0.0.0.0:3000')
STDOUT.reopen('/dev/null', 'w')
STDERR.reopen('/dev/null', 'w')
end

参见 suppresing output to console with ruby

关于ruby - 在已占用的端口上运行 Sinatra 时避免显示回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52904402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com