如何在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命令抛出run method 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
但是:
- 如果返回是!= 0,它就会中止,所以上面的内容永远不会到达
echo b
- 命令本身在输出之前回显
run
由Capistrano和其他东西用于启动命令,但Rake经常使用Kernel#system
。
您的命令可能正在运行,但无法运行。 为什么不创建一个可以独立测试的包装器shell脚本,或尝试使用完整路径启动:
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/
似乎很奇怪scripts/
system
调用应在成功时返回true
。 如果不是这种情况,则脚本返回错误代码,或者无法运行命令。