使用自定义环境运行命令行

发布于 2024-11-06 06:00:12 字数 986 浏览 0 评论 0原文

在 Ruby 中,我希望能够:

  1. 运行命令行(通过 shell)
  2. 捕获 stdout 和 stderr(最好作为单个流),而不使用 >2&1 (这里的某些命令失败)
  3. 使用附加环境变量运行(无需修改 ruby​​ 程序本身的环境)

我了解到 Open3 允许我执行 1 和 2。

              cmd = 'a_prog --arg ... --arg2 ...'
              Open3.popen3("#{cmd}") { |i,o,e|
                output = o.read()
                error = e.read()
                # FIXME: don't want to *separate out* stderr like this
                repr = "$ #{cmd}\n#{output}"
              }

我还了解到 popen 允许您传递环境,但在指定命令行时不能

如何编写同时完成这三个任务的代码?

...

换句话来说,以下 Python 代码的 Ruby 等价物是什么?

>>> import os, subprocess
>>> env = os.environ.copy()
>>> env['MYVAR'] = 'a_value'
>>> subprocess.check_output('ls -l /notexist', env=env, stderr=subprocess.STDOUT, shell=True)

In Ruby, I want to be able to:

  1. run a command line (via shell)
  2. capture both stdout and stderr (preferably as single stream) without using >2&1 (which fails for some commands here)
  3. run with additional enviornment variables (without modifying the environment of the ruby program itself)

I learned that Open3 allows me to do 1 and 2.

              cmd = 'a_prog --arg ... --arg2 ...'
              Open3.popen3("#{cmd}") { |i,o,e|
                output = o.read()
                error = e.read()
                # FIXME: don't want to *separate out* stderr like this
                repr = "$ #{cmd}\n#{output}"
              }

I also learned that popen allows you to pass an environment but not when specifying the commandline.

How do I write code that does all the three?

...

Put differently, what is the Ruby equivalent of the following Python code?

>>> import os, subprocess
>>> env = os.environ.copy()
>>> env['MYVAR'] = 'a_value'
>>> subprocess.check_output('ls -l /notexist', env=env, stderr=subprocess.STDOUT, shell=True)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆之渊 2024-11-13 06:00:12

Open.popen3 可以选择接受哈希作为第一个参数(在这种情况下,您的命令将是第二个参数:

cmd = 'a_prog --arg ... --arg2 ...'
Open3.popen3({"MYVAR" => "a_value"}, "#{cmd}") { |i,o,e|
  output = o.read()
  error = e.read()
  # FIXME: don't want to *separate out* stderr like this
  repr = "$ #{cmd}\n#{output}"
}

Open 使用 Process.spawn 来启动命令,这样你就可以查看Process.spawn的文档 查看全部这是选项。

Open.popen3 optionally accepts a hash as the first argument (in which case your command would be the second argument:

cmd = 'a_prog --arg ... --arg2 ...'
Open3.popen3({"MYVAR" => "a_value"}, "#{cmd}") { |i,o,e|
  output = o.read()
  error = e.read()
  # FIXME: don't want to *separate out* stderr like this
  repr = "$ #{cmd}\n#{output}"
}

Open uses Process.spawn to start the command, so you can look at the documentation for Process.spawn to see all of it's options.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文