Call Python script from local JavaScript App - javascript

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!

Related

How to use cv.pencilSketch method in Javascript. I know it works in Python, but it is not a function in javascript

I want to make image processing tool, and I have used cv2.pencilSketch() method in python. However, in JavaScript, it is not a function.
How do I do it in JavaScript? In my browser. (OpenCV js CDN)?
If it is not a function, I would like to make it a function with my own image processing, but I need help.
unfortunately, as of now, only a small subset of opencv is exposed to js.
you'll find the complete 'whitelist' here
(and no, pencilSketch() is not included, so you cannot use it)
IF you're able to build it locally, you could try to add the function to the photo section, and build your own.
and IF that works, please make a github PR with it, so others can profit from your effort !

Make Javascript Execute a Python Script

I have a question that has been asked several times here and other places around the internet*, but answers I've seen are incomplete or ineffective.
I would like to have a JavaScript function runPy() that, upon being called (in a browser, via a button-click for instance), will execute a Python script in my server that we'll call test.py.
Let's say that test.py is simply designed to create a text file and write in it 'hello world'
Python
f = open('test.txt', 'w+')
f.write('hello world')
Based on other answers, I have pieced together the following JavaScript/jQuery function:
JavaScript
function runPy() {
$.ajax({
type:'POST',
url:'test.py',
success: function(data) {
console.log(data)
};
});
}
Now, this is of course incorrect. As one might expect, rather than running the Python script, it prints to the console the contents of the script:
Console
f = open('test.txt', 'w+')
f.write('hello world')
How would I go about editing my JavaScript (and/or Python) to achieve the functionality I would like? In a perfect world, I would like to avoid importing any new dependencies (I've seen some answers dependent on Flask or Django) but of course beggars can't be choosers.
Additionally, if I will allow myself to get greedy, it would be very nice to be able to pass arguments to the Python script as well, or even use JavaScript to call a specific function in the Python script, and have the results passed back to the client-side JavaScript.
*Similar Questions
Call python function from JS
how to call python script from javascript?
Run Python scripts from JavaScript functions
You're going on the right path.
But, here's why the POST isn't working. Except for HTML filetype, making a POST call to fetch a static file on the server (i.e. random.js, random.css etc) will print the raw file content.
In this scenario, you'll need to handle this on the server-side backend code. I don't know which backend framework you're using but here are some articles that can help you with this:
NodeJS: https://medium.com/swlh/run-python-script-from-node-js-and-send-data-to-browser-15677fcf199f
.NET: https://medium.com/better-programming/running-python-script-from-c-and-working-with-the-results-843e68d230e5
Java: Running a .py file from Java
UPDATE!!: Due to the recent developments in the space of Web Development, it is now possible to run Python on the Client-side through WebAssembly. Please find more instructions here: Pyodide

How to manage a fully separate context with nodejs?

I am writing a javascript test framework based on nodejs. My server reads javacript files, instruments them, then executes them in its own context.
It (very) basically looks like this:
const file = process.argv[2];
require('fs').readFile(
file,
'utf-8',
(error, data) => {
eval(data);
}
);
This is all working fine but I do not like mixing my server context with a test context. How can nodejs execute javascript code in a totally separate context?
Ideally, it would be something like this:
other_context.eval(data);
Many thanks for your help!
There are multiple ways of doing this. The easiest thing that you could try right now is to replace the file read with child_process#fork().
This means you are running in a totally separate process which is good and that you don't need eval() which is also very good.
Essentially:
const {
fork
} = require('child_process');
const child = fork(file);
child.on("message", m => console.log(m));
The main thing is to get the code that you are testing out of the server. I just think terrible things can happen if you leave it that way.
Another option that is too broad to cover is to leverage Docker. That way, the code that gets executed is not only in another process, it's (and this is painting really broadly) practically on another computer.
isolated-vm might fit the bill for you.
isolated-vm is a library for nodejs which gives you access to v8's Isolate interface. This allows you to create JavaScript environments which are completely isolated from each other. You might find this module useful if you need to run some untrusted code in a secure way. You may also find this module useful if you need to run some JavaScript simultaneously in multiple threads. You may find this project very useful if you need to do both at the same time!

Javascript function like PHP exec()

I need to be able to execute a shell command through javascript, similar to the php function "exec()". I understand that this may be impractical in javascript because of security reasons, but my javascript code is running on the server, and no clients have direct access to the file.
Users make a request to the server for some data, and the server-side javascript code is called. From the javascript file, I need to execute a program in order to gather data based on user input, then pass this data back.
If this isn't possible in vanilla Javascript, please point me towards a library or tool that can do this, preferably in javascript/frameworks on javascript.
JavaScript has no 'exec' function like PHP does. It's all because JavaScript runs on the client and don't have access to the server part.
However you can create PHP page and send AJAX requests to it to execute particular command.
ALTHOUGH, you need to be VERY, VERY and VERY cautious about which commands to run.
It's very dangerous to do like that. I don't advice you to do like that, however, it's possible.
Good luck!
If it's client side - You can't
If it's node.js:
var exec = require('child_process').exec;
child = exec("command", function (error, stdout, stderr)
{
// handle the output
});
This might be what you're looking for: https://github.com/arturadib/shelljs
Or, if you want to have direct access to commands, perhaps this will help: http://nodejs.org/api/child_process.html

Lazy Loading templates in Meteor

I use require.js to do lazy loading for a Javascript app. I would love to switch to a meteor stack but right now it looks like Meteor sends the whole app (all the templates) through on the initial load. Has anyone had success with require.js and meteor or any other implementation?
You're asking different questions, but certainly they are connected. The first is about loading additional javascript code into your meteor app. Of course you can use thing like requirejs. This should work fine supposing your lazy code is located in the public directory of your meteor project. However, my experience is that requirejs goes mad when the contents of public gets updated often, so for example in the development environment. Maybe it's a matter of customizing the library, but I would rather recommend using some lightweight homebrewed package. Look here, if you need some inspiration.
The second question is about lazy template definition. Each template consists of two parts. The first is its html code, written in handlebars syntax, the second is all the javascript code which you write to define how your template should behave (e.g. helpers, event handlers). The second part is easy, as long as we assume that we already know how to load the lazy code (see the above paragraph) and the template, lets call it myLazyTemplate, is already defined, so basically speaking Template.myLazyTemplate is not undefined. So how to achieve the latter?
To dynamically define a new template you'll need to call
Template.__define__(name, raw_func)
on the client. So the last question is "what is raw_func?". This is a compiled version of your html code which is normally created automatically on the server and then sent down the wire to the client when the app gets loaded (look here to see how it's done in meteor). But we want to do it dynamically, right?
So the idea is to compile the template code manually with a help of the Handlebars.to_json_ast routine. You can feed it with your template html code, and the output is some javascript array that can be sent to the client anytime by the method we've already talked about. The last thing you need to do is to call Handlebars.json_ast_to_func on the client, using the data sent from the server as the only argument. The output produced by Handlebars.json_ast_to_func is the raw_func you can use to produce myLazyTemplate template.
I'm aware that this is only a rough idea, not the whole solution to your problem. I hope this will help you to figure out the final solution on your own.

Categories