JavaScript 等待 child_process 生成 python 脚本到 运行

JavaScript wait for child_process spawned python script to run

我想要的是让我的 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 or execSync延迟进程。

const cp = require('child_process')
const write_questions = spawnSync('python', ['src/write_questions.py'], { stdio: 'inherit' })

通过设置stdio继承,所有的标准输入和错误都会自动发送到您的终端。