【问题标题】:How to run python script from web page?如何从网页运行python脚本?
【发布时间】:2017-08-14 07:32:04
【问题描述】:

我在 Web 开发方面还很新,有人可以指点我正确的脚本帮助方向,以便在网页上运行 .py 脚本。以下是我正在使用的那些。我必须创建一个html文件和一个php文件吗? 如果是这样,请帮助我。我有一个使用 Apache 在 XAMPP 上运行的内部服务器,并配置为运行 CGI、.py 脚本。

工作流程:

上传>按钮运行下面的.py脚本>下载

上传脚本(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 脚本:

#!/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()

【问题讨论】:

标签: php python web-development-server


【解决方案1】:

你不能在网页上运行 .py,只有你可以在服务器上运行,因为 Python 是服务器端编程。但是您可以从 PHP 运行 python 脚本(因为您使用 XAMPP。) 示例 -

<?php
   $output =  exec('./filename.py');
?>

【讨论】:

  • 当我尝试上述方法时似乎没有任何效果。页面如何显示错误?
  • 只是回显 $output。当你运行 exec('./filename.py') 时,它会从 python 返回输出。核实。 php.net/manual/en/function.exec.php
  • 注意:使用未定义的常量输出 - 在第 3 行输出的 /opt/lampp/htdocs/IMG/ne.php 中假定“输出” - 这就是正在显示的内容。无法理解是什么意思
  • 这是 echo $output,而不是 echo 输出。
【解决方案2】:

您不需要创建单独的 php 和 html 文件。

首先,当服务器回到apache2时

sudo apt-get install libapache2-mod-wsgi

(它将apache2与wsgi连接起来。)

其次,你需要创建一个配置文件和

将配置文件移动到 Document_Root。

ex> server.conf

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

主选项 |连接地址 | Python文件位置

三、重启apache2服务。

EXAMPLE_CODES

main.py

server.conf

【讨论】:

  • 我在ubuntu上,document_root是apache htdoc文件夹中的一个文件夹吗?
  • 服务器错误!服务器遇到内部错误,无法完成您的请求。错误消息:标题前脚本输出结束:main.py 以上是我得到的错误..
  • 服务器错误!服务器遇到内部错误,无法完成您的请求。错误信息: End of script output before headers: main.py 如果您认为这是服务器错误,请联系站长。错误 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
猜你喜欢
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
相关资源
最近更新 更多