Ruby 스크립트 내에서 명령 줄 명령 실행
Ruby를 통해 명령 줄 명령을 실행하는 방법이 있습니까? 'screen', 'rcsz'등과 같은 명령 줄 프로그램을 통해 전화를 걸고 받고 / 보내는 작은 Ruby 프로그램을 만들려고합니다.
이 모든 것을 Ruby (MySQL 백엔드 등)와 연결하면 좋을 것입니다.
예. 여러 가지 방법이 있습니다.
ㅏ. 사용 %x
또는 '' ':
%x(echo hi) #=> "hi\n"
%x(echo hi >&2) #=> "" (prints 'hi' to stderr)
`echo hi` #=> "hi\n"
`echo hi >&2` #=> "" (prints 'hi' to stderr)
이 메서드는 stdout을 반환하고 stderr을 프로그램으로 리디렉션합니다.
비. 사용 system
:
system 'echo hi' #=> true (prints 'hi')
system 'echo hi >&2' #=> true (prints 'hi' to stderr)
system 'exit 1' #=> nil
이 메서드는 true
명령이 성공한 경우 반환 됩니다. 모든 출력을 프로그램으로 리디렉션합니다.
씨. 사용 exec
:
fork { exec 'sleep 60' } # you see a new process in top, "sleep", but no extra ruby process.
exec 'echo hi' # prints 'hi'
# the code will never get here.
그러면 현재 프로세스가 명령에 의해 생성 된 프로세스로 바뀝니다.
디. (루비 1.9) 사용 spawn
:
spawn 'sleep 1; echo one' #=> 430
spawn 'echo two' #=> 431
sleep 2
# This program will print "two\none".
이 메서드는 프로세스가 종료 될 때까지 기다리지 않고 PID를 반환합니다.
이자형. 사용 IO.popen
:
io = IO.popen 'cat', 'r+'
$stdout = io
puts 'hi'
$stdout = IO.new 0
p io.read(1)
io.close
# prints '"h"'.
이 메서드는 IO
새 프로세스의 입력 / 출력을 반영 하는 개체를 반환합니다 . 또한 현재 프로그램 입력을 제공하는 유일한 방법입니다.
에프. 사용 Open3
(1.9.2 이상)
require 'open3'
stdout,stderr,status = Open3.capture3(some_command)
STDERR.puts stderr
if status.successful?
puts stdout
else
STDERR.puts "OH NO!"
end
Open3
두 출력 스트림에 대한 명시 적 액세스를 얻기위한 몇 가지 다른 기능이 있습니다. popen과 비슷하지만 stderr에 액세스 할 수 있습니다.
Ruby에서 시스템 명령을 실행하는 몇 가지 방법이 있습니다.
irb(main):003:0> `date /t` # surround with backticks
=> "Thu 07/01/2010 \n"
irb(main):004:0> system("date /t") # system command (returns true/false)
Thu 07/01/2010
=> true
irb(main):005:0> %x{date /t} # %x{} wrapper
=> "Thu 07/01/2010 \n"
그러나 명령의 stdin / stdout을 사용하여 실제로 입력 및 출력을 수행해야하는 경우 IO::popen
특히 해당 기능을 제공하는 메서드 를보고 싶을 것입니다 .
folder = "/"
list_all_files = "ls -al #{folder}"
output = `#{list_all_files}`
puts output
Yes this is certainly doable but the method of implementation differs dependant on whether the "command line" program in question operates in "Full screen" or command line mode. Programs written for the command line tend to read STDIN and write to STDOUT. These can be called directly within Ruby using the standard backticks methods and/or system/exec calls.
If the program operates in "Full Screen" mode like screen or vi then the approach has to be different. For programs like this you should look for a Ruby implementation of the "expect" library. This will allow you to script what you expect to see on screen and what to send when you see those particular strings appear on screen.
This is unlikely to be the best approach and you should probably look at what you are trying to achieve and find the relevant library/gem to do that rather than trying to automate an existing full screen application. As an example "Need assistance with serial port communications in Ruby" deals with Serial Port communications, a pre-cursor to dialing if that is what you want to achieve using the specific programs you mentioned.
The Most Used method is Using Open3
here is my code edited version of the above code with some corrections:
require 'open3'
puts"Enter the command for execution"
some_command=gets
stdout,stderr,status = Open3.capture3(some_command)
STDERR.puts stderr
if status.success?
puts stdout
else
STDERR.puts "ERRRR"
end
참고URL : https://stackoverflow.com/questions/3159945/running-command-line-commands-within-ruby-script
'IT story' 카테고리의 다른 글
NSOperationQueue가 모든 작업을 완료하면 알림 받기 (0) | 2020.09.06 |
---|---|
.NET에는 List a에 List b의 모든 항목이 포함되어 있는지 확인할 수있는 방법이 있습니까? (0) | 2020.09.06 |
방화범을 사용하여 전체 프로그램에 대한 기능 로그 / 스택 추적 인쇄 (0) | 2020.09.06 |
libev와 libevent의 차이점은 무엇입니까? (0) | 2020.09.06 |
Bash 스크립트에 대한 매개 변수 유효성 검사 (0) | 2020.09.06 |