使用自定义环境运行命令行
在 Ruby 中,我希望能够:
- 运行命令行(通过 shell)
- 捕获 stdout 和 stderr(最好作为单个流),而不使用
>2&1
(这里的某些命令失败) - 使用附加环境变量运行(无需修改 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:
- run a command line (via shell)
- capture both stdout and stderr (preferably as single stream) without using
>2&1
(which fails for some commands here) - 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Open.popen3
可以选择接受哈希作为第一个参数(在这种情况下,您的命令将是第二个参数: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:Open
usesProcess.spawn
to start the command, so you can look at the documentation for Process.spawn to see all of it's options.