JavaScript Glib.spawn_async stdout file descriptor - javascript

I want to spawn a process using spawn_async in the GLib bindings in javascript in a gnome3 shell-extension.
I need something like the "standard_output=True" parameter in the python doc http://developer.gnome.org/pygobject/stable/glib-functions.html which, when enabled, returns a filedescriptor to stdout of the process. The python API and C API differ heavily in this point.
Unfortunately, I cannot find any precise documentation of the JS API to GTK anywhere, the official page doesn't even list it though the shell is written in js to big parts...
The background of my question is that I call a python script doing serial communication, since I saw no other way to let JS get its data from such a script but through spawning a process.
Do you have any guess how to get the stdout of a process started like this?

The pygobject documentation you referenced is for the static libraries. Since Seed works through GObject introspection, you're safer trusting the C documentation. (Seed is the GObject introspecting Java Script library)
Perhaps you can roll your own function that does what you want in C and expose it to Seed: http://developer.gnome.org/seed/stable/seed-Native-Functions.html

This page includes info about http://developer.gnome.org/seed/3.0/seed-Modules.html embedding/utilizing your "c-module" in the javascript. An example taken from the page:
hello = imports.hello;
hello.say_hello_to("Tim");

Related

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

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!

Execute R code on server via node

I made a website where I can write code into a textfield and I want to send this code to my nodes.js server and call R, which is installed on my server, and make it process the written R code.
What I have trouble with is, how can I start R on my server and input code into it via Javascript?
The security aspects are not relevant for this because it will never go live and will always stay localhost.
Any ideas on how to approach this problem?
If you use an R web framework, you can then use the eval function to run the contents of the text box as code.
Obviously, this is very risky, but you've said you only want this to run locally.
You could use other languages with an exec function to spawn a child process. Write the code to file, compile with exec, then run with the exec function.
In node you could use a child process to achieve this
https://nodejs.org/api/child_process.html
In PHP you could use exec to the same end
http://php.net/manual/en/function.exec.php
All of these options carry the same risk.
If you want to safely execute R code on the server, you could implement an RPC mechanism, a simple one would consist of the name of the command and the parameters to be passed. This way, you can effectively whitelist what is allowed to execute, but it does mean you can't excecute arbitrary R code.

Calling C functions inside javascript

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

How to parse html that includes javascript code

How does one parse html documents which make heavy use of javascript? I know there are a few libraries in python which can parse static xml/html files and I'm basically looking for a programme or library (or even firefox plugin) which reads html+javascript, executes the javascript bit and outputs html code without javascript so it would look identical if displayed in a browser.
As a simple example
link
should be replaced by the appropriate value the javascript function returns, e.g.
link
A more complex example would be a saved facebook html page which is littered with loads of javascript code.
Probably related to
How to "execute" HTML+Javascript page with Node.js
but do I really need Node.js and JSDOM? Also slightly related is
Python library for rendering HTML and javascript
but I'm not interested in rendering just the pure html output.
You can use Selenium with python as detailed here
Example:
import xmlrpclib
# Make an object to represent the XML-RPC server.
server_url = "http://localhost:8080/selenium-driver/RPC2"
app = xmlrpclib.ServerProxy(server_url)
# Bump timeout a little higher than the default 5 seconds
app.setTimeout(15)
import os
os.system('start run_firefox.bat')
print app.open('http://localhost:8080/AUT/000000A/http/www.amazon.com/')
print app.verifyTitle('Amazon.com: Welcome')
print app.verifySelected('url', 'All Products')
print app.select('url', 'Books')
print app.verifySelected('url', 'Books')
print app.verifyValue('field-keywords', '')
print app.type('field-keywords', 'Python Cookbook')
print app.clickAndWait('Go')
print app.verifyTitle('Amazon.com: Books Search Results: Python Cookbook')
print app.verifyTextPresent('Python Cookbook', '')
print app.verifyTextPresent('Alex Martellibot, David Ascher', '')
print app.testComplete()
From Mozilla Gecko FAQ:
Q. Can you invoke the Gecko engine from a Unix shell script? Could you send it HTML and get back a web page that might be sent to the printer?
A. Not really supported; you can probably get something close to what you want by writing your own application using Gecko's embedding APIs, though. Note that it's currently not possible to print without a widget on the screen to render to.
Embedding Gecko in a program that outputs what you want may be way too heavy, but at least your output will be as good as it gets.
PhantomJS can be loaded using Selenium
$ ipython
In [1]: from selenium import webdriver
In [2]: browser=webdriver.PhantomJS()
In [3]: browser.get('http://seleniumhq.org/')
In [4]: browser.title
Out[4]: u'Selenium - Web Browser Automation'

Categories