Python Forum

Full Version: replace html string with python variable !
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello all ...
im trying to run this command on the system ( whoami ) and i need to result for the command to be saved in html page ...

this is my code ...

import os
qassam = os.system("whoami")

html_str = """
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>test</h1> <============================================== i need to replace test with ( qassam = os.system("whoami") ) result !!
<p>My first paragraph.</p>

</body>
</html>
"""

Html_file= open(r"C:\Users\adam\AppData\q.html","w")
Html_file.write(html_str)
Html_file.close()
how i can do that ?
better use popen

import os

process = os.popen('whoami')
myname = process.read()
process.close()
 
html_str = """
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
 
<h1>test</h1>
<p>My first paragraph.</p>
 
</body>
</html>
"""
 
html_str = html_str.replace("test", myname)

Html_file= open(r"/tmp/q.html","w")
Html_file.write(html_str)
Html_file.close()
(Aug-30-2018, 11:12 AM)Axel_Erfurt Wrote: [ -> ]better use popen

import os

process = os.popen('whoami')
myname = process.read()
process.close()
 
html_str = """
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
 
<h1>test</h1>
<p>My first paragraph.</p>
 
</body>
</html>
"""
 
html_str = html_str.replace("test", myname)

Html_file= open(r"/tmp/q.html","w")
Html_file.write(html_str)
Html_file.close()

works thank u :)
can u explain why u used myname = process.read() ?
to keep the result of popen for using it for replace in the html string.

you can name it whatever you want.
Can also show a example with Jinja2.
Jinja2 is build for stuff like this,it's mostly used with a running server to transport values to HTML on client side.
It also work fine on it's own.
from jinja2 import Environment, FileSystemLoader
import os

html_str = """\
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>{{ test }}</h1>
<p>My first paragraph.</p>

</body>
</html>"""

process = os.popen('whoami')
myname = process.read().strip()
process.close()

# Print html
print(Environment().from_string(html_str).render(test=myname))

# Save html
#Environment().from_string(html_str).stream(test=myname).dump('name.html', encoding='utf-8')
Output:
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>Pc User Name</h1> <p>My first paragraph.</p> </body> </html>