简体   繁体   中英

JavaScript wait for child_process spawned python script to run

What I want is for my write_questions.py file to finish running before continuing with the rest of this code. (this is written in TypeScript, technically)

            //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);

You can use spawnSync or execSync to delay the process when creating a new child process.

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

By setting stdio to inherit, all the standard input and error will be automatically sent to your terminal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM