我已经安装了 python shell npm 并使用它从 node.js 调用 python 脚本。在 python 脚本执行结束时,一个 json 文件将被写入本地系统。
问题是我的 javascript 没有等待 python 执行完成并尝试读取尚未写入的文件。所以我没有得到预期的结果或出现错误。任何帮助将非常感激。谢谢!
这是我的代码:
import * as filePaths from './filePaths';
import * as scriptParameters from './pythonScriptParameters';
import * as constantmessages from './constantMessages';
import * as logger from '../Utilities/logger';
import fs from 'fs';
const { PythonShell } = require('python-shell');
export async function runManufacturingTest(){
PythonShell.run(scriptParameters.scriptFileName, scriptParameters.options, function(err, results) {
if (err) {
logger.error(err, '[ config - runManufacturingTest() ]');
}
const provisioningresultjson = fs.readFileSync(filePaths.provisioningresults);
const parsedResult = JSON.parse(provisioningresultjson);
\\ Rest of the code
}
}
最佳答案
你应该将回调转换为promise。所以你可以等待 js 线程直到 Promise 被解析/拒绝。
你可以尝试一下。
export async function runManufacturingTest() {
const { success, err = '', results } = await new Promise((resolve, reject) => {
PythonShell.run(scriptParameters.scriptFileName, scriptParameters.options, function(
err,
results
) {
if (err) {
logger.error(err, '[ config - runManufacturingTest() ]');
reject({ success: false, err });
}
resolve({ success: true, results });
});
if (success) {
const provisioningresultjson = fs.readFileSync(filePaths.provisioningresults);
const parsedResult = JSON.parse(provisioningresultjson);
// rest of your Code
}
});
}
关于JavaScript 不会等到 python 执行完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58871017/