Writing Files not working (Windows 7) - python

I'm trying to output some of my data to an HTML file.
Python has no problem creating a new file, but it seems to have problem with the write command. The program functions with no errors or warnings, but the filesize remains 0kb (empty).
I'm a bit of a newbie to python, so I'm hoping someone can point out my mistake.
Here is the code:
#OUTPUT
calcfile = open('calculation.html','w');
CALCOUT = """<!DOCTYPE html>
<html>
<head>
<title>Quick Calculation</title>
</head>
<body>
<h1>Estimate</h1>
<table>
"""
#Some code which appends to CALCOUT -- long but it works perfectly via STDOUT.
calcfile.write("%s" % CALCOUT);
#also tried calcfile.write(CALCOUT);

You have to remember to close the file after opening it. Or even better, use the with constuct, which closes files automatically as soon as the scope of the with block is exited.
with open('calculation.html','w') as calcfile:
CALCOUT = """<!DOCTYPE html>
<html>
<head>
<title>Quick Calculation</title>
</head>
<body>
<h1>Estimate</h1>
<table>
"""
calcfile.write(CALCOUT)

Try this:
calcfile.write(str(CALCOUT))
Also, there are no semicolons needed in Python.

You have to calcfile.close() the file of course.

Related

python eel - and 404 when block=False

Just looking a bit into the idea of python and eel - and got somehow a strange behavior by trying around the callbacks and expose'es.
Well - I put out all my code with feedbacks and came back again to the basic level. But the behavior is still there. block=False seems not working and will crash:
import eel
eel.init("view")
eel.start("index_blank.html", block=False)
And my puristic html code:
<!doctype html>
<html lang="en">
<head>
<script src="eel.js"></script>
</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>
It gives me a 404 error.
But when I start eel with this basic pattern:
eel.start("index_blank.html")
it will work. When I use block=False it wont't:
eel.start("index_blank.html", block=False)
Any idea?
Yes... I know. I kicked out all my callbacks out of this code and came back to this very basic pattern. Just to get the idea what's wrong. I know that I do not need block=False here - but at the end of the day I want draw back something on the html-code.
python3. pip3.

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}}') )

Repetitive execution of a Python code daily without Javascript

I intend to use Python to generate an HTML code that will be saved to an external file. The HTML code will display the current day. No Javascript nor PHP allowed. How can I make the Python code repeat every day after midnight, so that the corresponding HTML file will contain a valid day in a week info? Thank you. My code:
import datetime
t=datetime.datetime.now()
s="""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Daily Portal</title>
</head>
<body>
<div>{maininfo:}</div>
</body>
</html>"""
s1=t.strftime("%A")
s2="Good morning John. Today is "+s1+"."+" Have a beautiful day."
s=s.format(maininfo=s2)
print(s)
You can set a job scheduler to execute the code everyday. Refer here and here (if you are running on a unix system).

Correct way of hard-coding html code in python script?

I have developed a web-based tool, and currently trying to make it python-launchable. I figured using CEFpython is probably the way to do it. I followed the tutorial here and wrote the following code:
from cefpython3 import cefpython as cef
import base64
import platform
import sys
import threading
import os
HTML_code = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link href="static/css/main.css" rel="stylesheet" />
</head>
<body>
<div id="UI">
</div>
<div id="container"></div>
<script src="static/main.js"></script>
<script type="text/javascript">
function defineData(datainput){
console.log("start")
data = datainput;
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(loc);
console.log(dir);
Main();
}
</script>
</body>
</html>
"""
def html_to_data_uri(html):
html = html.encode("utf-8", "replace")
b64 = base64.b64encode(html).decode("utf-8", "replace")
ret = "data:text/html;base64,{data}".format(data=b64)
return ret
def main(config):
sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error
settings = {}
cef.Initialize(settings=settings)
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),window_title="Test")
browser.SetClientHandler(LoadHandler(config))
cef.MessageLoop()
cef.Shutdown()
return
class LoadHandler(object):
def __init__(self, config):
self.config = config
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
if not is_loading:
# Loading is complete. DOM is ready.
browser.ExecuteFunction("defineData", self.config)
unfortunately, unlike in the tutorial, my tool has to load a local .js file where the main function is defined (), and it seems if I code the html file this way, my working directory is not actually the directory where I call the script, but some strange place
the output of these lines are:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(loc);
console.log(dir);
output:
text/html;base64,CjwhRE9DVFlQRSBodG1sPgo8aHRtbCBsYW5nPSJlbiI+Cgk8aGVhZD4KCQk8bWV0YSBjaGFyc2V0PSJ1dGYtOCI+CgkJPG1ldGEgbmFtZT0idmlld3BvcnQiIGNvbnRlbnQ9IndpZHRoPWRldmljZS13aWR0aCwgdXNlci1zY2FsYWJsZT1ubywgbWluaW11bS1zY2FsZT0xLjAsIG1heGltdW0tc2NhbGU9MS4wIj4KCQk8bGluayBocmVmPSJzdGF0aWMvY3NzL21haW4uY3NzIiByZWw9InN0eWxlc2hlZXQiIC8+CgkJPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCQkJKiB7CgkJCQkuYm9yZGV....
text
Could you help me finding the correct way of hard coding html code in python with the correct path? maybe I need to somehow set the path?
PS: I did try including the html code in a separate .html file, and it worked on Windows machines, but it seems MacOS doesn't like it. Since this tutorial did work on MAC, I'm trying to hard code the html part into the python script and hope it would work on both Windows and Mac
Well, the HTML document has been converted to the body of a data URI by html_to_data_uri, so the U[niversal]R[esource]L[ocator] (window.location) of the document isn't a location on a server, but the data URI itself (the "strange place" you mention).
Remember that URLs are a subset of URIs, and you passed the URI as a URL to CEF with:
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),window_title="Test")
So, as long as you are using a data URI/URL, I don't think that window.location will be helpful. Instead, you could extract the HTML code into a separate .html file, and change that line to:
browser = cef.CreateBrowserSync(url="/path/to/that_html_file.html", window_title="Test")

wx HtmlEasyPrinting encoding issues when Printing

I have an html text with non-ascii characters, and I want it printed using HtmlEasyPrinting module.
printer = HtmlEasyPrinting()
text = '''
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<b><</b>
<p>é</p>
</body>
</html>'''
printer.PreviewText(text)
printer.PrintText(text)
When I run the preview part, everything looks ok! (right encoding applied)
When I try to PrintText instead, things go wrong and it seems that non-ascii characters got funny representations on paper/exported file.
Anyone have an idea why the Preview works ok, but not the Printing itself? Are there some setting to be applied?
wx.version = 2.8.11.0 (gtk2-unicode)
python 2.7

Categories

Resources