我习惯于使用open3在Ruby中运行命令。由于在crystal-lang中似乎没有等效的库,所以我制作了以下代码:
def run_cmd(cmd, args)
stdout_str = IO::Memory.new
stderr_str = IO::Memory.new
result = [] of Int32 | String
status = Process.run(cmd, args: args, output: stdout_str, error: stderr_str)
if status.success?
result = [status.exit_code, "#{stdout_str}"]
else
result = [status.exit_code, "#{stderr_str}"]
end
stdout_str.close
stderr_str.close
result
end
cmd = "ping"
hostname = "my_host"
args = ["-c 2", "#{hostname}"]
result = run_cmd(cmd, args)
puts "ping: #{hostname}: Name or service not known" if result[0] != 0
有更好的方法吗?这是一位退休的网络专家提出的问题,他不是软件开发人员,正在探索crystal-lang。
感谢所有建议。
stdout.gets_to_end
,结果返回了一个空字符串。而to_s
则按预期工作。这种行为让我感到惊讶。它是由什么引起的呢? - harm