运行 shell 命令 crystal 语言并捕获输出

running shell commands crystal language and capturing the output

我习惯在Ruby中使用open3 to 运行命令。由于 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.

提前感谢所有建议。

大概是这样的:

def run_cmd(cmd, args)
  stdout = IO::Memory.new
  stderr = IO::Memory.new
  status = Process.run(cmd, args: args, output: stdout, error: stderr)
  if status.success?
    {status.exit_code, stdout.to_s}
  else
    {status.exit_code, stderr.to_s}
  end
end

我们不需要关闭 IO::Memory 因为它不代表任何 OS 资源的句柄,只是一块内存,我们使用元组而不是数组来return。这意味着调用者知道我们正好 returning 两个项目,第一个是数字,第二个是字符串。使用数组 return 调用者只知道我们正在 returning 任意数量的项目,其中任何一个都可以是 int32 或字符串。

然后您可以像这样使用它:

cmd = "ping"
hostname = "my_host"
args = ["-c 2", hostname]
status, output = run_cmd(cmd, args)
puts "ping: #{hostname}: Name or service not known" unless status == 0