如何在Rake任务中执行命令?
我的Rails应用程序中有rake任务。 我想用rake任务运行一个命令行命令。 我怎样才能做到这一点。 我尝试了以下但失败
desc "Sending the newsletter to all the users"
task :sending_mail do
run "cd #{RAILS_ROOT} && ar_sendmail -o -t NewsLetters -v"
system "cd #{RAILS_ROOT} && ar_sendmail -o -t NewsLetters -v &"
end
上面的运行命令抛出run方法undefined&System命令不抛出任何错误但不执行。
这个链接可以帮助你运行命令行命令进入ruby ...
http://zhangxh.net/programming/ruby/6-ways-to-run-shell-commands-in-ruby/
从Ruby调用shell命令
http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html
%x[command].each do |f|
value = f
end
sh
rake内置可能是最好的方法:
task(:sh) do
sh('echo', 'a')
sh('false')
sh('echo', 'b')
end
该界面与Kernel.system
类似,但是:
echo b
Capistrano和其他方面使用run
来启动命令,但Rake经常使用Kernel#system
。
您的命令可能正在运行,但无法运行。 为什么不制作一个可以独立测试的封装外壳脚本,或者尝试使用完整路径启动:
newsletter_script = File.expand_path('ar_sendmail', RAILS_ROOT)
if (File.exist?(newsletter_script))
unless (system(newsletter_script + ' -o -t NewsLetters -v &'))
STDERR.puts("Script #{newsletter_script} returned error condition")
end
else
STDERR.puts("Could not find newsletter sending script #{newsletter_script}")
end
让您的脚本不在scripts/
system
调用应该在成功时返回true
。 如果不是这种情况,则该脚本返回错误代码,或者该命令无法运行。
上一篇: How to execute commands within Rake tasks?
下一篇: How to integrate a standalone Python script into a Rails application?