Python on the web: How to use Environment variables to detect script path

If you are writing Python scripts to run from the cgi-bin of your website, here is some code that will allow the script to detect it’s own path, so that it doesn’t have to be hard coded. The preferable way is to use the environment variable 'SCRIPT_URI'. For example:
this_script = os.environ['script_uri']

Note: Depending on your host configurations, your Environment variables may be in all caps or all lower case. My web host is all upper case, but my local apache server is configured for lower case.

If ‘SCRIPT_URI’ or ‘script_uri’ is not found in your Environment variables, here is an alternative using ‘http_host’ and ‘script_name’. For example:

http = r'http://'
http_host = os.environ['http_host']
script_name = os.environ['script_name']
this_script = http + http_host + script_name

For example:
http://bluegalaxy.info/cgi-bin/this_script.py

In order to view this output in a web browser, you will need to:

  1. Set shebang line at the top: #!/usr/bin/python
    Note: Your shebang line might be different. For example: #!C:\Python27\python.exe -u
  2. import os
  3. Send ‘Content-type: text/html’ to the browser:  print "Content-type: text/html\n\n";

Here is what the complete code looks like:

#!/usr/bin/python

import os

print "Content-type: text/html\n\n";
print "<html><head></head>"
print "<body>"

http = r'http://'
http_host = os.environ['HTTP_HOST']
script_name = os.environ['SCRIPT_NAME']
this_script = http + http_host + script_name

print "\n<BR><b>This script:</b><BR>", this_script
print "</body></html>"

Leave a Reply