Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-22 Thread Richard D. Moores
On Thu, Oct 21, 2010 at 15:44, Richard D. Moores  wrote:
>> If you want to control the number of decimal places in the string
>> formatting do something like:
>>
> i = 3
> print ("NEW LOW: %%.%sf at %%s" % i) % (lowz, timestamp)
>> NEW LOW: 81.750 at 22:55:13
> i = 6
> print ("NEW LOW: %%.%sf at %%s" % i) % (lowz, timestamp)
>> NEW LOW: 81.75 at 22:55:13
>
> Thanks very much for the string formatting instruction.

So I wrote a function:

def float2n_decimals(floatt, n):
"""
Given a float (floatt), return floatt to n decimal places.

E.g., with n = 2, 81.34567 -> 81.35
"""
return ("%%.%sf" % n) % floatt

which works fine, but a question remains: n is an integer. Why the 's'
in '%sf'?

(Also, please suggest a better name for this function.)

See this latest revision at .

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-22 Thread David Hutto
On Fri, Oct 22, 2010 at 9:42 AM, Richard D. Moores  wrote:
> On Thu, Oct 21, 2010 at 15:44, Richard D. Moores  wrote:
>>> If you want to control the number of decimal places in the string
>>> formatting do something like:
>>>
>> i = 3
>> print ("NEW LOW: %%.%sf at %%s" % i) % (lowz, timestamp)
>>> NEW LOW: 81.750 at 22:55:13
>> i = 6
>> print ("NEW LOW: %%.%sf at %%s" % i) % (lowz, timestamp)
>>> NEW LOW: 81.75 at 22:55:13
>>
>> Thanks very much for the string formatting instruction.
>
> So I wrote a function:
>
> def float2n_decimals(floatt, n):
>    """
>    Given a float (floatt), return floatt to n decimal places.
>
>    E.g., with n = 2, 81.34567 -> 81.35
>    """
>    return ("%%.%sf" % n) % floatt
>
> which works fine, but a question remains: n is an integer. Why the 's'
> in '%sf'?

Right here:
http://docs.python.org/release/2.5.2/lib/typesseq-strings.html

>
> (Also, please suggest a better name for this function.)
>
> See this latest revision at .
>
> Dick
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-22 Thread Richard D. Moores
On Fri, Oct 22, 2010 at 06:47, David Hutto  wrote:
>> which works fine, but a question remains: n is an integer. Why the 's'
>> in '%sf'?
>
> Right here:
> http://docs.python.org/release/2.5.2/lib/typesseq-strings.html

Sorry, but I don't see the answer to my question there.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] csv DictReader/Writer question

2010-10-22 Thread Peter Otten
Ara Kooser wrote:

>   Thank you for your response. I did try reading the documentation but I
> missed something (or several somethings in this case). So what I see in
> the code you supplied is:
> 
> with open(source, "rb") as instream:
>reader = csv.DictReader(instream, skipinitialspace=True)
> 
>destfieldnames = list(reader.fieldnames)
>destfieldnames.remove("Species2")
>destfieldnames.remove("Protein ID2")
> 
> So this reads the csv file in but I need to run it to see what
> skipinitialspace does. 

Your csv header looks like

Field1, Field2, Field3, ...

When you feed that to the DictReader you get fieldnames

["Field1", " Field2", " Field3", ...]

skipinitialspace advises the DictReader to remove the leading spaces, i. e. 
you get

["Field1", "Field2", "Field3", ...]

instead.

> Then it reads in the header line and removes the
> Species2 and Protein ID2. Does this remove all the data associated with
> those columns? For some reason I thought I had to bring these into a
> dictionary to manipulate them.

destfieldnames is the list of field names that will be written to the output 
file. I construct it by making a copy of the list of field names of the 
source and then removing the two names of the columns that you don't want in 
the output. Alternatively you could use a constant list like

destfieldnames = ["Field2", "Field5, "Field7"]

to handpick the columns.

>with open(dest, "wb") as outstream:
>writer = csv.DictWriter(outstream,
> destfieldnames,extrasaction="ignore")

The following line uses the csv.writer instance wrapped by the 
csv.DictWriter to write the header.

>writer.writer.writerow(destfieldnames)

The line below iterates over the rows in the source file and writes them 
into the output file.

>writer.writerows(reader)

A more verbose way to achieve the same thing would be

for row in reader:
writer.writerow(row)

Remember that row is a dictionary that has items that shall not be copied 
into the output? By default the DictWriter raises an exception if it 
encounters such extra items. But we told it to silently ignore them with 
extrasaction="ignore".
 
> I think the first line after the open writes the field names to the file
> and the follow lines write the data is that correct? I am going to run the
> code as soon as I get home.

Come back if you have more questions.

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-22 Thread David Hutto
On Fri, Oct 22, 2010 at 9:55 AM, Richard D. Moores  wrote:
> On Fri, Oct 22, 2010 at 06:47, David Hutto  wrote:
>>> which works fine, but a question remains: n is an integer. Why the 's'
>>> in '%sf'?
>>
>> Right here:
>> http://docs.python.org/release/2.5.2/lib/typesseq-strings.html
>
> Sorry, but I don't see the answer to my question there.

Usually the docs explain it better than I do, which is why I prefer
references. But short answer is, if you'll look in the chart on the
page given above, it states :

%s  String (converts any python object using str()).

So each % tells the string what to expect while interlacing that which
is given at the end. of the string after the final %

>
> Dick
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-22 Thread David Hutto
If I understand what i just said correctly, it just means it tells the
string what type to convert from when placing it into the final
result.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] URL test function.

2010-10-22 Thread Jeff Honey
I am trying to create a function to plug into a restart script I'm creating. I 
can't seem to successfully loop through making an http connection, if it fails 
to retry, if it succeeds, to end and continue with its parent function.

I'm  using the Fabric project's module and including my functions in fabfile.py.

the most rudimentary I've got right now is this:



def is_ready():
 with settings(
  warn_only=True
 ):
  try:
   urllib2.urlopen('http://'+env.host_string+'\:8080') 
  except urllib2.URLError:
   time.sleep(10)
   urllib2.urlopen('http://'+env.host_string+'\:8080')


I am trying to get the 'host_string' environment variable to plug in here but 
not sure if the parent function will pass along that information nor if I can 
call it like this. Additionally, I have never used try/except so I don't know 
if this will just try twice and quit. As it is now, it raises URLError and 
bombs out.


--
 ¤¤
¤ kyoboku kazeoshi ¤
 ¤¤
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] URL test function.

2010-10-22 Thread bob gailer

On 10/22/2010 10:54 AM, Jeff Honey wrote:

I am trying to create a function to plug into a restart script I'm creating. I 
can't seem to successfully loop through making an http connection, if it fails 
to retry, if it succeeds, to end and continue with its parent function.

I'm  using the Fabric project's module and including my functions in fabfile.py.

the most rudimentary I've got right now is this:



def is_ready():
  with settings(
   warn_only=True
  ):
   try:
urllib2.urlopen('http://'+env.host_string+'\:8080')
   except urllib2.URLError:
time.sleep(10)
urllib2.urlopen('http://'+env.host_string+'\:8080')


I am trying to get the 'host_string' environment variable to plug in here but 
not sure if the parent function will pass along that information nor if I can 
call it like this.


I don't understand this part. Please clarify or show us the parent function.

Additionally, I have never used try/except so I don't know if this will just 
try twice and quit. As it is now, it raises URLError and bombs out.
Whenever you want to repeat something you need either a loop or 
recursion. A loop is appropriate here.


  while True:
   try:
urllib2.urlopen('http://'+env.host_string+'\:8080')
   except urllib2.URLError:
time.sleep(10)
   else:
break


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] URL test function.

2010-10-22 Thread M. George Hansen
> def is_ready():
>
>  with settings(
>
>  warn_only=True
>
>  ):
>
>  try:
>
>   urllib2.urlopen('http://'+env.host_string+'\:8080')
>
>  except urllib2.URLError:
>
>   time.sleep(10)
>
>   urllib2.urlopen('http://'+env.host_string+'\:8080')
>
> I am trying to get the 'host_string' environment variable to plug in here but 
> not sure if the parent function will pass along that information nor if I can 
> call it like this. Additionally, I have never used try/except so I don't know 
> if this will just try twice and quit. As it is now, it raises URLError and 
> bombs out.

Your try..except block does execute the urlopen function twice
(provided the first time fails). The problem is that if the second
attempt also fails and raises an exception within the except clause
there is no handler for the exception and it will probably stop
execution.

I assume that the "settings" context manager may have some means of
turning exceptions into warnings, hence the "warn_only=True" argument,
but for some reason isn't handling URLError exceptions.

You could use nested try..except clauses like so:

def is_ready():
with settings(warn_only=True):
try:
urllib2.urlopen('http://'+env.host_string+'\:8080')
except urllib2.URLError:
time.sleep(10)
try:
urllib2.urlopen('http://'+env.host_string+'\:8080')
except urllib2.URLError:
pass # Or log a warning message, etc.

But this is rather ugly syntax. Instead, I'd suggest using a while loop:

def is_ready():
max_tries = 2
try_n = 0
with settings(warn_only=True):
while(True):
try_n += 1
try:
urllib2.urlopen('http://'+env.host_string+'\:8080')
except urllib2.URLError:
if (try_n < max_tries):
# We'll wait and try again...
time.sleep(10)
else:
# Maximum number of tries exceeded! Print a
warning message and break
# out of the loop
break
else:
# It worked! So get out of the while loop
break

This is much more explicit and will allow you to easily change the
maximum number of tries you will allow.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable"mean?

2010-10-22 Thread Alan Gauld


"Richard D. Moores"  wrote


   return ("%%.%sf" % n) % floatt

which works fine, but a question remains: n is an integer. Why the 
's'

in '%sf'?


Its arbitrary. You could use %d just as easily.
%s will put the numner into the string, so will %d.
%d is probably a bit more picky about what it inserts - so might
actually be a better choice in this case since

float2n(1.234567, 3.5)

Doesn't work as you might hope... but changing it to use %d might - 
depending

on your definition of better! And what you might hope! :-)

OTOH %s handles this better:

float2n(1.234567, '3')

maybe...

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem Passing VARs to Python from PHP & capturing return string

2010-10-22 Thread Roy Hinkelman
My script doesn't want to recognize the variables from the exec() command in
PHP. Plus, it won't capture the results of the script.

This Python script works in IDLE, and I've got some testing code in there.

One Known Unsolved Issue:
I put Python in C:\Program Files\Python26\python.exe and have tried
$command = "C:\Program Files\Python26\python.exe include/weatherFeed.py -c
$city -s $state";
to no avail.

I added .py to Windows IIS Web Service Extensions and to the Application
Configuration.

Any help appreciated.

[code]

#!C:\Program Files\Python26\python.exe -u
# Current weather feed
# # Weather page sources: http://www.weather.gov/
# Capture relevant data, strip unusable stuff out, fix URLs, display in our
HTML page

# import program modules
import mechanize, re, urllib2, sys # 'standard' set
from BeautifulSoup import BeautifulSoup as B_S

query = 'Chicago, IL' #test to make sure script works!
city = 'Establish'
state = 'Variables'
count = 0
for ea in sys.argv:
if ea == '-c':
city = sys.argv[count+1]
elif ea == '-s':
state = sys.argv[count+1]
count+=1
cityState = city + ', ' + state

_URL = "http://www.weather.gov/";
#_URL = "
http://forecast.weather.gov/MapClick.php?CityName=Novato&state=CA&site=MTR&lat=38.1032&lon=-122.63
"

br=mechanize.Browser()
br.open( _URL )
br.select_form( nr=1 ) #assuming form is 2nd form on page
br['inputstring'] = query
html = br.submit()

_soup = B_S(html)

# finding the correct table
_step1 = _soup.findAll('table', limit=7)[6]
col = _step1.findAll('td')
_thumb = 'Forecast for ' + query + '' +
str(sys.argv) + '' + str(col[0]) + str(col[1]) +
''
_thumb = _thumb.replace( '11%','50%' )
_thumb = _thumb.replace( '/images/', 'images/weather/' )

#write to txt file TEST
_temp = 'D:\\Inetpub\\AtoZ\\hometown\\include\\weatherFeed_TEMP.txt'
temp = open( _temp, 'w' )
temp.write( _thumb )
temp.close()

#print _thumb

[/code]

And my PHP:

[code]

Python Weather Feed for ' . $city . ', ' . $state .
'';

  ob_start();
  $command = "include/weatherFeed.py -c " . $city . "-s " . $state;
  exec($command);
  $content=ob_get_contents();
  ob_end_clean();

  echo 'Content: ' . $content . '';
  echo 'Result: ' . $result . '';
  echo 'Data: ' . $data . '';
  include('include\weatherFeed_TEMP.txt')
   ?>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem Passing VARs to Python from PHP & capturing return string

2010-10-22 Thread bob gailer

On 10/22/2010 2:52 PM, Roy Hinkelman wrote:


My script doesn't want to recognize the variables from the exec() 
command in PHP. Plus, it won't capture the results of the script.




This is a pretty vague description of the problem. Please provide 
explicit details.



This Python script works in IDLE, and I've got some testing code in there.

One Known Unsolved Issue:
I put Python in C:\Program Files\Python26\python.exe and have tried
$command = "C:\Program Files\Python26\python.exe 
include/weatherFeed.py -c $city -s $state";

to no avail.

The full path to Python must be in quotes (due to the space in the 
path). I don't know enough Perl to tell you how to do this.


In Python I would:
command = '"C:\Program Files\Python26\python.exe" include/weatherFeed.py 
-c %s -s %s' % (city, state)


[snip]


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable"mean?

2010-10-22 Thread Richard D. Moores
On Fri, Oct 22, 2010 at 11:27, Alan Gauld  wrote:
>
> "Richard D. Moores"  wrote
>
>>   return ("%%.%sf" % n) % floatt
>>
>> which works fine, but a question remains: n is an integer. Why the 's'
>> in '%sf'?
>
> Its arbitrary. You could use %d just as easily.
> %s will put the numner into the string, so will %d.
> %d is probably a bit more picky about what it inserts - so might
> actually be a better choice in this case since
>
> float2n(1.234567, 3.5)
>
> Doesn't work as you might hope... but changing it to use %d might -
> depending
> on your definition of better! And what you might hope! :-)
>
> OTOH %s handles this better:
>
> float2n(1.234567, '3')

If I use n = 2.5 and replace %s with %d,

my function is

def float2n_decimals(floatt, n):
"""
Given a float (floatt), return floatt to n decimal places.

E.g., with n = 2, 81.34567 -> 81.35
"""
return ("%%.%df" % n) % floatt

This works (the d converts the 2.5 to an int, 2), but I get a
deprecation warning: "DeprecationWarning: integer argument expected,
got float
  rate = rate1 = round(float(rate2),n)"

Of course, n = 2.5 makes no sense in my script.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem Passing VARs to Python from PHP & capturing return string

2010-10-22 Thread Roy Hinkelman
My script doesn't want to recognize the variables from the exec() command in
PHP. Plus, it won't capture the results of the script.

This Python script works in IDLE, and I've got some testing code in there.

One Known Unsolved Issue:
I put Python in C:\Program Files\Python26\python.exe and have tried
$command = "C:\Program Files\Python26\python.exe include/weatherFeed.py -c
$city -s $state";
to no avail.

I added .py to Windows IIS Web Service Extensions and to the Application
Configuration.

Any help appreciated.

[code]

#!C:\Program Files\Python26\python.exe -u
# Current weather feed
# # Weather page sources: http://www.weather.gov/
# Capture relevant data, strip unusable stuff out, fix URLs, display in our
HTML page

# import program modules
import mechanize, re, urllib2, sys # 'standard' set
from BeautifulSoup import BeautifulSoup as B_S

query = 'Chicago, IL' #test to make sure script works!
city = 'Establish'
state = 'Variables'
count = 0
for ea in sys.argv:
if ea == '-c':
city = sys.argv[count+1]
elif ea == '-s':
state = sys.argv[count+1]
count+=1
cityState = city + ', ' + state

_URL = "http://www.weather.gov/";
#_URL =
"http://forecast.weather.gov/MapClick.php?CityName=Novato&state=CA&site=MTR&;
lat=38.1032&lon=-122.63"

br=mechanize.Browser()
br.open( _URL )
br.select_form( nr=1 ) #assuming form is 2nd form on page
br['inputstring'] = query
html = br.submit()

_soup = B_S(html)

# finding the correct table
_step1 = _soup.findAll('table', limit=7)[6]
col = _step1.findAll('td')
_thumb = 'Forecast for ' + query + '' +
str(sys.argv) + '' + str(col[0]) + str(col[1]) +
''
_thumb = _thumb.replace( '11%','50%' )
_thumb = _thumb.replace( '/images/', 'images/weather/' )

#write to txt file TEST
_temp = 'D:\\Inetpub\\AtoZ\\hometown\\include\\weatherFeed_TEMP.txt'
temp = open( _temp, 'w' )
temp.write( _thumb )
temp.close()

#print _thumb

[/code]

And my PHP:

[code]

Python Weather Feed for ' . $city . ', ' . $state .
'';

  ob_start();
  $command = "include/weatherFeed.py -c " . $city . "-s " . $state;
  exec($command);
  $content=ob_get_contents();
  ob_end_clean();
  
  echo 'Content: ' . $content . '';
  echo 'Result: ' . $result . '';
  echo 'Data: ' . $data . '';
  include('include\weatherFeed_TEMP.txt')
   ?>

 

 

Roy Hinkelman
Technical Services
Website Development & Management
707-774-7411
  r...@worldtradepress.com

www.WorldTradePress.com (main website)
www.StockMapAgency.com (3700+ Antique & Modern Maps)
www.BestCountryReports.com (country reports for 175 countries)
www.GiantMapArt.com (giant wall maps)
www.WorldTradeRef.com (trade and logistics)
www.GlobalRoadWarrior.com (175-country database) 
www.AtoZMapsOnline.com (worlds largest map database)
  www.AtoZtheUSA.com (extensive state facts
database)

 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Syntax Error Messages

2010-10-22 Thread Terry Green
Am new to Python, and having difficulty with Error Messages

I 'm using Python 3.1

And PyScripter as my editor

 

I want to process a comma delimited file one line at a time and

Interact with the fields within each line.

I found this script when looking at the CVS module and loaded

It into PyScripter, but get: Syntax Error: Invalid Syntax

Cannot figure out why and Googleing for help doesn't help

Any ideas?

 

 

import csv, sys

filename = "some.csv"

reader = csv.reader(open(filename, "rb"))

try:

for row in reader:

print (row)

except csv.Error, e:

sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))

 

 

 

thanks,

 

Terry Green

 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-22 Thread Steven D'Aprano
On Sat, 23 Oct 2010 12:42:50 am Richard D. Moores wrote:

> So I wrote a function:
>
> def float2n_decimals(floatt, n):
> """
> Given a float (floatt), return floatt to n decimal places.
>
> E.g., with n = 2, 81.34567 -> 81.35
> """
> return ("%%.%sf" % n) % floatt
>
> which works fine, 


float2n_decimals(x, 3)

is better written in place as:

"%.*f" % (3, x)

There's no need for a function for something so simple.



> but a question remains: n is an integer. Why the 
> 's' in '%sf'?


Your function might be more clear if you split the formatting into two 
lines:

template = "%%.%sf" % n
return template % floatt

The first line builds a template string from n. Now it becomes clear 
what %s is for: it's to insert the n as a string into the template. %d 
would express the intention of the function better.


By the way, the function docstring is seriously misleading. It describes 
a completely different function:

> Given a float (floatt), return floatt to n decimal places.
>
> E.g., with n = 2, 81.34567 -> 81.35

It does nothing of the sort! What you are describing is the built-in 
function round:

>>> print round(81.34567, 2)
81.35

What your function does is return a string, not a float. Besides, given 
a float, where does n come from? A global variable?

There is a convention for giving examples that you should follow. 
Putting the three of these together, your docstring should say 
something like:

Given a float floatt and an integer n, returns floatt formatted 
as a string to n decimal places.

>>> float2n_decimals(2, 81.34567)
'81.35'



(BTW, I really hate the name "floatt". It makes me think you're 
stuttering.)



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax Error Messages

2010-10-22 Thread Hugo Arts
On Fri, Oct 22, 2010 at 8:49 PM, Terry Green  wrote:
> Am new to Python, and having difficulty with Error Messages
>
> I ‘m using Python 3.1
>
> And PyScripter as my editor
>
>
>
> I want to process a comma delimited file one line at a time and
> Interact with the fields within each line.
> I found this script when looking at the CVS module and loaded
> It into PyScripter, but get: Syntax Error: Invalid Syntax
> Cannot figure out why and Googleing for help doesn’t help
>
> Any ideas?
>
> import csv, sys
>
> filename = "some.csv"
>
> reader = csv.reader(open(filename, "rb"))
>
> try:
>
>     for row in reader:
>
>     print (row)
>
> except csv.Error, e:
>
>     sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
>
>
> thanks,
> Terry Green
>

You should have gotten more information than just that error. The
offending line should also be printed, along with an estimate of where
exactly the error occurred. Please copy-paste *all* information the
traceback gives you, unless it is too long (a good rule of thumb is
"would *I* read all this just to help some stranger out?"). The more
information we have to work with, the better.

In any case, that python code was written for python 2.x, not 3.x. If
you change "except csv.Error, e:" to "except csv.Error as e:" it
should work.

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] URL test function.

2010-10-22 Thread Steven D'Aprano
On Sat, 23 Oct 2010 01:54:47 am Jeff Honey wrote:

> def is_ready():
>  with settings(
>   warn_only=True
>  ):
>   try:
>urllib2.urlopen('http://'+env.host_string+'\:8080')
>   except urllib2.URLError:
>time.sleep(10)
>urllib2.urlopen('http://'+env.host_string+'\:8080')

That will only try twice, then give up with an exception.


> I am trying to get the 'host_string' environment variable to plug in
> here but not sure if the parent function will pass along that
> information nor if I can call it like this.

Have you tried it to see what happens?


> Additionally, I have 
> never used try/except so I don't know if this will just try twice and
> quit. As it is now, it raises URLError and bombs out.

What does the error say?


I would try something like this:

def urlopen_retry(url, maxretries=10, time_to_wait=10):
"""Call urlopen on a url. If the call fails, try again up to a
maximum of maxretries attempts, or until it succeeds. Delay 
between attempts by time_to_wait seconds, increasing each time."""
if maxretries < 1:
return None
for i in range(maxretries):
try:
return urllib2.urlopen(url)
except urllib2.URLError:
# Delay by (e.g.) 10 seconds, then 20, then 30, then ... 
time.sleep(time_to_wait*(i+1))
raise  # re-raise the last exception


and then call it with:

def is_ready():
   url = 'http://' + env.host_string + '\:8080'
   with settings(warn_only=True):
   return urlopen_retry(url)


Hope this helps.

-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem Passing VARs to Python from PHP & capturing return string

2010-10-22 Thread Steven D'Aprano
On Sat, 23 Oct 2010 05:52:06 am Roy Hinkelman wrote:
> My script doesn't want to recognize the variables from the exec()
> command in PHP. Plus, it won't capture the results of the script.

"My script"? What are you talking about? You have at least two -- a PHP 
script and a Python script. If you're having problems with the PHP 
exec() command, that's probably a problem with the PHP script and you 
need to take it up with a PHP list.

> This Python script works in IDLE, and I've got some testing code in
> there.

If it works fine, why are you showing it to us?


> One Known Unsolved Issue:
> I put Python in C:\Program Files\Python26\python.exe and have tried
> $command = "C:\Program Files\Python26\python.exe
> include/weatherFeed.py -c $city -s $state";
> to no avail.

Unfortunately my crystal ball is broken, and I have a court order 
prohibiting me from reading people's minds, so I'm afraid I'm going to 
have to insist that you actually explain *what the problem is* instead 
of expecting us to guess.

What is the unsolved issue? 
What do you expect the above line to do? 
What does it do instead?


> I added .py to Windows IIS Web Service Extensions and to the
> Application Configuration.

How exciting! And what happened then?



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax Error Messages

2010-10-22 Thread Steven D'Aprano
On Sat, 23 Oct 2010 05:49:07 am Terry Green wrote:

> I found this script when looking at the CVS module and loaded
> It into PyScripter, but get: Syntax Error: Invalid Syntax
> Cannot figure out why and Googleing for help doesn't help
>
> Any ideas?

No, no, don't show us the actual error that you got! I LOVE guessing 
games.



Nah, I'm actually lying, I hate guessing games.

Please COPY AND PASTE (do NOT retype, summarise, paraphrase or write out 
from memory) the EXACT error message you get. It will include the line 
causing the syntax error, like this:

>>> print "abc
  File "", line 1
print "abc
 ^
SyntaxError: EOL while scanning string literal


We need to see the entire message, not just a vague description that 
it's a syntax error.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax Error Messages

2010-10-22 Thread David Hutto
What my buddy pal is saying, is that you should start at the
beginning. I first downloaded x version of python to x operating
system, then I tried this tutorial with these explicit
modules/requirements(which I may or not have) then progress to the
smaller aspects, like this won't iterate, or that doesn't coagulate
with this, etc.

After asking a few initially awkwardly ignorant questions, you might
know as much as me...How to use the basic library, with, a few
exceptions in personal taste.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-22 Thread Richard D. Moores
It's great to have you chime in, Steven. I do wish you would stop
pulling your punches, however. ;)

On Fri, Oct 22, 2010 at 17:23, Steven D'Aprano  wrote:
> On Sat, 23 Oct 2010 12:42:50 am Richard D. Moores wrote:
>
>> So I wrote a function:
>>
>> def float2n_decimals(floatt, n):
>>     """
>>     Given a float (floatt), return floatt to n decimal places.
>>
>>     E.g., with n = 2, 81.34567 -> 81.35
>>     """
>>     return ("%%.%sf" % n) % floatt
>>
>> which works fine,
>
>
> float2n_decimals(x, 3)
>
> is better written in place as:
>
> "%.*f" % (3, x)
>
> There's no need for a function for something so simple.

Yes, but I needed one for ("%%.%sf" % n) % floatt .

>> but a question remains: n is an integer. Why the
>> 's' in '%sf'?
>
> Your function might be more clear if you split the formatting into two
> lines:
>
> template = "%%.%sf" % n
> return template % floatt
>
> The first line builds a template string from n. Now it becomes clear
> what %s is for: it's to insert the n as a string into the template. %d
> would express the intention of the function better.
>
OK, I'll do that.
>
> By the way, the function docstring is seriously misleading. It describes
> a completely different function:
>
>>     Given a float (floatt), return floatt to n decimal places.
>>
>>     E.g., with n = 2, 81.34567 -> 81.35
>
> It does nothing of the sort! What you are describing is the built-in
> function round:
>
 print round(81.34567, 2)
> 81.35
>
> What your function does is return a string, not a float.

OK, point well-taken.

> Besides, given
> a float, where does n come from? A global variable?

Yes. See line 5 of . This
version incorporates all your suggestions.

> There is a convention for giving examples that you should follow.
> Putting the three of these together, your docstring should say
> something like:
>
>    Given a float floatt and an integer n, returns floatt formatted
>    as a string to n decimal places.
>
>    >>> float2n_decimals(2, 81.34567)
>    '81.35'

I've never seen that convention, but I'll try to follow it.

>
> (BTW, I really hate the name "floatt". It makes me think you're
> stuttering.)

I'll use "x" instead. Anything you'd like to say about the rest of the script?

Thanks, Steven.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor