I need help, I have a Python script that do some work and print html web page.
I need to pass string from that outputed web page to that script.
Is that possible ?
In future I want to use radio buttons where user will thick data for plotting from predefinned ones.
Thanks for any advice...
My code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgitb
cgitb.enable()
import subprocess
import os
print "Content-type: text/html\n\n";
web = """
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
</head>
<body>
<div id='wrapper'>
<div id='header'>
</div>
<div id='content'>
<div class='content'>
<div><h3>GRAPH</h3></div>
<br>
<div style='height:520px;width:1000px;overflow:scroll;overflow-x:auto;overflow-y:hidden;'>
<img src='http://localhost/steps.png' alt='image' />
</div>
<br>
<button onclick="myFunction()">REFRESH</button>
<script>
function myFunction() {
location.reload();
}
</script>
<br>
<form action='/cgi-bin/test.py' method='post'>
nazov suboru: <input type='text' data='data'> <br />
<input type='submit' value='Submit' />
</form>
</div>
</div>
</div>
</body>
</html>
"""
print web
proc = subprocess.Popen(['gnuplot','-p'],
shell=True,
stdin=subprocess.PIPE,
)
proc.communicate("""
reset
set terminal pngcairo enhanced size 3000,500 font 'Arial,11' rounded;
set output '/opt/lampp/htdocs/%s.png'
set datafile separator "|"
plot \
\
'%s.txt' u 0:3 sm cs w l ls 1 t 'X-suradnice',\
'%s.txt' u 0:4 sm cs w l ls 2 t 'Y-suradnice',\
'%s.txt' u 0:5 sm cs w l ls 3 t 'Z-suradnice'
"""%(data,data,data,data))
Your question is quite hard to understand, but I think you are trying to work out how to access the data parameter submitted by the form POST. You can do that with the cgi module:
import cgi
form = cgi.FieldStorage()
data = form.getvalue('data')
Related
<html>
<body>
<head>
<title>HTML Forms</title>
</head>
<p>Add your details:</p>
<form name="form" method="get">
Number 1:<br> <input type="number" name="first">
<br>
Number 2:<br> <input type="number" name="second">
<br>
Number 3:<br> <input type="number" name="third">
<input type="submit" value="submit" id="submit" />
</form>
</body>
</html>
<?php
$var1 = $_GET['first'];
$var2 = $_GET['second'];
$var3 = $_GET['third'];
$command = escapeshellcmd("python total.py $var1 $var2 $var3");
$output = shell_exec($command);
echo ($output);
?>
import sys
num_1 = sys.argv[1]
num_2 = sys.argv[2]
num_3 = sys.argv[3]
print("total:", num_1+num_2+num_3)
I have shared the code I am using. I want to get the values from user using the HTML code and read it using PHP. Then pass the values from PHP script to python script, do the task and display the output.
For some reason I am unable to do that. Can someone help me?
I am trying to run a c++ executable from a flask application.
I created two input for the arguments and one button to submit and run the executable.
What I want to execute is this command line: ./Ex02_DriveStatus 5 blablabla.sw
The executable Ex02_DriveStatus is on the same folder than the python file.
When I run it from the terminal ./Ex02_DriveStatus 5 blablabla.sw
it's working well.But I would like to be able to run it from my flask application/ web interface.
Here is my python code:
import canopen
from datetime import datetime
import time
import os
import numpy as np
import argparse
from DriveLib import Drive
from flask import Flask
from flask import request
from flask import render_template
import subprocess
from subprocess import PIPE
# os.system("sudo ifconfig can0 down")
# os.system("sudo ip link set can0 type can bitrate 500000")
# os.system("sudo ifconfig can0 up")
app = Flask(__name__)
#app.route('/')
def home():
return render_template('flashing.html')
#app.route('/flashing/')
def home_flash():
return render_template('flashing.html')
#app.route('/flashing/', methods=['POST'])
def flash():
global node_id
global file_name
node_id = request.form['node_id']
file_name = request.form['file_name']
if request.form.get("submit"):
node_id = request.form['node_id']
file_name = request.form['file_name']
if node_id == '':
node_id = 0
if file_name == '':
file_name = 0
if request.method == 'POST':
output = run(node_id, file_name)
return render_template('flashing.html', output=output, node_id=node_id, file_name=file_name)
def run(node_id, file_name):
s=subprocess.run(["./Ex02_DriveStatus", node_id, file_name],stdout=PIPE)
print(s)
return s.stdout.decode("utf-8")
And my HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href='/static/main.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type=text/javascript src="{{
url_for('static', filename='main.js') }}"></script>
<script>
window.addEventListener("load", function(){
// BASIC
numpad.attach({target: "demoA"});
// WITH OPTIONS
numpad.attach({target: "demoB"});
numpad.attach({target: "demoC"});
});
</script>
<title>FLASH the drive</title>
<p class="title"><strong>FLASH THE DRIVE</strong></p>
</head>
<body>
<div id="menu">
<ul id="onglets" >
<li class="active"> Flash drive </li>
<li> Test drive </li>
<li> Test module </li>
</ul>
</div>
<div class="content">
<!--test form-->
<form method="post" action="/flashing/">
<textarea id="output" name="output" rows="30" cols="50" style="resize:none" placeholder="//Your output here.">{{output}}</textarea><br>
<table>
<tr>
<td> <p>Chose the ID you want to flash with:</p> </td>
<td> <input name="node_id" id="demoA" style="height:50px;"> </td>
</tr>
<tr>
<td> <p>File name:</p> </td>
<td> <input name="file_name" style="height:50px;"> </td>
</tr>
<tr>
<td> <input id="buttonid" type="submit" name="submit" class="submit" value="FLASH"> </td>
</tr>
</table>
</form>
</div>
</body>
</html>
When I try this flask run it's running for ever without results.
I tried to create a python file test.py with just a print print("hello").
I assume this line is the problem:
s=subprocess.run(["./Ex02_DriveStatus", node_id, file_name],stdout=PIPE)
so I tested it with a simple file (the test.py):
s=subprocess.run(["python", file_name],stdout=PIPE)
and on the file_name input I would enter test.py and it is working.
So I don't know if it is because the executable from c++ gives me some conflict or if there is something I didn't write well.
Make sure your program is outputting to STDOUT.
Try removing the stdout=PIPE or try piping STDERR as well.
I have data with a .txt extension . I want to read the file, but the result of his error result < cStringIO.StringO object at 0x7f5078d18068 > What 's wrong ?
My file
Abedus
Accer
Chrome
HTML
<html>
<body>
<form enctype="multipart/form-data" action="http://localhost/cgi-bin/my.py" method="post">
<p>File: <input type="file" name="filename"></p>
<p><input type="submit" value="Upload"></p>
</form>
</body>
</html>
CGI Python
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
data = form['filename'].file
print "Content-Type: text/plain"
print ""
print "result %s" % data,
I have one test.html:
<form action="/cgi-bin/test.py" method="GET">
<input type="text" name="search">
<input type="submit" value="Submit">
</form>
<div id="res"></res>
And one python script test.py:
#....
print Result
#....
I want instead of printing result on the test.py, return it to the test.html and write it in the div with id res... How I can do that?
<form id="myform">
<input id="my_text">
<button id="submit_btn">
</form>
<div id="result">
</div>
<script>
//you need to use jquery for this part
$("#submit_btn").click( function() {
$("#result").load("/path/to/cgi?my_text="+$("#my_text").val())
})
</script>
something like that... (this is real hacky 1 minute post that is untested so it may need some work ...
your question really has nothing to do with python ... it is just web technology question ... it would be the same if it was a php or C# or whatever processing the form data
it has nothing to do with python because it doesnt matter how you are processing the form data ... this is just web technology it would work exactly the same with a perl script instead of a python script or with a C# instead of python or whatever ... you want to return some data back to a web page ... how you got the data is really not relevant
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<form action="someother.html" method="get">
<input id="my_text">
<input type="button" id="my_button" value="click me">
</form>
<div id="result">
</div>
<script>
$("#my_button").click(function(){
$("#result").load("");
})
</script>
</body>
</html>
here is an example ... just paste it into a file.html and go to it and click the button ...
its just loading its self load("") so it should duplicate the data thats on the page when you click it ...
Well I understood your question in this way, maybe you are looking for other thing but i know a way that do exactly what are you looking for: Ajax.
Just make an ajax request to the cgi python and put the response into a div. Luckily, this is very easy nowadays.
If you know something about jQuery (a javascript framework) you should visit this link to getting started: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax
byeeee
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello World</h2>"
print "<p>Executing HTML code from python script</p>"
print "</body>"
print "</html>"
Just doing a basic python project with HTML file, i came across a tutorial which gave an idea about how i can execute the code,
here is the HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Admin Login</title>
</head>
<body>
<big><big>Login
Here<br>
<br>
</big></big>
<form action="/var/www/cgi-bin/Login.py" name="LoginForm"><big>Administration
Login<br>
User Name<br>
<input name="UserName"><br>
<br>
<br>
Password<br>
<input name="PassWord"><br>
</big><br>
<br>
<br>
<input type="submit">
<br>
</form>
__ <br>
</body>
</html>
and the python code..
#!/usr/bin/python
import cgi
import cgitb; cgitb.enable()
# get the info from the html form
form = cgi.FieldStorage()
#set up the html stuff
reshtml = """Content-Type: text/html\n
<html>
<head><title>Security Precaution</title></head>
<body>
"""
print reshtml
User = form['UserName'].value
Pass = form['PassWord'].value
if User == 'Myusername' and Pass == 'MyPasword':
print '<big><big>Welcome'
print 'Hello</big></big><br>'
print '<br>'
else:
print 'Sorry, incorrect user name or password'
print '</body>'
print '</html>'
The problem is, when i submit the username and password, it just shows the whole code back on the browser and not the required Welcome message :(. I use Fedora13 .. can anyone tell me what is going wrong? I even changed the permissions of the file(s).
Most likely, your webserver is not configured to execute the script. Even if it's marked as 'executable' in the file system, that doesn't necessarily mean the webserver knows that it should be executing .py files (rather than just serving them 'straight up'). Have a look here if you're running Apache: http://httpd.apache.org/docs/2.0/howto/cgi.html
<form action="/var/www/cgi-bin/Login.py" name="LoginForm">
Try
<form action="/cgi-bin/Login.py" name="LoginForm">
/var/www is probably the path from your ftp site. The web server will only look inside /var/www, so it puts that part there automatically.