我无法弄清楚编写一个
shell命令在
Windows上从
Ruby运行的正确方法.以下脚本重现了该问题:
# encoding: utf-8 def test(word) returned = `echo #{word}`.chomp puts "#{word} == #{returned}" raise "Cannot roundtrip #{word}" unless word == returned end test "good" test "bÃd" puts "Success" # win7,cmd.exe font set to Lucinda Console,chcp 65001 # good == good # bÃd == bÃd
这是Ruby中的错误,还是我需要手动将命令字符串编码为特定的编码,然后才能传递给cmd.exe进程?
更新:我想清楚地说明问题不在于将输出读回Ruby,而是纯粹将命令发送到shell.展示:
# encoding: utf-8 File.open("bbbÃd.txt","w") do |f| f.puts "nothing to see here" end filename = Dir.glob("bbb*.txt").first command = "attrib #{filename}" puts command.encoding puts "#{filename} exists?: #{ File.exists?(filename) }" system command File.delete(filename) #=> # UTF-8 # bbbÃd.txt exists?: true # File not found - bbbÃd.txt
您可以看到文件是否正确创建,File.exists?方法确认Ruby可以看到它,但是当我尝试在其上运行attrib命令时,它试图使用不同的文件名.
解决方法
尝试像这样设置环境变量LC_CTYPE:
LC_CTYPE=en_US.UTF-8
在命令shell或Ruby脚本内全局设置:
ENV['LC_CTYPE']='en_US.UTF-8'