How to redirect a "system" standard output to a variable

V

Venks

Note: parts of this message were removed by the gateway to make it a legal Usenet post.

Hi,

I need to redirect any standard output thrown when using a system call into
a Ruby variable. I tried to search for a solution but couldn't find anything
that worked. May be I am not using the right search terms.

Here is what I am trying to do.

begin

`rm somefile`

end

If "somefile" doesn't exist the OS throws the message "rm: cannot remove
`somefile': No such file or directory" which I want to capture into a
variable.

Thanks,
 
D

dusty

Note: parts of this message were removed by the gateway to make it a legal Usenet post.

Hi,

I need to redirect any standard output thrown when using a system call into
a Ruby variable. I tried to search for a solution but couldn't find anything
that worked. May be I am not using the right search terms.

Here is what I am trying to do.

begin

`rm somefile`

end

If "somefile" doesn't exist the OS throws the message "rm: cannot remove
`somefile': No such file or directory" which I want to capture into a
variable.

Thanks,

I use open4 for things like that. Try this it will show you how it
works.
http://codeforpeople.com/lib/ruby/open4/

# test.rb
require 'rubygems'
require 'open4'

commands = ["rm somefile","ls"]
commands.each do |command|
status = Open4::popen4(command) do |pid,stdin,stdout,stderr|
puts "Running command: #{command}\n\n"
puts "pid:\n#{pid}"
puts "\nstdout:\n#{stdout.read.strip}"
puts "\nstderr:\n#{stderr.read.strip}"
end
puts "\nexitcode\n#{status.exitstatus}\n"
puts "----------\n\n\n"
end

$ ruby test.rb
Running command: rm somefile

pid:
11207

stdout:

stderr:
rm: somefile: No such file or directory

exitcode
1
----------


Running command: ls

pid:
11208

stdout:
test.rb

stderr:

exitcode
0
----------
 
M

Morton Goldberg

Hi,

I need to redirect any standard output thrown when using a system
call into
a Ruby variable. I tried to search for a solution but couldn't find
anything
that worked. May be I am not using the right search terms.

Here is what I am trying to do.

begin

`rm somefile`

end

If "somefile" doesn't exist the OS throws the message "rm: cannot
remove
`somefile': No such file or directory" which I want to capture into a
variable.

Thanks,

sys_msg = `rm /Users/Desktop/foo.txt 2>&1`
sys_msg # => "rm: /Users/Desktop/foo.txt: No such file or directory\n"

Regards, Morton
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,733
Latest member
LonaMonzon

Latest Threads

Top