Methods and instances for calling system commands, Shell scripts, and Python scripts in Nodejs, nodejspython

Source: Internet
Author: User

Methods and instances for calling system commands, Shell scripts, and Python scripts in Nodejs, nodejspython

Each language has its own advantages. It can be combined with each other to develop programs that are more efficient to execute, or use which implementation method is simpler. nodejs uses sub-processes to call system commands or files, for more information about the documentation, see refer to interfaces for standard input, standard output, and standard error output.

 

The node. js subprocess provides important interfaces for interaction with the system. Its main APIs include:

 

Interfaces 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
Obtain the child process PID: child. pid
Provides the method to generate sub-processes: child_process.spawn (cmd, args = [], [options])
You can run the following command directly: child_process.exec (cmd, [options], callback)
Provide the method to call the script file: child_process.execFile (file, [args], [options], [callback])
Provides a method to kill a process: child. kill (signal = 'signature ')

 

It's interesting to use instances ~~

 

1. Use sub-processes to call system commands (obtain system memory usage)

 

Create a nodejs file named pai_spawn.js. The Code is as follows:
Copy codeThe Code is as follows:
Var spawn = require ('child _ Process'). spawn;
Free = spawn ('free', ['-m']);

// Capture the 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 );
});

// Register the sub-process Close event
Free. on ('exit ', function (code, signal ){
Console. log ('child process eixt, exit: '+ code );
});

The result of running the script is exactly the same as that of running the command 'free-m:

 

 

2. Execute the system command (child_process.exe c ())

 

I am still very often using this feature, and it feels a little more powerful than above. For example, I like the weather very much. Now I want to curl the weather interface to return json-format data. Maybe I want to perform some operations on it. I will print it out here without any operation.

Create a nodejs file named cmd_exec.js:

Copy codeThe Code is as follows:
Var exec = require('child_process'cmd.exe c;
Var login STR = 'curl http://www.weather.com.cn/data/sk/101010100.html ';
Exec (reverse STR, function (err, stdout, stderr ){
If (err ){
Console. log ('get weather api error: '+ stderr );
} Else {
/*
The content of this stdout is the content from the above curl:
{"Weatherinfo": {"city": "Beijing", "cityid": "101010100", "temp": "3", "WD": "northwest wind ", "WS": "Level 3", "SD": "23%", "WSE": "3", "time": "", "isRadar ": "1", "Radar": "JC_RADAR_AZ9010_JB", "njd": "No live", "qy": "1019 "}}
*/
Var data = JSON. parse (stdout );
Console. log (data );
}
});

The result of the direct curl is the same as that of the script:

 

 

3rd. Use the uploaded shellscript (child_process.exe cFile ())

 

Prepare a shell script first. For example, if I want to connect to a server to change its password, I want to provide IP, user, new pwd, old pwd, create a shell script file change_password.sh:

Copy codeThe Code is as follows:
#! /Bin/sh

IP = ""
NAME = ""
PASSWORD = ""
NEWPASSWORD = ""

While getopts "H: U: P: N:" arg # The colon following the option indicates that parameters are required for this option.
Do
Case $ arg in
H)
IP = $ OPTARG
;;
U)
NAME = $ OPTARG
;;
P)
PASSWORD = $ OPTARG
;;
N)
NEWPASSWORD = $ OPTARG
;;
?) # When there are unrecognized options, What Is arg?
Echo "contains unknown parameters"
Exit 1
;;
Esac
Done

# Obtain userid first
USERID = '/usr/bin/ipmitool-I lanplus-H $ IP-U $ NAME-P $ PASSWORD user list | grep root | awk' {print $1 }''
# Echo $ USERID
# Change Password Based on userid
/Usr/bin/ipmitool-I lanplus-H $ IP-U $ NAME-P $ PASSWORD user set password $ USERID $ NEWPASSWORD

Then I prepare a nodejs file to call this shell script, called file_changepwd.js:

Copy codeThe Code is as follows:
Var callfile = require ('child _ Process ');
Var ip = '1. 1.1.1 ';
Var username = 'test ';
Var password = 'pwd ';
Var newpassword = 'newpwd ';

Callfile.exe cFile ('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 paste the running results here, But I can use the personality guarantee, it is tested.

After reading the above, it is no suspense to call the python script. In essence, it is to execute the command.

 

4. Call the python script (the python script itself transmits parameters)

 

Here, we will insert a digress. The following section describes how to pass parameters in python:

Copy codeThe Code is 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): # The parameter starts from 1.
Print u "parameter", I, sys. argv [I]

 

Running result:

I have also prepared a nodejs file to call this python script (I have modified py_test.py, see the following), file_python.js:

Copy codeThe Code is as follows:
Var exec = require('child_process'cmd.exe c;
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 );
}
});

The content of py_test.py is as follows:
#-*-Coding: UTF-8 -*-
Import sys
Print sys. argv

The running result is as follows:

I still liked it and completed an exquisite blog for 2014. Haha ~~

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.