Haris P
Haris P

Reputation: 47

Python runs on terminal, not on web browser

I'm trying to run a simple python script on my webserver, but it's not showing up in the web browser.

In terminal I check if python is installed:

whereis python
python: /usr/bin/python2.7 /usr/bin/python2.7-config /usr/bin/python /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/local/bin/python3.9-config /usr/local/bin/python3.9 /usr/local/lib/python3.9 /usr/include/python2.7 /opt/imh-python/bin/python2.7 /opt/imh-python/bin/python2.7-config /opt/imh-python/bin/python3.9 /opt/imh-python/bin/python /usr/share/man/man1/python.1.gz

This tells me that I have python installed. I created a simple file that contains this code:

#! /usr/bin/python

print('Content-Type: text/html\r\n\r\n')
print('\r\n')

print('Hello World')

I ran dos2unix and chmod a+x on the file.

I ran the file in terminal and get this output:

Content-Type: text/html




Hello World

When I try to open the file in the web browser this is the output I get:

#! /usr/bin/python

print('Content-Type: text/html\r\n\r\n')
print('\r\n')

print('Hello World')

I changed the single quotes in the print statement to double. I tried different ways of entering new lines, but nothing seems to work. Am I missing or overlooking something crucial here?

Upvotes: 1

Views: 806

Answers (1)

DMcC
DMcC

Reputation: 567

The browser doesn't have a Python interpreter. So opening the file in a browser is just going to show your source code. If you want it to show on a browser you need to run it on a server where it can be interpreted. A simple solution is to use Flask, which comes with a development server. Once you've installed flask:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello():
    return 'Hello World'


app.run()

Then navigate to http://localhost:5000 in your browser.

Upvotes: 1

Related Questions