Execute Python Script from PHP and Keeping Script Open - python

I am creating a project on a raspberry pi using a motion detector to send a text message. Having some issues executing a python script from PHP (Apache2).
Trying to execute this python script:
#!/usr/bin/env python
from gpiozero import MotionSensor
import time
import os
#Motion sensor in GPIO23
ms = MotionSensor(23)
def send_notification():
#Debug Motion Statement
print("There was a movement!")
#Notification script is stored in notification variable
notification = os.popen ('bash /home/pi/project/notification.sh')
#Send Notification
print(notification.read())
#Delay between notifications
time.sleep(15)
#Execute send_notification function on motion
ms.when_motion = send_notification
The notification.sh script for reference. It uses postfix to send a text message.
echo "Motion was detected in your Smart Mailbox!" | mail myphonenumber#vtext.com
From this PHP code:
<!DOCTYPE html>
<html>
<head>
<title>Smart Mailbox</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<div class="form-style-5">
<body style="text-align:center;">
<h1>Smart Mailbox Application</h1>
<p>Enter Your Phone Number:</p>
<form method="post">
<input type="tel" name="phonenumber" placeholder="10 Digit Phone Number" pattern="[0-9]{10}" required>
<br>
<p>Select Your Phone Carrier:</p>
<select name="carrierdropdown" required>
<option value=""></option>
<option value="Verizon">Verizon</option>
<option value="ATT">ATT</option>
<option value="Sprint">Sprint</option>
<option value="TMobile">T-Mobile</option>
</select>
<br><br>
<input type="submit" name="submit" value="Start SmartMailbox">
</form>
</body>
</div>
</html>
<?php
if(isset($_POST['submit'])) {
//Appends phone carrier address to email address
if($_POST['carrierdropdown']=="Verizon"){
//echo "DEBUG:Verizon";
$carrier = "#vtext.com";
} elseif ($_POST['carrierdropdown']=="ATT"){
//echo "DEBUG:ATT";
$carrier = "#txt.att.net";
} elseif ($_POST['carrierdropdown']=="Sprint"){
//echo "DEBUG:Sprint";
$carrier = "#messaging.sprintpcs.com";
} elseif ($_POST['carrierdropdown']=="TMobile"){
//echo "DEBUG:T-Mobile";
} else{
echo "Break";
}
//Gets users phone number from HTML form
$phonenumber = $_POST['phonenumber'];
//Opens notification script for editing
$file = fopen('/var/www/html/notification.sh','w');
//Writes mail command to file appending phonenumber
fwrite($file,'echo "Motion was detected in your Smart Mailbox!" | mail ' . $phonenumber . $carrier);
//Closes file
fclose($file);
//Runs python scripts
exec('node /home/pi/project/blynkconnect.js');
exec('python -i /home/pi/project/MotionNotification.py &');
}
?>
This following command works on the command line alone. I have to use the -i flag so that the session will stay open to detect motion.
python -i /home/pi/project/MotionNotification.py &
So I suppose my issue is running this from PHP (I am using apache2 web server to host). All files have read,write,execute permissions. The node command I am running from PHP works flawlessly FYI. I have tried to give the apache web user root access and still no luck.
Any ideas I can give a try? Thanks!

Related

Html form open's file in text insted of showing output from python code

This form shuld show the output on current page
<div class="form">
<form action="QA.py" method="POST" onsubmit="return false; >
<label for="form-search"></label>
<input type="text" id="form-search" placeholder="Search code ">
<!-- BUTTONS -->
<input type="submit" value="code Search" id="code_search" onclick = "processQuery()">
</form>
<p>Answer: </p>
<p id = 'output'></p>
</div>
Insted it just opens this code given billow
def main():
print("Hello,")
IN = input("query ")
QT = f"Q: {IN} ? A:"
response = openai.Completion.create(
model="text-davinci-003",
prompt=QT,
temperature=0,
max_tokens=64,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
stop=["\n\n"]
)
user will input query in form-search on Html page
after clicking submit query shuld go to QA.py Python code
in python code input quary shud be submited to "IN"
after python Proveieds "A:" output shuld seen in 'output
Insted it just opens QA.py
You are missing a quotation mark on the form OnSubmit. The resulting javascript error allows the form to submit to the specified action which is your python file.
The Python file will only execute if run on a webserver that is properly configured. It may be that your web server is not configured for Python, or that you are running the html as a local file (ie from disk, not via a web server), and thus your Python file gets served as a file rather than executed.
It would appear you are trying to run a submit through javascript on a button. In which case the form action isn't required. Instead your processQuery() function which you haven't shared needs to specify which file to exectue.

Simple PHP page to use Python not working

Thanks for your time.
I took a new VPS, just to put online a software I'm developing. The VPS is on CentOs 7. I've installed HTTPD and PHP, Python was already installed. The index page is online.
I've found a sample at cyberwarzone and I've created an index.php page like this:
<html>
<body>
<form action="#" method="post">
Name: <input type="text" name="NAME"><br>
<input type="submit" value="NAME">
</form>
</body>
</html>
<?php
error_reporting(E_ALL);
$param1 = $_POST["NAME"];
$command = escapeshellcmd("/var/www/html/cyberwarzone.py $param1 ");
$resultAsString = shell_exec($command);
echo $resultAsString;
?>
And a cyberwarzone.py file like this:
#!/usr/bin/python
import sys
workvalue = sys.argv[1]
workvalue = workvalue + '\t' + "Hello World, send from Cyberwarzone.py"
print(workvalue)
Now, when I enter any data, nothing happens. Python is in /usr/bin/python and html files are in /var/www/html/. Can anybody help me to troubleshoot it?
Thanks.
I've found the problem. I was saving the .py file with windows EOL. Changing them, in NP++, resolved the problem. Thanks for your time

Opening a file with Python in the browser [duplicate]

This question already has answers here:
How to copy / download file created in Pyodide in browser?
(2 answers)
Closed 9 months ago.
I am doing a project with an html, js and css front-end and a python back-end.
I linked back-end and front-end with the py-script library.
I have to open a json file with the python script and it works, the problem is that it doesn't open the file where i want... it stores the file in this directory: /home/pyodide/file.json
How can I select the location where the file opens/gets created?
by the way, the code I am working with is this:
python
open("my_file.json")
# and it doesn't open it in the same directory as the python file who created it
The file /home/pyodide/file.json is located within the browser virtual file system. That file system is not part of your local disk storage. The virtual file system is not persistent. When you refresh the page any files stored are lost.
There is a set of FS APIs that manage the virtual file system which includes the ability to mount an IDBFS virtual file system for persistent storage. However, that is not the feature you are looking for.
Python applications have the same restrictions that JavaScript applies have. Neither can directly access the local file system. Applications must request access from the web browser and read data from the web browser. This is performed using HTML INPUT elements. The actual file access is performed by the FileRead class.
[UPDATE] Tonight I published an article on Pyscript Files and File Systems that explains in more detail with several examples.
This example is available on my website to experiment with: File Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>File Example</title>
</head>
<body>
<p>This example shows how to read a file from the local file system and display its contents</p>
<br />
<p>Warning: Not every file type will display. PyScript removes content with tags such as XML, HTML, PHP, etc. Normal text files will work.</p>
<br />
<p>No content type checking is performed to detect images, executables, etc.</p>
<br />
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br />
<br />
<div id="print_output"></div>
<br />
<p>File Content:</p>
<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:600px; resize:both">
<div id="content">
</div>
</div>
<py-script output="print_output">
import asyncio
from js import document, FileReader
from pyodide import create_proxy
async def process_file(event):
fileList = event.target.files.to_py()
for f in fileList:
data = await f.text()
document.getElementById("content").innerHTML = data
def main():
# Create a Python proxy for the callback function
# process_file() is your function to process events from FileReader
file_event = create_proxy(process_file)
# Set the listener to the callback
e = document.getElementById("myfile")
e.addEventListener("change", file_event, False)
main()
</py-script>
</body>
</html>

Connecting python script with html button and flask

I am trying to create a webapp and am fairly new to it. I have a python script(file.py) that transforms data selected by a user. It handles all the inputs and outputs.
I am using flask(main.py) for the server part of it and html. I want to place a button in my html code so it will start the execution of the file.py. Can anyone assist me with an example setup for the connections between the 3?
I've looked at other examples but I'm unable to recreate it as they're doing different things. Also, file.py is fairly large so I want to avoid putting it into a function.
Edit: not looking for a flask tutorial. I've tried 3things:
A shell pops up for half a second but the disappears. Then I'm redirected to a page which just has the text in my return statement
in my html file
<form action="/pic" method="POST">
<input type="submit" value="GET THE SCRIPT">
</form>
in my main.py flask file
#app.route('/pic', methods=['GET', 'POST'])
def pic():
os.system("python file.py") #file.py is the script I'm trying to start
return "done"
Doesn't do anything at all.
in html file:
<input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function goPython(){
$.ajax({
url: "/scripts/file.py",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
I get a GET "/scripts/file.py HTTP/1.1" 404 message. I have my scripts folder in the same directory as my templates folder. Also tried placing the scripts folder inside the templates folder.
in html
<form action="/run" method = "POST">
<input type="button" id='script' name="submit" value="Run Scripttttttt">
</form>
in flask main.py
#app.route('/run',methods=['GET', 'POST'])
def index():
def inner():
proc = subprocess.Popen(
['python file.py'],
shell=True,
stdout=subprocess.PIPE
)
for line in iter(proc.stdout.readline,''):
time.sleep(1)
yield line.rstrip() + '<br/>\n'
return Flask.Response(inner(), mimetype='text/html')
Using an HTML Anchor tag (i.e ) is the easiest way. Here is an example:
This is a link
But since you've chosen button, JavaScript will come in handy. Here's an example(inline):
<button onclick="window.location.href='your_flask_route';">
This is a link
</button>
and then in your flask main.py file you should have this:
#app.route('/your_flask_route')
def your_flask_route():
'''some lines of code'''
You can set up a Flask endpoint that your button can send a request to. Then let the endpoint's function call your python script.
Have a look at this discussion about Flask - Calling python function on button OnClick event and this discussion about How can I make one python file run another? to get you started.

Problem Getting a PHP Script on a Raspberry Pi to execute a Python Script that turns a motor

Im a trying to make an automated light switch. To do this I am using a stepper motor. The goal is for the me to be able to access my raspberry pi from a browser and using 2 simple buttons, "Turn on" and "Turn off", control the motor which will turn the light switch. I have written this simple python script to turn the motor, which has been tested from the Pi and works perfectly. It is called stepper.py and it is located in /var/www/html:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
control_pins = [7,11,13,15]
for pin in control_pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, 0)
halfstep_seq = [
[1,0,0,0],
[1,1,0,0],
[0,1,0,0],
[0,1,1,0],
[0,0,1,0],
[0,0,1,1],
[0,0,0,1],
[1,0,0,1]
]
for i in range(256):
for halfstep in range(8):
for pin in range(4):
GPIO.output(control_pins[pin], halfstep_seq[halfstep][pin])
time.sleep(0.001)
GPIO.cleanup()
print "Motor Rotation Completed"
Also in /var/www/html I have an index.html and index.php pages:
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Smart Light Switch</title>
</head>
<body>
<h1>Smart Light Switch</h1>
<form action="index.php" method="post">
<input type="submit" name="on" value="Turn Lights On">
<input type="submit" name="off" value="Turn Lights Off">
</form>
</body>
</html>
index.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['on']))
{
lightOn();
} elseif ($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['off']))
{
lightOff();
}
function lightOn()
{
$command = escapeshellcmd('python stepper.py');
$output = shell_exec($command);
echo "Light Turned On";
}
function lightOff()
{
echo "Light Turned Off";
}
?>
Essentially the HTML just displays the 2 buttons and on the click it goes to the php file where the functions are successfully reached. However, the script to turn the stepper motor does not get executed. I have looked online and it would seem that what I have is the correct way to execute a python script from php, but it doesn't work.

Categories