Re: [Tutor] Website monitoring program.
Below is a program I found at http://starship.python.net/crew/neale/ (though it does not seem to be there anymore.) It uses a seperate file for the URLs --- Adisegna <[EMAIL PROTECTED]> wrote: > 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. #!/usr/bin/env python """watch.py -- Web site change notification tool Author: Neale Pickett <[EMAIL PROTECTED]> Time-stamp: <2003-01-24 13:52:13 neale> This is something you can run from a cron job to notify you of changes to a web site. You just set up a ~/.watchrc file, and run watcher.py from cron. It mails you when a page has changed. I use this to check for new software releases on sites that just change web pages; my wife uses it to check pages for classes she's in. You'll want a ~/.watchrc that looks something like this: to: [EMAIL PROTECTED] http://www.example.com/path/to/some/page.html The 'to:' line tells watch.py where to send change notification email. You can also specify 'from:' for an address the message should come from (defaults to whatever to: is), and 'host:' for what SMTP server to send the message through (defaults to localhost). When watch.py checks a URL for the first time, it will send you a message (so you know it's working) and write some funny characters after the URL in the .watchrc file. This is normal--watch.py uses these characters to remember what the page looked like the last time it checked. """ import os.path import urllib2 as urllib import sha import smtplib rc = '~/.watchrc' host = 'localhost' fromaddr = None toaddr = None def hash(data): return sha.new(data).hexdigest() def notify(url): msg = """From: URL Watcher <%(from)s> To: %(to)s Subject: %(url)s changed %(url)s has changed! """ % {'from': fromaddr, 'to': toaddr, 'url': url} s = smtplib.SMTP(host) s.sendmail(fromaddr, toaddr, msg) s.quit() fn = os.path.expanduser(rc) f = open(fn) outlines = [] for line in f.xreadlines(): if line[0] == '#': continue line = line.strip() if not line: continue splits = line.split(' ', 1) url = splits[0] if url == 'from:': fromaddr = splits[1] elif url == 'to:': toaddr = splits[1] if not fromaddr: fromaddr = toaddr elif url == 'host:': host = splits[1] else: if (not fromaddr) or (not toaddr): raise ValueError("must set to: before any urls") page = urllib.urlopen(url).read() ph = hash(page) try: h = splits[1] except IndexError: h = None if h != ph: notify(url) line = '%s %s' % (url, ph) outlines.append(line) f.close() f = open(fn, 'w') f.write('\n'.join(outlines) + '\n') f.close() ___ Yahoo! Model Search 2005 - Find the next catwalk superstars - http://uk.news.yahoo.com/hot/model-search/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Lists with just an item
Hi all. In my application I have chosen as data structure a list of dictionaries. Each dictionary has just one key and the corresponding value. structure = [{'field1': lenght1}, {'field2': lenght2}, ] Initially, to obtain the key and the value I used this code, for structure in record_structure: field_name = structure.keys()[0] displacement = structure[field_name] but after some thoughts I arrived to: field_name, displacement = structure.items()[0] which to me seems a lot better. At this point I don't like much that [0] to access a list that I know always contains a single element. Can I improve the code with something better? Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reduce with comprehension
János Juhász said unto the world upon 2005-11-21 01:20: > 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 > Hi János, I think it is. >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) >>> b = [] >>> [b.extend(x) for x in a] [None, None, None] >>> b [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] But don't do that :-) Seems very poor form to me, as the desired operation is a side effect of the creation of the list via the comprehension. If, however, you are just trying to avoid reduce: >>> b=[] >>> for x in a: b.extend(x) >>> b [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] >>> Notice, too, that these ways result in a list of lists, whereas yours provided a tuple of lists. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists with just an item
Negroup - said unto the world upon 2005-11-21 03:26: > Hi all. > In my application I have chosen as data structure a list of > dictionaries. Each dictionary has just one key and the corresponding > value. > > structure = [{'field1': lenght1}, {'field2': lenght2}, ] > > Initially, to obtain the key and the value I used this code, > > for structure in record_structure: > field_name = structure.keys()[0] > displacement = structure[field_name] > > but after some thoughts I arrived to: > field_name, displacement = structure.items()[0] > > which to me seems a lot better. > > At this point I don't like much that [0] to access a list that I know > always contains a single element. Can I improve the code with > something better? > > Thanks! Hi Negroup, why not just make structure a dict: structure = {'field1': lenght1, 'field2': lenght2} What does having a list of dicts all with a single key add but a layer of referencing when you want to access? If you are trying to preserve order and your key examples are real: >>> structure = {'field1': 1, 'field2': 2, 'field3': 3} >>> for item in sorted(structure.items()): print item ('field1', 1) ('field2', 2) ('field3', 3) >>> Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists with just an item
Hi, mydic = {'one': 1, 'two': 2} # to access key: for x in mydic.keys(): print x # to access value --> use key print mydic['one'] Cheers, pujo On 11/21/05, Negroup - <[EMAIL PROTECTED]> wrote: Hi all.In my application I have chosen as data structure a list ofdictionaries. Each dictionary has just one key and the corresponding value.structure = [{'field1': lenght1}, {'field2': lenght2}, ]Initially, to obtain the key and the value I used this code,for structure in record_structure:field_name = structure.keys ()[0]displacement = structure[field_name]but after some thoughts I arrived to:field_name, displacement = structure.items()[0]which to me seems a lot better.At this point I don't like much that [0] to access a list that I know always contains a single element. Can I improve the code withsomething better?Thanks!___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] reduce with comprehension
>>> 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 >>> [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 You are not using operator add anywhere in there. So you won't reduce anything! But reduce is tricky to reproduce using comprehensions because it involves combining two elements using an operation. And one of the elements is the running result. So count = 0 [count + item for item in alist] won't work because we never change count - and assignments aren't allowed inside a comprehension. There may be a clever way of doing it but I can't think of it and certainly not a way that would be as readable as reduce()! Do you have any particular need to avoid reduce? Or is it just curiosity? Alan g ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists with just an item
> Each dictionary has just one key and the corresponding > value. > > structure = [{'field1': lenght1}, {'field2': lenght2}, ] I'd use a tuple rather than a dictionary here: structure = [('field1', lenght1), ('field2', lenght2), ] > but after some thoughts I arrived to: > field_name, displacement = structure.items()[0] > >At this point I don't like much that [0] to access a list that I know > always contains a single element. Can I improve the code with you can now do for field_name, displacement in structure: # work with values here Is that any better? 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] Lists with just an item
2005/11/21, Brian van den Broek <[EMAIL PROTECTED]>: > Hi Negroup, > > why not just make structure a dict: > > structure = {'field1': lenght1, 'field2': lenght2} > > What does having a list of dicts all with a single key add but a layer > of referencing when you want to access? > > If you are trying to preserve order and your key examples are real: > > >>> structure = {'field1': 1, 'field2': 2, 'field3': 3} > >>> for item in sorted(structure.items()): print item At first I used a unique dictionary, but as you told, the point is that I need to preserve the order of items, so I switched to list of dictionaries. I neither can rely on sorting 'field1', 'field2', ..., as these are not real key names and instead vary from case to case (they are obtained splitting in chunks the header line of a file submitted by a user, that may be different each time). So I'm going to think that my solution is at least "acceptable", wow ;-) > Best, > > Brian vdB Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists with just an item
2005/11/21, Alan Gauld <[EMAIL PROTECTED]>: > > Each dictionary has just one key and the corresponding > > value. > > > > structure = [{'field1': lenght1}, {'field2': lenght2}, ] > > I'd use a tuple rather than a dictionary here: Of course, this makes a lot of sense. [cut] > you can now do > > for field_name, displacement in structure: > # work with values here > > Is that any better? Yes, it is exactly what I was looking for! Probably due to the lacking of experience, but each time I code a datastructure I am never satisfied, and I have the feeling that I'm not on the right way.. Thanks a lot for your opinion. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reduce with comprehension
János Juhász wrote: > 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 > > Is it possible to substitute reduce with comprehension anyway ? Not that I know. Why are you trying to eliminate reduce()? If it is for compatibility with Python 3.0, PEP 3000 recommends replacing reduce() with an explicit loop. http://www.python.org/peps/pep-3000.html#built-in-namespace Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Numeric array incosistence in unittest
hello, I found that if I use Numeric.array into unittest it is not consistance, Is that normal ? import unittestimport Numeric class myTest(unittest.TestCase): def runTest(self): var1 = Numeric.array([1,22]) var2 = Numeric.array([1,33]) self.assertEqual(var1,var2) if __name__ == '__main__': unittest.main() This will not raise any error ??? Any idea? Sincerely Yours, pujo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tkinter modal dialogs
Hello tutors! My file search dialog is working now! I attach a copy of the module. It would be nice, if someone could look over it and make suggestions to improve it. There are at least two points I find not very elegant in the program: 1. The dialog is ended by raising a SystemExit exception. (I found the idea searching www.koders.com for Tkinter programs.) Here is a small example of the technique: --- snip --- import Tix from Tkconstants import * class YesNo: def __init__(self, root, title="", question=""): self.top= Tix.Toplevel(root) self.top.title(title) self.top.withdraw() # don't show Tix.Label(self.top, text=question).pack() Tix.Button(self.top, text="Yes", command=self.yes_cmd).pack(side=LEFT) Tix.Button(self.top, text="No", command=self.no_cmd).pack(side=RIGHT) def ask(self): self.top.deiconify() self.top.tkraise() self.top.grab_set() try: self.top.mainloop() except SystemExit, answer: self.top.grab_release() self.top.withdraw() return answer def yes_cmd(self, event=None): raise SystemExit, True def no_cmd(self, event=None): raise SystemExit, False if __name__=="__main__": def set_label(): global yes_no_dlg, yes_no_label answer= yes_no_dlg.ask() yes_no_label["text"]= str(answer) yes_no_label.update_idletasks() root = Tix.Tk() root.title("Modal Dialog Demo") yes_no_dlg = YesNo(root, "Question", "Do you find this approach elegant?") yes_no_label= Tix.Label(root, text="Unknown.") yes_no_label.pack() Tix.Button(root, text = 'Question..', command = set_label).pack() Tix.Button(root, text = 'Exit', command = root.destroy).pack() root.mainloop() --- snip --- This is deceiving. A SystemExit exception should, in my opinion, exit the program. Is there an other way to do this? 2. The Listbox in the file search dialog seems to have two selection modes. When scrolling with the page-up/page-down keys, only the underlined selection moves, while the other selection (indicated by a different background color) remains where it is unless I press the space key. That is imo too complicated. Is there a Listbox with only one selection type (or an option to Tix.ScrolledListbox)? Kind regards, Karsten. -- 10 GB Mailbox, 100 FreeSMS/Monat http://www.gmx.net/de/go/topmail +++ GMX - die erste Adresse für Mail, Message, More +++import Tix from Tkconstants import * from tkFileDialog import askdirectory from tkMessageBox import showerror from grep_mod import grep import os, re, thread, time class FileSearchBase: def __init__(self, root, search_func, func_caller): """root... parent window search_func... a "worker" function which performs the search func_caller... the call to the search_func is wrapped to allow threading etc.""" self.root = root self.top = None self.title= "File Search" self.subdirs= Tix.BooleanVar() self.is_regex= Tix.BooleanVar() self.is_stopped= False self.search_func= search_func self.func_caller= func_caller self.time= 0 self.dir= None self.file_combo= None self.search_combo= None self.startstop= None self.statusbar= None def ask_file_by_search(self): self._open() try: self.top.mainloop() except SystemExit, file_name: self._close() return file_name def _open(self): """Window management: displays the File search dialog window""" if not self.top: self._create_widgets() else: self.top.deiconify() self.top.tkraise() self.search_combo.entry.focus_set() self.search_combo.entry.selection_range(0, "end") self.search_combo.entry.icursor(0) self.top.grab_set() def _close(self, event=None): """Window management: closes the File search dialog""" if self.top is not None: self.top.grab_release() self.top.withdraw() def _create_widgets(self): """Window management: called by _open() to create the dialog widgets.""" top = Tix.Toplevel(self.root) top.resizable(0,0) top.bind("", self._start_search_cmd) top.bind("", self._cancel_cmd) top.protocol("WM_DELETE_WINDOW", self._cancel_cmd) top.wm_title(self.title) #top.wm_iconname(self.icon) self.top = top self.top.grid_columnconfigure(0, pad=2, weight=0) self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100) # first row: folder information ## first column: Folder entry + pick folder button frame= Tix.Frame(top) self.dir = Tix.LabelEntry(frame, label="Folder:", options='entry.width 20') self.dir.entry.insert("end", os.getcwd()) # use os.getcwdu() for unicode self.dir.pack(side=LEFT) w= Tix.Button(frame, text = 'Pick..', command = self._pick_dir_cmd) w.pack(side=RIGHT) frame.grid(row=0, column=0) ## second column: checkbox w= Tix.Checkbutton(top, text = 'Look in subfolders, too', # Label variable=self.subdirs # Variab
[Tutor] again... regular expression
Hallo. I want to parse a website for links of this type: http://www.example.com/good.php?test=anything&egal=total&nochmal=nummer&so=site&seite=22";> - re_site = re.compile(r'http://\w+.\w+.\w+./good.php?.+";>') for a in file: z = re_site.search(a) if z != None: print z.group(0) - I still don't understand RE-Expressions. I tried some other expressions but didn't get it work. The End of the link is ">. So it should not be a problem to extract the link but it is. Thank you for the help. mac ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] again... regular expression
lmac wrote: > Hallo. > I want to parse a website for links of this type: > > http://www.example.com/good.php?test=anything&egal=total&nochmal=nummer&so=site&seite=22";> > > - > re_site = re.compile(r'http://\w+.\w+.\w+./good.php?.+";>') . and ? have special meaning in re's so they should be escaped with \ You should use a non-greedy match at the end so you match the *first* "> So I would try re_site = re.compile(r'http://\w+\.\w+\.\w+\./good.php\?.+?";>') > for a in file: > z = re_site.search(a) > if z != None: > print z.group(0) > > - > > I still don't understand RE-Expressions. I tried some other expressions > but didn't get it work. There is a handy re tester that comes with Python, look for C:\Python24\Tools\Scripts\redemo.py Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] again... regular expression
Ok. There is an error i made. The links in the HTML-Site are starting with good.php so there was no way ever to find an link. re_site = re.compile(r"good\.php.+'") for a in file: z = re_site.search(a) if z != None: print z.group(0) This will give me every line starting with "good.php" but does contain not the first ' at the end, there are more tags and text which ends with ' too. So how can i tell in an regex to stop at the first found ' after good.php ??? Thank you. > Hallo. > I want to parse a website for links of this type: > > http://www.example.com/good.php?test=anything&egal=total&nochmal=nummer&so=site&seite=22";> > > - > re_site = re.compile(r'http://\w+.\w+.\w+./good.php?.+";>') > for a in file: > z = re_site.search(a) > if z != None: > print z.group(0) > > - > > I still don't understand RE-Expressions. I tried some other expressions > but didn't get it work. > > The End of the link is ">. So it should not be a problem to extract the > link but it is. > > Thank you for the help. > > mac > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] again... regular expression
lmac wrote: > Ok. There is an error i made. The links in the HTML-Site are starting > with good.php so there was no way ever to find an link. > > re_site = re.compile(r"good\.php.+'") > for a in file: > z = re_site.search(a) > if z != None: > print z.group(0) > > > This will give me every line starting with "good.php" but does contain > not the first ' at the end, there are more tags and text which ends with > ' too. So how can i tell in an regex to stop at the first found ' after > good.php ??? Use a non-greedy match. Normally + will match the longest possible string; if you put a ? after it, it will match the shortest string. So r"good\.php.+?'" will match just to the first '. Kent > > Thank you. > > > >>Hallo. >>I want to parse a website for links of this type: >> >>http://www.example.com/good.php?test=anything&egal=total&nochmal=nummer&so=site&seite=22";> >> >>- >>re_site = re.compile(r'http://\w+.\w+.\w+./good.php?.+";>') >>for a in file: >> z = re_site.search(a) >> if z != None: >> print z.group(0) >> >>- >> >>I still don't understand RE-Expressions. I tried some other expressions >> but didn't get it work. >> >>The End of the link is ">. So it should not be a problem to extract the >>link but it is. >> >>Thank you for the help. >> >>mac >> > > > ___ > 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] Trouble with classes - Pypeg again
At 08:52 PM 11/20/2005, ->Terry<- wrote: -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' screen.blit(Peg.peg, (Peg.pegs[i])) Peg is the name of a class rather than an instance of a class. Instances of Peg have the attribute peg. The class itself does not. Without analyzing your code in detail I'm not sure of the fix, except to suggest you put an instance of Peg in place of Pe. The new code is at: < URL: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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists with just an item
> Probably due to the lacking of experience, but each time I code a > datastructure I am never satisfied, and I have the feeling that I'm > not on the right way.. The same thing happens to me. I actually have a very similar problem to yours now, and I'm rather considering a list of two-element tuples. Greetings, Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] smtplib problems ?
Hi all, I am not sure if this is a Python problem not not but here goes I wrote the following small script to email by boss 'email_addr' a rather important reminder and also send a copy to myself 'email_addr2' several times a day. #!/usr/bin/env python # -*- coding: iso8859_1 -*- from smtplib import SMTP from time import sleep import sys email_SMTP = 'mail.pusspaws.net' email_addr = '[EMAIL PROTECTED]' email_addr2 = '[EMAIL PROTECTED]' def email_remind(): for trys in xrange(10): try: mail_server = SMTP(email_SMTP) # email the office with a full email blog="""\n\nHi,\n\nHi,This is just a reminder, can you sort me out a date for my re-grade exam as soon as possible. I have tied an email script into my cron (time scheduling) daemon to remind you an ever increasing number of times a day ;) - Got to love Linux\n\nCheers\n\nDave""" msg = ('Subject: Friendly reminder :)\r\nFrom: Dave Selby\r\nTo: '+\ email_addr+'\r\n\r\n'+blog+'\r\n\r\n') mail_server.sendmail('Friendly reminder :)', email_addr, msg) mail_server.sendmail('Friendly reminder :)', email_addr2, msg) mail_server.quit() # If we get to here, all is well, drop out of the loop break except: print 'Mailing error ... Re-trying ... '+str(trys+1)+' of 10\n' sleep(300) if trys==9: raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) email_remind() It does the job (regrade exam now booked :)) but It succeeds in sending emails only about 50% of the time. The other 50% I get ... Mailing error ... Re-trying ... 1 of 10 Mailing error ... Re-trying ... 2 of 10 Mailing error ... Re-trying ... 3 of 10 Mailing error ... Re-trying ... 4 of 10 Mailing error ... Re-trying ... 5 of 10 Mailing error ... Re-trying ... 6 of 10 Mailing error ... Re-trying ... 7 of 10 Mailing error ... Re-trying ... 8 of 10 Mailing error ... Re-trying ... 9 of 10 Mailing error ... Re-trying ... 10 of 10 Traceback (most recent call last): File "/home/dave/my files/andrew_torture/email_remind.py", line 49, in ? email_remind() File "/home/dave/my files/andrew_torture/email_remind.py", line 43, in email_remind raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) Mail Failure smtplib.SMTPRecipientsRefused {'[EMAIL PROTECTED]': (553, "sorry, that domain isn't in my list of allowed rcpthosts (#5.7.1)")} I do not know if the is me not using the SMTP function correctly, I have noticed the emails arrive and kmail cannot work out when they were sent, or if the problem lies elsewear. Any suggestions gratefully recieved Cheers Dave ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] smtplib problems ?
On Mon, 2005-11-21 at 19:59 +, dave wrote: > Traceback (most recent call last): > File "/home/dave/my files/andrew_torture/email_remind.py", line 49, in ? > email_remind() > File "/home/dave/my files/andrew_torture/email_remind.py", line 43, in > email_remind > raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) > Mail Failure > smtplib.SMTPRecipientsRefused > {'[EMAIL PROTECTED]': (553, "sorry, that domain isn't in my list of allowed > rcpthosts (#5.7.1)")} http://www.greenend.org.uk/rjk/2000/05/21/smtp-replies.html It is a standard SMTP error message. Essentially the mail server is trying to prevent relaying. Your script is working correctly. This SMTP server, since it works some of the time, probably uses POP before SMTP to authenticate your request. So if you login to the POP server using your mailbox name and password, it will authenticate your IP address as permitted to relay. This authentication will time out after a few minutes. Test this by checking your email on that server and then see if your script runs successfully. If you can use an SMTP server from your ISP that uses IP addresses to control relaying, you can avoid the need to login to the POP server. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter modal dialogs
Hi Karsten, You might want to look at Python MegaWidgets: http://pmw.sourceforge.net/ PMW is an alternative to Tix, built using only python and basic Tkinter. It has a scrolled listbox widget and a way of easily creating modal dialogs. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reduce with comprehension
On 21/11/05, János Juhász <[EMAIL PROTECTED]> wrote: > 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]) Everything is possible with list comprehensions! >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) >>> [x for y in a for x in y] [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] We can even go a level deeper! >>> [x for z in a for y in z for x in y] [1, 2, 3, 31, 32, 4, 5, 6, 7, 71, 72, 8, 9] Just make sure your depth is consistent throughout. And remember that that single-line expression is hiding nested FOR loops! -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] O/T:META: Crossposting
On Mon, 21 Nov 2005, enas khalil wrote: > i want to confirm with you that the right addresses to send to are : > python-list@python.org > tutor@python.org > arent they ? [Keeping Tutor in CC; if I'm out of line, I want to make sure someone calls me on it and keeps me grounded.] Hi Enas, I can't help but feel we're having a language issue here. (If there's anything below that confuses you, please ask for clarification, because I feel like I've been repeating this several times now, and I don't know what I'm saying wrong.) When I use the term "crosspost", I mean the act of posting the same question to more than one mailing list at once. The two addresses you've listed above are two distinct mailing lists. 1. The one we're on now is Python-tutor (tutor@python.org). 2. python-list@python.org is a gateway to the comp.lang.python general discussion newsgroup. You have been missing the whole point when I asked you not to crosspost: the main point is not topicality, but verbosity. Your questions would fit in both comp.lang.python and Python-Tutor. But just choose one: don't ask both at the same time. Don't flood all possible avenues at once: if everyone did this, all of the mailing lists would get clogged, and no one would be satisfied. We're trying to avoid a "tragedy of the commons" situation here. The research strategy you've been using to get answers, by flooding all channels for help at once, is ineffective and, frankly, annoying. And because everyone who helps here does so by free will --- this is not a day job --- we must make sure things aren't annoying, or else helpers will stop helping. Again, I want to emphasize that we want to help you learn how to program Python, and we are happy to get good questions from you. But please change your behavior so that you are not the only one who benefits. See: http://www.catb.org/~esr/faqs/smart-questions.html#forum http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html#SECTION0007 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] O/T:META: Crossposting
On Mon, 21 Nov 2005, enas khalil wrote: > thanks again ,sir > i finally understand what you mean > sorry for annoying you several times ,promise not to do this again > > execuse me can i ask you aquestion about how can i use codecs in read > and tag an arabic text file > thanks again [Forwarding to tutor to see if anyone else is interested. I'm too busy to research this for Enas. Thanks.] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Ellipsis syntax
Hi all, I have looked for any references of ellipsis '...' syntax for Python slices, but I keep finding the same BNF grammar in the LanguageRreference. Is there any page with examples on how to do this, or is this just very obscure? I remember reading something about this syntax somewhere, long ago. I don't even know how it is supposed to be used, but it is in the grammar... Any help would be appreciated. Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Ellipsis syntax
On 22/11/05, Hugo González Monteverde <[EMAIL PROTECTED]> wrote: > I have looked for any references of ellipsis '...' syntax for Python > slices, but I keep finding the same BNF grammar in the > LanguageRreference. Is there any page with examples on how to do this, > or is this just very obscure? Wow, funky. I found some links from when someone asked this last year: Main thread: http://mail.python.org/pipermail/python-list/2004-November/thread.html#252683 Good posts: http://mail.python.org/pipermail/python-list/2004-November/252614.html http://mail.python.org/pipermail/python-list/2004-November/252616.html http://mail.python.org/pipermail/python-list/2004-November/252622.html It seems that python slicing syntax supports slices like a[1, 2, ...], but no builtin types (list, string, tuple, etc) are capable of decoding slices like that. But you can implement your own classes if you want (say, if you want to implement multidimensional arrays). -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Ellipsis syntax
Hugo González Monteverde wrote: > Hi all, > > I have looked for any references of ellipsis '...' syntax for Python > slices, but I keep finding the same BNF grammar in the > LanguageRreference. Is there any page with examples on how to do this, > or is this just very obscure? ellipsis is used by Numeric for more flexible slicing. See the bottom of this page: http://numeric.scipy.org/numpydoc/numpy-6.html#pgfId-37311 Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Ellipsis syntax
Ok, now I know I don't need them just now *grin* Next time I will remember to search the newsgroup Now I think it was the perlish skeletons in my closet coming back to me. Thanks a lot for that, Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Website monitoring program.
I need to add the count statement to give urllib access the tuple of urls. urllib needs to be given a different value each time in order to check all the urls. This is the only way I could get the value (web) in urllib to change each time. I tried indenting the count statement and it runs without error but still only makes one pass. Thanks Message: 1 Date: Sun, 20 Nov 2005 22:26:10 -0500 From: Kent Johnson <[EMAIL PROTECTED]> Subject: Re: [Tutor] Website monitoring program. Cc: tutor@python.org Message-ID: <[EMAIL PROTECTED]> Content-Type: text/plain; charset=ISO-8859-1; format=flowed 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"> < http://website4.net/imalive.asp%22>,)>> 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 < http://mail.authentium.com>'> RECIPIENTS = ['[EMAIL PROTECTED] [EMAIL PROTECTED]>']> SENDER = '[EMAIL PROTECTED]> [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 -- Arthur DiSegnaNetwork Operations CenterAuthentium, Inc. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Website monitoring program.
This worked for me. Thanks! -- for web in urls: for site in urllib.urlopen(web): --- 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"> < http://website4.net/imalive.asp%22>,)>> 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 < http://mail.authentium.com>'> RECIPIENTS = ['[EMAIL PROTECTED] [EMAIL PROTECTED]>']> SENDER = '[EMAIL PROTECTED]> [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 -- Arthur DiSegnaNetwork Operations CenterAuthentium, Inc. -- Arthur DiSegnaNetwork Operations CenterAuthentium, Inc. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help with objects
I'm trying to write a tree data structure as part of my first object oriented program I have an error "can't assign to function call" caused by this line: Tree.nodeList(self.name) = self however, nodeList is a dictionary I'm trying to index. Beyond the error I'm still not sure I understand how to make and use a tree data structure using objects. Thank you for the help Here is my code # obj_tree1.py import random # constants that control the simulation NUMBER_REPS = 10# run's the simulation MAX_LINAGES = 10# number of species in each run BRANCHING_PROBABILITY = 0.5 class Tree(object): numLinages = 0# keeps track of how many nodes there are nodeList = {}# keeps track of the nodes class Node(object): def __init__(self, name): self.name = name# an integer self.alive = True self.descendents = {}# nodes descending from self Tree.numLinages += 1# records node creation Tree.nodeList(self.name) = self# makes node accesable from tree def __init__(self): nodeList(0) = Tree.Node(0)# adds a root node 0 to the tree def AddBranch(self, offspring): self.descendents(offspring) = Tree.Node(offspring)# adds a descendent node def NumLinages( ): return Tree.numLinages NumLinages = staticmethod(NumLinages) currentTree = Tree() for i in range(NUMBER_REPS): j = 0 while j <= currentTree.NumLinages(): # checks all node because their names are sequential integers if j.alive: if random.random() >= BRANCHING_PROBABILITY: currentTree.AddBranch(j, (currentTree.NumLinages() + 1)) # creates a new node j += 1 Vincent Wan -- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with objects
At 08:38 PM 11/21/2005, Vincent Wan wrote: >I'm trying to write a tree data structure as part of my first >object oriented program > >I have an error "can't assign to function call" caused by this line: >Tree.nodeList(self.name) = self Tree.nodeList[self.name] = self >however, nodeList is a dictionary I'm trying to index. > >Beyond the error I'm still not sure I understand how to make and >use a tree data structure using objects. > >Thank you for the help > >Here is my code > ># obj_tree1.py > >import random > ># constants that control the simulation >NUMBER_REPS = 10# run's the simulation >MAX_LINAGES = 10# number of species in each run >BRANCHING_PROBABILITY = 0.5 > >class Tree(object): > numLinages = 0# keeps track of how many nodes there are > nodeList = {}# keeps track of the nodes > class Node(object): > def __init__(self, name): > self.name = name# an integer > self.alive = True > self.descendents = {}# nodes descending from self > Tree.numLinages += 1# records node creation > Tree.nodeList(self.name) = self# makes node >accesable from tree > def __init__(self): > nodeList(0) = Tree.Node(0)# adds a root node 0 to the tree > def AddBranch(self, offspring): > self.descendents(offspring) = Tree.Node(offspring)# adds >a descendent node > def NumLinages( ): > return Tree.numLinages > NumLinages = staticmethod(NumLinages) > >currentTree = Tree() > >for i in range(NUMBER_REPS): > j = 0 > while j <= currentTree.NumLinages(): # checks all node because >their names are sequential integers > if j.alive: > if random.random() >= BRANCHING_PROBABILITY: > currentTree.AddBranch(j, (currentTree.NumLinages() + >1)) # creates a new node > j += 1 > > >Vincent Wan > > >-- >PhD Candidate >Committee on the Conceptual and Historical Studies of Science >University of Chicago > >PO Box 73727 >Fairbanks, AK 99707 > >wan AT walrus DOT us (change CAPS to @ and . ) > >___ >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] Help with objects
Thank you bob. I fixed the errors where I tried to index a dictionary with name() so so that they say name[] >> Beyond the error I'm still not sure I understand how to make and >> use a tree data structure using objects. There is a new error as well Traceback (most recent call last): File "/Users/Wally/obj_tree1.py", line 28, in -toplevel- currentTree = Tree() File "/Users/Wally/obj_tree1.py", line 21, in __init__ nodeList[0] = Tree.Node(0)# adds a root node 0 to the tree NameError: global name 'nodeList' is not defined Code with error bob fixed fixed throughout # obj_tree1.py import random # constants that control the simulation NUMBER_REPS = 10# run's the simulation MAX_LINAGES = 10# number of species in each run BRANCHING_PROBABILITY = 0.5 class Tree(object): numLinages = 0# keeps track of how many nodes there are nodeList = {}# keeps track of the nodes class Node(object): def __init__(self, name): self.name = name# an integer self.alive = True self.descendents = {}# nodes descending from self Tree.numLinages += 1# records node creation Tree.nodeList[self.name] = self# makes node accesable from tree def __init__(self): nodeList[0] = Tree.Node(0)# adds a root node 0 to the tree def AddBranch(self, offspring): self.descendents[offspring] = Tree.Node(offspring)# adds a descendent node def NumLinages( ): return Tree.numLinages NumLinages = staticmethod(NumLinages) currentTree = Tree() for i in range(NUMBER_REPS): j = 0 while j <= currentTree.NumLinages(): # checks all node because their names are sequential integers if j.alive: if random.random() >= BRANCHING_PROBABILITY: currentTree.AddBranch(j, (currentTree.NumLinages() + 1)) # creates a new node j += 1 Thank you for the help Vincent Wan -- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] about global definition
I have a code here. I understand i can not draw lines without the global definition of lastX and lastY. But still confused by its use. when should we use global definition? from Tkinter import * root = Tk() c = Canvas(root, bg='#0e2e0e', height=500, width=1000) frame = c lastX="" lastY="" def click(event): global lastX, lastY if lastX != "": c.create_line(lastX,lastY,event.x,event.y,fill="white") lastX = event.x lastY = event.y c.bind('<1>',click) c.pack() root.mainloop() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reduce with comprehension
Hi John, thanks it. It is great. I looked for it, but I couldn't made it. I have tried it with wrong order: # I have tried it so [x for x in y for y in a] [[8], [8], [8], [9], [9], [9]] # that is wrong, # Instead of that you wrote [x for y in a for x in y] [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] Yours sincerely, __ János Juhász [EMAIL PROTECTED] wrote on 2005.11.21 23:26:03: > On 21/11/05, János Juhász <[EMAIL PROTECTED]> wrote: > > 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]) > Everything is possible with list comprehensions! > >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) > >>> [x for y in a for x in y] > [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] > We can even go a level deeper! > >>> [x for z in a for y in z for x in y] > [1, 2, 3, 31, 32, 4, 5, 6, 7, 71, 72, 8, 9] > Just make sure your depth is consistent throughout. > And remember that that single-line expression is hiding nested FOR loops! > -- > John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor