用html按钮运行python脚本 [英] run python script with html button
问题描述
我有一个Python脚本 a.py
,它提示输入一个URL:
url = input('URL:')
它使用模块检查URL的标题有效性,采用有效的URL并使用美丽的汤从网页(URL)下载第一个图像。它可以作为一个独立的Python脚本完美工作,我可以在终端/命令提示符下运行。
我想要构建的是一个利用我的Python脚本的网页,允许用户从Web界面输入URL。示例:
< input type =textname =url/>
<按钮>下载< /按钮>
当用户点击下载时,从输入中输入的URL将被传递到python脚本中按钮。
有几种方法可以实现这一点。您可以使用Apache模块,如mod_python或mod_wsgi(遵守wsgi python标准),您可以使用cgi脚本,也可以使用PHP(在Web环境中相当常见)通过exec或system函数执行python脚本。 / p>
我认为最简单的就是使用PHP。
exec ('python /path/to/file.py');
编辑:我刚刚意识到我的解决方案只介绍如何运行python脚本。
您可以通过python参数传递url输入。
$ url = $ _GET [ 'URL'];
exec(python /path/to/file.py $ url);
即使通过用户输入验证,这也是潜在的危险。
要通过按钮执行它,您可以执行AJAX调用。 (jQuery示例)
$ p $ $('#button')。on('click',function(){
$ .get('python.php',{url:'url'});
});
I have a Python script a.py
that prompts for a URL:
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.
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:
<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.
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.
I think the easiest one would be just use PHP.
exec('python /path/to/file.py');
Edit: I just realized that my solution only describes how to run the python script.
You could pass the url input through an argument on python.
$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)
$('#button').on('click', function() {
$.get('python.php', {url : 'url' });
});
这篇关于用html按钮运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!