简体   繁体   English

从javascript调用python脚本

[英]Calling python script from javascript

I have the following html code (index.html): 我有以下html代码(index.html):

<!DOCTYPE html>
<html>
<head>


        <script>
        function addParagraphText()
        {
        var arg1=2
        var arg2=34
        var arg3="john"
        var myResult = runMe.py(arg1, arg2, arg3)
                document.getElementById("para").innerHTML = myResult
        }
        </script>
</head>
<body>
<button onclick="addParagraphText();">Click me</button>
<p id="para"></p>
</html>

and the following python file runMe.py: 和以下python文件runMe.py:

import sys

myArg1 = sys.argv[1]
myArg2 = sys.argv[2]
myArg3 = sys.argv[3]
# some long calculations using various libraries and modules



myOutput = '''<table style=\"border:solid;\"><tr><td> bla </td><td> lol bla <button>myButton</button> </td></tr><tr><td> blabla </td><td> blablabla </td></tr></table>'''

return myOutput

Obviously it doesn't work. 显然,它不起作用。 What would be the easiest and quickest way to do it? 最简单,最快的方法是什么? I have a very long Python script that does some calculations and outputs a rather long string in html format which I would like to present after user clicks on the button. 我有一个很长的Python脚本,它可以进行一些计算并以html格式输出一个相当长的字符串,我想在用户单击按钮后显示该字符串。 As of now, I do not need a state of the art approach, I am rather looking for a fast and easy solution. 到目前为止,我不需要最先进的方法,而是在寻找一种快速简便的解决方案。

In short: JavaScript in a html page executed by a browser cannot start the python interpreter and cannot run python scripts. 简而言之:浏览器执行的html页面中的JavaScript无法启动python解释器,也无法运行python脚本。

Browser security will prevent this. 浏览器安全性将阻止这种情况。

You'll have to use something like XHR and cgi like in this question . 这个问题中,您将不得不使用XHR和cgi之类的东西。 The first answer seems to be a complete example. 第一个答案似乎是一个完整的例子。 Otherwise try wsgi python . 否则请尝试wsgi python

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM