ruby rails -将控制台输出重定向到文件

fcg9iug3  于 5个月前  发布在  Ruby
关注(0)|答案(7)|浏览(83)

在bash控制台上,如果我这样做:

cd mydir
ls -l > mydir.txt

字符串

操作符捕获标准输入并将其重定向到一个文件;因此我在mydir.txt中而不是在标准输出中获得文件列表。
有没有办法在rails控制台上做类似的事情?
我有一个ruby语句,它会生成大量的打印(大约8 k行),我希望能够完整地看到它,但是控制台只“记住”最后1024行左右。所以我想重定向到一个文件-如果有人知道更好的选择,我洗耳恭听。

jhdbpxl9

jhdbpxl91#

一个快速的一次性解决方案:

irb:001> f = File.new('statements.xml', 'w')
irb:002> f << Account.find(1).statements.to_xml
irb:003> f.close

字符串
创建一个JSON fixture:

irb:004> f = File.new(Rails.root + 'spec/fixtures/qbo/amy_cust.json', 'w')
irb:005> f << JSON.pretty_generate((q.get :customer, 1).as_json)
irb:006> f.close

izkcnapc

izkcnapc2#

您可以使用override $stdout重定向控制台输出:

$stdout = File.new('console.out', 'w')

字符串
您可能还需要调用此命令一次:

$stdout.sync = true


要恢复,请执行以下操作:

$stdout = STDOUT

2nbm6dog

2nbm6dog3#

除了Veger的答案,还有一种方法可以做到这一点,它也提供了许多其他的选择。
打开你的rails项目目录,输入命令:

rails c | tee output.txt

字符串
tee命令还有许多其他选项,您可以通过以下方式检出:

man tee

tvokkenx

tvokkenx4#

如果在环境文件中编写以下代码,它应该可以工作。

if "irb" == $0
  config.logger = Logger.new(Rails.root.join('path_to_log_file.txt'))
end

字符串
您还可以使用

config.logger = Logger.new(Rails.root.join('path_to_log_file.txt'), number_of_files, file_roation_size_threshold)


为了只记录与活动记录相关的操作,您可以

ActiveRecord::Base.logger = Logger.new(Rails.root.join('path_to_log_file.txt'))


这也允许您在不同的环境中使用不同的logger config/file。

7bsow1i6

7bsow1i65#

使用Hirb,你可以选择只将Hirb输出记录到一个文本文件中。这使得你仍然可以看到你在控制台窗口中输入的命令,只有模型输出会进入文件。
Hirb readme
虽然视图默认打印到STDOUT,但可以轻松修改它们以写入任何位置:

# Setup views to write to file 'console.log'.
>> Hirb::View.render_method = lambda {|output| File.open("console.log", 'w') {|f| f.write(output) } }

# Doesn't write to file because Symbol doesn't have a view and thus defaults to irb's echo mode.
>> :blah
=> :blah

# Go back to printing Hirb views to STDOUT.
>> Hirb::View.reset_render_method

字符串

webghufk

webghufk6#

如果您使用的是基于Unix的操作系统,请尝试使用script实用程序。
script -c "rails runner -e development lib/scripts/my_script.rb" report.txt
这帮助我轻松地将Rails runner脚本的超长输出捕获到文件中。
我尝试使用重定向到一个文件,但它只在脚本结束时写入(就像脚本执行结束时一样)。这对我没有帮助,因为我的脚本中几乎没有交互式命令。
然后我只使用script,然后在脚本会话中运行rails runner,但它没有写所有内容。然后我找到了这个script -c "runner command here" output_file,它按照需要保存了所有输出。这是在Ubuntu 14.04 LTS上
参考文献:
https://askubuntu.com/questions/290322/how-to-get-and-copy-a-too-long-output-completely-in-terminal#comment1668695_715798
将Ruby控制台输出写入文本文件

rhfm7lfc

rhfm7lfc7#

使用hirb。它会自动分页irb中任何长于一个屏幕的输出。将其放入控制台会话中以查看其工作情况:

>> require 'rubygems'
>> require 'hirb'
>> Hirb.enable

字符串
更多关于它是如何工作的,read this post

相关问题