In Ruby, I want to be able to:
>2&1
(which fails for some commands here)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)
Command line environment The environment of the command line refers to the settings and preferences of the current user. It enables users to set greetings, alias commands, variables, and much more.
If you have a Unix/Linux/MacOs terminal you navigate to the project root directory and type touch . env which will create a file named . env to hold configuration information.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With