How to run python script from web page? - php

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()

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

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

Related

the php code is unable to open the python script

i was trying to open and read a pdf from php using python. but after executing the php code in my browser, its not redirecting to python script.
i want my php code to execute the python script and return the output to
php
php code:
<?php
$command = escapeshellcmd("python filename.py");
$output = shell_exec($command);
echo $output;
?>
python code:
this code will read the pdf from the directory and extracts required data from the pdf and gives the corresponding result as an output to the php code which is printed on the browser
import PyPDF2
import re,time
import sys
start_time =time.time()
# open the pdf file
address="pv3.pdf"
object = PyPDF2.PdfFileReader(address)
#print('hello')
# get number of pages
NumPages = object.getNumPages()
l = list()
# extract text and do the search
for i in range(0, NumPages):
PageObj = object.getPage(i)
Text = PageObj.extractText()
l.append(Text)
#print(len(l))
#print(l[0])
d={}
count=0
for i in range(len(l)):
x = l[i].split('\n')
for j in range(len(x)):
if re.search('[0-9]{8}',x[j]) and (j!=len(x)-1 and re.search('-',x[j+1])==None):
#print(x[j],'in page',i+1,',line no',j+1)
count +=1
str = ''
temp =0
for m in range(j+1,len(x)):
if '~na' not in x[m]:
str+=x[m]
else:
temp = 1
break
if temp==0:
#print('hello')
y=l[i+1].split('\n')
for n in range(len(y)):
if '~' in y[n]:
break
str+=y[n]
# if d[x[j]]==None:
d[x[j]]=str
for x,y in d.items():
print(x,"::::",y,"...,")
print()
#print(l[i])
#print(d)
#print('No of matches are',count)
#print(l[0])
end_time = time.time()
#print('Total time taken :',end_time-start_time)

PHP shell_exec works in terminal, but displays no output on webpage

As the title says, I am running a python script from PHP using shell_exec, and this works when running it from a SSH session into my web server by running 'php ./python.php'. I get the expected output.
However when the page is loaded on a web browser, I simply get a blank web page with no PHP warnings or errors. Any help is appreciated.
python.php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('memory_limit', '-1');
$command = escapeshellcmd("python3 ./test.py 2>&1");
$output = shell_exec($command);
echo $output;
?>
test.py:
#!/usr/bin/env python
import pandas as pd
import math
import csv
url = 'https://afltables.com/afl/stats/2018a.html'
dfs = pd.read_html(url)
dfs = dfs[1]
dfs.to_csv('hmm.csv', sep=',', encoding='utf-8');
dfs = dfs[dfs.TM == "NM"]
dfs = dfs[dfs.GM > 3]
url = 'https://afltables.com/afl/seas/2018.html'
lad = pd.read_html(url)
scores = []
for index, row in dfs.iterrows():
score = (math.sqrt(row['CP']) * 2 + (row['IF']) * 2 + (row['CL']) ** 2)
scores.append([row['Player'], score])
pos = 1
scores = sorted(scores, key=lambda x: x[1], reverse=True)
for item in scores:
print(str(pos) + ". " + item[0] + ": " + str(item[1]))
pos = pos + 1

run a python file by calling from php file

i have a php file through which i am sending variables to python file using:
echo
shell_exec("C:/xampp/htdocs/Ai_Edutech_trial_project/eclipse_workspace
/Project/dbConn.py '$sess'");
it is working fine and but only a very small portion of python file is getting executed. I want execute whole python file for it have code to insert data in db.
This is my python file:
import mysql.connector
import numpy as np
import sqlite3
import sys
conn= mysql.conector.connect
(user="root",password="",host="localhost",database="videojs")
conn_two= sqlite3.connect('videojs')
c=conn_two.cursor()
def read_from_db():
sess_id=sys.argv[1]
print(sess_id)
cursor_one = conn.cursor()
cursor_one.execute("select time_arr from info where sess_id= '%s'" %
(sess_id))
data=cursor_one.fetchone()
cursor_two = conn.cursor()
cursor_two.execute("select type from questions")
data_two=cursor_two.fetchall()
str_data_two = ''.join(map(str, data_two))
split_data_two=str_data_two.replace(")
('","").replace("'","").split(',')
the_new_list = [x.split(',') for x in data]
str_data = ''.join(map(str, the_new_list))
split_data=str_data.replace(" ", "").strip('[]').split(',')
i = 0
while i < len(split_data):
print(split_data[i])
i += 1
#Open the file
fobj = open("one.srt")
text = fobj.read().strip().split()
quo_text= (', '.join("'" + item + "'" for item in text))
add_list=[]
i = 0
while i < len(split_data):
print(split_data[i])
if split_data[i] in quo_text: #string in present in the text file
print("matched")
ind_text=text.index(split_data[i].replace("'",""))
fix_max=ind_text+5
fix_min=ind_text-5
while ind_text < fix_max:
print(text[ind_text])
add_list.append(text[ind_text])
ind_text += 1
while ind_text > fix_min:
print(text[ind_text])
add_list.append(text[ind_text])
ind_text -= 1
else:
print("not matched" )
i += 1
database_list=[]
i = 0
while i < len(split_data_two):
print(split_data_two[i])
if split_data_two[i] in add_list: #string in present in the text
file
print("matched")
ind_text=add_list.index(split_data_two[i])
database_list.append(add_list[ind_text])
else:
print("not matched" )
i += 1
sess= sess_id
cursor_three=conn.cursor()
for elem in database_list:
cursor_three.execute("INSERT INTO data(sess_id,list) VALUES
(%s,%s)",(sess,elem))
conn.commit()
fobj.close()
read_from_db()
But when i pass value from php file only this portion of file is being executed from python file
def read_from_db():
sess_id=sys.argv[1]
print(sess_id)
can someone please help me out..?

Python program is not executing from php

I developed a script to extract entities from the given text and script is executing fine.
python code:
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
with open('C:\\pythonScripts\\input.txt', 'r') as f:
sample = f.read()
import nltk
def list_tokens(sampletext):
nltk.internals.config_java("C:\\Program Files\\Java\\jdk1.8.0_131\\bin\\java.exe")
classifier='C:\\Users\\gsrilakshmi.INDIA\\Desktop\\stanford\\stanford-ner-2016-10-31\\classifiers\\english.all.3class.distsim.crf.ser.gz'
jar='C:\\Users\\gsrilakshmi.INDIA\\Desktop\\stanford\\stanford-ner-2016-10-31\\stanford-ner.jar'
st = StanfordNERTagger(classifier,jar,encoding='utf-8')
tokenized_text = word_tokenize(sampletext)
classified_text = st.tag(tokenized_text)
with open('C:\\pythonScripts\\output.txt', 'w') as fp:
fp.write('\n'.join('%s %s' % x for x in classified_text))
return classified_text
tokens = list_tokens(sample)
print(tokens)
While calling the python script from php,the output file is not generated.
php code:
$pyscript = 'C:\\Python\Python36-32\python C:\pythonScripts\sample1.py';
$python = 'C:\Python\Python36-32\python.exe';
$p=exec($pyscript,$fulloutput);
exec("python C:\\pythonScripts\\sample1.py > C:\\pythonScripts\\out.txt");
echo $p;
I got the output: '[Found C:\Program Files\Java\jdk1.8.0_131\bin\java.exe: C:\Program Files\Java\jdk1.8.0_131\bin\java.exe]'
Please help me in solving this issue.
Thanks,
Srilu

Howto edit specific lines by different users in text file in PHP

I have a Subversion server running with AuthzSVNAccessFile specified in a virtual host.
The file "permissions.txt" should be edited by the users themselves to add or remove team members but limited to max. 4 members. Possible via PHP and how to implement it?
In PHP each logged in user has the $username = user_x; whereas x is an integer.
The AuthzSVNAccessFile "permissions.txt":
[repo_1001:/]
user_1 = rw
# the lines below only editable by user_1
user_1-member_1 = r
user_1-member_2 = r
user_1-member_3 = r
user_1-member_4 = r
[repo_1002:/]
user_2 = rw
# the lines below only editable by user_2
user_2-member_1 = rw
user_2-member_2 = rw
Reading and writing the file in PHP:
$file_permissions = "/.../permissions.txt";
if (isset($_POST) && ...) {
$textFileContents = $_POST['textFileContents'];
$fd=fopen($file_permissions ,"w");
fwrite($fd, $textFileContents);
fclose($fd);
}
$fd = fopen($file_permissions,"r");
$textFileContents = fread($fd,filesize($file_permissions));
fclose($fd);
var_dump($textFileContents);
I tried "AbraCadaver" mentioned parse-ini-file function but I do not get any output.Even no errors are seen:
$file_permissions = "/.../permissions.txt";
$textFileContents = parse_ini_file($file_permissions);
var_dump($textFileContents);
The output is just "NULL".
ADD: The cause why I got "NULL" is that my php.ini on the remote server was configured to disable the function parse_ini_file for security reasons.Now it works!

Categories