Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - run python script with html button

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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' });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...