admin管理员组文章数量:1333195
(server.js)
I have following code to run my server -
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './public/index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
}
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('500 Internal Server error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(8000);
console.log('Server running at http://localhost:8000/');
(index.html)
And my index.html file inside public directory is following -
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript" src="./algebra.js"></script>
<script type="text/javascript" src="./math.js"></script>
<script>
//Some more code ...
function runPythonCode(x, y){
//process python file and get result
}
runPythonCode(2, 3);
</script>
</body>
</html>
In above code inside runPythonCode
function I want to pass variable x
and y
to my python code and do some processing with x
and y
and want the value return back to javascript.
I was simply tried like this inside the script tag in index.html just to check if python script is running or not -
text = "hello"
$.ajax({
type: "GET",
url: "./app.py",
//data: { param: text}
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
})
And my aap.py
python code -
import csv
from numpy import matrix
def main():
x =2
return x
if __name__ == "__main__":
x=main()
But after running this code I am simply getting whole python code inside console. What I am doing wrong here? How to run python file inside js?
(server.js)
I have following code to run my server -
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './public/index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
}
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('500 Internal Server error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(8000);
console.log('Server running at http://localhost:8000/');
(index.html)
And my index.html file inside public directory is following -
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript" src="./algebra.js"></script>
<script type="text/javascript" src="./math.js"></script>
<script>
//Some more code ...
function runPythonCode(x, y){
//process python file and get result
}
runPythonCode(2, 3);
</script>
</body>
</html>
In above code inside runPythonCode
function I want to pass variable x
and y
to my python code and do some processing with x
and y
and want the value return back to javascript.
I was simply tried like this inside the script tag in index.html just to check if python script is running or not -
text = "hello"
$.ajax({
type: "GET",
url: "./app.py",
//data: { param: text}
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
})
And my aap.py
python code -
import csv
from numpy import matrix
def main():
x =2
return x
if __name__ == "__main__":
x=main()
But after running this code I am simply getting whole python code inside console. What I am doing wrong here? How to run python file inside js?
Share Improve this question asked Feb 1, 2018 at 12:29 abhjtabhjt 4425 gold badges11 silver badges26 bronze badges 5- 1 Side note: I'd have major security concerns allowing to run arbitrary user code on a server not packed inside a sandbox. You may want to rethink your approach in case you want to put this into production. – jbndlr Commented Feb 1, 2018 at 12:34
- @jbndlr I can modify later for production purpose first I simply want to try this thing whether it is possible to do or not. – abhjt Commented Feb 1, 2018 at 12:38
- You can't use Python as if it were PHP. You need to have a running Python web server with a callable REST endpoint that will execute your code and return the result via HTTP. – Gorka Hernandez Commented Feb 1, 2018 at 12:38
- @GorkaHernandez Ok. Can you please explain it by giving an example. – abhjt Commented Feb 1, 2018 at 12:39
- I am not too familiar as to create an educated example featuring this behavior, though this link to the Python documentation may be a good start: docs.python/2/library/simplehttpserver.html, you basically need to create an HTTP server like you have done with Node.js above. – Gorka Hernandez Commented Feb 1, 2018 at 12:42
3 Answers
Reset to default 4There is a tool called brython which allows you to add python 3 code inside a script tag of html file.
However, I assume it works by converting your python code into javascript and have it consumed by the browser. Here is an example of how a python script might look like:
<script type="text/python">
"""Code for the clock"""
import time
import math
from browser import document
import browser.timer
sin, cos = math.sin, math.cos
width, height = 250, 250 # canvas dimensions
ray = 100 # clock ray
background = "#111"
digits = "#fff"
border = "#333"
def needle(angle, r1, r2, color="#000000"):
"""Draw a needle at specified angle in specified color.
r1 and r2 are percentages of clock ray.
"""
x1 = width / 2 - ray * cos(angle) * r1
y1 = height / 2 - ray * sin(angle) * r1
x2 = width / 2 + ray * cos(angle) * r2
y2 = height / 2 + ray * sin(angle) * r2
ctx.beginPath()
ctx.strokeStyle = "#fff"
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
</script>
The only client-side scripting language that's supported by browsers is JavaScript. Python is not suitable for the web.
If you are interested in using python on server-side: https://www.djangoproject./
Your node.js HTTP server is configured to not execute python scripts; consequently, they are delivered as plain text to the caller.
In your node.js server, you can use the npm
module for executing python like so: How to call python script from NodeJs
However, still be warned! Never, ever execute code that es from or may be altered by your site visitors.
本文标签: javascriptRun python code inside ltscriptgt tag of HTML fileStack Overflow
版权声明:本文标题:javascript - Run python code inside <script> tag of HTML file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742285952a2446932.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论