运行shell脚本时缺少Ruby双引号
我从发送的数据中创建了一些json,当我将存储在变量中的json传递给另一个脚本(用python创建)时,我注意到json元素不再是双引号运行shell脚本时缺少Ruby双引号,ruby,json,shell,Ruby,Json,Shell,我从发送的数据中创建了一些json,当我将存储在变量中的json传递给另一个脚本(用python创建)时,我注意到json元素不再是双引号 json = @report.resultReportToJSON(result_type, result, unit) puts "#{json}" `"python ./post_request.py --json '#{json}'"` 我的输出是这样的。从这个角度来看: {"test_name":"Launch","requester":"foo
json = @report.resultReportToJSON(result_type, result, unit)
puts "#{json}"
`"python ./post_request.py --json '#{json}'"`
我的输出是这样的。从这个角度来看:
{"test_name":"Launch","requester":"foo","device_serial":"1234"}
执行的命令(我们有一些输出命令的日志记录)是
您可以注意到双引号消失了请尝试以下操作:
require 'json'
`"python ./post_request.py --json '#{json.to_json}'"`
这可能有助于确保在转换为系统命令时使用转义引号序列化对象 使用
system
,而不是反勾号,怎么样:
system "python", "./post_request.py", "--json", json
由于反勾选命令是由/bin/sh执行的,所以双引号会被shell占用。使用system
可以让您不用玩带引号的猜谜游戏:
$ irb
irb(main):001:0> json = '{"test_name":"Launch","requester":"foo","device_serial":"1234"}'
=> "{\"test_name\":\"Launch\",\"requester\":\"foo\",\"device_serial\":\"1234\"}"
irb(main):002:0> puts `echo #{json}`
test_name:Launch requester:foo device_serial:1234
=> nil
irb(main):003:0> puts `echo "#{json}"`
{test_name:Launch,requester:foo,device_serial:1234}
=> nil
irb(main):004:0> puts `echo '#{json}'`
{"test_name":"Launch","requester":"foo","device_serial":"1234"}
=> nil
irb(main):005:0> system "echo", json
{"test_name":"Launch","requester":"foo","device_serial":"1234"}
=> true
这看起来很可疑:
“python./post_request.py--json'.{json}'
--为什么整个命令都用双引号括起来?您好,这可能很好地解决了问题。。。但是,如果你能提供一些关于它如何工作以及为什么工作的解释,那就太好了:)别忘了——堆栈溢出上有很多新手,他们可以从你的专业知识中学到一两件事——对你来说显而易见的事对他们来说可能不是这样。
$ irb
irb(main):001:0> json = '{"test_name":"Launch","requester":"foo","device_serial":"1234"}'
=> "{\"test_name\":\"Launch\",\"requester\":\"foo\",\"device_serial\":\"1234\"}"
irb(main):002:0> puts `echo #{json}`
test_name:Launch requester:foo device_serial:1234
=> nil
irb(main):003:0> puts `echo "#{json}"`
{test_name:Launch,requester:foo,device_serial:1234}
=> nil
irb(main):004:0> puts `echo '#{json}'`
{"test_name":"Launch","requester":"foo","device_serial":"1234"}
=> nil
irb(main):005:0> system "echo", json
{"test_name":"Launch","requester":"foo","device_serial":"1234"}
=> true