Re: [Tutor] opts and try except

2005-11-20 Thread Johan Geldenhuys
Maybe this recipe will help. Here I used and tested the arguments that 
the user must enter before using the module:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440476

Johan

Eric Walker wrote:

>All,
>I have a program now that works just like I want it. Now I want to 
>integerate something to say print usage info when the user puts in the wrong 
>number or type of options. Also print usage say if you type program name and 
>-h or -H. I currently just have functions defined and at the bottom make a 
>function call. Do I need to do like the def main(): and then the if __name__ 
>== "__main__"? I need an example of how to implement this. 
>
>Thanks in advance.
>
>
>python newbie.
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How should I store data ?

2005-11-20 Thread Alan Gauld

>I want to store data in the shape of (for example):
>  First name, Last name, Age, ... few more characteristics.
>  I must  be able to search data by any of this fields. For example, search 
> for age, or name ... etc

For small quantities you can store the data in a list or tuple or 
dictionary.
You can then just write (orPickle) the container to a file.
See my file handling tutorial topic for an example of an address book.

>  Also, I want to put option in main program to change (update), add and 
> remove that data.
>  How do I do that (easiest way, please) ?

If there is a lot of data you should use a database, see the Working with 
Databases
topic for the address book example revisited.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic inheritance?

2005-11-20 Thread Kent Johnson
Jan Eden wrote:
> The situation is this:
> 
> For every object, two string attributes are determined during
> initialization (one being read from a database, the other inherited
> as a superclass attribute). The first contains the site name, the
> second the object type. I'd like to set the template attribute to the
> proper class:
> 
> import Templates
> 
> self.site_name = 'SiteA'
> self.template_type = 'Page'
> 
> self.template = ???
> 
> self.template should refer to Templates.SiteA.Page in this case
> (where SiteA is a module of package Templates, and Page is a class
> within that module). Danny already said that classes can be treated
> just like any other object - but how do I get from a string to a
> class or module name?

Use getattr() to access attributes by name. SiteA is an attribute of Templates 
and Page is an attribute of SiteA so you can get use getattr() twice to get 
what you want:

site = getattr(Templates, self.site_name)
self.template = getattr(site, self.template_type)

> Thanks for all your help, and sorry for my ignorance,

No problem, this list is for beginners!

Kent
-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] need help in how to make my script read arabic lang

2005-11-20 Thread enas khalil
hello ,  i want to know if yu please how can i use python code in tagging arabic text file   my code is as follow :  # -*- coding: cp1256 -*-import codecsfrom nltk.tagger import *from nltk.corpus import brownfrom nltk.tokenizer import WhitespaceTokenizerfrom nltk import *from nltk.tokenreader.tagged import TaggedTokenReader  # Tokenize ten texts from the Brown Corpustrain_tokens = []  text_str = (open('fataha2.txt').read())#codecs.encode(text_str,'cp1256')reader = TaggedTokenReader(SUBTOKENS='WORDS')text_token = reader.read_token(text_str)print text_token['WORDS']  for l in text_token['WORDS']:    train_tokens.append(l)     #Initialise and train a unigram taggermytagger = UnigramTagger(SUBTOKENS='WORDS')  for xx in train_tokens:    cc = reader.read_token(xx['TEXT'])   #!
  print
 cc.keys()    cc['SUBTOKENS']= cc['WORDS']        mytagger.train(cc)    #Once a UnigramTagger has been trained, the tag() method can be used to tag new text: text_token = Token(TEXT="ÇáÍãÏ ááå ÑÈ ÇáÚÇáãíä")WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(text_token)mytagger.tag(text_token)#print 'The first example : Using Unigram Tagger the reseults are : 'printprint text_token     and i  got the following error :     Traceback (most recent call last):  File "I:/examples/unigramgtag1update1.py", line 13, in ?    codecs.encode(text_str,'cp1256')  File "C:\Python24\lib\encodings\cp1256.py", line 18, in encode    return codecs.charmap_encode(input,errors,encoding_map)UnicodeDecodeError: 'ascii' codec can't decode byte 0xc8 in position 0: ordinal not in
 range(128)      please help
		 Yahoo! FareChase - Search multiple travel sites in one click.

 

 ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smtplib alternative???

2005-11-20 Thread Adisegna
Hi Danny,



Yes, when sending an email your mail client will always send the email
to the mail server specified by the MX record in the authoritive domain. Usually the domain specificed after the @
symbol. The problem with smtplib is that I have to specify the mail
server I'm sending email too. What if I wanted to send an email to 3
different people on three different domains hosted by 3 different mail servers? Smtlib prohibits this
functionality. Do you see what I mean now...? 



Thanks for replying...On 11/20/05, Danny Yoo <
[EMAIL PROTECTED]> wrote:
On Sat, 19 Nov 2005, Adisegna wrote:> I found this script to send mail online. It works fine but requires me> to enter an mail server. I'm looking for something else that doesn't> require and SMTP server. Having to specify a mail server prohibits me
> from sending to alternate domains.Hi Adisegna,I've always assumed that emails have to talk with some SMTP server.RFC821 seems to confirm this:

http://www.faqs.org/rfcs/rfc821.htmlso what you're asking, to be able to send mail without an SMTP server, maynot be possible.  There is an 'smtpd' module that comes with Python:

http://www.python.org/doc/lib/module-smtpd.htmlI'm also not sure I understand the reason you're trying to avoid talkingto an outside smtp server.  But again, I'm unfamiliar enough with how theSMTP email protocol really works that perhaps I'm just overlooking
something.-- Arthur DiSegnaNetwork Operations CenterAuthentium, Inc.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic inheritance?

2005-11-20 Thread Jan Eden
Kent Johnson wrote on 20.11.2005:

>Use getattr() to access attributes by name. SiteA is an attribute of Templates 
>and Page is an attribute of SiteA so you can get use getattr() twice to get 
>what 
>you want:
>
>site = getattr(Templates, self.site_name)
>self.template = getattr(site, self.template_type)
>

Thank you! I did not take into account that modules and classes can be treated 
just like data attributes.

- Jan
-- 
Remember: use logout to logout.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Can Phython...

2005-11-20 Thread Merrie



Hello everyone, thank you for having this list. I have a 
couple of starting questions as I learn Python. 
 
My goal is to create something similar to Phaos, a browser 
controlled text base game written in PHP and MySQL. http://www.3eproductions.com/games.php
 
But as Python is easier to learn and I know there is a 
specific DB that is Python friendly this is what I wish to work with.  I 
have also seen a 'module?' that allows you to place Python code into 
HTML. 
 
So a few of my starting questions.
1 - Is what I have described above possible?
2 - What modules or components will I need?
3 - Is there a book or reference tutorial to help me gain 
the knowledge needed?
 
Thank you for your assistance.
Merrie Schonbach
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smtplib alternative???

2005-11-20 Thread Nick Lunt
Hi Adisegna,

Lets say that you are [EMAIL PROTECTED] and you want to send email to
[EMAIL PROTECTED], [EMAIL PROTECTED] and [EMAIL PROTECTED] .

You setup SMTPLib to talk to the MX server for abc.com which all users on
abc.com use to send email.
SMTP connects to that email server and you can send emails to anyone you
like (unless theyre blacklisted).

So by telling python to use [EMAIL PROTECTED] (your ISP's mail server) you
can send email to [EMAIL PROTECTED] (obviously), [EMAIL PROTECTED] (because 
your a member of
abc.com) and [EMAIL PROTECTED] (again cos your a member of abc.com).

However, if you want your emails to be received with a different address, ie
your using the isp abc.com and you want to send an email to [EMAIL PROTECTED] 
and it
to appear to have come from [EMAIL PROTECTED] then you will need to tell
pythons smptlib to connect to the MX server for pinkstuff.com to send the
email, and you'll probably have to be dialled in to pinkstuff.com.

Webmail MX servers differ in that they require authentication so it doesnt
matter which ISP your dialled in from.

Generally smtp servers are only configured to send to or from domains in
which they belong.

Hope that helps,
Nick .


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of
Adisegna
Sent: 20 November 2005 14:26
To: Danny Yoo
Cc: tutor@python.org
Subject: Re: [Tutor] smtplib alternative???


Hi Danny,

Yes, when sending an email your mail client will always send the email to
the mail server specified by the MX record in the authoritive domain.
Usually the domain specificed after the @ symbol. The problem with smtplib
is that I have to specify the mail server I'm sending email too. What if I
wanted to send an email to 3 different people on three different domains
hosted by 3 different mail servers? Smtlib prohibits this functionality. Do
you see what I mean now...?

Thanks for replying...


On 11/20/05, Danny Yoo < [EMAIL PROTECTED]> wrote:


On Sat, 19 Nov 2005, Adisegna wrote:

> I found this script to send mail online. It works fine but requires me
> to enter an mail server. I'm looking for something else that doesn't
> require and SMTP server. Having to specify a mail server prohibits me
> from sending to alternate domains.

Hi Adisegna,

I've always assumed that emails have to talk with some SMTP server.
RFC821 seems to confirm this:

 http://www.faqs.org/rfcs/rfc821.html

so what you're asking, to be able to send mail without an SMTP server, may
not be possible.  There is an 'smtpd' module that comes with Python:

 http://www.python.org/doc/lib/module-smtpd.html

I'm also not sure I understand the reason you're trying to avoid talking
to an outside smtp server.  But again, I'm unfamiliar enough with how the
SMTP email protocol really works that perhaps I'm just overlooking
something.





--
Arthur DiSegna
Network Operations Center
Authentium, Inc.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic inheritance?

2005-11-20 Thread Alan Gauld
> import Templates
>
> self.site_name = 'SiteA'
> self.template_type = 'Page'
>
> self.template = ???

How about a dictionary holding references to the classes against their 
names?
The dictionary could be a class attribute of the top level superclass or a 
module
level dictionary. It should be updated ideally by the class definition or 
more
simply by hard coding a registration fuinction.

Something like

class Root:
   subclasses = {'Root': Root}
   @classmethod
   def registerSubclass(name, aClass):
#could check it really is a subclass here...
Root.subclasses[name] = aClass

class Sub(Root):
pass
Root.registerSubclass("Sub",Sub)

Now your code becomes:

 self.site_name = 'SiteA'
 self.template_type = 'Page'

 self.template = Root.subclasses[self.template_name]()  # instance of Page

In fact it could just be a dictionary of templates, it needn't be subclasses
at all, however for the sake of clean polymorphism its probably better
if they are.

HTH

Alan G. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Website monitoring program.

2005-11-20 Thread Adisegna
I guess I should keep the same subject line (above)
from now on since my last few posts (urllib, smtplib) are about the
same program.  

My question is how to use a loop to go through a tuple of URLs. Please feel free to suggest an easier way to do the same thing.

Here is my rudimentary program so far.

---
import urllib, smtplib

urls = ("http://website0.net/imalive.asp",
  "http://website1.net/imalive.asp",
  "http://website2.net/imalive.asp",
  "http://website3.net/imalive.asp",
  "http://website4.net/imalive.asp",)
  
# I added these just to make the loop work and be more readable

qa = urls[0]
n4k = urls[1]
metro = urls[4]

for i in urls:   # <-- this obviously doens't work because I have to specify a value "metro" below

    for site in urllib.urlopen(metro):  #<- What can I use here to loop through the 'urls' tupple

    good = "400 Bad Request"
    bad = "Invalid Hostname"
    smtpserver = 'mail.authentium.com'
    RECIPIENTS = ['[EMAIL PROTECTED]']
    SENDER = '[EMAIL PROTECTED]'
    mssg = site

    if good in site:
    print "OK"
    text_file = open("test.log", "a")
    text_file.writelines('sometext : ')
    text_file.writelines(site)
    text_file.writelines("\n")
    text_file.close()

    elif bad in site:
  print "NOT OK"
  text_file = open("test.log", "a")
  text_file.writelines('metro-ams : ')
  text_file.writelines(site)
  text_file.writelines("\n")
  text_file.close()
  session = smtplib.SMTP(smtpserver)
 
smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
  if smtpresult:
   
errstr = ""
   
for recip in smtpresult.keys():
   
errstr = """Could not delivery mail to: %s

   
Server said: %s 
    %s

   
%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
   
raise smtplib.SMTPException, errstr

    
    else:
  text_file = open("test.log", "a")
 
text_file.writelines('Another type of error occurred : ')

  text_file.writelines(site)

  text_file.writelines("\n")

  text_file.close()
    
---

Thanks 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can Phython...

2005-11-20 Thread Alan Gauld
> My goal is to create a browser controlled text base game ...

>So a few of my starting questions.
> 1 - Is what I have described above possible?

Yes

> 2 - What modules or components will I need?

That depends onthe gane to some extent, I don;t know it.
But for HTML/Web apps you need to decide if the basic cgi module is
good enough or whether you want to use a more sophisticated framework
(like CherryPy say)

Also you will need the database driver for your database (Python can
support a wide variety of databases, I'm not sure which you have in mind)

Then you might find uses for the random module, or maybe the math one.
It just depends on how sophisticated the game is.

The best thing is
a) get an understanding of Python itself
b) try producing a console based version of your game
c) port it to the web.

At each stage when you find a specific problem send us a mail message
with the question, any code that reproduces it and any error messages.

> 3 - Is there a book or reference tutorial to help me gain the knowledge 
> needed?

Check out the Python web site. \Depending on whether you have programmed
in any other language or not will deternine which tutoriakl suits you best.
If you are a complete beginner you might find mine useful(see .sig), but
there are others if you dont like my style. If you have programmed before
then try the official tutorial, its pretty good.

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] need a tutorial in tokens ,different types

2005-11-20 Thread enas khalil
hello all  could any one suggest me tutorials in different tokenizations and clear describtion of how can i use token type and assign diff attributes to tokens  ,also good tutorials in diff data types in python   thanks every body  enas
		 Yahoo! FareChase - Search multiple travel sites in one click.

 

 ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Website monitoring program.

2005-11-20 Thread Kent Johnson
Adisegna wrote:
> 
> I guess I should keep the same subject line (above) from now on since my 
> last few posts (urllib, smtplib) are about the same program. 

My preference is to start a new subject for each new question.
> 
> My question is how to use a loop to go through a tuple of URLs. Please 
> feel free to suggest an easier way to do the same thing.
> 
> Here is my rudimentary program so far.
> 
> ---
> import urllib, smtplib
> 
> urls = ("http://website0.net/imalive.asp";,
>   "http://website1.net/imalive.asp";,
>   "http://website2.net/imalive.asp";,
>   "http://website3.net/imalive.asp";,
>   "http://website4.net/imalive.asp"; 
> ,)
>  
> # I added these just to make the loop work and be more readable
> 
> qa = urls[0]
> n4k = urls[1]
> metro = urls[4]
> 
> for i in urls:   # <-- this obviously doens't work because I have to 
> specify a value "metro" below
> 
> for site in urllib.urlopen(metro):  #<- What can I use here to 
> loop through the 'urls' tupple

I'm not sure I understand but I think what you want is

for url in urls:  # url will take on each value from urls
  site = urllib.urlopen(url).read()  # site will have the entire text from the 
page you opened

You might also be interested in EDDIE which seems to support building this kind 
of monitoring app fairly easily.
http://eddie-tool.net/doc/manual.html

Kent

> 
> good = "400 Bad Request"
> bad = "Invalid Hostname"
> smtpserver = 'mail.authentium.com '
> RECIPIENTS = ['[EMAIL PROTECTED] ']
> SENDER = '[EMAIL PROTECTED] 
> '
> mssg = site
> 
> if good in site:
> print "OK"
> text_file = open("test.log", "a")
> text_file.writelines('sometext : ')
> text_file.writelines(site)
> text_file.writelines("\n")
> text_file.close()
> 
> elif bad in site:
>   print "NOT OK"
>   text_file = open("test.log", "a")
>   text_file.writelines('metro-ams : ')
>   text_file.writelines(site)
>   text_file.writelines("\n")
>   text_file.close()
>   session = smtplib.SMTP(smtpserver)
>   smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
>   if smtpresult:
> errstr = ""
> for recip in smtpresult.keys():
> errstr = """Could not delivery mail to: %s
> 
> Server said: %s
> %s
> 
> %s""" % (recip, smtpresult[recip][0], 
> smtpresult[recip][1], errstr)
> raise smtplib.SMTPException, errstr
> 
>
> else:
>   text_file = open("test.log", "a")
>   text_file.writelines('Another type of error occurred : ')
>   text_file.writelines(site)
>   text_file.writelines("\n")
>   text_file.close()
>
> ---
> 
> Thanks
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] UnboundLocal Error

2005-11-20 Thread Jason Massey
I've got a problem with scope that I can't say I've ever encountered.

The comments explain the situation pretty well.


import player

class Game:
def __init__(self,screen):
self.market = Market.Market()
self.countries = pickle.load(open("sup.coords",'r'))
self.deck = deck.Deck()
self.players = {}
print player.Player('foo') # this line works fine, prints 
out a
player instance
self.setupPlayers()   # want to set up all the 
players so...

self.screen = screen

def setupPlayers(self):
print player.Player('bar') # this line fails, with the unbound 
local error
for super_power in SUPER_POWERS:
self.players[super_power] = player.Player(super_power)
for position,card in enumerate(self.deck):
if card.location in SUPER_POWERS[super_power]:


Ouput and traceback:


Traceback (most recent call last):
  File "C:\Python24\sup.py", line 199, in ?
game = Game(screen)
  File "C:\Python24\sup.py", line 51, in __init__
self.setupPlayers()
  File "C:\Python24\sup.py", line 56, in setupPlayers
print player.Player('bar')
UnboundLocalError: local variable 'player' referenced before assignment


Something blindingly obvious probably, but I'm at a loss.

thanks,

jason
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Random Numbers

2005-11-20 Thread Merrie



Ok first thing I need a direction on is random number 
generation, I looked through the Python manual and I must be missing it. 

 
What Im looking for, needing is a random generation 1 
through 10 + modifier, example
like rolling a 1d10 +1
 
Not sure what syntex to use.
 
Thanks!
Merrie
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Random Numbers

2005-11-20 Thread John Fouhy
On 21/11/05, Merrie <[EMAIL PROTECTED]> wrote:
> Ok first thing I need a direction on is random number generation, I looked
> through the Python manual and I must be missing it.
>
> What Im looking for, needing is a random generation 1 through 10 + modifier,
> example  like rolling a 1d10 +1

Hi Merrie,

The manual section you want is the random module:
http://docs.python.org/lib/module-random.html

In particular, the randrange() function will help you out here. 
random.randrange() is equivalent to generating a list using the
builtin function range(), and then choosing one element from that list
at random.

For example, I can generate some random numbers in the range 0..9 like this:

>>> import random
>>> for i in range(10):
...  print random.randrange(10)
...
8
2
0
9
7
5
8
0
7
9
>>>

HTH!

--
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Random Numbers

2005-11-20 Thread Hugo González Monteverde
Hi,

Take a look at the random module, function randint:

 >>> import random
 >>> random.randint(1, 10)
7
 >>> random.randint(1, 10)
9
 >>> random.randint(1, 10)
1
 >>> random.randint(1, 10)
8
 >>> random.randint(1, 10)
7
 >>> random.randint(1, 10)
9
 >>> random.randint(1, 10)
1
 >>> random.randint(1, 10)
1
 >>> random.randint(1, 10)
7
 >>> random.randint(1, 10)
2
 >>> random.randint(1, 10)
9
 >>>
Hugo

Merrie wrote:
> Ok first thing I need a direction on is random number generation, I 
> looked through the Python manual and I must be missing it.
>  
> What Im looking for, needing is a random generation 1 through 10 + 
> modifier, example
> like rolling a 1d10 +1
>  
> Not sure what syntex to use.
>  
> Thanks!
> Merrie
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Website monitoring program.

2005-11-20 Thread Liam Clarke-Hutchinson
Ah, this kind of programme would be so much simpler if Last-Modified and
ETag were commonly used *sigh*. Unfortunately, advertising kinda killed
it...

I recommend www.watchthispage.com if you just need a quick update without
killing your own bandwidth.

Regards,

Liam Clarke-Hutchinson


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Kent Johnson
Sent: Monday, 21 November 2005 10:25 a.m.
Cc: tutor@python.org
Subject: Re: [Tutor] Website monitoring program.


Adisegna wrote:
> 
> I guess I should keep the same subject line (above) from now on since 
> my
> last few posts (urllib, smtplib) are about the same program. 

My preference is to start a new subject for each new question.
> 
> My question is how to use a loop to go through a tuple of URLs. Please
> feel free to suggest an easier way to do the same thing.
> 
> Here is my rudimentary program so far.
> 
> ---
> import urllib, smtplib
> 
> urls = ("http://website0.net/imalive.asp";,
>   "http://website1.net/imalive.asp";,
>   "http://website2.net/imalive.asp";,
>   "http://website3.net/imalive.asp";,
>   "http://website4.net/imalive.asp";
> ,)
>  
> # I added these just to make the loop work and be more readable
> 
> qa = urls[0]
> n4k = urls[1]
> metro = urls[4]
> 
> for i in urls:   # <-- this obviously doens't work because I have to 
> specify a value "metro" below
> 
> for site in urllib.urlopen(metro):  #<- What can I use here to
> loop through the 'urls' tupple

I'm not sure I understand but I think what you want is

for url in urls:  # url will take on each value from urls
  site = urllib.urlopen(url).read()  # site will have the entire text from
the page you opened

You might also be interested in EDDIE which seems to support building this
kind of monitoring app fairly easily. http://eddie-tool.net/doc/manual.html

Kent

> 
> good = "400 Bad Request"
> bad = "Invalid Hostname"
> smtpserver = 'mail.authentium.com '
> RECIPIENTS = ['[EMAIL PROTECTED] ']
> SENDER = '[EMAIL PROTECTED]
> '
> mssg = site
> 
> if good in site:
> print "OK"
> text_file = open("test.log", "a")
> text_file.writelines('sometext : ')
> text_file.writelines(site)
> text_file.writelines("\n")
> text_file.close()
> 
> elif bad in site:
>   print "NOT OK"
>   text_file = open("test.log", "a")
>   text_file.writelines('metro-ams : ')
>   text_file.writelines(site)
>   text_file.writelines("\n")
>   text_file.close()
>   session = smtplib.SMTP(smtpserver)
>   smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
>   if smtpresult:
> errstr = ""
> for recip in smtpresult.keys():
> errstr = """Could not delivery mail to: %s
> 
> Server said: %s
> %s
> 
> %s""" % (recip, smtpresult[recip][0],
> smtpresult[recip][1], errstr)
> raise smtplib.SMTPException, errstr
> 
>
> else:
>   text_file = open("test.log", "a")
>   text_file.writelines('Another type of error occurred : ')
>   text_file.writelines(site)
>   text_file.writelines("\n")
>   text_file.close()
>
> --
> -
> 
> Thanks
> 
> 
> --
> --
> 
> ___
> Tutor maillist  -  Tutor@python.org 
> http://mail.python.org/mailman/listinfo/tutor

-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this messa

Re: [Tutor] UnboundLocal Error

2005-11-20 Thread Kent Johnson
Jason Massey wrote:
> I've got a problem with scope that I can't say I've ever encountered.

My guess is that later in setupPlayers() you assign to a variable 'player'. 
When you do this, every reference to the variable in the function is a local 
reference. For example:

 >>> x=1
 >>> def bump():
 ...   print x
 ...   x = x + 1
 ...
 >>> bump()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in bump
UnboundLocalError: local variable 'x' referenced before assignment

Because x is assigned in bump(), the x in print x is a local variable and it is 
not bound a the time of use.

Kent

> 
> The comments explain the situation pretty well.
> 
> 
> import player
> 
> class Game:
>   def __init__(self,screen):
>   self.market = Market.Market()
>   self.countries = pickle.load(open("sup.coords",'r'))
>   self.deck = deck.Deck()
>   self.players = {}
>   print player.Player('foo') # this line works fine, prints 
> out a
> player instance
>   self.setupPlayers()   # want to set up all the 
> players so...
>   
>   self.screen = screen
>   
>   def setupPlayers(self):
>   print player.Player('bar') # this line fails, with the unbound 
> local error
>   for super_power in SUPER_POWERS:
>   self.players[super_power] = player.Player(super_power)
>   for position,card in enumerate(self.deck):
>   if card.location in SUPER_POWERS[super_power]:
>   
> 
> Ouput and traceback:
> 
> 
> Traceback (most recent call last):
>   File "C:\Python24\sup.py", line 199, in ?
> game = Game(screen)
>   File "C:\Python24\sup.py", line 51, in __init__
> self.setupPlayers()
>   File "C:\Python24\sup.py", line 56, in setupPlayers
> print player.Player('bar')
> UnboundLocalError: local variable 'player' referenced before assignment
> 
> 
> Something blindingly obvious probably, but I'm at a loss.
> 
> thanks,
> 
> jason
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need a tutorial in tokens ,different types

2005-11-20 Thread Alan Gauld
>  could any one suggest me tutorials in different tokenizations and 
> clear describtion of how can i use token type and assign diff attributes 
> to tokens  

What kind of tokens? Are we talking l;exical tokens in a parser 
or security tokens or what?

> also good tutorials in diff data types in python 

The official documentaton explains most of it.

You can try the Raw Materials topic in my tutorial if you like.

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] UnboundLocal Error

2005-11-20 Thread Alan Gauld
> The comments explain the situation pretty well.

Unfortunately the formatting has been lost so I'm not totally
clear whats going on.

BUT it does look like you have posted the class definition
but not the driver code that actually causes the error.

> class Game:
> def __init__(self,screen):
> print player.Player('foo') # this line works fine, prints out a
> self.setupPlayers()   # want to set up all the players so...
>self.screen = screen

>def setupPlayers(self):
> print player.Player('bar') # this line fails, with the unbound local error

> Ouput and traceback:
>
> 
> Traceback (most recent call last):
>   File "C:\Python24\sup.py", line 199, in ?
> game = Game(screen)

where is this line? its nowhere above?
is it in a separate file? or lower in the same file?
It looks like its the same file but much later on.

>  File "C:\Python24\sup.py", line 56, in setupPlayers
>print player.Player('bar')
> UnboundLocalError: local variable 'player' referenced before assignment

which looks like the import hasn't worked, except the previous print
statement did work. That seems odd I agree.

> Something blindingly obvious probably, but I'm at a loss.

Me too, but I'd start by checking I don;t have a conflict of variable names.
you don't for example del(player) at some point?

strange,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smtplib alternative???

2005-11-20 Thread Liam Clarke-Hutchinson


>Generally smtp servers are only configured to send to or from domains in
which they belong.

Hmmm... several ISP's I've used allow any value in the "From" header field.
I'd also like to mention that while many SMTP servers will only allow a
valid domain address in the From field, there is usually no such restriction
on what you stick in the "Reply-To" header field.

(I'd like to point out that using fake "From" addresses gets boring after
about the fifth prank email from [EMAIL PROTECTED] to your
friends...)

The ability to change a "From" field is very useful for automated emailing.
(By which I don't mean spam, but those emails from [EMAIL PROTECTED])

Regards, 

Liam Clarke


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of
Adisegna
Sent: 20 November 2005 14:26
To: Danny Yoo
Cc: tutor@python.org
Subject: Re: [Tutor] smtplib alternative???


Hi Danny,

Yes, when sending an email your mail client will always send the email to
the mail server specified by the MX record in the authoritive domain.
Usually the domain specificed after the @ symbol. The problem with smtplib
is that I have to specify the mail server I'm sending email too. What if I
wanted to send an email to 3 different people on three different domains
hosted by 3 different mail servers? Smtlib prohibits this functionality. Do
you see what I mean now...?

Thanks for replying...


On 11/20/05, Danny Yoo < [EMAIL PROTECTED]> wrote:


On Sat, 19 Nov 2005, Adisegna wrote:

> I found this script to send mail online. It works fine but requires me 
> to enter an mail server. I'm looking for something else that doesn't 
> require and SMTP server. Having to specify a mail server prohibits me 
> from sending to alternate domains.

Hi Adisegna,

I've always assumed that emails have to talk with some SMTP server. RFC821
seems to confirm this:

 http://www.faqs.org/rfcs/rfc821.html

so what you're asking, to be able to send mail without an SMTP server, may
not be possible.  There is an 'smtpd' module that comes with Python:

 http://www.python.org/doc/lib/module-smtpd.html

I'm also not sure I understand the reason you're trying to avoid talking to
an outside smtp server.  But again, I'm unfamiliar enough with how the SMTP
email protocol really works that perhaps I'm just overlooking something.





--
Arthur DiSegna
Network Operations Center
Authentium, Inc.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

A new monthly electronic newsletter covering all aspects of MED's work is now 
available.  Subscribers can choose to receive news from any or all of seven 
categories, free of charge: Growth and Innovation, Strategic Directions, Energy 
and Resources, Business News, ICT, Consumer Issues and Tourism.  See 
http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government 
services

Any opinions expressed in this message are not necessarily those of the 
Ministry of Economic Development. This message and any files transmitted with 
it are confidential and solely for the use of the intended recipient. If you 
are not the intended recipient or the person responsible for delivery to the 
intended recipient, be advised that you have received this message in error and 
that any use is strictly prohibited. Please contact the sender and delete the 
message and any attachment from your computer.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smtplib alternative???

2005-11-20 Thread Python
On Sun, 2005-11-20 at 09:26 -0500, Adisegna wrote:
> Hi Danny,
> 
> Yes, when sending an email your mail client will always send the email
> to the mail server specified by the MX record in the authoritive
> domain. Usually the domain specificed after the @ symbol. The problem
> with smtplib is that I have to specify the mail server I'm sending
> email too. 
No.  It is asking you to specify the server that the email will be
coming from.

Your email to the list went through the gmail server.  If you look at
the email headers, you will see entries from the mail servers that
handled the message.  Your local smtp server will handle the MX lookups.

Simply specify the mail server provided by the ISP that provides your
Internet connection, if you do not run a mail server yourself.

> What if I wanted to send an email to 3 different people on three
> different domains hosted by 3 different mail servers? Smtlib prohibits
> this functionality. Do you see what I mean now...? 
> 
> Thanks for replying...

If you have a conventional email program (e.g. Thunderbird, Evolution,
Outlook Express) then the smtp server listed in that config should work
with your Python script.

-- 
Lloyd Kvam
Venix Corp

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Website monitoring program.

2005-11-20 Thread Adisegna
How do I get the counting loop to come
back around? It makes one pass fine. How do I get it to come back up
and go through again?  

Thanks

---
import urllib, smtplib

urls = ("http://website0.net/imalive.asp",
  "http://website1.net/imalive.asp",
  "http://website2.net/imalive.asp",
  "http://website3.net/imalive.asp",
  "http://website4.net/imalive.asp",)
  count = 0
for i in urls:  
    web = urls[count]
    
    for site in urllib.urlopen(web):

    good = "400 Bad Request"
    bad = "Invalid Hostname"
    smtpserver = 'mail.authentium.com'
    RECIPIENTS = ['[EMAIL PROTECTED]']
    SENDER = '[EMAIL PROTECTED]'
    mssg = site

    if good in site:
    print "OK"
    text_file = open("test.log", "a")
    text_file.writelines('sometext : ')
    text_file.writelines(site)
    text_file.writelines("\n")
    text_file.close()

    elif bad in site:
  print "NOT OK"
  text_file = open("test.log", "a")
  text_file.writelines('metro-ams : ')
  text_file.writelines(site)
  text_file.writelines("\n")
  text_file.close()
  session = smtplib.SMTP(smtpserver)
 
smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
  if smtpresult:   
errstr = ""
   
for recip in smtpresult.keys():
   
errstr = """Could not delivery mail to: %s

   
Server said: %s 
    %s

   
%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
   
raise smtplib.SMTPException, errstr

    
    else:
  text_file = open("test.log", "a")
 
text_file.writelines('Another type of error occurred : ')

  text_file.writelines(site)

  text_file.writelines("\n")

  text_file.close()print web
count +=1
print count
---

Thanks 


-- Arthur DiSegnaNetwork Operations CenterAuthentium, Inc.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Website monitoring program.

2005-11-20 Thread Kent Johnson
Adisegna wrote:
> How do I get the counting loop to come back around? It makes one pass 
> fine. How do I get it to come back up and go through again? 

You have to indent the statement 'count += 1' so it is part of the loop. But 
you misunderstand the for loop - the count variable is not needed at all. Your 
variable 'i' will receive each element of urls, one each time through the loop. 
For a simpler example,

 >>> u = ['a', 'b', 'c']
 >>> for letter in u:
 ...   print letter
 ...
a
b
c

So instead of 
count = 0
for i in urls: 
web = urls[count]

you can write simply
for web in urls:

See the Python tutorial for more examples of for loops:
http://docs.python.org/tut/node6.html#SECTION00620

Kent

> 
> Thanks
> 
> ---
> import urllib, smtplib
> 
> urls = ("http://website0.net/imalive.asp";,
>   "http://website1.net/imalive.asp";,
>   "http://website2.net/imalive.asp";,
>   "http://website3.net/imalive.asp";,
>   "http://website4.net/imalive.asp"; 
> ,)
>  
> count = 0
> for i in urls: 
> web = urls[count]
>
> for site in urllib.urlopen(web):
> 
> good = "400 Bad Request"
> bad = "Invalid Hostname"
> smtpserver = 'mail.authentium.com '
> RECIPIENTS = ['[EMAIL PROTECTED] ']
> SENDER = '[EMAIL PROTECTED] 
> '
> mssg = site
> 
> if good in site:
> print "OK"
> text_file = open("test.log", "a")
> text_file.writelines('sometext : ')
> text_file.writelines(site)
> text_file.writelines("\n")
> text_file.close()
> 
> elif bad in site:
>   print "NOT OK"
>   text_file = open("test.log", "a")
>   text_file.writelines('metro-ams : ')
>   text_file.writelines(site)
>   text_file.writelines("\n")
>   text_file.close()
>   session = smtplib.SMTP(smtpserver)
>   smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
>   if smtpresult:
> errstr = ""
> for recip in smtpresult.keys():
> errstr = """Could not delivery mail to: %s
> 
> Server said: %s
> %s
> 
> %s""" % (recip, smtpresult[recip][0], 
> smtpresult[recip][1], errstr)
> raise smtplib.SMTPException, errstr
> 
>
> else:
>   text_file = open("test.log", "a")
>   text_file.writelines('Another type of error occurred : ')
>   text_file.writelines(site)
>   text_file.writelines("\n")
>   text_file.close()
> print web
> count +=1
> print count
> ---
> 
> Thanks
> 
> 
> -- 
> Arthur DiSegna
> Network Operations Center
> Authentium, Inc.
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trouble with classes - Pypeg again

2005-11-20 Thread ->Terry<-
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


Ok, I've got my peg game roughed out and I'm having
problems.

The error is:

Traceback (most recent call last):
   File "pypeg.py", line 113, in ?
 main()
   File "pypeg.py", line 107, in main
 x.draw_board() # Refresh screen
   File "pypeg.py", line 30, in draw_board
 screen.blit(Peg.peg, (Peg.pegs[i]))  # Blit it.
AttributeError: class Peg has no attribute 'peg'

The new code is at:

http://members.socket.net/~tvbare/pypeg/new_pypeg.py>

I'm confused as to why. The whole OO picture
has my head reeling, but I thought I had some
grasp of the basics. Now I'm not so sure. d:^)

Thanks much,
- -- 
 Terry


"Be who you are and say what you feel, because those
  who mind don't matter and those who matter don't mind."
  -- Dr. Seuss
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.7 (GNU/Linux)

iD8DBQFDgVKHQvSnsfFzkV0RAnlyAJ9snqBt0GOWS7IpimsMkB2xaBqu2gCbBovs
ATTVhm0JbWiz+VfKSxXrGqY=
=oGAu
-END PGP SIGNATURE-

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need a tutorial in tokens ,different types

2005-11-20 Thread Danny Yoo


Taking python-list out of CC yet again.

Enas, please fix your email client setup.  I really don't want to
threaten, but as a power-hungry dictatorial list admin, I have an
responsibility to help maintain a healthy mailing list.

You been warned twice now not to crosspost.  You continue to crosspost the
same question to several mailing lists, not only to comp.lang.python, but
also to NLTK's developer list.

http://sourceforge.net/mailarchive/forum.php?thread_id=9019717&forum_id=959

so I doubt your behavior is accidental now: it looks pretty deliberate to
me.

Enas, please don't push me into the Bad Cop role.  Change your behavior:
you've violating community norms.  If you don't correct yourself, I will
moderate your messsages.  I hate threatening you like this.  Don't make me
follow through with the threat.


On Sun, 20 Nov 2005, Alan Gauld wrote:

> >  could any one suggest me tutorials in different tokenizations and
> > clear describtion of how can i use token type and assign diff
> > attributes to tokens
>
> What kind of tokens? Are we talking lexical tokens in a parser or
> security tokens or what?

Anyway, I think we are talking about the tokens defined by the NLTK
natural language toolkit.  I'm not sure we can do much better than
recommend the tutorials that come with NLTK:

http://nltk.sourceforge.net/lite/doc/
http://nltk.sourceforge.net/tutorial/index.html

They go through several examples of assigning attributes to tokens.  If
you has questions about NLTK, again, Enas may be better off asking on an
NLTK-specific mailing list.  There's one specifically set up for
help:

http://sourceforge.net/forum/forum.php?forum_id=97413


> > also good tutorials in diff data types in python
>
> The official documentaton explains most of it.
>
> You can try the Raw Materials topic in my tutorial if you like.

Those tutorials are here:

http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

They should give enough grounding to understand how NLTK works better.
Again, if you has any questions relating to learning how to program, we're
glad to be of help.

But take some time to learn how to use your email client.  Also, if people
have not recommend it, read through:

http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html
http://www.catb.org/~esr/faqs/smart-questions.html

so that you have a sense of what kind of community norms are expected of
you when you ask for help.  Violating them impovershes the entire
community, which is why I take this so seriously.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] reduce with comprehension

2005-11-20 Thread János Juhász
Hi,

I can't imagine how this could be made with list comprehension.

>>> import operator
>>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
>>> reduce(operator.add, a) # it makes a long list now
([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9])

When I make list comprehension, the list hierarchy is allways the same or
deeper than the original hierarchy. But now it should be reduced with one
level.


>>> [item for item in a] # the deepnes is the same
[([1], [2], [3, 31, 32], [4]), ([5], [6], [7, 71, 72]), ([8], [9])]
>>> [(item, item) for item in a] # it is deeper with one level
>>>


Is it possible to substitute reduce with comprehension anyway ?


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor