简体   繁体   中英

Call Python script from local JavaScript App

so I've looked around quite a bit now and wasn't able to find quite the use case I think I am confronted with.

For some background: I'm fairly new to JavaScript and have never had to call any other program/script from it. Now I did develop a Python script that pulls some data from online sources, formats it and dumps it into JSON files. In order to display this data in a proper way I figured I would use Electron.

While handling the JSON files is completely fine (would be quite sad if it wasn't I guess), I need to be able to call the Python script updating the data from my Electron UI. As everything is local, I hoped, that there would be an easier way, than setting up some server for the Python script to run on, just to be able to trigger its execution from my Desktop App. This is especially true, as I don't even need to get or process any returns, I just want to trigger the execution of that script.

So the question now is: is there such an "easy" way to execute Python scripts from an Electron/JavaScript based locally saved Desktop app?

Thanks in advance for any answers!

Like a previous commenter mentioned, you should be able to follow this SO answer in Node.js (which is what Electron uses).

To expound upon that answer just a bit, I'd recommend using the built-in Python JSON utility to dump JSON to the standard out (just printing out the JSON string), and the using the built-in Node.js JSON utility to parse that JSON string into a javascript object for use in your application.

Alright, so after being redirected to this thread , which I can only recommend reading through if you have an interest in this issue, I took their solution and altered a little, which took me a bit of time, due to some confusion, which I now would like to spare you guys!

To re-introduce the issue: The goal is to call a python script from a JavaScipt/Electron based UI. The python script only needs to be executed, but it needs to happen onClick, as it is an update function.

Now this is the code I used:

const exec = require("child_process").exec;

function triggerUpdateAndRefreshFooter() {
  exec('python relativePathToScript/update.py',
    function(error, stdout, stderr) {                    //callback function, receives script output
      refreshFooter();                                  //don't use the output, but I could here
    }
  )
}

I did have some issues figuring out all of that const stuff in the other thread, as well as having to guess IF I could just execute my script in a separate function. In the end this did work!

I hope this was helpful!

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