Ruby打开文件名,在Windows上带有来自shell的空格

时间:2018-05-20 11:45:48

标签: ruby windows shell filenames

因此,我可以使用带有system("start filename")的ruby从shell打开文件。但是,当文件上有空格时,即使我添加了转义\,或者我使用了shellescape,它也无法正常工作。

显然,一种方法是先获取文件的8.3短名称,但尝试了这个并没有成功。有谁知道在这种情况下我怎么能简单地逃离一个空间?我目前的代码如下:

    require 'shellwords'
    filename = "#{$filenamewithspaces}.docx".shellescape
    system("start #{filename}")

非常感谢!

3 个答案:

答案 0 :(得分:1)

shellescape在Windows上无效。在Windows上,您可以使用引号来包含复杂的文件名。另请注意,如果使用引号,则需要为start提供两个参数,因为第一个参数被解释为命令窗口标题:

  

START [“title”] [/ D path] [/ I] [/ MIN] [/ MAX] [/ SEPARATE | /共享]         [/ LOW | / NORMAL | / HIGH | / REALTIME | / ABOVENORMAL | /低于一般]         [/ AFFINITY] [/ WAIT] [/ B] [命令/程序]         [参数]

解决这些问题的最简单方法是使用system的多参数版本:

system('start', '', $filenamewithspaces)

如果必须使用单参数版本,则:

system("start \"\" \"#{$filenamewithspaces}\"")

......正如你所看到的那样,它更加丑陋且不易阅读。

答案 1 :(得分:0)

在变量替换中删除美元符号:

filename = "#{$filenamewithspaces}.docx".shellescape

提示是始终在命令行中启动irb并测试每个命令:

2.4.1 :001 > filenamewithspaces = "string with spaces"
 => "string with spaces"
2.4.1 :002 > "#{$filenamewithspaces}"
 => ""
2.4.1 :003 > "#{filenamewithspaces}"
 => "string with spaces"

答案 2 :(得分:0)

filename="my filename should not have spaces but it does.exe"
system("cmd","/c","start",filename)

我明确地写了" cmd",因此它适用于Ruby,Windows原生和Cygwin Ruby。

如果没有令人信服的理由将整个命令作为单个字符串传递,我总是将这些参数作为数组单独传递。