Python-Perl Translation

hamish_lawson hamish_lawson at yahoo.co.uk
Tue Jan 29 06:38:06 EST 2002


Others have pointed out using the cgi module instead to do the query-
string decoding, but a straight translation of your Perl script would 
be as follows:

*  import string, os
*
*  user_id, banner_id, page = string.split(os.environ
['QUERY_STRING'], "&")
*  redirect = "http://www.myaffiliateprogram.com/u/%(user_id)s/t.asp?
id=%(banner_id)s&p=%(page)s" % locals()
*  print "Location: %(redirect)s\n" % locals()

Python doesn't automatically interpolate variables into strings, but 
has to be invoked explicitly using the '%' operator and a supplied 
set of values. Also note that the print statement adds a carriage 
return itself, and so only only one need be included in the argument.

If you are using version 2.0 or later of Python, then you can omit 
importing the string module and instead call split as a method of the 
query string itself:

*  user_id, banner_id, page = os.environ['QUERY_STRING'].split("&")

Note that the urlopen function actually fetches a web page; in this 
case you don't actually want your server-side script to fetch the web 
page itself, but instead return an HTTP header that instructs the 
user's browser to fetch that page.

Hamish Lawson






More information about the Python-list mailing list