node 调用 python3 子进程失败
var fs = require('fs'),
stdin = process.stdin,
stdout = process.stdout,
spawn = require("child_process").spawn;
var path= require('path');
//限制访问路径,及权限
var userdir= '/Users/FusGoethe/Desktop';
//process.cwd() 返回当前文件夹路经
var args = process.argv.slice(2),
filePath = args[0],
pyPath =path.join(userdir,args[1]);
var pathname = path.join(userdir,filePath);
var datas = [],
accounts = 0,
lock = true;
/**
* 读取文件
* [@param](/user/param) dir 目标文件夹路径
* [@param](/user/param) callback
*/
function readFiles(dir,callback){
fs.readdir(dir,function(err,files){
if(!files){
stdout.write('your path is wrong\n');
return;
}
accounts = files.length;
files.forEach(function(file){
if(file.indexOf('.') === -1 || file[0] == '.'){
accounts--;
return;
}
console.log(file);
//得到文件路径
var pathname = path.join(dir,file);
fs.readFile(pathname,'utf-8', function (err, data) {
if (err) throw err;
console.log(1);
callback(data);
});
});
});
stdout.write('Please wait...\n');
}
function startChild(data){
datas.push(data);
if(!(--accounts) && lock ){
lock = false;
datas.join("#NODEJS#");
var child = spawn('python3',[pyPath,datas]);
console.log(2);
child.stdout.setEncoding('utf-8');
child.stdout.on("data",function(data){
console.log(data);
}).on("end",function(){
console.log("stdoutOver");
});
child.on("err",function(err){
console.log(err);
}).on("exit",function(){
console.log("\n\nover!");
});
}
}
readFiles(pathname,startChild);
以上为js代码
import sys
data = sys.argv[1]
string=data.split("#NODEJS#").join("#PYTHON3#");
print(string)
fh = open('./dat/ex.dat','w',encoding='utf-8')
fh.write(string)
以上是py代码
$ node ex.js ./work/py ./work/py/nodepy.py
Please wait...
exforfoundmantal.py
generate_usernames.py
kk.html
nodepy.py
statistics.py
1
1
1
1
1
2
stdoutOver
over!
以上为输出
文件也没有任何变化
1 回复
#抱歉,已解决,是我将python3和js的语法搞混了