我在ruby脚本中使用了system "java -cp xxx.jar",它在Mac上运行良好。但当我在Windows7 x64上运行脚本时,这些java -cp xxx.jar没有被执行,也没有报告错误。
发布于 2010-10-12 14:02:42
如果您的命令无法运行,system不会抛出异常或其他任何东西(这可能是您说“没有报告错误”的原因)。
因此,您需要检查java是否在您的PATH中;在Windows上,缺省情况下没有,并且需要将JDK的bin目录添加到您的PATH中。
发布于 2010-10-12 21:42:08
同样,如果您在类路径中使用多个java类,并使用“:”(冒号)而不是Windows中的“;”(分号),则无法执行脚本;
classpath_separator = RUBY_PLATFORM =~ /mswin/ ? ';' : ':'
如果你想捕获系统命令的输出,你可以使用下面的代码:
def run_cmd cmd, cmd_name = 'Command'
# save current STDOUT reference
default_stdout = STDOUT.dup
# temp file used to capture output of the child processes
# and avoid conflicts between several processes running at the same time
# (temp file has a unique name and will be cleaned after close)
tmp_file = Tempfile.new 'tmp'
cmd_output = ''
puts "Begin #{cmd_name}: #{cmd}"
begin
# redirect default STDOUT to the tempfile
$stdout.reopen tmp_file
# execute command
system "#{cmd} 2>&1"
ensure
# read temp file content
tmp_file.rewind
cmd_output = tmp_file.read
tmp_file.close
# restore default STDOUT
$stdout.reopen default_stdout
end
# push output to console
puts "Output of #{cmd_name}: #{cmd_output}"
puts "End #{cmd_name}"
cmd_output
endhttps://stackoverflow.com/questions/3912038
复制相似问题