Passing a parameter to a Python script from a web page

I have a Python script that I use to process a copy of a webpage downloaded from a website and stored on my MacBook Pro laptop's hard drive to produce a CSV file from the data within that file. I was running the script from a command-line interface (CLI), i.e., a Terminal window, on the system by issuing a command like ./ inputfile outputfile where inputfile and outputfile were the file names and locations of the file holding the data and the output CSV file, respectively. I wanted to execute that script from a link on a web page, instead, so I needed a way to pass the arguments I had been passing on the command line to the Python script in the URL that I'd specify as the link on the web page. One way that you can do that for Python is explained at [Tutor] Passing Arguments to a Remote CGI Script where the following sample Python script is shown:

Mastering Python
Mastering Python
1x1 px

"""test.cgi  --- a small CGI program to show how one can pass parameters.

import cgi
fs = cgi.FieldStorage()

print "Content-type: text/plain\n"
for key in fs.keys():
    print "%s = %s" % (key, fs[key].value)

The script imports the cgi module and will display parameters passed in a URL. If I place the script in a cgi-bin directory for the webserver I'm running on the laptop and make it executable with chmod +x test.cgi, I can then call the script with http://localhost/cgi-bin/test.cgi. If I don't pass any parameters to it, there won't be any output to display, so I would just see a blank page as a result, but if I use http://localhost/cgi-bin/test.cgi?a=1 as the URL, I would see the following displayed:

a = 1

To pass a value as an argument to the script in the URL, you put a question mark at the end of the URL followed by a variable name and then an equals sign and its value, i.e., ?a=1 in this case. But, what if you need to pass multiple arguments to the script, which is what I need to do for my script that expects an input and an output file name? For the script above, I could specify multiple parameters by separating them with an ampersand, e.g., http://localhost/cgi-bin/test.cgi?a=1&b=2 would display the following:

a = 1
b = 2

Rather than looping through all of the values, you could also print them individually using the following Python code:

print fs["a"].value
print fs["b"].value

Related articles:

  1. Using Python scripts with Apache on OS X El Capitan
  2. Running an Apache web server under OS X El Capitan
  3. Writing to a CSV file with Python


  1. [Tutor] Passing Arguments to a Remote CGI Script
    Posted: Friday September 13, 2002
    By: Danny Yoo Mailing Lists