2

Im quite new in web developing, could someone please point me in the right direction of help with the scripts to run a .py script on a web page. Below are the ones that i am using. Do i have to create a html file and a php file?? If so please help me. I have a internal server running on XAMPP with Apache and configured to run CGI, .py scripts.

Work flow:

Upload > button to run the below .py script > download

Upload script(php):

<?php
if(isset($_POST['UploadButton'])){ //check if form was submitted

$target_dir = '/opt/lampp/htdocs/pic-el/Dump/';
$target_file = $target_dir . basename($_FILES["filepath"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["filepath"]["tmp_name"], $target_file);
} 
?>

Python script:

#!/usr/bin/env python

import CGIHTTPServer
CGIHTTPServer.test()
import os
import urllib
import cgi
import webcolors 
import xlsxwriter
from PIL import Image

filename = "/home/Desktop/tess/test1"

imageNameArray = []


def downloadfile(urlData):
    urllib.urlretrieve(urlData[0], urlData[1])
    print " image downloaded: " + str(urlData[1])
    return


# open file to read
with open("{0}.csv".format(filename), 'r') as csvfile:
    # iterate on all lines
    i = 0
    for line in csvfile:
        splitted_line = line.split(',')
        # check if we have an image URL
        if splitted_line[1] != '' and splitted_line[1] != "\n":
            # urllib.urlretrieve(splitted_line[1], '/home/tf_files/images/{0}.jpg'.format (splitted_line[0]))
            imageNameArray.append(
                (splitted_line[1], '/home/Desktop/tess/images/{0}.jpg'.format(splitted_line[0])))
            print "Image added to list for processing for {0}".format(splitted_line[0])
            i += 1
        else:
            print "No result for {0}".format(splitted_line[0])

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

from multiprocessing import Pool

processPool = Pool(5)
processPool.map(downloadfile, imageNameArray)

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('output1.xlsx')
worksheet = workbook.add_worksheet()
# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# search for files in 'images' dir
files_dir = os.getcwd() + '/images'
files = os.listdir(files_dir)


def closest_colour(requested_colour):
    min_colours = {}
    for key, name in webcolors.css3_hex_to_names.items():
        r_c, g_c, b_c = webcolors.hex_to_rgb(key)
        rd = (r_c - requested_colour[0]) ** 2
        gd = (g_c - requested_colour[1]) ** 2
        bd = (b_c - requested_colour[2]) ** 2
        min_colours[(rd + gd + bd)] = name
    return min_colours[min(min_colours.keys())]


def get_colour_name(requested_colour):
    try:
        closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
    except ValueError:
        closest_name = closest_colour(requested_colour)
        actual_name = None
    return actual_name, closest_name


for f in files:
    if f.lower().endswith(('.png', '.jpg', '.jpeg')):
        image_path = files_dir + '/' + f
        im = Image.open(image_path)
        n, cl = max(im.getcolors(im.size[0] * im.size[1]))
        requested_colour = cl
        actual_name, closest_name = get_colour_name(requested_colour)


        width = im.size
        if width < (500, 500):
            worksheet.write(row, 4, "False")
        else:
            worksheet.write(row, 4, "True")

        print image_path
        print cl
        print width
        print "Actual colour name:", actual_name, ", closest colour name:", closest_name


        worksheet.write_string(row, 1, image_path)
        worksheet.write(row, 3, closest_name)   
        row += 1





workbook.close()
2

2 Answers 2

1

you can't run .py on a web page, only u can run on the server since Python's a server side programming. But you can run python script from PHP (since u r using XAMPP.) Example -

<?php
   $output =  exec('./filename.py');
?>
Sign up to request clarification or add additional context in comments.

6 Comments

Nothing seems to work when i tried the above. How display error on the page?
just echo out the $output. When u run exec('./filename.py'), it'll return the output from python. check it. php.net/manual/en/function.exec.php
Notice: Use of undefined constant output - assumed 'output' in /opt/lampp/htdocs/IMG/ne.php on line 3 output - Thats what is being displayed. Unable to understand what it means
<?php $output = exec('./tet.py'); echo output ?>
it's echo $output, not echo output.
|
1

You don't need to create separate php and html files.

First, when the server goes back to apache2

sudo apt-get install libapache2-mod-wsgi

(It connects apache2 with wsgi.)

Second, you need to create a configuration file and

Move the configuration file to Document_Root.

ex> server.conf

WSGIScriptAlias /test /var/www/wsgi/main.py

MainOption |  Address to be connected | Python file location

Third, restart apache2 service.

EXAMPLE_CODES

main.py

server.conf

3 Comments

im on ubuntu, is document_root a folder in apache htdoc folder?
Server error! The server encountered an internal error and was unable to complete your request. Error message: End of script output before headers: main.py Above is the error that i got ..
Server error! The server encountered an internal error and was unable to complete your request. Error message: End of script output before headers: main.py If you think this is a server error, please contact the webmaster. Error 500 172.27.181.60 Apache/2.4.26 (Unix) OpenSSL/1.0.2l PHP/7.1.7 mod_perl/2.0.8-dev Perl/v5.16.3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.