如何从Ruby程序内部调用shell命令?然后如何将这些命令的输出返回到Ruby中?
当前回答
您可以使用如下格式方法打印一些信息:
puts format('%s', `ps`)
puts format('%d MB', (`ps -o rss= -p #{Process.pid}`.to_i / 1024))
其他回答
下面是我在OS X上的ruby脚本中使用的一个很酷的脚本(这样我就可以在切换离开窗口后启动脚本并获得更新):
cmd = %Q|osascript -e 'display notification "Server was reset" with title "Posted Update"'|
system ( cmd )
在我看来,这是关于在Ruby中运行shell脚本的最好的文章:“在Ruby中运行shell命令的6种方法”。
如果您只需要获得输出,请使用反勾号。
我需要更高级的东西,比如STDOUT和STDERR,所以我使用了Open4 gem。这里已经解释了所有的方法。
我喜欢的方法是使用%x文字,这使得在命令中使用引号很容易(而且易读!),如下所示:
directorylist = %x[find . -name '*test.rb' | sort]
在这种情况下,它将填充当前目录下的所有测试文件的文件列表,您可以按照预期进行处理:
directorylist.each do |filename|
filename.chomp!
# work with file
end
你也可以使用反勾操作符('),类似于Perl:
directoryListing = `ls /`
puts directoryListing # prints the contents of the root directory
如果你需要简单的东西,很方便。
你想要使用哪种方法取决于你想要完成什么;有关不同方法的更多细节,请查看文档。
这个解释是基于我的一个朋友写的带注释的Ruby脚本。如果您想改进脚本,请在链接中进行更新。
首先,请注意,当Ruby调用shell时,它通常调用/bin/sh,而不是Bash。在所有系统上/bin/sh不支持某些Bash语法。
以下是执行shell脚本的方法:
cmd = "echo 'hi'" # Sample string that can be used
Kernel#` , commonly called backticks – `cmd` This is like many other languages, including Bash, PHP, and Perl. Returns the result (i.e. standard output) of the shell command. Docs: http://ruby-doc.org/core/Kernel.html#method-i-60 value = `echo 'hi'` value = `#{cmd}` Built-in syntax, %x( cmd ) Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters (, [, {, or <, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{ ... } is allowed. Returns the result (i.e. standard output) of the shell command, just like the backticks. Docs: https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings value = %x( echo 'hi' ) value = %x[ #{cmd} ] Kernel#system Executes the given command in a subshell. Returns true if the command was found and run successfully, false otherwise. Docs: http://ruby-doc.org/core/Kernel.html#method-i-system wasGood = system( "echo 'hi'" ) wasGood = system( cmd ) Kernel#exec Replaces the current process by running the given external command. Returns none, the current process is replaced and never continues. Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec exec( "echo 'hi'" ) exec( cmd ) # Note: this will never be reached because of the line above
这里有一些额外的建议: $ ?,与$CHILD_STATUS相同,如果使用反勾号、system()或%x{},则访问最后一个系统执行命令的状态。 然后你可以访问exitstatus和pid属性:
$?.exitstatus
更多阅读请参见:
http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html http://tech.natemurray.com/2007/03/ruby-shell-commands.html