I am trying to call and execute a python script via the following javascript code in an electronjs app
function getProgramstatus(){
const { exec } = require('child_process');
exec('python python\\getProgramstatus.py', (error, stdout, stderr) => {
});
let jsonData = require('.\\js\\programstatus.json');
let itemData = JSON.stringify(jsonData);
let programstatus = JSON.parse(itemData);
sessionStorage.setItem('programstatus check', programstatus.status);
}
The goal of the python script is to write a value at a json file.
data1={
"status": "12",
"time" : time.ctime(start)
}
json_object = json.dumps( data1, indent = 4)
with open('..\js\programstatus.json', 'w') as outfile:
outfile.write(json_object)
#print("2")
sys.exit("2")
When i execute the python script via terminal it writes at json file, but when i call it from javascript it doen't write at json file. Any ideas;
Try outputting the response for hints, like this:
function getProgramstatus(){
const { exec } = require('child_process');
exec('python python\\getProgramstatus.py', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
let jsonData = require('.\\js\\programstatus.json');
let itemData = JSON.stringify(jsonData);
let programstatus = JSON.parse(itemData);
sessionStorage.setItem('programstatus check', programstatus.status);
}
And please share the output.
Also the code execution continues while getProgramstatus.py is still running, you want to use execSync / move the code below exec inside the callback or create a promise, so that let jsonData = require('.\\js\\programstatus.json'); gets executed when the python script has finished.
I found the answer, why the json file was not written when the python script was called by the application and not by me at the terminal.
The problem is the folder/file location. It should be relative to the main.js of the electron app.
So I changed the following:
with open('..\js\programstatus.json', 'w') as outfile:
outfile.write(json_object)
To: with open('.\js\programstatus.json', 'w') as outfile: outfile.write(json_object)
and work fine.