使用 html 按钮运行 python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26792899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
run python script with html button
提问by O P
I have a Python script a.pythat prompts for a URL:
我有一个a.py提示输入 URL的 Python 脚本:
url = input('URL: ')
It uses modules to check headers for URL validity, takes the valid URL and downloads the first image from the webpage (URL) using Beautiful Soup. It works perfectly as a standalone Python script that I can run in my terminal/command prompt.
它使用模块来检查 URL 有效性的标头,获取有效 URL 并使用 Beautiful Soup 从网页 (URL) 下载第一张图像。它可以完美地作为一个独立的 Python 脚本运行,我可以在我的终端/命令提示符下运行它。
What I'd like to build is a webpage that utilizes my Python script and allows users to enter a URL form a web interface. Example:
我想要构建的是一个利用我的 Python 脚本并允许用户从 Web 界面输入 URL 的网页。例子:
<input type="text" name="url" />
<button>Download</button>
The URL entered from the input would then be passed into the python script when the user clicks on the Download button.
当用户单击“下载”按钮时,从输入中输入的 URL 将被传递到 python 脚本中。
采纳答案by MinusFour
There are a couple of ways to achieve this. You could use Apache modules like mod_python or mod_wsgi (which adheres to wsgi python standard), you could use a cgi script or you can use PHP (which is fairly common in web environments) to execute the python script through exec or system function.
有几种方法可以实现这一点。你可以使用像 mod_python 或 mod_wsgi 这样的 Apache 模块(它遵循 wsgi python 标准),你可以使用 cgi 脚本或者你可以使用 PHP(这在 web 环境中很常见)通过 exec 或 system 函数来执行 python 脚本。
I think the easiest one would be just use PHP.
我认为最简单的方法就是使用 PHP。
exec('python /path/to/file.py');
Edit: I just realized that my solution only describes how to run the python script.
编辑:我刚刚意识到我的解决方案只描述了如何运行 python 脚本。
You could pass the url input through an argument on python.
您可以通过 python 上的参数传递 url 输入。
$url = $_GET['url'];
exec("python /path/to/file.py $url");
This is potentially dangerous even with user input validation.
即使使用用户输入验证,这也有潜在危险。
To execute it through a button, you could do an AJAX call. (jQuery example)
要通过按钮执行它,您可以执行 AJAX 调用。(jQuery 示例)
$('#button').on('click', function() {
$.get('python.php', {url : 'url' });
});

