现有两个文件,且在同一目录下
test.py
print("py 启动")
x = input()
if(x == "1"):
print("recived!")
index.js
const {
exec
} = require("child_process")
const test = exec("python test.py", {
cwd: process.cwd()
})
test.stdin.write("1")
test.stdout.on("data", (data) => {
console.log(data.toString());
})
index.js代码写的有问题,要求就是用index去执行python脚本,且往脚本里面输入1。并打印出结果,test.py代码不可改动,index.js代码随便改,换个库都行,只要实现下效果。
即执行node index,index.js调用python脚本,并往里面输入了1,并打印出结果
py 启动
1
recived!
var spawn = require('child_process').spawn,
py = spawn('python', ['test01.py']),
dataString = '';
py.stdout.on('data', function (data) {
dataString += data.toString();
});
py.stdout.on('end', function () {
console.log(dataString);
});
py.stdin.write('1');
py.stdin.end();
Node.js中的child_process及进程通信
https://blog.csdn.net/wensonlee/article/details/84662099
这是mac os 系统下的参考代码:
py_test.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import time
# 定义接收到的不同环节码,执行不同逻辑
def foo(var):
if var == '100':
# 与服务器交互 虚拟请求数据时间1秒
time.sleep(1)
print('100#'+'{"sign":"1", "msg":"登录成功"}')
elif var == '200':
# 与服务器交互 虚拟请求数据时间1秒
time.sleep(1)
print('200#'+'{"sign":"1", "msg":"进入大厅成功"}')
elif var == '300':
# 与服务器交互 虚拟请求数据时间1秒
time.sleep(1)
print('300#'+'{"sign":"1", "msg":"匹配成功"}')
else:
print('run the orderError')
# 参数为从命令行传过来的参数 sys.argv ['py_test.py', arg1, arg2...]
# 所以取参数要从1开始,就是第二位置开始取
foo(sys.argv[1])
nodejs_test.js
var exec = require('child_process').exec;
var cmds = ['100', '200', '300'];
var no = 0;
//先发第一个环节码100,等待返回正确数据再进行发送下一个码
execCmd();
//该方法用于命令行执行python命令 类似于: python py_test.py arg1
//这样在python中就可以接受传递过去的参数
function execCmd() {
exec('python py_test.py '+ cmds[no++], function (error, stdout, stderr) {
if(error){
console.error('error: ' + error);
return;
}
console.log('receive: ' + stdout.split("#")[0] + ": " + stdout.split("#")[1]);
//将返回的json数据解析,判断是都执行下一步
var json = JSON.parse(stdout.split("#")[1]);
console.log(json.msg);
if(json.sign == "1" && no < 3){
execCmd();
}
});
}