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
Related
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!
We have a PHP script that runs daily ( already working fine) that generates a PDF report for our employees. Now upon this generated PDF we need to add attachments/files that are generated by a JavaScript function. In this JavaScript function we work with data, loaded from our database. This data is different every day and saves a daily attachment file on our server.
In the PHP script mentioned above, we need to include those files/attachments created by JS.
My though was to run a JS function when the PHP script runs, daily. As I have found in this stackoverflow question ( see answer by Vladimir ) it is basically impossible to run js from a PHP script.
How can I achieve this? How can I make sure the files/attachments are generated by JS every day, before the PHP script runs?
(It is allowed for the javascript attachments/files to be generated at 2am, for example. While the PHP script can run at 3am. It doesn't have to be the exact same time).
Any suggestinos would help!
I would work toward using curl to get the JS to run by calling the html file with curl from within the PHP script.
A lot of this depends, of course, on what the JS is doing, exactly, but if you have access to both codebases, you should be able to get it to work, by saving the response from curl into a variable and then parsing and handling it appropriately.
I know this answer is a generalization, but this is because we only generally know how the JS and PHP need to interact. I will be happy to be more specific if we get a few more details.
Good luck and Take care,
JB
I have a JavaScript file on my server that contains a function. I would like to develop a REST Api to connect to this server, run the JavaScript function and send back the output.
Is it possible to call a JavaScript function from a php file?
I read this but it doesn't answer my question, because my js file is hosted on the same server as the php file.
Is the V8Js extensions what I am looking for?
Edit
The js function looks like this:
function (line, userWeight, weightunit){
//logic is here
var computed = {
userLengthFtin: userLengthFtin,
userLevel: userLevel,
proId: line['id'],
proLengthFeetin: proLengthFeetin,
proThick: proThickFtin,
weightunit: weightunit
};
return computed;
}
Is it possible to call a javascript function from a php file ?
You would need to hand things over to some other software which can execute JS. This might be through shelling out or it might be though a library such as Selenium or the V8js library you found.
Whatever you choose, it would need to be able to handle the particular needs of the JS (e.g. if the JS expects to be embedded in a webpage with access to a DOM and all the APIs provided by a web browser, then you couldn't simply run it with Node.js).
It would probably be simpler to rewrite the function in PHP.
The javascript is printing out the HTML onto the page example below, is it possible to call a C function on it for example in C to convert something to another language there is a function LANG_Str("text") which converts the text into the specified language. Would it be possible to use this function on the below text inside Javascript?.
"<tr><th>Service</th><th>Target Allocation (%)</th><th></th>"
EDIT:
I'm basically wanting to do a human language translation. The site already supports multi-language, the problem is on the custom screen like the one shown above which gets generated in Javascript, cannot use the function used to translate text the way its done normally in C.
If it's running in the browser: no. Sorry.
You might be able to do it in server-side code beforehand (e.g. Python or PHP which can call C) when putting together the page content. Alternatively you can make an AJAX request to a server which exposes the C function as an HTTP API/Endpoint (via, GCI, FCGI or Python/PHP/Perl). But not in the browser.
This is because the JS runs in a sandboxed virtual environment which has no access to system calls or anything outside the runtime.
EDIT
In response to your comment "The script is ran in the C using HTML_WriteToCgi", this suggests that you are putting together the HTML in C on your server. If this is correct, go for my option 1 above, by injecting the values directly into the JS source code if all values come out of some data known by the server.
You might consider moving some functionality out of browser JS and back into server-side code to solve your problem.
You can make a special request, so the webserver can use that request and send it to the webpage.
JavaScript can't access any other processes directly, but it can make a server request for the information. The server can call a C function if need be.
In the end, it's not JavaScript calling the C function, it's the server (and whatever language it's using: Python, PHP, ASP.NET, JSP, etc) that would be calling the C function.
My interpretation is that your goal is to call a C function within HTML / Javascript and capture the output.
What you could do is make a VM. Basically, you have a huge array "memory", a couple of "registers", etc... The hardest part is to make sure that they instruction set and the bytecodes of your VM mirrors some common instruction set that there is a C compiler for. You compile the C code that VM on your computer, save it to a file, and run it on the VM. If doing that is too hard, you could just get a C to assembly converter, and just define a couple of Assembly instructions instead. There is a Linux emulator in pure javascript with no server calls that does precisely that.
You might consider creating a RESTful web service on your server that will receive the source text and target language id, then return the translated text. You could then access it from your webpage via an ajax call.
I’m not an expert on web development. But isn’t it possible for javascript to invoke c using webassembly?
Not sure of it’s limitation/constraints though - such as memory
Something like this?
https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm
I would like to retrieve the contents of a javascript script instead of executing it upon requesting it.
EDIT: I understand that Python is not executing the javascript code. The issue is that when I request this online JS script it gets executed. I'm unable to retrieve the contents of the script. Maybe what I want is to decode the script like so http://jsunpack.jeek.org/dec/go
That's what my code looks like to request the js file:
def request(self, uri):
data = None
req = urllib2.Request(uri, data, self.header)
response = urllib2.urlopen(req)
html_text = response.read()
return html_text.decode()
I know approximately what the insides of the script look like but all I get after the request is issued is a 'loaded' message. My guess is that the JS code gets executed. Is there any way to just request the code?
There is no HTML or JavaScript interpreter in urllib2. This module does nothing but fetch the resource and return it to you raw; it certainly will not attempt to execute any JavaScript code it receives. If you are not receiving the response you expect, check the URL with a tool like wget or monitor the network connection with Wireshark or Fiddler to see what the server is actually returning.
(decode() here only converts the bytes of the HTTP response body to Unicode characters—using the default character encoding, which probably isn't a good idea.)
ETA:
I guess what I want is to decode the Javascript like so jsunpack.jeek.org/dec/go
Ah, well that's a different game entirely. You can get the source for that here, though you'll also need to install SpiderMonkey, the JavaScript engine from Mozilla, to allow it to run the downloaded JavaScript.
There's no way to automatically ‘unpack’ obfuscated JavaScript without running it, since the packing code can do anything at all and JS is a Turing-complete language. All this tool does is run it with some wrapper code for functions like eval which packers/obfuscators typically use. Unfortunately, this sabotage is easily detectable, so if it's malware you're trying to unpack you'll find this fails as often as it succeeds.
I'm not sure I understand. If I do a simplified version of your code and run it on a URI that's sure to have some javascript:
>>> import urllib2
>>> res = urllib2.urlopen("http://stackoverflow.com/questions/6946867/how-to-unpack-javascript-in-python")
And you print res (or res.decode()), the javascript is intact.
Doing urlopen should retrieve whatever character stream the source provides. It's up to you to do something with it (render it as html, interpret it as javascript, etc).