程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

node. JS call script (python/shell) and system commands

編輯:Python

Every language has its own advantages , Combining with each other, we can learn from each other's strong points. The program is more efficient in execution, or we can use which method is simpler ,nodejs Is the use of child processes to call system commands or files , See http://nodejs.org/api/child_process.html,NodeJS Subprocesses provide important interfaces to interact with the system , The main thing is API Yes : The standard input 、 Interface of standard output and standard error output .

NodeJS Subprocesses provide important interfaces to interact with the system , The main thing is API Yes :

The standard input 、 Interface of standard output and standard error output

child.stdin Get standard input

child.stdout Get standard output

child.stderr Get standard error output

Gets the name of the child process PID:child.pid

Provide methods for generating child processes :child_process.spawn(cmd, args=[], [options])

Provide a way to directly execute system commands :child_process.exec(cmd, [options], callback)

Provide methods to call script files :child_process.execFile(file, [args], [options], [callback])

Provide methods to kill processes :child.kill(signal='SIGTERM')

Use examples to feel , It's very interesting , ha-ha ~~

1、 Using sub processes to call system commands ( Get the memory usage of the system )

newly build nodejs file , be known as cmd_spawn.js, The code is 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 the standard error output and print it to the console free.stderr.on('data', function (data) {console.log('standard error output:\n' + data);});// Register subprocess shutdown event free.on('exit', function (code, signal) {console.log('child process eixt ,exit:' + code);});

The following is to run the script and run the command directly 'free -m' Result , As like as two peas :

2、 Execute system commands (child_process.exec())

I still use this very often , The function feels a little stronger than the above . For example, I like to pay attention to the weather , Now I want to curl The weather interface returns json Formatted data , Maybe I'll do something about it , Here, print it out without operation .

newly build nodejs file , be known as cmd_exec.js:

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) { console.log('get weather api error:'+stderr); } else { /* This stdout The content of is above me curl This thing came out : {"weatherinfo":{"city":" Beijing ","cityid":"101010100","temp":"3","WD":" The northwest ","WS":"3 level ","SD":"23%","WSE":"3","time":"21:20","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":" There's no real news ","qy":"1019"}} */ var data = JSON.parse(stdout); console.log(data); }});

Come and feel the direct curl The result is the same as that of running the script :

3、 Call the shell Script (child_process.execFile())

This needs to be prepared first shell Script , For example, I want to connect to a server , To change its password , Then I want to provide IP,user,new pwd,old pwd, newly build shell Script files change_password.sh:

#!/bin/shIP=""NAME=""PASSWORD=""NEWPASSWORD=""while getopts "H:U:P:N:" arg # A colon after an option indicates that the option requires an argument do case $arg in H) IP=$OPTARG ;; U) NAME=$OPTARG ;; P) PASSWORD=$OPTARG ;; N) NEWPASSWORD=$OPTARG ;; ?) # When there are options you don't know arg by ? echo " Contains unknown parameters " exit 1 ;; esacdone# First get useridUSERID=`/usr/bin/ipmitool -I lanplus -H $IP -U $NAME -P $PASSWORD user list | grep root | awk '{print $1}'`# echo $USERID# according to userid To change the password /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 , It's 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);});

It's not convenient to post the running results here , But I can guarantee with my personality , It is tested .

Look at the above , Actually call python There is no suspense about the script , In essence, it means executing orders .

4、 call python Script (python The script itself passes parameters )

Insert a digression here , The following paragraph is right python A brief description of the transmission parameters

# -*-coding:utf-8 -*-''' Module required :sys Number of parameters :len(sys.argv) Script name : sys.argv[0] Parameters 1: sys.argv[1] Parameters 2: sys.argv[2]'''import sysprint u" Script name :", sys.argv[0]for i in range(1, len(sys.argv)):# Here the parameters are from 1 Start print u" Parameters ", i, sys.argv[i]

Running results :

I'll prepare one too nodejs File to call this python Script ( I am right. py_test.py Made modifications , See below ),file_python.js:

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 The contents are as follows :

# -*-coding:utf-8 -*-import sysprint sys.argv

The operation results are as follows :

This is about node.js Call script (python/shell) And system commands are introduced here . I hope it will be helpful for your study , I also hope you can support the software development network .



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved