Transition my results from python to html file - python

I need to transition my results from python to html file. How i can do this. I used format function. I know about split html, hybrid of Python and HTML. Both metod cannot be use. My project is big and i need operate on variables to move results from many function to HTML report file.
The code below is a simplified example of what I need to do
def function(n):
result = n + 5
return result
def main():
n = int(input('n: '))
result = function(n)
report = open('result.html', 'w')
html = """
<!DOCTYPE html>
<html>
<body>
<h1>First Head</h1>
<p>My result: ---> I need my result here <--- </p>
</body>
</html>
"""
report.write(html)
report.close()
if __name__ == '__main__':
main()

So you want the results from that function in the middle? Not that hard um. Really no fan of multiple line strings with """ but here goes...
html = """
<!DOCTYPE html>
<html>
<body>
<h1>First Head</h1>
<p>"""
html += result
html += """</p>
</body>
</html>"""
OR you could make it an easier oneliner... with "{}".format():
html = "<!DOCTYPE html>\n<html>\n<body>\n\n<h1>First Head</h1>\n<p>{}</p>\n\n</body>\n</html>".format(result)

Related

HTML Output in Pyscript

I was experimenting in Pyscript and I tried to print an HTML table, but it didn't work. It seems to delete the tags and mantain just the plain text.
Why is that? I tried to search online, but being a new technology i didn't find much.
This is my code:
<py-script>
print("<table>")
for i in range (2):
print("<tr>")
for j in range (2):
print("<td>test</td>")
print("</tr>")
print("</table>")
</py-script>
And this is the output I get:
I tried to replace the print() method with the pyscript.write() method, but it didn't work too.
I dig in source code pyscript.py
and at this moment works for me only code similar to JavaScript
For example this adds <h1>Hello</h1>
<div id="output"></div>
<py-script>
element = document.createElement('h1')
element.innerText = "Hello"
document.getElementById("output").append(element)
</py-script>
Full working code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PyScript Demo</title>
<!--<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />-->
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div id="output"></div>
<py-script>
element = document.createElement('h1')
element.innerText = "Hello"
document.getElementById("output").append(element)
</py-script>
</body>
</html>
EDIT:
After digging in source code I found that pyscript.js runs function htmlDecode() which removes all tags from code in <py-script> (and probably it also removes tags when you load code from file) and this makes problem.
See Pyscript issue: [BUG] print() doesn't output HTML tags. · Issue #347 · pyscript/pyscript
Some workaround is to use some replacement - ie. {{ }} instead of < > in code - and later use code to replace it back to < >
print( "{{h1}}Hello{{/h1}}".replace("{{", "<").replace("}}", ">") )
or more universal - using function for this
def HTML(text):
return text.replace("{{", "<").replace("}}", ">")
print( HTML("{{h1}}Hello{{/h1}}") )
pyscript.write(some_id, HTML("{{h1}}Hello{{/h1}}") )
document.getElementById(some_id).innerHTML = HTML("{{h1}}Hello{{/h1}}")
Sometimes problem can be also pyscript.css which redefines some items and ie. <h1> looks like normal text.
One solution is to remove pyscript.css.
Other solution is to use classes from pyscript.css like in examples/index.html
<h1 class="text-4xl font-bold">Hello World</h1>
which means
print( HTML('{{h1 class="text-4xl font-bold"}}Hello{{/h1}}') )

Genshi: for loop inserts line breaks

Source code: I have the following program.
import genshi
from genshi.template import MarkupTemplate
html = '''
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">
<head>
</head>
<body>
<py:for each="i in range(3)">
<py:choose>
<del py:when="i == 1">
${i}
</del>
<py:otherwise>
${i}
</py:otherwise>
</py:choose>
</py:for>
</body>
</html>
'''
template = MarkupTemplate(html)
stream = template.generate()
html = stream.render('html')
print(html)
Expected output: the numbers are printed consecutively with no whitespace (and most critically no line-break) between them.
<html>
<head>
</head>
<body>
0<del>1</del>2
</body>
</html>
Actual output: It outputs the following:
<html>
<head>
</head>
<body>
0
<del>1</del>
2
</body>
</html>
Question: How do I eliminate the line-breaks? I can deal with the leading whitespace by stripping it from the final HTML, but I don't know how to get rid of the line-breaks. I need the contents of the for loop to be displayed as a single continuous "word" (e.g. 012 instead of 0 \n 1 \n 2).
What I've tried:
Reading the Genshi documentation.
Searching StackOverflow
Searching Google
Using a <?python ...code... ?> code block. This doesn't work since the carets in the <del> tags are escaped and displayed.
<?python
def numbers():
n = ''
for i in range(3):
if i == 1:
n += '<del>{i}</del>'.format(i=i)
else:
n += str(i)
return n
?>
${numbers()}
Produces 0<del>1</del>2
I also tried this, but using genshi.builder.Element('del') instead. The results are the same, and I was able to conclusively determine that the string returned by numbers() is being escaped after the return occurs.
A bunch of other things that I can't recall at the moment.
Not ideal, but I did finally find an acceptable solution. The trick is to put the closing caret for a given tag on the next line right before the next tag's opening caret.
<body>
<py:for each="i in range(3)"
><py:choose
><del py:when="i == 1">${i}</del
><py:otherwise>${i}</py:otherwise
></py:choose
</py:for>
</body>
Source: https://css-tricks.com/fighting-the-space-between-inline-block-elements/
If anyone has a better approach I'd love to hear it.

How can I see output from a Brython script on the page? Why doesn't `print` work?

I try to use Brython. I have a Python script (test.py) and I would like to display the result of this script in the browser.
I have tried :
<html>
<head>
<script src="brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python" src="test.py"></script>
</body>
</html>
and my script is :
x = int(input("Value: "))
x = pow(x,2)
print("Result: " + str(x))
Unfortunately, I cannot display the result in the browser. Is there something missing ?
In Brython, print displays in the browser console.
If you want to write the result in the HTML document:
from browser import document
x = int(input("Value: "))
x = pow(x, 2)
document <= "Result: " + str(x)
[edit] Another option is to set sys.stdout to an object with a write() method, for instance document in module browser :
from browser import document
import sys
sys.stdout = document
print("Hello", "world !")
Add an id='fish' whatever for tag and then overwrite it in python:
<body id='fish' onload='brython()'>
and then:
d = document['fish']
d.clear()
d <= "Result: %s" % str(x)
Note that you need to call element .clear() first, <= is the same as Javascript .appendChild(), see the documentation: https://brython.info/static_doc/en/cookbook/content_in_div.html
If you want to see it in proper XHTML page, don't replace the whole body but just one div-element/tag for example. Or overwrite the whole body with all needed XHTML tags.

Python code to change the background color of html

I have created a dashboard using python. I have a requirement to make some cosmetic changes in the html page.
Change the font and size
Changing the background color
Putting one company logo.
I researched with turtle and tkinter,and installed the same but the system is not recogonizing the modules. Is there a way to achieve the above functionality.
Source code is as below
#!/usr/local/bin/python
import requests
import json
import datetime
import sys
import os
from html import HTML
todayDate=datetime.date.today().strftime("%Y-%m-%d")
h=HTML('html','')
p=h.p('DETAILS for ',' ', todayDate)
t=h.table(border='1')
r=t.tr()
r.td('Import Timestamp')
r.td('JobId')
r.td('Status')
r.td('RecordsProcessed')
r.td('RecordsFailed')
r.td('FileName')
r.td('Duration')
r.td('Throughput')
print '\n'
def genHTMLforImportSuccess():
responseurl = requests.get(url)
if(responseurl.ok):
jData = json.loads(responseurl.content)
if jData > 0:
for responseurl in jData['response']:
starttime=responseurl['statistics']['startTime']
jobId= responseurl['jobId']
status = responseurl['status']
recordsProcessed=responseurl['statistics']['recordsProcessed']
recordsFailed=responseurl['statistics']['recordsFailed']
fileName=responseurl['fileName']
duration=responseurl['statistics']['duration']
throughput=responseurl['statistics']['throughput']
print '\n'
r=t.tr()
r.td(str(starttime))
r.td(str(jobId))
r.td(str(status))
r.td(str(recordsProcessed))
r.td(str(recordsFailed))
r.td(str(fileName))
r.td(str(duration))
r.td(str(throughput))
print '\n'
else:
print "No data feed"
else:
responseurl.raise_for_status()
genHTMLforImportSuccess()
print h
Any help is highly appreciated
I added the below code after the
from html import HTML
html = """
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>testpage </title>
<style>
body {
background-color: aqua;
}
</style>
</head>
<body>
</body>
</html>
"""
but could not get the desired result.how can i fix this

Take list elements as strings in new lines on html page using python script

I have one list of bugs = ['bug1','bug2']. I want to put that in HTML page which I create from python script.
bgs = "print '\\n'.join(bugs_list)"
html_str = """
<html>
<body>
%(bugs_list)s
</body>
</html>
"""% {'bugs_list' : bgs}
How can I take bgs value as strings in new lines on html page?
bug1
bug2
bgs = exec(bgs) -> I can't take output of exec in variable, so got stuck here. Can someone please suggest me how to do this?

Categories

Resources