[Ruby] Calling external programs

Source: Internet
Author: User

1. system method. System is followed by the command string of the System Shell to be executed as the parameter. This method allows the system program to run in a sub-shell. This is a conventional method for booting external programs in the system through Ruby scripts.

System "CMD/C del./hello.txt"
System "calc"

System ("D: & cd d:/opt/rails-app & Ruby script/Server ")

2. Exec method. This method is somewhat similar to the system method. It accepts a string format command, but the difference is obvious, the new process started by the program guided by exec will overwrite the current process, and a script will be released. For example, we write:

Exec ('dir ')

Puts 'can show the message? '# This line of code will never be executed

3. Run the command using. Ruby contains an interesting way to execute external programs: by including the system shell between the symbols. In this way, if the shell returns information after execution, the returned information can be saved in a variable. For example, if we want to determine whether a process is running in the system and kill it, we can write:

Show_p = 'tasklist'

System ('tskill ipolice') If show_p.include? 'Ipluse'

In Windows XP, The tasklist command can obtain information about all processes in the system. We put the system shell in ''for execution, assigned a value to the show_p object, and then called its include? Method to check whether there is an iexplore process (IE browser). If yes, close it. (The code is really easy to read, right? Like reading simple English statements, this is Ruby's charm !) With these two statements, we can actually manage the execution of any process in the system!

If there is a path problem, you need to switch to the required path for calling.

Get current job path
X = dir. getwd
Print_status (X)

Switch path to path
Dir. chdir ("path ")

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.