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}}') )
Related
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.
I wish to import my own library in Brython. This page of the documentation purports to show how, by adding the appropriate directory to the python path, but I can't make it work because I can't make Brython import sys.
Here's the simplest example code from the first page of the Brython documentation:
<html>
<head>
<script src="../src/Brython3.2.8/brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document, alert
def echo(ev):
alert(document["zone"].value)
document['mybutton'].bind('click', echo)
</script>
<input id="zone"><button id="mybutton">click !</button>
</body>
</html>
And that works fine.
But if I try to import sys:
<html>
<head>
<script src="../src/Brython3.2.8/brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
import sys
from browser import document, alert
def echo(ev):
alert(document["zone"].value)
document['mybutton'].bind('click', echo)
</script>
<input id="zone"><button id="mybutton">click !</button>
</body>
</html>
Then the html will display but the button will not do anything.
The Console on Chrome shows the following error:
brython.js:6929 XMLHttpRequest cannot load file:///C:/Users/XXXXXXXXX/XXXXXX/src/Brython3.2.8/Lib/sys.py?v=1476283159509. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
$download_module # brython.js.6929
import_py # brython.js.6929
exec_module # brython.js.6929
etc etc
So, how can I import sys in brython, and/or how can I import my own library in python?
Thanks.
You need to include brython_stdlib.js in your html code. So your html should look like this:
<html>
<head>
<script src="../src/Brython3.2.8/brython.js"></script>
<script src="../src/Brython3.2.8/brython_stdlib.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
import sys
from browser import document, alert
def echo(ev):
alert(document["zone"].value)
document['mybutton'].bind('click', echo)
</script>
<input id="zone"><button id="mybutton">click !</button>
</body>
</html>
Source Code : https://github.com/imvickykumar999/Brython/blob/master/index.html#L36
Deployed Code : https://imvickykumar999.github.io/Brython/
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Brython</title>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.8.9/brython.min.js">
</script>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.8.9/brython_stdlib.js">
</script>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
crossorigin="anonymous">
</head>
<body onload="brython()">
<style>
body {
/* background-color: yellow; */
background-image: url(https://images.unsplash.com/photo-1573196872258-41425124bf5d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80);
/* background-repeat: no-repeat; */
}
</style>
<script type="text/python">
from browser import document
def calc(a, b, o):
d = { '+' : a+b,
'-' : a-b,
'*' : a*b,
'/' : a/b,
'%' : a%b
}
return f"({a}{o}{b})=({d[o]})"
a = float(input('Enter first number : '))
b = float(input('Enter second number : '))
o = input('Enter the Operator (+,-,*,/,%) : ')
document <= calc(a, b, o)
</script>
</body>
</html>
Brython cannot import from any Python package that is part of any Python installation on the user's computer. It works by transpiling to JavaScript and running in the browser's Javascript engine. It has no knowledge of any local Python installations, and does not require any such installations to exist.
To use Python's standard library
Add a script tag to include brython_stdlib.js as well as the base brython.js. Several CDNs provide this already.
The Brython implementation of the Python standard library does not match the reference implementation exactly. See the documentation for details on what is included and how it is organized.
Importing your own code from within the document
For organizational purposes, Python code within the HTML document can be split across multiple <script> tags. The id attribute for the tag gives a "module name" that can be used in import statements in other scripts, as long as that script has already executed. The documentation includes an example:
<script type="text/python" id="module">
def hello():
return "world"
</script>
<script type="text/python">
from browser import document
import module
document.body <= module.hello()
</script>
The browser will have loaded the first <script> tag first, creating a (JavaScript representation of) a Python module named module that contains the hello function. The second script tag will be able to import that module and use the function as usual in Python.
Importing your own code from the server
Make the files available in the appropriate place as described in the documentation. Brython's implementation of the import statement (equivalently, __import__ builtin function) will attempt to find the code on the server using AJAX.
Importing your own code as a compiled Brython package
As explained in the documentation, use the Brython package (pip install brython) to create a JavaScript file that represents the Python code. (For third-party libraries, also check if such a JavaScript file is already available from a CDN.)
Suppose we have a project that creates a package named example. Navigate to the folder that contains that package (either src or the project folder, according to how the project is organized), then run brython-cli make_package example.
This should generate a example.brython.js file. Put it somewhere on the server, and configure the server to host that file at a specific URL. Then add the corresponding tag to the client page source (or the template that generates that page).
After that it should be possible to import example, from example import ... etc. in the Brython code.
Alternately, use brython-cli modules, as described in the 'Optimization' section, to create a combined library JavaScript file representing the entire server-side part of the project.
I have been learning about stacks (which I created a class for) in Python lately and I learned that you can use them to check if parentheses are balanced, which is each opening symbol has a corresponding closing symbol and the pairs of parentheses are properly nested.
Now I am trying to use a stack to do the same but with HTML. So for example, my program would take the following document-
<html>
<head>
<title>
Example
</title>
</head>
<body>
<h1>Hello, world</h1>
</body>
</html>
and check it to make sure that it has proper opening and closing tags.
I just don't even have an idea on where to start and I'm very confused. Any help is appreciated.
If you want to approach the problem this way, think about what you did before:
You used a stack to keep track of (, [, or {.
What's the difference between ( and <html>? One of these is just a collection of characters. So change your code - instead of reading a single character and placing that on the stack, read the tag and place that on the stack instead.
You may also want to decide if you want to ensure that you've got some valid(ish) HTML - i.e. what happens if you encounter <<html>?
#Old interesting question:use usual stack for pop, push, and peek
#inserted space for each ">x" and "x<" where x is any char,
import re
text='''<html>
<head>
<title>
Example
</title>
</head>
<body>
<h1>Hello, world</h1>
</body>
</html>'''
def check_html_balance(text):
s=Stack()
x=text.replace('<', ' <'); y=x.replace('>', '> ')
a=[w for w in y.split() if re.search('<\S+>',w)]
b=[w for w in a if "/" not in w]
c=[w for w in a if "/" in w]
for w in text.split():
if w in b:
s.push(w)
elif not s.is_empty() and (w in c) and (w.replace('/','')==s.peek()):
s.pop()
return s.is_empty()
check_html_balance(text)
# A second, shorter solution without replacing "x<" by "x <"...
text='''<html>
<head>
<title>
Example
</title>
</head>
<body>
<h1>Hello, world</h1>
</body>
</html>'''
import re
def check_balance(text):
L=re.split('(<[^>]*>)', text)[1::2]
s=Stack()
for word in L:
if ('/' not in word):
s.push(word)
elif not s.is_empty() and (word.replace('/','')==s.peek()):
s.pop()
return s.is_empty()
check_balance(text)
So i have a need to process some HTML in Python, and my requirement is that i need to find a certain tag and replace it with different charecter based on the content of the charecters...
<html>
<Head>
</HEAD>
<body>
<blah>
<_translate attr="french"> I am no one,
and no where <_translate>
<Blah/>
</body>
</html>
Should become
<html>
<Head>
</HEAD>
<body>
<blah>
Je suis personne et je suis nulle part
<Blah/>
</body>
</html>
I would like to leave the original HTML untouched an only replace the tags labeled 'important-tag'. Attributes and the contents of that tag will be important to generate the tags output.
I had though about using extending HTMLParser Object but I am having trouble getting out the orginal HTML when i want it. I think what i most want is to parse the HTML into tokens, with the orginal text in each token so i can output my desired output ... i.e. get somthing like
(tag, "<html>")
(data, "\n ")
(tag, "<head>")
(data, "\n ")
(end-tag,"</HEAD>")
ect...
ect...
Anyone know of a good pythonic way to accomplish this ? Python 2.7 standard libs are prefered, third party would also be useful to consider...
Thanks!
You can use lxml to perform such a task http://lxml.de/tutorial.html and use XPath to navigate easily trough your html:
from lxml.html import fromstring
my_html = "HTML CONTENT"
root = fromstring(my_html)
nodes_to_process = root.xpath("//_translate")
for node in nodes_to_process:
lang = node.attrib["attr"]
translate = AWESOME_TRANSLATE(node.text, lang)
node.parent.text = translate
I'll leave up to you the implementation of the AWESOME_TRANSLATE function ;)
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.