Nodejs Call Scripts (Python/shell) and system commands

Source: Internet
Author: User
Tags 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 the use of child processes to invoke system commands or files, documents see Http://nodejs.org/api/child_ The Process.html,nodejs sub-process provides an important interface for interacting with the system, and its main APIs are: standard input, standard output, and standard error output interface.

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

Interfaces for standard input, standard output, and standard error outputs
Child.stdin Get Standard input
Child.stdout Get Standard output
Child.stderr Get standard error output
Gets the PID:child.pid of the child process
Provides methods for generating child processes: Child_process.spawn (cmd, args=[], [options])
Provides methods for executing system commands directly: Child_process.exec (cmd, [options], callback)
Provides methods for invoking script files: child_process.execfile (file, [args], [options], [callback])
Ways to Kill a process: Child.kill (signal= ' SIGTERM ')

Use examples to feel, very interesting, hehe ~ ~

1. Invoke system commands with child processes (get system memory usage)

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

varSpawn = require (' child_process ')). Spawn;free= Spawn (' Free ', ['-M ']); //capture standard output and print it to the consoleFree.stdout.on (' Data ',function(data) {Console.log (' Standard output:\n ' +data); }); //captures the standard error output and prints it to the consoleFree.stderr.on (' Data ',function(data) {Console.log (' Standard error output:\n ' +data); }); //registering a child process Shutdown eventFree.on (' exit ',function(code, signal) {Console.log (' Child process Eixt, exit: ' +code); });

The following is the result of running the script and running the command ' free-m ' directly:

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

This I am still very common, the function feeling is stronger than the above a little bit. For example, I like to pay attention to the weather, now I want to curl the weather interface to return data in JSON format, maybe I want to do something about it, here to print out do not operate.

Create a new Nodejs file named Cmd_exec.js:

varexec = require (' child_process '). exec; varCmdstr = ' Curl http://www.weather.com.cn/data/sk/101010100.html '; exec (CMDSTR,function(err,stdout,stderr) {if(Err) {Console.log (' Get Weather API error: ' +stderr); } Else {        /*This stdout content is the above 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" }}        */        vardata =Json.parse (stdout);    Console.log (data); }});

To feel the direct curl out and run the script out of the result is the same:

3. Invoke shell script with arguments (Child_process.execfile ())

This is 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, the new shell script file change_password.sh:

#!/bin/SHIP=""NAME=""PASSWORD=""NewPassword="" whileGetopts"h:u:p:n:"Arg #选项后面的冒号表示该选项需要参数 Do         Case$arginchH) IP=$OPTARG;; U) NAME=$OPTARG;; P) PASSWORD=$OPTARG;; N) NewPassword=$OPTARG;; ?) #当有不认识的选项的时候arg为?Echo "contains unknown parameters"Exit1        ;; Esac Done#先获取useridUSERID= '/usr/bin/ipmitool-i lanplus-h $IP-u $NAME-P $PASSWORD user list |grepRoot |awk '{print $}'`# Echo$USERID # Change Password according to USERID/usr/bin/ipmitool-i lanplus-h $IP-u $NAME-P $PASSWORD user set PASSWORD $USERID $NEWPASSWORD

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

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);});

This is not easy to paste the results of the operation, but I can use the personality assurance, it is tested.

Seen above, in fact, the call to the Python script is no suspense, essentially the execution of commands.

4. Call the Python script (the Python script itself is a parameter)

Insert a digression here, the following is a brief description of the Python parameters:

# -*-coding:utf-8-*- " " module required: SYS parameter number: 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 in Range (1, Len (SYS.ARGV)):# Here the parameter starts with 1    print u" parameters " , I, Sys.argv[i]

Operation Result:

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

Nodejs Call Scripts (Python/shell) and system commands

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.