Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call python from javascript [duplicate]

Possible Duplicate:
Calling Python from JavaScript

I have a test.py and test.js.

I want to be able to run my test.py by opening test.js. I don't know how to create an api because it's not a web app, it's just 2 files sitting on my linux mint desktop.

I don't want to use npapi, because it's just a simple task, i don't want to use pyjamas because it's too hard to install the pyjamas desktop, so how to do it?

please note that i can use php, ajax, jquery instead of javascript, if it could be done with these languages. I am also able to use C++ or C instead of python. I just want to know a simple way to do it.

I know this can be done if i use java instead of python, but i want to know if i can do it with python, C or C++.

like image 226
user Avatar asked Mar 27 '12 10:03

user


People also ask

Can we call Python script from JavaScript?

PyScript lets you run Python scripts right in the browser, side by side with JavaScript, with two-way interaction between your code and the web page.

Can I use Python and JavaScript together?

It can be used for developing desktop as well as web applications. Q #5) Can I learn JavaScript and Python at the same time? Answer: Yes, Javascript and Python can both be learned at the same time. Javascript is mainly used for front-end programming whereas Python is used for backend programming.

How do I call a JavaScript function from Python?

Calling JavaScript from Python The key is to import the module js and call JavaScript functions using the js namespace. This is a complete example that you can copy and paste into a local file and load into the browser. I prefer to start a simple Python webserver to run examples: python -m http. server 9000 .


1 Answers

If you put your test.py file where ever you put your cgi files, (I think it's /usr/lib/cgi-bin by default for apache on ubuntu linux), you should be able to run the python file just by making a request to it's address.

If you just want to run the python file, and not use its output in the browser afterward, you could probably get away with something like:

document.write('<img src="http://localhost/cgi-bin/test.py" />');

if you want to use the output in the browser, you will probably be best served by using jQuery or some other library to do an easy ajax call.

something like:

jQuery.get('/cgi-bin/test.py', function(data) {
    //do stuff with the data
})

would probably do you just fine.

the second method would require that you also use apache, or equivalent, to serve the test.js file from localhost because jQuery ajax generally requires requests to go to the same domain that the script is running on.

like image 112
Andbdrew Avatar answered Oct 01 '22 03:10

Andbdrew