Python Forum
No new line from print in a browser
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
No new line from print in a browser
#1
When called from a terminal, the following script prints 5 lines as expected.

#!C:\Users\User\AppData\Local\Programs\Python\Python312\python.exe
print("Content-Type: text/html\n\n")

print("This is expedience over elegance.", end="\r\n")
print()
print('12')
print('**', end="\n")
print(f"Click the browser's back button/arrow, then the RED Exit arrow to return to the menu. ")
However, when called from a browser there are no newlines (\n) displayed/sent. localhost/hellow.py

Output:
This is expedience over elegance. 12 ** Click the browser's back button/arrow, then the RED Exit arrow to return to the menu.
I am running a current version on Windows 11. I have installed xampp Apache for my local server.
Apache/2.4.58 (Win64) OpenSSL/3.1.3 PHP/8.2.12 Server at localhost Port 80
I have added the following to the Apache HTTP server configuration file, httpd.conf, to enable calls to python.
Quote:# Add Python server
AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict

I have tried using python ver 3.12, 3.13, 3.14. I have called using FireFox, Chrome, and Edge all with the same results. Wall
Say what you will about Sisyphus. He always has work.
Reply
#2
You should report this to python.org, the authors of python.
Perhaos add to this thread
Reply
#3
HTML doesn't break lines on newlines. This doesn't seem like a python issue at all, but how browsers render text.

If you want a newline in your HTML rendering, you'll need to output a "<br>" token (or maybe in some cases you'll want "<p>").
Reply
#4
@Lou: running Python via CGI is as dead as it can be and totally outdated for more than ten years. Python removed even the CGI module from it's standard library with Python 3.13

The Python standard for running web applications is WSGI for a long time and it is a very recommended best practice to use one of the numerous Python WSGI frameworks. The most common ones for standard web based applications are probably Flask, Django and Bottle, wheres the later is probably the easiest (to learn) for simple task. For creating web-based APIs, FastAPI is another very popular Python Webframework.

Regards, noisefloor
snippsat and buran like this post
Reply
#5
(Nov-28-2025, 04:19 AM)Lou Wrote: I am running a current version on Windows 11. I have installed xampp Apache for my local server.
Apache/2.4.58 (Win64) OpenSSL/3.1.3 PHP/8.2.12 Server at localhost Port 80
I have added the following to the Apache HTTP server configuration file, httpd.conf, to enable calls to python.
As mention this stuff and CGI has been dead💀 for long time in Python.
I done a lot of stuff in Flask and some Django stuff,i also like Litestart.
Here is demo of your stuff with Litestar(all is build in and has a production ready web server) so no need for xampp,Apache,CGI...

HTML version (with <br>(or CSS usually dos this stuff)line breaks),the normal way or usually load the html from a file.
app.py:
# pip install litestar
from litestar import Litestar, get

@get("/hellow", media_type="text/html")
async def hellow_html() -> str:
    return """<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello</title>
</head>
<body>
    This is expedience over elegance.<br>
    <br>
    12<br>
    **<br>
    Click the browser's back button/arrow, then the RED Exit arrow to return to the menu.
</body>
</html>
"""

app = Litestar(route_handlers=[hellow_html])
Plain text version (browser shows raw newlines)
app.py:
from litestar import Litestar, get, Response

@get("/hellow-text")
async def hellow_text() -> Response:
    body = (
        "This is expedience over elegance.\n"
        "\n"
        "12\n"
        "**\n"
        "Click the browser's back button/arrow, then the RED Exit arrow to return to the menu.\n"
    )
    return Response(body, media_type="text/plain")

app = Litestar(route_handlers=[hellow_text])
Run with:
litestar run --reload
in browser eg http://127.0.0.1:8000/hellow
Reply
#6
Not sure why you want to run Python in your browser to see text there.

An html file is just a text file. Make a blanko html file, something like this:

Quote:<!DOCTYPE html>
<html>
<head>
<meta http-equiv="CONTENT-TYPE" CONTENT="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Texan Text</title>
<link rel="stylesheet" type="text/css" href="css/mystyle1.css" />
</head>

<body><br>
<div id="div-header">Big Deal Here</div><br>

<div id="div-with-bg">
HTML
</div><br>
</body>
</html>

and in a div or p just put HTML then, each week or whenever, replace HTML with the text you want + br Very simple, basic and fast.

First save the text you want, each line being a line of text as you want it displayed. Then Python can take over.

Here is what you see if you open my week48.txt:

Quote:Text I want displayed in my browser:

#!C:\Users\User\AppData\Local\Programs\Python\Python312\python.exe
Content-Type: text/html
This is expedience over elegance.

12
**
Click the browser's back button/arrow, then the RED Exit arrow to return to the menu.

Python puts the text in the blanko html file;

source = '/home/peterr/temp/html_text/week48.txt'
blanko_html = '/home/peterr/public_html/www/html/blanko_html/simple_blanko_html_file.html'
# make sure your css file is in a folder css under wherever your html file is saved
# or change the link in the blanko html
savefile = '/home/peterr/public_html/www/week48_2025.html'

with open(source) as infile:
    text = infile.readlines()

# don't actually need .strip()
for i in range(len(text)):
    text[i] = text[i].strip() + '<br>'
    print(text[i])

webtext = ''.join(text)

with open(blanko_html) as webpage,  open(savefile, 'w') as outfile:
    html = webpage.read()
    new = html.replace('HTML', webtext)
    outfile.write(new)
Let css take care of any styling you want!
Reply
#7
(Nov-29-2025, 10:05 AM)Pedroski55 Wrote: ot sure why you want to run Python in your browser to see text there.
By his post locks like he try to web-development in Python bye using a old stuff like CGI,xampp,Apache.
So this was the way to do web-development in Python before WSGI.
Now these days all Python web stuff is build on WSGI or ASGI (Asynchronous Server Gateway Interface) is a spiritual successor to WSGI.
Usually want more than make a HTML file and give to browser,
so if do web-development in Python use eg Flask,Django,FastApi or as mention Litestar which is a lightweight and flexible ASGI framework.
Reply
#8
@snippsat Is there something you could do with html and Python that could not be done using html and PHP?
Reply
#9
Pedroski55 Wrote:@snippsat Is there something you could do with html and Python that could not be done using html and PHP?
From the browser’s point of view, there is no difference: it just receives HTML (plus CSS/JS).
The real difference is how that HTML is generated on the server.

How HTML + PHP works
Typical stack: XAMPP / Apache / Nginx + PHP
You usually have files like index.php, products.php, etc.
The file is mostly HTML with bits of PHP embedded:
<!-- index.php -->
<html>
  <body>
    <h1>Hello, <?= htmlspecialchars($name) ?></h1>
    <?php if ($isLoggedIn): ?>
      <p>Welcome back!</p>
    <?php else: ?>
      <p>Please log in.</p>
    <?php endif; ?>
  </body>
</html>
In Python if do same stuff could eg use Flask with Jinja that build into Flask.
# app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def index():
    name = "Joe"
    is_logged_in = True
    return render_template("index.html", name=name, is_logged_in=is_logged_in)

if __name__ == "__main__":
    app.run()
So here us Jinja to put stuff in the HTML.
<!-- templates/index.html -->
<html>
  <body>
    <h1>Hello, {{ name }}</h1>
    {% if is_logged_in %}
      <p>Welcome back!</p>
    {% else %}
      <p>Please log in.</p>
    {% endif %}
  </body>
</html>
Jinja syntax:
{{ variable }} → output a value
Flask handles routing with decorators (@app.route("/something")).
Logic (database, business rules, etc.) lives in Python files; HTML stays mostly in templates.
Deployment you use WSGI servers like gunicorn/uwsgi + nginx) or Uvcorn for ASGI.
There is no other instal to start than(pip instal Flask) as web-server is included in Flask(WSGI server) or Litestrat(Uvcorn server).
Pedroski55 likes this post
Reply
#10
@snippsat Thanks very much for the explanation!

So using Flask, some other page handles the login, not index.html? You have the login details in MySQL I presume. Then you get a personalized index.html by replacing strings in a template html:

Quote:<h1>Hello, {{ name }}</h1>

My index.php is a form which calls login.php when you click submit.

login.php repeatedly calls index.php if login fails. If login succeeds, login.php calls another webpage:

Quote:include 'some_webpage.html.php';
exit();

Apache will go on the warpath if I stop using it!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  problem with spliting line in print akbarza 3 2,020 Jan-23-2024, 04:11 PM
Last Post: deanhystad
  Print the line before the corrent line tester_V 9 4,350 Nov-18-2022, 08:39 AM
Last Post: Gribouillis
  Print to a New Line when Appending File DaveG 0 2,316 Mar-30-2022, 04:14 AM
Last Post: DaveG
  If match not found print last line tester_V 2 4,285 Apr-26-2021, 05:18 AM
Last Post: tester_V
  print a line break in writelines() method leodavinci1990 1 12,869 Oct-12-2020, 06:36 AM
Last Post: DeaD_EyE
  Print characters in a single line rather than one at a time hhydration 1 3,228 Oct-10-2020, 10:00 PM
Last Post: bowlofred
  How to print string multiple times on new line ace19887 7 10,601 Sep-30-2020, 02:53 PM
Last Post: buran
  Pattern Require Last Line Print() why? Harshil 4 4,011 Aug-08-2020, 04:54 PM
Last Post: Harshil
  print only last matched line tester_V 24 12,328 Apr-30-2020, 05:16 AM
Last Post: deanhystad
  item from a line to list however when i print the line instead of words i get letters Sutsro 5 4,975 Apr-22-2020, 02:39 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020