Ruby-on-rails 如何在 Rake 任务中执行命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3668607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:10:59  来源:igfitidea点击:

How to execute commands within Rake tasks?

ruby-on-railsshellcommand-linerakerake-task

提问by palani

I have the rake tasks in my rails application. i want to run a commandline commands with in rake task. how can i do this. i tried by the following but fails

我的 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

The above run command throws run method undefined & System command not throwing any errors but not executed.

上面的 run 命令抛出 run method undefined & System 命令没有抛出任何错误但没有执行。

回答by tadman

runis used by Capistrano and other things for launching commands, but Rake often makes use of Kernel#systeminstead.

runCapistrano 和其他东西使用它来启动命令,但 Rake 经常使用它来Kernel#system代替。

Your command might be being run, but not working. Why not make a wrapper shell script you can test independently, or try and kick off using the full path:

您的命令可能正在运行,但不起作用。为什么不制作一个可以独立测试的包装器 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

It would seem odd to have your script not in scripts/

没有你的脚本似乎很奇怪 scripts/

The systemcall should return trueon success. If this is not the case, either the script returned an error code, or the command could't be run.

system调用应该返回true成功。如果不是这种情况,要么是脚本返回了错误代码,要么是无法运行命令。