Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写rakefile以在windows中运行命令的最佳方法是什么?_Windows_Ruby_Command Line_Command_Rake - Fatal编程技术网

编写rakefile以在windows中运行命令的最佳方法是什么?

编写rakefile以在windows中运行命令的最佳方法是什么?,windows,ruby,command-line,command,rake,Windows,Ruby,Command Line,Command,Rake,例如,我想在rake下运行以下命令 robocopy C:\Media \\other\Media /mir 我能工作的耙子是 def sh(str) str.tr!('|', '\\') IO.popen(str) do |pipe| pipe.each do |line| puts line end end end task :default do sh 'robocopy C:|Media ||other|Media /mir' end 然

例如,我想在rake下运行以下命令

robocopy C:\Media \\other\Media /mir
我能工作的耙子是

def sh(str)
  str.tr!('|', '\\')
  IO.popen(str) do |pipe|
    pipe.each do |line|
      puts line
    end
  end
end

task :default do
  sh 'robocopy C:|Media ||other|Media /mir'
end
然而,字符串文本的处理是笨拙的

如果我使用heredoc输入字符串文字

<<HEREDOC
copy C:\Media \\other\Media /mir
HEREDOC
如果我使用单引号,其中一个反斜杠就会丢失

irb(main):001:0> 'copy C:\Media \\other\Media /mir'
=> "copy C:\\Media \\other\\Media /mir"

双反斜杠被解释为转义单反斜杠。您应该转义字符串中的每个反斜杠

irb(main):001:0> puts 'robocopy C:\\Media \\\\other\\Media /mir'
robocopy C:\Media \\other\Media /mir
或者,如果您确实不想避开反斜杠,可以使用带有单引号标识符的here文档

irb(main):001:0> <<'HEREDOC'
irb(main):002:0' copy C:\Media \\other\Media /mir
irb(main):003:0' HEREDOC
=> "copy C:\\Media \\\\other\\Media /mir\n"
irb(main):004:0> puts _
copy C:\Media \\other\Media /mir
irb(main):001:0>put_
复制C:\Media\\other\Media/mir

是的,但就像我在问题中列出的代码一样,转义所有反斜杠字符很难。我认为简单地转义字符串中的反斜杠是最不难的,但我用可行的here doc语法更新了答案。好的,太好了!埃雷多克是最好的选择。。。这是我第一次看到引号类型指示如何处理字符串。执行shell命令的倒勾(`)也是有效的。看见
irb(main):001:0> <<'HEREDOC'
irb(main):002:0' copy C:\Media \\other\Media /mir
irb(main):003:0' HEREDOC
=> "copy C:\\Media \\\\other\\Media /mir\n"
irb(main):004:0> puts _
copy C:\Media \\other\Media /mir