Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.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
如何从Ruby on Windows运行非ASCII/Unicode shell命令?_Ruby_Unicode_Character Encoding - Fatal编程技术网

如何从Ruby on Windows运行非ASCII/Unicode shell命令?

如何从Ruby on Windows运行非ASCII/Unicode shell命令?,ruby,unicode,character-encoding,Ruby,Unicode,Character Encoding,我无法找到正确的方法来编码要在Ruby on Windows上运行的shell命令。以下脚本再现了该问题: # 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 "S

我无法找到正确的方法来编码要在Ruby on Windows上运行的shell命令。以下脚本再现了该问题:

# 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中的一个bug,还是我需要在将命令字符串传递到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\u CTYPE
,如下所示:

 LC_CTYPE=en_US.UTF-8
在命令shell或Ruby脚本中全局设置:

ENV['LC_CTYPE']='en_US.UTF-8' 

我在windows中使用拖放时也遇到了同样的问题。 当我删除一个名称中包含unicode字符的文件时,unicode字符被问号替换。 尝试了编码、更改drophandler等方面的一切。 唯一有效的方法是创建一个包含以下内容的批处理文件

ruby.exe -Eutf-8 C:\Users\user\myscript.rb %*
批处理文件确实正确接收unicode字符,正如您首先执行
echo%*
然后执行
pause

我需要添加
-Eutf-8
参数,使文件名在脚本本身中以UTF-8的形式出现,在脚本中包含以下行是不够的

#encoding: UTF-8
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8

希望这能帮助有类似问题的人。

这并不能解决我的问题。我上面的脚本是否适用于您的更改?显然,使用cmd.exe是不可能的。如果在shell命令之后添加
put returned.encoding
,您会得到什么?
UTF-8
。所有的ruby字符串都是UTF-8。这与发送到cmd.exe的命令的编码有关。这里也有同样的问题。必须有一种方法将Unicode添加到shell中。。。