在Ruby中,我希望能够:
>2&1
(这里的某些命令失败)我了解到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)
答案 0 :(得分:15)
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
启动命令,因此您可以查看documentation for Process.spawn以查看所有选项。