javascript - JavaScript 等待 child_process 生成的 python 脚本运行
问题描述
我想要的是让我的write_questions.py
文件在继续执行其余代码之前完成运行。(从技术上讲,这是用 TypeScript 编写的)
//imports used in this question
const fs = require('fs');
const { spawn } = require('child_process');
const write_questions = spawn('python', ['src/write_questions.py']);
//Listens to output from write_questions.py
write_questions.stdout.on('data', function (data) {
console.log("" + data);
});
write_questions.stderr.on('data', function (data) {
console.log("" + data);
});
const embedArray = [];
let dir = fs.readdirSync('./src/answers/Mathematics/')
function readFiles(dirname, onFileContent, onError) {
fs.readdir(dirname, function (err, filenames) {
if (err) {
onError(err);
return;
}
filenames.forEach(function (filename) {
fs.readFile(dirname + filename, 'utf-8', function (err, content) {
if (err) {
onError(err);
return;
}
onFileContent(filename, content);
});
});
});
}
var data = {};
readFiles('./src/answers/Mathematics/', function(filename, content) {
data[filename] = content;
console.log(filename, content);
}, function(err) {
throw err;
});
console.log(data);
解决方案
您可以在创建新子进程时使用spawnSync或execSync来延迟该进程。
const cp = require('child_process')
const write_questions = spawnSync('python', ['src/write_questions.py'], { stdio: 'inherit' })
通过设置stdio
为继承,所有标准输入和错误将自动发送到您的终端。
推荐阅读
- ios - UIImage 获取 CVPixelBuffer 移除 Alpha
- javascript - 如何使用 intl-tel-input 的 utils.js 保存计数器代码?如何使用 javascript 提供的数据到 django 应用程序中?
- java - 在 Spring Boot JPA 中编辑对象值和使用 save() 时出现 MySQL java.sql.SQLSyntaxErrorException
- python - 使用 cv2 和 svm 的 setTermCriteria
- node.js - 可以看到视频流的开始,但没有别的。Node.js、MP4、HTML5。第一个 blob 中的文件签名
- c# - 是否可以让 MEF 多次实例化一个类?
- javascript - 如何更改 SweetAlert2 的关闭动画?
- python - 如何在 pygame 中制作具有透明色键的图像?
- bash - bash 中多个 seq 的外积
- python-3.x - 如何只切片部分数据帧并旋转成新的数据帧,无论行大小如何?