Methods and instances of calling system commands, shell scripts, and Python scripts in Nodejs _node.js

Source: Internet
Author: User
Tags curl memory usage prepare python script

Each language has its own advantages, the combination of each to take the director of the program to execute more efficient or to say which implementation is simpler to use which, Nodejs is to use the child process to invoke system commands or files, documents see Http://nodejs.org/api/child_ The PROCESS.HTML,NODEJS process provides an important interface for interacting with the system, with the main APIs: standard input, standard output, and standard error output interfaces.

The NODEJS process provides an important interface for interacting with the system, and its main APIs are:

Interface for standard input, standard output, and standard error output

Child.stdin Get Standard input
Child.stdout Get Standard output
Child.stderr Get standard error output
To get the PID:child.pid of a child process
Provides methods for generating child processes: Child_process.spawn (cmd, args=[], [options])
Provides methods for direct execution of system commands: Child_process.exec (cmd, [options], callback)
Provides methods for invoking script files: child_process.execfile (file, [args], [options], [callback])
Provide a way to kill the process: Child.kill (signal= ' sigterm ')

With an example to feel, very interesting, hehe ~ ~

1, the use of child processes to invoke system commands (get system memory usage)

Create a new Nodejs file named Cmd_spawn.js with the following code:

Copy Code code as follows:

var spawn = require (' child_process '). Spawn;
Free = spawn (' Free ', [' m ']);

Capture standard output and print it to the console
Free.stdout.on (' Data ', function (data) {
Console.log (' Standard output:\n ' + data);
});

Capture standard error output and print it to the console
Free.stderr.on (' Data ', function (data) {
Console.log (' standard error output:\n ' + data);
});

Registering child process shutdown events
Free.on (' Exit ', function (code, signal) {
Console.log (' child process eixt, exit: ' + code ');
});

Here's the result of running the script and running the command ' free-m ' directly, exactly the same:

2. Execute system Command (CHILD_PROCESS.EXEC ())

This I am still very commonly used, the function feeling is stronger than above a little bit. For example, I like to focus on the weather, and now I'm going to curl the weather interface. Returns JSON-formatted data, maybe I'll do something about it and print it out.

New Nodejs file, named Cmd_exec.js:

Copy Code code as follows:

var exec = require (' child_process '). exec;
var cmdstr = ' Curl http://www.weather.com.cn/data/sk/101010100.html ';
Exec (cmdstr, function (err,stdout,stderr) {
    if (err) {
     & nbsp;  console.log (' Get Weather API error: ' +stderr ');
   } else {
       /*
         This stdout is what I curl out of this thing:
        {"Weatherinfo": {"City": " Beijing "," Cityid ":" 101010100 "," temp ":" 3 "," WD ":" Northwest Wind "," WS ":" Level 3 "," SD ":" 23% "," WSE ":" 3 "," Time ":" 21:20 "," Isradar ":" 1 "," Radar ":" JC_RADAR_AZ9010_JB "," NJD ":" No Live "," qy ":" 1019 "}}
        *
        var data = Json.parse (stdout);
        console.log (data);
   }
});

To feel the direct curl out and run the script out of the results are the same:

3, call the pass parameters of the shell script (Child_process.execfile ())

To prepare a shell script, such as I want to connect to a server, to modify its password, I would like to provide Ip,user,new pwd,old pwd, new shell script file change_password.sh:

Copy Code code as follows:



#!/bin/sh

Ip= ""
Name= ""
Password= ""
Newpassword= ""

While getopts "h:u:p:n:" Arg #选项后面的冒号表示该选项需要参数


Todo


Case $arg in


H


ip= $OPTARG


;;


U


Name= $OPTARG


;;


P


password= $OPTARG


;;


N


newpassword= $OPTARG


;;


?) #当有不认识的选项的时候arg为?


echo "contains unknown parameters"


Exit 1


;;


Esac


Done

#先获取userid
Userid= '/usr/bin/ipmitool-i lanplus-h $IP-u $NAME-P $PASSWORD user list | grep root | awk ' {print '} '
# echo $USERID
#根据userid来修改密码
/usr/bin/ipmitool-i lanplus-h $IP-u $NAME-P $PASSWORD user set PASSWORD $USERID $NEWPASSWORD

I then prepare a Nodejs file to invoke this shell script called File_changepwd.js:

Copy Code code as follows:

var callfile = require (' child_process ');
var ip = ' 1.1.1.1 ';
var username = ' Test ';
var password = ' pwd ';
var newpassword = ' newpwd ';

Callfile.execfile (' change_password.sh ', [' H ', IP, '-u ', username, '-p ', password, '-n ', newpassword],null,function ( Err, stdout, stderr) {
Callback (Err, stdout, stderr);
});

It is not convenient to post the results of the operation, but I can use personality assurance, it is tested.

Read the above, in fact, calling the Python script is no suspense, essentially is the execution of commands.

4. Invoke the Python script (the Python script itself is a passing parameter)

Here's a digression, and here's a brief description of the Python pass parameter:

Copy Code code as follows:

#-*-coding:utf-8-*-
'''
Required module: SYS
Number of parameters: Len (SYS.ARGV)
Script Name: sys.argv[0]
Parameter 1:sys.argv[1]
Parameter 2:sys.argv[2]
'''
Import Sys
Print U "script name:", Sys.argv[0]
For I in range (1, Len (SYS.ARGV)): #这里参数从1开始
Print U "Parameters", I, Sys.argv[i]

Run Result:

I'm also going to prepare a Nodejs file to invoke this Python script (I made changes to py_test.py, see below), File_python.js:

Copy Code code as follows:

var exec = require (' child_process '). exec;
var arg1 = ' Hello '
var arg2 = ' Jzhou '
EXEC (' python py_test.py ' + arg1+ ' +arg2+ ', function (Error,stdout,stderr) {
if (Stdout.length >1) {
Console.log (' You offer args: ', stdout);
} else {
Console.log (' You don\ ' t offer args ');
}
if (Error) {
Console.info (' stderr: ' +stderr);
}
});

py_test.py contents are as follows:
#-*-coding:utf-8-*-
Import Sys
Print SYS.ARGV

The results of the operation are as follows:

Still very good, and for 2014 completed an exquisite blog. haha ~ ~

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.