Important notice about this site

I graduated from the University of Texas at Austin in December 2020. This blog is archived and no updates will be made to it.

Running Python CGI scripts on your UTCS website

May 15, 2019

Did you know you can run Python scripts on your UTCS website? Getting Python scripts to run as a webpage is as simple as creating a file with the .cgi extension, putting a Python shebang, and providing the proper HTTP headers.

For instance, I wrote a random CGI script in Python which is available on my website. It is nothing special, but it takes these two tricks to get it to work properly:

#!/usr/bin/python
print "Content-Type: text/html\n\n"

The first line specifies that I wish to use Python to execute this CGI script (as I very well could've put Perl in this file). The second line makes the Content-Type header known. These two lines are all that's necessary for the script to begin running. After that, you can do whatever you want in your Python file. Hope this helps!

Thanks to Garrett Gu for discovering the Content-Type header requirement. Without sending the Content-Type header, things won't work correctly.

For those curious, here are the contents of apgoodluck.cgi:

#!/usr/bin/python
print "Content-Type: text/html\n\n"

exams = [
        ["AP United States Government and Politics", "AP Chinese Language and Culture", "AP Environmental Science"],
        ["AP Seminar", "AP Spanish Language and Culture", "AP Japanese Language and Culture", "AP Physics 1: Algebra-Based"],
        ["AP English Literature and Composition", "AP European History", "AP French Language and Culture"],
        ["AP Chemistry", "AP Spanish Literature and Culture", "AP German Language and Culture", "AP Psychology"],
        ["AP United States History", "AP Computer Science Principles", "AP Physics 2: Algebra-Based"],
        ["AP Biology", "AP Physics C: Mechanics", "AP Physics C: Electricity and Magnetism"],
        ["AP Calculus AB", "AP Calculus BC", "AP Art History", "AP Human Geography"],
        ["AP English Language and Composition", "AP Italian Language and Culture", "AP Macroeconomics"],
        ["AP Comparative Government and Politics", "AP World History", "AP Statistics"],
        ["AP Microeconomics", "AP Music Theory", "AP Computer Science A", "AP Latin"]
]
for x in range(0, len(exams)):
        pout = ""
        for y in exams[x]:
                pout += y + " and/or "
        pout = pout[:len(pout)-8]
        print "Week " + str((x // 5) + 1) + ", Day " + str((x % 5) + 1) + "<br />"
        print "Good luck to everyone who is taking " + pout + "!<br />"

Update (May 19, 2019): For more documentation on using Python CGI scripts, see this page for Python 2 and this page for Python 3.

Back to blog

Back to top