Re: A question about Python Classes
On Apr 22, 12:47 pm, Carl Banks wrote: > On Thursday, April 21, 2011 11:00:08 AM UTC-7, MRAB wrote: > > On 21/04/2011 18:12, Pascal J. Bourguignon wrote: > > > chad writes: > > > >> Let's say I have the following > > > >> class BaseHandler: > > >> def foo(self): > > >> print "Hello" > > > >> class HomeHandler(BaseHandler): > > >> pass > > > >> Then I do the following... > > > >> test = HomeHandler() > > >> test.foo() > > > >> How can HomeHandler call foo() when I never created an instance of > > >> BaseHandler? > > > > But you created one! > > > No, he didn't, he created an instance of HomeHandler. > > > > test is an instance of HomeHandler, which is a subclass of BaseHandler, > > > so test is also an instance of BaseHandler. > > > test isn't really an instance of BaseHandler, it's an instance of > > HomeHandler, which is a subclass of BaseHandler. > > I'm going to vote that this is incorrect usage. An instance of HomeHandler > is also an instance of BaseHandler, and it is incorrect to say it is not. > The call to HomeHandler does create an instance of BaseHandler. > What do you mean by the "call to HomeHandler"? Don't I call HomeHandler after I create an instance of BaseHandler? Chad -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about Python Classes
On Apr 21, 9:30 am, Jean-Michel Pichavant wrote: > chad wrote: > > Let's say I have the following > > > class BaseHandler: > > def foo(self): > > print "Hello" > > > class HomeHandler(BaseHandler): > > pass > > > Then I do the following... > > > test = HomeHandler() > > test.foo() > > > How can HomeHandler call foo() when I never created an instance of > > BaseHandler? > > > Chad > > you did, test is an instance of BaseHandler. > > > isinstance(test, HomeHandler) > < True > > > isinstance(test, BaseHandler) > < True > So it just just creates an instance of every class that it inherits? Chad -- http://mail.python.org/mailman/listinfo/python-list
A question about Python Classes
Let's say I have the following class BaseHandler: def foo(self): print "Hello" class HomeHandler(BaseHandler): pass Then I do the following... test = HomeHandler() test.foo() How can HomeHandler call foo() when I never created an instance of BaseHandler? Chad -- http://mail.python.org/mailman/listinfo/python-list
Re: I don't why there is no output....
On Dec 24, 4:00 pm, chad wrote: > Given the following... > > #!/usr/bin/python > > import pexpect > > p = pexpect.spawn('cat') > p.sendline('1234') > p.expect (['1234']) > p.expect (['1234']) > > I no output when I run it... > > [cdal...@localhost oakland]$ ./ecat.py > [cdal...@localhost oakland]$ > > I don't get it. I was expecting to see the output from both the tty > and cat. Instead, I see nothing. Why? Never mind. I figured it out. -- http://mail.python.org/mailman/listinfo/python-list
I don't why there is no output....
Given the following... #!/usr/bin/python import pexpect p = pexpect.spawn('cat') p.sendline('1234') p.expect (['1234']) p.expect (['1234']) I no output when I run it... [cdal...@localhost oakland]$ ./ecat.py [cdal...@localhost oakland]$ I don't get it. I was expecting to see the output from both the tty and cat. Instead, I see nothing. Why? -- http://mail.python.org/mailman/listinfo/python-list
Automating a shell session question
I manually log into a remote shell and so some stuff. After I do some stuff, I want the rest of the session to be automated. I've tried pexpect using the interact() function. However, I don't see any way to go into non-interactive mode going this route. Ideas? -- http://mail.python.org/mailman/listinfo/python-list
I can't seem to change the timeout value on pexpect
I tried to change the timeout value from 30 to 90 for pexpect in the following script... #!/usr/bin/python import telnetlib import time import pexpect def get_name(): user = raw_input("\nUsername: ") password = raw_input("Password: ") idle(user, password) def idle(user, password): child = pexpect.spawn('telnet game.mortalrealms.com 4321') child.expect("Who art thou:", timeout=90) child.sendline(user) print "\nEntered username.." child.expect("Password:",timeout=90) child.sendline(password) print "Entered pass.." child.expect('Press return to continue:', timeout=90) child.sendline('\n') if child == 2: print "Connection timeout" elif child == 3: print "Another timeout" #while 1: child.expect('Druidess Supi burps loudly.') child.sendline('say oh my aching back') #time.sleep(15) #time.sleep(5) #now.write("\n") #while 1: #now.write("wc") #time.sleep(15) if __name__ == "__main__": get_name() However, when I run it, the timeout still shows 30 seconds... Entered username.. Entered pass.. TrF[;37;44mAv[;33;44mAvaricest): File "./mort.py", line 42, in ? F[;37;44mAv[;33;44mAvarice File "./mort.py", line 10, in get_name idle(user, password) File "./mort.py", line 31, in idle child.expect('Druidess Supi burps loudly.') File "/usr/lib/python2.4/site-packages/pexpect.py", line 1311, in expect return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) File "/usr/lib/python2.4/site-packages/pexpect.py", line 1325, in expect_list return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize) File "/usr/lib/python2.4/site-packages/pexpect.py", line 1409, in expect_loop raise TIMEOUT (str(e) + '\n' + str(self)) pexpect.TIMEOUT: Timeout exceeded in read_nonblocking(). version: 2.3 ($Revision: 399 $) command: /usr/kerberos/bin/telnet args: ['/usr/kerberos/bin/telnet', 'game.mortalrealms.com', '4321'] searcher: searcher_re: 0: re.compile("Druidess Supi burps loudly.") buffer (last 100 chars): all. before (last 100 chars): all. after: pexpect.TIMEOUT match: None match_index: None exitstatus: None flag_eof: False pid: 23652 child_fd: 3 closed: False timeout: 30 delimiter: pexpect.EOF logfile: None logfile_read: None logfile_send: None maxread: 2000 ignorecase: False searchwindowsize: None delaybeforesend: 0.05 delayafterclose: 0.1 delayafterterminate: 0.1 What am I doing wrong? -- http://mail.python.org/mailman/listinfo/python-list
How do I skip over multiple words in a file?
Let's say that I have an article. What I want to do is read in this file and have the program skip over ever instance of the words "the", "and", "or", and "but". What would be the general strategy for attacking a problem like this? -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about yield
On Nov 7, 9:47 am, Chris Rebert wrote: > On Sun, Nov 7, 2010 at 9:34 AM, chad wrote: > > > > > > > #!/usr/local/bin/python > > > import sys > > > def construct_set(data): > > for line in data: > > lines = line.splitlines() > > for curline in lines: > > if curline.strip(): > > key = curline.split(' ') > > value = int(key[0]) > > yield value > > > def approximate(first, second): > > midpoint = (first + second) / 2 > > return midpoint > > > def format(input): > > prev = 0 > > value = int(input) > > > with open("/home/cdalten/oakland/freq") as f: > > for next in construct_set(f): > > if value > prev: > > current = prev > > prev = next > > > middle = approximate(current, prev) > > if middle < prev and value > middle: > > return prev > > elif value > current and current < middle: > > return current > > > The question is about the construct_set() function. > > > I have it yield on 'value' instead of 'curline'. Will the program > > still read the input file named freq line by line even though I don't > > have it yielding on 'curline'? Or since I have it yield on 'value', > > will it read the entire input file into memory at once? > > The former. The yield has no effect at all on how the file is read. > The "for line in data:" iteration over the file object is what makes > Python read from the file line-by-line. Incidentally, the use of > splitlines() is pointless; you're already getting single lines from > the file object by iterating over it, so splitlines() will always > return a single-element list. > But what happens if the input file is say 250MB? Will all 250MB be loaded into memory at once? Just curious, because I thought maybe using something like 'yield curline' would prevent this scenario. -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about yield
On Nov 7, 9:34 am, chad wrote: > I have an input file named 'freq' which contains the following data > > 123 0 > > 133 3 > 146 1 > 200 0 > 233 10 > 400 2 > > Now I've attempted to write a script that would take a number from the > standard input and then > have the program return the number in the input file that is closest > to that input file. *and then have the program return the number in the input file that is closest to the number the user inputs (or enters).* -- http://mail.python.org/mailman/listinfo/python-list
A question about yield
I have an input file named 'freq' which contains the following data 123 0 133 3 146 1 200 0 233 10 400 2 Now I've attempted to write a script that would take a number from the standard input and then have the program return the number in the input file that is closest to that input file. #!/usr/local/bin/python import sys def construct_set(data): for line in data: lines = line.splitlines() for curline in lines: if curline.strip(): key = curline.split(' ') value = int(key[0]) yield value def approximate(first, second): midpoint = (first + second) / 2 return midpoint def format(input): prev = 0 value = int(input) with open("/home/cdalten/oakland/freq") as f: for next in construct_set(f): if value > prev: current = prev prev = next middle = approximate(current, prev) if middle < prev and value > middle: return prev elif value > current and current < middle: return current if __name__ == "__main__": if len(sys.argv) != 2: print >> sys.stderr, "You need to enter a number\n" sys.exit(1) nearest = format(sys.argv[1]) print "The closest value to", sys.argv[1], "is", nearest When I run it, I get the following... [cdal...@localhost oakland]$ ./android4.py 123 The closest value to 123 is 123 [cdal...@localhost oakland]$ ./android4.py 130 The closest value to 130 is 133 [cdal...@localhost oakland]$ ./android4.py 140 The closest value to 140 is 146 [cdal...@localhost oakland]$ ./android4.py 146 The closest value to 146 is 146 [cdal...@localhost oakland]$ ./android4.py 190 The closest value to 190 is 200 [cdal...@localhost oakland]$ ./android4.py 200 The closest value to 200 is 200 [cdal...@localhost oakland]$ ./android4.py 205 The closest value to 205 is 200 [cdal...@localhost oakland]$ ./android4.py 210 The closest value to 210 is 200 [cdal...@localhost oakland]$ ./android4.py 300 The closest value to 300 is 233 [cdal...@localhost oakland]$ ./android4.py 500 The closest value to 500 is 400 [cdal...@localhost oakland]$ ./android4.py 100 The closest value to 100 is 400 [cdal...@localhost oakland]$ The question is about the construct_set() function. def construct_set(data): for line in data: lines = line.splitlines() for curline in lines: if curline.strip(): key = curline.split(' ') value = int(key[0]) yield value I have it yield on 'value' instead of 'curline'. Will the program still read the input file named freq line by line even though I don't have it yielding on 'curline'? Or since I have it yield on 'value', will it read the entire input file into memory at once? Chad -- http://mail.python.org/mailman/listinfo/python-list
What is the best way to handle a missing newline in the following case
I have an text file with the following numbers 1 3 5 7 3 9 Now the program reads in this file. When it encounters a '\n', it will do some stuff and then move to the next line. For example, it will read 1 and then '\n'. When it sees '\n', it will do some stuff and go on to read 3. The problem is when I get to the last line. When the program sees '\n' after the 9, everything works fine. However, when there isn't a '\n', the program doesn't process the last line. What would be the best approach to handle the case of the possible missing '\n' at the end of the file? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I chain methods?
On Oct 24, 4:11 pm, James Mills wrote: > On Mon, Oct 25, 2010 at 9:02 AM, Chris Rebert wrote: > > Method chaining is usually* not idiomatic in Python. > > I don't agree but anyway... I've just not seen it commonly used > amongst python programmers. > > cheers > James > I just saw this technique used in python script that was/is used to automatically log them in myspace.com. Hence the question. -- http://mail.python.org/mailman/listinfo/python-list
How do I chain methods?
I tried the following... #!/usr/bin/python class foo: def first(self): print "Chad " def last(self): print "A " x = foo() y = x.first() y.last() But when I ran it, I got the following... [cdal...@localhost oakland]$ ./chain.py Chad Traceback (most recent call last): File "./chain.py", line 12, in ? y.last() AttributeError: 'NoneType' object has no attribute 'last' [cdal...@localhost oakland]$ -- http://mail.python.org/mailman/listinfo/python-list
Ideas on how to parse a dynamically generated html pages
Let's say there is a site that uses javascript to generate menus. More or less what happens is when a person clicks on url, a pop up menu appears asking the users for some data. How would I go about automating this? Just curious because the web spider doesn't actually pick up the urls that generate the menu. I'm assuming the actual url link is dynamically generated? Here is the code I'm using to get the URLs... >>> from HTMLParser import HTMLParser >>> from urllib2 import urlopen >>> class Spider(HTMLParser): ... def __init__(self, url): ... HTMLParser.__init__(self) ... req = urlopen(url) ... self.feed(req.read()) ... def handle_starttag(self, tag, attrs): ... if tag == 'a' and attrs: ... print "Found Link => %s" % attrs[0][1] -- http://mail.python.org/mailman/listinfo/python-list
Re: asyncore.poll() question
On Oct 16, 11:02 am, Felipe Bastos Nunes wrote: > You edited the source of asyncore.py puttin the print statments and > nothing happend? It should work as the method is called as the page > you posted said. > > 2010/10/16, chad : > > > > > On Oct 16, 6:47 am, Lucasm wrote: > >> On 16 Okt, 15:31, chad wrote: > > >> > At the following url.. > > >> >http://www.nightmare.com/medusa/programming.html > > >> > The author has the following code for a simple HTTP client > > >> > #!/usr/bin/python > > >> > import asyncore > >> > import socket > >> > import string > > >> > class http_client (asyncore.dispatcher): > > >> > def __init__ (self, host, path): > >> > asyncore.dispatcher.__init__ (self) > >> > self.path = path > >> > self.create_socket (socket.AF_INET, socket.SOCK_STREAM) > >> > self.connect ((host, 80)) > > >> > def handle_connect (self): > >> > self.send ('GET %s HTTP/1.0\r\n\r\n' % self.path) > > >> > def handle_read (self): > >> > data = self.recv (8192) > >> > print data > > >> > def handle_write (self): > >> > pass > > >> > if __name__ == '__main__': > >> > import sys > >> > import urlparse > >> > for url in sys.argv[1:]: > >> > parts = urlparse.urlparse (url) > >> > if parts[0] != 'http': > >> > raise ValueError, "HTTP URL's only, please" > >> > else: > >> > host = parts[1] > >> > path = parts[2] > >> > http_client (host, path) > >> > asyncore.loop() > > >> > Right after that, the author states the following... > > >> > " A really good way to understand select() is to put a print statement > >> > into the asyncore.poll() function: > > >> > [...] > >> > (r,w,e) = select.select (r,w,e, timeout) > >> > print '---' > >> > print 'read', r > >> > print 'write', w > >> > [...] > > >> > Each time through the loop you will see which channels have fired > >> > which events. > >> > " > > >> > How the heck do I modify the code put the print statement into the > >> > asyncore.poll() function? > > >> > Chad > > >> Hi, > > >> You can find the file in your Python directory, in my case /usr/lib/ > >> Python2.6/asyncore.py. You should delete the .pyc file to make sure it > >> is recompiled. And you will need root access :). > > >> Lucas > > > I just did that... > > > [r...@localhost python2.6]# ls -al asyncore.py > > -rw-r--r-- 1 root root 19262 Oct 16 10:22 asyncore.py > > [r...@localhost python2.6]# ls -al asyncore.pyc > > -rw-r--r-- 1 root root 16773 Oct 16 10:26 asyncore.pyc > > [r...@localhost python2.6]# ls -al asyncore.pyo > > -rw-r--r-- 1 root root 16773 Oct 16 10:42 asyncore.pyo > > [r...@localhost python2.6]# > > > And nothing happened. Ideas? > > -- One last question. Why does the author have both import sys and import urlparse below __main__? Ie if __name__ == '__main__': import sys import urlparse Why not just put them at the top with the rest? Chad -- http://mail.python.org/mailman/listinfo/python-list
Re: asyncore.poll() question
On Oct 16, 11:02 am, Felipe Bastos Nunes wrote: > You edited the source of asyncore.py puttin the print statments and > nothing happend? It should work as the method is called as the page > you posted said. > > 2010/10/16, chad : > > > > > On Oct 16, 6:47 am, Lucasm wrote: > >> On 16 Okt, 15:31, chad wrote: > > >> > At the following url.. > > >> >http://www.nightmare.com/medusa/programming.html > > >> > The author has the following code for a simple HTTP client > > >> > #!/usr/bin/python > > >> > import asyncore > >> > import socket > >> > import string > > >> > class http_client (asyncore.dispatcher): > > >> > def __init__ (self, host, path): > >> > asyncore.dispatcher.__init__ (self) > >> > self.path = path > >> > self.create_socket (socket.AF_INET, socket.SOCK_STREAM) > >> > self.connect ((host, 80)) > > >> > def handle_connect (self): > >> > self.send ('GET %s HTTP/1.0\r\n\r\n' % self.path) > > >> > def handle_read (self): > >> > data = self.recv (8192) > >> > print data > > >> > def handle_write (self): > >> > pass > > >> > if __name__ == '__main__': > >> > import sys > >> > import urlparse > >> > for url in sys.argv[1:]: > >> > parts = urlparse.urlparse (url) > >> > if parts[0] != 'http': > >> > raise ValueError, "HTTP URL's only, please" > >> > else: > >> > host = parts[1] > >> > path = parts[2] > >> > http_client (host, path) > >> > asyncore.loop() > > >> > Right after that, the author states the following... > > >> > " A really good way to understand select() is to put a print statement > >> > into the asyncore.poll() function: > > >> > [...] > >> > (r,w,e) = select.select (r,w,e, timeout) > >> > print '---' > >> > print 'read', r > >> > print 'write', w > >> > [...] > > >> > Each time through the loop you will see which channels have fired > >> > which events. > >> > " > > >> > How the heck do I modify the code put the print statement into the > >> > asyncore.poll() function? > > >> > Chad > > >> Hi, > > >> You can find the file in your Python directory, in my case /usr/lib/ > >> Python2.6/asyncore.py. You should delete the .pyc file to make sure it > >> is recompiled. And you will need root access :). > > >> Lucas > > > I just did that... > > > [r...@localhost python2.6]# ls -al asyncore.py > > -rw-r--r-- 1 root root 19262 Oct 16 10:22 asyncore.py > > [r...@localhost python2.6]# ls -al asyncore.pyc > > -rw-r--r-- 1 root root 16773 Oct 16 10:26 asyncore.pyc > > [r...@localhost python2.6]# ls -al asyncore.pyo > > -rw-r--r-- 1 root root 16773 Oct 16 10:42 asyncore.pyo > > [r...@localhost python2.6]# > > > And nothing happened. Ideas? I edited the wrong file. Now it works. -- http://mail.python.org/mailman/listinfo/python-list
Re: asyncore.poll() question
On Oct 16, 6:47 am, Lucasm wrote: > On 16 Okt, 15:31, chad wrote: > > > > > At the following url.. > > >http://www.nightmare.com/medusa/programming.html > > > The author has the following code for a simple HTTP client > > > #!/usr/bin/python > > > import asyncore > > import socket > > import string > > > class http_client (asyncore.dispatcher): > > > def __init__ (self, host, path): > > asyncore.dispatcher.__init__ (self) > > self.path = path > > self.create_socket (socket.AF_INET, socket.SOCK_STREAM) > > self.connect ((host, 80)) > > > def handle_connect (self): > > self.send ('GET %s HTTP/1.0\r\n\r\n' % self.path) > > > def handle_read (self): > > data = self.recv (8192) > > print data > > > def handle_write (self): > > pass > > > if __name__ == '__main__': > > import sys > > import urlparse > > for url in sys.argv[1:]: > > parts = urlparse.urlparse (url) > > if parts[0] != 'http': > > raise ValueError, "HTTP URL's only, please" > > else: > > host = parts[1] > > path = parts[2] > > http_client (host, path) > > asyncore.loop() > > > Right after that, the author states the following... > > > " A really good way to understand select() is to put a print statement > > into the asyncore.poll() function: > > > [...] > > (r,w,e) = select.select (r,w,e, timeout) > > print '---' > > print 'read', r > > print 'write', w > > [...] > > > Each time through the loop you will see which channels have fired > > which events. > > " > > > How the heck do I modify the code put the print statement into the > > asyncore.poll() function? > > > Chad > > Hi, > > You can find the file in your Python directory, in my case /usr/lib/ > Python2.6/asyncore.py. You should delete the .pyc file to make sure it > is recompiled. And you will need root access :). > > Lucas I just did that... [r...@localhost python2.6]# ls -al asyncore.py -rw-r--r-- 1 root root 19262 Oct 16 10:22 asyncore.py [r...@localhost python2.6]# ls -al asyncore.pyc -rw-r--r-- 1 root root 16773 Oct 16 10:26 asyncore.pyc [r...@localhost python2.6]# ls -al asyncore.pyo -rw-r--r-- 1 root root 16773 Oct 16 10:42 asyncore.pyo [r...@localhost python2.6]# And nothing happened. Ideas? -- http://mail.python.org/mailman/listinfo/python-list
asyncore.poll() question
At the following url.. http://www.nightmare.com/medusa/programming.html The author has the following code for a simple HTTP client #!/usr/bin/python import asyncore import socket import string class http_client (asyncore.dispatcher): def __init__ (self, host, path): asyncore.dispatcher.__init__ (self) self.path = path self.create_socket (socket.AF_INET, socket.SOCK_STREAM) self.connect ((host, 80)) def handle_connect (self): self.send ('GET %s HTTP/1.0\r\n\r\n' % self.path) def handle_read (self): data = self.recv (8192) print data def handle_write (self): pass if __name__ == '__main__': import sys import urlparse for url in sys.argv[1:]: parts = urlparse.urlparse (url) if parts[0] != 'http': raise ValueError, "HTTP URL's only, please" else: host = parts[1] path = parts[2] http_client (host, path) asyncore.loop() Right after that, the author states the following... " A really good way to understand select() is to put a print statement into the asyncore.poll() function: [...] (r,w,e) = select.select (r,w,e, timeout) print '---' print 'read', r print 'write', w [...] Each time through the loop you will see which channels have fired which events. " How the heck do I modify the code put the print statement into the asyncore.poll() function? Chad -- http://mail.python.org/mailman/listinfo/python-list
Re: reference vs. name space question
On Oct 9, 5:52 pm, Steven D'Aprano wrote: > On Sat, 09 Oct 2010 12:44:29 -0700, chad wrote: > > Given the following... > > > [cdal...@localhost oakland]$ python > > Python 2.6.2 (r262:71600, May 3 2009, 17:04:44) [GCC 4.1.1 20061011 > > (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or > > "license" for more information. > >>>> class foo: > > ... x = 1 > > ... y = 2 > > ... > >>>> one = foo() > >>>> two = foo() > >>>> print one > > <__main__.foo instance at 0xb7f3a2ec> > >>>> print two > > <__main__.foo instance at 0xb7f3a16c> > >>>> one.x > > 1 > > > Is 'one' a reference or a name space? Also, in 'one.x'. would 'one' > > be the name space? > > 'one' is a name. Since it is a bound name, it naturally refers to some > object (in this case an instance of foo), which also makes it a reference. > > The object that 'one' is bound to is the namespace. The name itself is > not -- the name itself comes *from* a namespace (in this case the global > namespace). > > However, since people are lazy, and 98% of the time it makes no > difference, and it is long and tedious to say "the object which the name > 'one' is bound to is a namespace", people (including me) will often > shorten that to "'one' is a namespace". But remember that when people use > a name sometimes they're talking about the name itself and sometimes the > object it is bound to: > > > > >>> x = 123 # x applies to the name 'x'. > >>> print x # x applies to the object the name is bound to > 123 > >>> del x # x applies to the name 'x' > > Not all names are references: > > >>> spam > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'spam' is not defined > > Since the name 'spam' is not bound to any object, it is not a reference. > Likewise, given: > > def func(x, y): > pass > > the name 'func' is a name which is bound to a function object. The > function object includes two names 'x' and 'y'. Since they're not bound > to anything, they are not references *yet*, but when you call the > function, they become (temporarily) bound. > > Hope this helps. Maybe I'm being a bit dense, but how something like [cdal...@localhost oakland]$ python Python 2.6.2 (r262:71600, May 3 2009, 17:04:44) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> spam Traceback (most recent call last): File "", line 1, in NameError: name 'spam' is not defined >>> Generate an error, but something like >>> def foo(x, y): ... pass ... >>> Doesn't? I mean, in the first case, 'spam' isn't bound to anything. Likewise, in the second case, both 'x' and 'y' aren't bound to anything. I don't see why the interpreter doesn't complain about 'x' and 'y' not being defined. Chad -- http://mail.python.org/mailman/listinfo/python-list
reference vs. name space question
Given the following... [cdal...@localhost oakland]$ python Python 2.6.2 (r262:71600, May 3 2009, 17:04:44) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class foo: ... x = 1 ... y = 2 ... >>> one = foo() >>> two = foo() >>> print one <__main__.foo instance at 0xb7f3a2ec> >>> print two <__main__.foo instance at 0xb7f3a16c> >>> one.x 1 Is 'one' a reference or a name space? Also, in 'one.x'. would 'one' be the name space? Chad -- http://mail.python.org/mailman/listinfo/python-list
I don't get why sys.exit(1) doesn't exit the while loop in the follow case
Given the following.. #!/usr/bin/python import urllib2 import sys import time while 1: try: con = urllib2.urlopen("http://www.google.com";) data = con.read() print "connected" #The loop doesn't exit if I use sys.exit(1) break except: time.sleep(2) If I would replace 'break' with 'sys.exit(1)', the while loop will keep printing connected every 2 seconds? Why I this? I thought exit meant exit. -- http://mail.python.org/mailman/listinfo/python-list
pattern matching with multiple lists
Greetings, I have some code that I wrote and know there is a better way to write it. I wonder if anyone could point me in the right direction on making this 'cleaner'. I have two lists: liveHostList = [ app11, app12, web11, web12, host11 ] stageHostList = [ web21, web22, host21, app21, app22 ] I need to pair the elements in the list such that: app11 pairs with app21 app12 pairs with app22 web11 pairs with web21 web12 pairs with web22 host11pairs with host21 each time I get the list I don't know the order, and the lists will grow over time. (hosts will be added in pairs. app13 to liveHostList and app23 to stageHostList, etc) Anyways this is what I have. I think it can be written better with map, but not sure. Any help would be appreciated. import re for liveHost in liveHostlist: nameList = list(liveHost) clone = nameList[-1] di = nameList[-2] generic = liveHost[:-2] for stageHost in stageHostList: if re.match( generic + '.' + clone, stageHost ): print "Got a pair: " + stageHost + liveHost Thanks again for any suggestions, Chad -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -- http://mail.python.org/mailman/listinfo/python-list
Re: python namespace question
On Jul 13, 8:37 pm, Steven D'Aprano wrote: > On Tue, 13 Jul 2010 20:03:14 -0700, chad wrote: > > Given the following code... > > > #!/usr/bin/python > > > class cgraph: > > def printme(self): > > print "hello\n" > > > x = cgraph() > > x.printme() > > > Does the function print() exist in the cgraph namespace or the printme() > > one? > > What function print()? You're calling the print STATEMENT. It doesn't > exist in any namespace, it's a Python keyword like "if", "for", "return", > and similar. > > Note: this changes in Python 3, where print becomes a function like > len(), chr(), max(), and similar. In Python 3, you would write: > > print("hello\n") > > and the function lives in the built-in namespace. > > BTW, print (both versions) automatically prints a newline at the end of > the output, so printing "hello\n" will end up with an extra blank line. > Is that what you wanted? > I could care less about the extra blank line. I guess I was just more concerned about the namespace question. -- http://mail.python.org/mailman/listinfo/python-list
python namespace question
Given the following code... #!/usr/bin/python class cgraph: def printme(self): print "hello\n" x = cgraph() x.printme() Does the function print() exist in the cgraph namespace or the printme() one? -- http://mail.python.org/mailman/listinfo/python-list
Re: unique values of a Dictionary list (removing duplicate elements of a list)
On Fri, May 21, 2010 at 8:07 AM, Chad Kellerman wrote: > > > On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__pete...@web.de> wrote: > >> Chad Kellerman wrote: >> >> > Python users, >> > I am parsing an AIX trace file and creating a dictionary >> containing >> > keys (PIDS) and values (a list of TIDS). With PIDS being unique process >> > ids >> > and TIDS, being a list of thread ids. My function populates the keys so >> > that they are unique, but my list contains duplicates. >> > >> > Can someone point me in the right direction so that my dictionary >> > value >> > does not contain duplicate elements? >> > >> > >> > here is what I got. >> > >> > >> > >> > pidtids = {} >> > >> > # --- function to add pid and tid to a dictionary >> > def addpidtids(pid,tid): >> > pidtids.setdefault(pid,[]).append(tid) >> >> Use a set instead of a list (and maybe a defaultdict): >> >> from collections import defaultdict >> >> pidtids = defaultdict(set) >> >> def addpidtids(pid, tid): >>pidtids[pid].add(tid) >> >> Peter >> > > Thanks. I guess I should have posted this in my original question. > > I'm on 2.4.3 looks like defautldict is new in 2.5. > > I'll see if I can upgrade. > > Thanks again. > instead of upgrading.. (probably be faster to use techniques in available 2.4.3) Couldn't I check to see if the pid exists (has_key I believe) and then check if the tid is a value, in the the list for that key, prior to passing it to the function? Or would that be too 'expensive'? > > > >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > A grasshopper walks into a bar and the bartender says "Hey, we have a drink > named after you." And the grasshopper says "Really, You have a drink named > Murray?" > -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -- http://mail.python.org/mailman/listinfo/python-list
Re: unique values of a Dictionary list (removing duplicate elements of a list)
On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__pete...@web.de> wrote: > Chad Kellerman wrote: > > > Python users, > > I am parsing an AIX trace file and creating a dictionary containing > > keys (PIDS) and values (a list of TIDS). With PIDS being unique process > > ids > > and TIDS, being a list of thread ids. My function populates the keys so > > that they are unique, but my list contains duplicates. > > > > Can someone point me in the right direction so that my dictionary > > value > > does not contain duplicate elements? > > > > > > here is what I got. > > > > > > > > pidtids = {} > > > > # --- function to add pid and tid to a dictionary > > def addpidtids(pid,tid): > > pidtids.setdefault(pid,[]).append(tid) > > Use a set instead of a list (and maybe a defaultdict): > > from collections import defaultdict > > pidtids = defaultdict(set) > > def addpidtids(pid, tid): >pidtids[pid].add(tid) > > Peter > Thanks. I guess I should have posted this in my original question. I'm on 2.4.3 looks like defautldict is new in 2.5. I'll see if I can upgrade. Thanks again. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -- http://mail.python.org/mailman/listinfo/python-list
unique values of a Dictionary list (removing duplicate elements of a list)
Python users, I am parsing an AIX trace file and creating a dictionary containing keys (PIDS) and values (a list of TIDS). With PIDS being unique process ids and TIDS, being a list of thread ids. My function populates the keys so that they are unique, but my list contains duplicates. Can someone point me in the right direction so that my dictionary value does not contain duplicate elements? here is what I got. pidtids = {} # --- function to add pid and tid to a dictionary def addpidtids(pid,tid): pidtids.setdefault(pid,[]).append(tid) # --- function to parse a file def grep(pattern, fileObj, include_line_nums=False): r=[] compgrep = re.compile(pattern) for line_num, line in enumerate(fileObj): if compgrep.search(line): info = line.split() p = info[7].lstrip("pid=") t = info[8].lstrip("tid=") addpidtids(p,t) # process trace.int tf = open(tracefile, 'r') grep("cmd=java pid",tf) tf.close() Any help would be greatly appreciated. Thanks, Chad -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -- http://mail.python.org/mailman/listinfo/python-list
How would I do a continuous write over a pipe in the following code...
Given the following #!/usr/bin/python import subprocess as s broadcast = s.Popen("echo test | wall", shell=True,stdout=s.PIPE) out = broadcast.stdout while 1: out broadcast.wait() broadcast.stdout.close() The code only executes once. What I want to do is be able to continuously write over the pipe once it is open. I could put s.Popen() inside the while loop, but that seems a bit too messy. So is there some way to just open the pipe once, and once it is open, just continuously write over it vs just opening and closing the pipe every time? -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial directory search question
On Sep 29, 7:52 pm, chad wrote: > On Sep 29, 7:20 pm, Tim Chase wrote: > > > > What's the sanest way to print out all the files in the directory that > > > start with the underscore? Ie, I just want to list _1, _2, _3, _4. > > > I'd use a string's join() method to combine the results of a > > list-comprehension or generator that filtered the output of > > os.listdir() based on the startswith() method of the strings. > > > Left intentionally oblique and code-free because this sounds a > > bit like a home-work problem. If you're a python coder, that > > should make pretty decent sense and be a one-liner to implement. > > > -tkc > > Okay, sorry for the delay to the response. I got side tracked trying > to stalk, I mean talk to the 59 year old neighbor girl. Anyways, I > couldn't get it to one in one line. Here is what I did... > > % more rec.py > #!/usr/local/bin/python > > import os > import time > > for filename in os.listdir("/usr/bbs/confs/september"): > #stat = os.stat(filename) > if filename.startswith("_"): > print filename > > ./rec.py > _1 > _2 > _3 > _4 > _5 > _6 > _7 > _8 > > It correctly prints out all the files in the directory that start with > an underscore. er *couldn't get it into a one liner*. -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial directory search question
On Sep 29, 7:20 pm, Tim Chase wrote: > > What's the sanest way to print out all the files in the directory that > > start with the underscore? Ie, I just want to list _1, _2, _3, _4. > > I'd use a string's join() method to combine the results of a > list-comprehension or generator that filtered the output of > os.listdir() based on the startswith() method of the strings. > > Left intentionally oblique and code-free because this sounds a > bit like a home-work problem. If you're a python coder, that > should make pretty decent sense and be a one-liner to implement. > > -tkc Okay, sorry for the delay to the response. I got side tracked trying to stalk, I mean talk to the 59 year old neighbor girl. Anyways, I couldn't get it to one in one line. Here is what I did... % more rec.py #!/usr/local/bin/python import os import time for filename in os.listdir("/usr/bbs/confs/september"): #stat = os.stat(filename) if filename.startswith("_"): print filename ./rec.py _1 _2 _3 _4 _5 _6 _7 _8 It correctly prints out all the files in the directory that start with an underscore. -- http://mail.python.org/mailman/listinfo/python-list
Partial directory search question
I have a directory that contains the following login rc sum _1 _2 _3 _4 What's the sanest way to print out all the files in the directory that start with the underscore? Ie, I just want to list _1, _2, _3, _4. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I continue after the error?
On Jun 4, 7:36 pm, Steven D'Aprano wrote: > On Thu, 04 Jun 2009 18:26:49 -0700, chad wrote: > > Let's say I have a list of 5 files. Now lets say that one of the files > > reads nude333.txt instead of nude3.txt. When this happens, the program > > generates an error and quits. What I want it to do is just skip over the > > bad file and continue on with the next one. > > This should give you some hints. > > import errno > > for name in list_of_file_names: > try: > f = open(name, 'r') > except IOError, e: > if e.errno == errno.ENOENT: # or just use 2 if you're lazy > # no such file, skip > continue > # some other more serious error, re-raise the exception > raise > do_something_with(f) > > [...] > > > def scroll_some_porn(now): > > while 1: > > for some_titty_porn in my_porn_collection: > > now.write(" \n") > > bitch_please = generate(some_titty_porn) > > now.write(bitch_please) > > time.sleep(10) > > now.write(" \n") > > Shouldn't you have some way of escaping from the infinite loop other than > typing Ctrl-C at the console? I imagine your hands will be busy. > Like what? All the program is meant to do is scroll ASCII art in a chat room. -- http://mail.python.org/mailman/listinfo/python-list
How do I continue after the error?
Let's say I have a list of 5 files. Now lets say that one of the files reads nude333.txt instead of nude3.txt. When this happens, the program generates an error and quits. What I want it to do is just skip over the bad file and continue on with the next one. Below is the actual code. It only works on the local bbs that I hang out on. Sorry. I couldn't think of the simple case that could isolate my problem. #!/usr/bin/python #The original code was written by Mr.Pardue, which sounds a lot like #fuck you import telnetlib, os import time import glob my_porn_collection = ["nude.txt", "nude2.txt", "nude333.txt", "nude4.txt", "nude5.txt"] path = 'porn/' #my_porn_collection = [] def get_files(): for infile in glob.glob( os.path.join(path, '*.txt*')): my_porn_collection.append(infile) def generate(some_naked_bitches): try: f = open(some_naked_bitches, "r") except: pass art = f.read() f.close() return art def get_name(): user = raw_input("\nUsername: ") password = raw_input("Password: ") enter_party(user, password) def enter_party(user, password): now = telnetlib.Telnet("m-net.arbornet.org") now.read_until("login: ") print "\nEntered username.." now.write(user + "\n") now.read_until("Password:") now.write(password + "\n" ) print "Entered pass.." now.read_until("m-net%") now.write("party\n") print "Entered into party.." scroll_some_porn(now) def scroll_some_porn(now): while 1: for some_titty_porn in my_porn_collection: now.write(" \n") bitch_please = generate(some_titty_porn) now.write(bitch_please) time.sleep(10) now.write(" \n") if __name__ == "__main__": #get_files() get_name() -- http://mail.python.org/mailman/listinfo/python-list
Re: morning in Python
On Fri, May 16, 2008 at 2:54 PM, Dan Upton <[EMAIL PROTECTED]> wrote: > On Fri, May 16, 2008 at 2:12 PM, inhahe <[EMAIL PROTECTED]> wrote: > > > > "George Sakkis" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > > On May 16, 11:58 am, "inhahe" <[EMAIL PROTECTED]> wrote: > >> I'm not an expert in this but what does it mean to emphasize state? It > >> seems the opposite of that would be a) functional programming, and b) > >> passing parameters instead of using global or relatively local > variables. > >> And maybe c) coroutines (generators as implemented in Python), although > >> perhaps coroutines could be said to emphasize state inasmuch as they go > >> out > >> of their way to capture, objectify and reuse it (Stackless' > microthreads, > >> even moreso). And Python seems to be well-noted for implementing some > >> functional programming methodology, and as for passing parameters it's > >> just > >> as object-oriented as the rest of them. > >> > >> But as I said, I'm not an expert, so let me know if I've gone astray.. > >> > >> > I have a proposition to ask you all: Python emphasizes state. Is it > >> > true? > > > > Please don't feed the bots. > > > > -- > > > > > > I figured the question was interesting enough to warrant discussion > whether > > it was a bot or not. But i'm not an avid forum user, so maybe I'm wrong. > > > > Also, if it's a bot I'm floored and the man who wrote it could probably > > solve cancer and world hunger with five lines of asm. > > > > Yeah... when he/she/it first appeared the replies were at least mostly > lucid, if not necessarily helpful, and spawned a few interesting > discussions. Recently it's gone downhill... Could be some sort of bot > that was trying to learn 'speech' patterns and it overloaded its > database. (I've seen that happen on at least one chatbot...) > -- > http://mail.python.org/mailman/listinfo/python-list > I am trying to filter out this bot via my gmail account but what ends up happening is that any thread it posts ends up being deleted instead of just its individual posts. Does anyone know how to filter out just a specific user in gmail thread view? Thanks, Chad -- http://mail.python.org/mailman/listinfo/python-list
Re: IDE for Python
On Fri, May 16, 2008 at 11:33 AM, Jonathan Barbero < [EMAIL PROTECTED]> wrote: > Hi! > > I´m newbie with Python and to learn it better I want to use a good IDE to > concentrate on Python power. There is any IDE like Eclipse for Java for > Python? If not, what is the best Python´s IDE for you? > > Thanks, > >Jonathan. > > -- > http://mail.python.org/mailman/listinfo/python-list > Jonathan, PyDev is a Python plugin for Eclipse, here is a link to its SourceForge site: http://sourceforge.net/projects/pydev Chad -- http://mail.python.org/mailman/listinfo/python-list
Re: GeneratorExit should derive from BaseException, not Exception
Oops, forgot to mention this: I wouldn't be opposed to a different extension that would effectively let me accomplish the same goals... arbitrary exception filters. Imagine this: try: raise GeneratorExit except ExceptionFilter: # blah where ExceptionFilter is any object that can be tested for containment. Perhaps implemented like this: class ExceptionFilter(object): def __init__(self): self.includes = set() self.excludes = set() self.include = self.includes.add self.exclude = self.excludes.add def __contains__(self, exc): return any(isinstance(exc, cls) for cls in self.includes) and \ not any(isinstance(exc, cls) for cls in self.excludes) ImvuExceptionFilter = ExceptionFilter() ImvuExceptionFilter.include(Exception) ImvuExceptionFilter.exclude(GeneratorExit) Then, our code could just "catch" ImvuExceptionFilter. This type of extension would be backwards compatible with the current except (FooError, BarError) tuple syntax. I've never hacked on CPython itself, so I don't know what kind of changes there would be involved, but if there is sufficient pushback against making GeneratorExit derive from BaseException, I think this is a fine alternative. Thoughts? Chad Chad Austin wrote: > Hi Terry, > > Thank you for your feedback. Responses inline: > > Terry Reedy wrote: >> "Chad Austin" <[EMAIL PROTECTED]> wrote in message >> news:[EMAIL PROTECTED] >> || try: >> | result = yield chatGateway.checkForInvite({'userId': userId}) >> | logger.info('checkForInvite2 returned %s', result) >> >> would not >> except GeneratorExit: >> solve your problem? > > Yes, we could add an "except GeneratorExit: raise" clause to every place > we currently catch Exception, but I feel like this is one of those > things where it's hard to get it right in all places and also hard to > cover with unit tests. Instead, we'll have subtle bugs where finally > clauses don't run because the GeneratorExit was swallowed. > > Also, SystemExit and KeyboardInterrupt were made into BaseExceptions for > the same reasons as I'm giving. (As I understand it, anyway.) > >> | except Exception: >> >> Such catchalls are known to be prone to catch too much >> and are therefore not encouraged ;-). >> As in 'use at your own risk'. >> Guido encourages specific catches just for the reasons you give here. > > More below: > >> There was a *long* discussion of the current 2.5 exception hierarchy on >> pydev. Search either python.org's or gmane's archive if you want to pursue >> this. But I expect the people involved would say much the same as above. > > I've actually read the background on the exception hierarchy (and agree > with it all), especially other suggestions that GeneratorExit derive > from BaseException. As I understand it, Guido's objections are threefold: > > 1) The previous "generators as coroutines" examples were too > theoretical: I've wanted GeneratorExit to derive from BaseException for > months now, but didn't write this proposal until I actually wrote code > that failed in the presence of task cancellation. > > 2) You should avoid catching everything with except Exception: I think > that's too idealistic. Just do a search for try: except: through > publicly available Python. :) Sometimes, you really _do_ want to catch > everything. When you're making a network request that involves > xmlrpclib, urllib2, httplib, etc. you don't actually care what the error > was. (Well, except that the exceptions are submitted for automated > analysis.) Similarly, when loading a cache file with pickle, I don't > care what went wrong, because it's not critical and should not be turned > into a crash for the user. (We automatically report exceptions that > bubble into the main loop as crashes.) > > 3) If GeneratorExit escapes from the generator somehow and gets raised > in the main loop, then it will bubble out of the application like > SystemExit and KeyboardInterrupt would: I think this argument is > somewhat specious, because I can't imagine how that would happen. You'd > have to store exceptions in your generator and explicitly bubble them > out somehow. Our crash handling has to specially handle > KeyboardInterrupt and SystemExit anyway, since there are currently > non-Exception exceptions, such as strings and custom classes tha
Re: GeneratorExit should derive from BaseException, not Exception
Hi Terry, Thank you for your feedback. Responses inline: Terry Reedy wrote: > "Chad Austin" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > || try: > | result = yield chatGateway.checkForInvite({'userId': userId}) > | logger.info('checkForInvite2 returned %s', result) > > would not > except GeneratorExit: > solve your problem? Yes, we could add an "except GeneratorExit: raise" clause to every place we currently catch Exception, but I feel like this is one of those things where it's hard to get it right in all places and also hard to cover with unit tests. Instead, we'll have subtle bugs where finally clauses don't run because the GeneratorExit was swallowed. Also, SystemExit and KeyboardInterrupt were made into BaseExceptions for the same reasons as I'm giving. (As I understand it, anyway.) > | except Exception: > > Such catchalls are known to be prone to catch too much > and are therefore not encouraged ;-). > As in 'use at your own risk'. > Guido encourages specific catches just for the reasons you give here. More below: > There was a *long* discussion of the current 2.5 exception hierarchy on > pydev. Search either python.org's or gmane's archive if you want to pursue > this. But I expect the people involved would say much the same as above. I've actually read the background on the exception hierarchy (and agree with it all), especially other suggestions that GeneratorExit derive from BaseException. As I understand it, Guido's objections are threefold: 1) The previous "generators as coroutines" examples were too theoretical: I've wanted GeneratorExit to derive from BaseException for months now, but didn't write this proposal until I actually wrote code that failed in the presence of task cancellation. 2) You should avoid catching everything with except Exception: I think that's too idealistic. Just do a search for try: except: through publicly available Python. :) Sometimes, you really _do_ want to catch everything. When you're making a network request that involves xmlrpclib, urllib2, httplib, etc. you don't actually care what the error was. (Well, except that the exceptions are submitted for automated analysis.) Similarly, when loading a cache file with pickle, I don't care what went wrong, because it's not critical and should not be turned into a crash for the user. (We automatically report exceptions that bubble into the main loop as crashes.) 3) If GeneratorExit escapes from the generator somehow and gets raised in the main loop, then it will bubble out of the application like SystemExit and KeyboardInterrupt would: I think this argument is somewhat specious, because I can't imagine how that would happen. You'd have to store exceptions in your generator and explicitly bubble them out somehow. Our crash handling has to specially handle KeyboardInterrupt and SystemExit anyway, since there are currently non-Exception exceptions, such as strings and custom classes that forgot to derive from Exception, that should count as crashes. I personally can't think of any cases where I would _want_ to handle GeneratorExit. I just want finally: and with: clauses to do the right thing when a task is cancelled. Anyway, I haven't yet encountered any serious bugs due to this yet... I'm just worried that if a task is holding some resource and blocking on something, then the resource won't get released. If this really does come up, then I do have a little bit of python + ctypes that replaces GeneratorExit with ImvuGeneratorExit (deriving from BaseException), but that's not very appealing. Thanks again, -- Chad Austin http://imvu.com/technology -- http://mail.python.org/mailman/listinfo/python-list
GeneratorExit should derive from BaseException, not Exception
Hi all, First, I'd like to describe a system that we've built here at IMVU in order to manage the complexity of our network- and UI-heavy application: Our application is a standard Windows desktop application, with the main thread pumping Windows messages as fast as they become available. On top of that, we've added the ability to queue arbitrary Python actions in the message pump so that they get executed on the main thread when its ready. You can think of our EventPump as being similar to Twisted's reactor. On top of the EventPump, we have a TaskScheduler which runs "tasks" in parallel. Tasks are generators that behave like coroutines, and it's probably easiest to explain how they work with an example (made up on the spot, so there may be minor typos): def openContentsWindow(contents): # Imagine a notepad-like window with the URL's contents... # ... @threadtask def readURL(url): return urllib2.urlopen(url).read() @task def displayURL(url): with LoadingDialog(): # blocks this task from running while contents are being downloaded, but does not block # main thread because readURL runs in the threadpool. contents = yield readURL(url) openContentsWindow(contents) A bit of explanation: The @task decorator turns a generator-returning function into a coroutine that is run by the scheduler. It can call other tasks via "yield" and block on network requests, etc. All blocking network calls such as urllib2's urlopen and friends and xmlrpclib ServerProxy calls go behind the @threadtask decorator. This means those functions will run in the thread pool and allow other ready tasks to execute in the meantime. There are several benefits to this approach: 1) The logic is very readable. The code doesn't have to go through any hoops to be performant or correct. 2) It's also very testable. All of the threading-specific logic goes into the scheduler itself, which means our unit tests don't need to deal with any (many?) thread safety issues or races. 3) Exceptions bubble correctly through tasks, and the stack traces are what you would expect. 4) Tasks always run on the main thread, which is beneficial when you're dealing with external objects with thread-affinity, such as Direct3D and Windows. 5) Unlike threads, tasks can be cancelled. ANYWAY, all advocacy aside, here is one problem we've run into: Imagine a bit of code like this: @task def pollForChatInvites(chatGateway, userId, decisionCallback, startChatCallback, timeProvider, minimumPollInterval = 5): while True: now = timeProvider() try: result = yield chatGateway.checkForInvite({'userId': userId}) logger.info('checkForInvite2 returned %s', result) except Exception: logger.exception('checkForInvite2 failed') result = None # ... yield Sleep(10) This is real code that I wrote in the last week. The key portion is the try: except: Basically, there are many reasons the checkForInvite2 call can fail. Maybe a socket.error (connection timeout), maybe some kind of httplib error, maybe an xmlrpclib.ProtocolError... I actually don't care how it fails. If it fails at all, then sleep for a while and try again. All fine and good. The problem is that, if the task is cancelled while it's waiting on checkForInvite2, GeneratorExit gets caught and handled rather than (correctly) bubbling out of the task. GeneratorExit is similar in practice to SystemExit here, so it would make sense for it to be a BaseException as well. So, my proposal is that GeneratorExit derive from BaseException instead of Exception. p.s. Should I have sent this mail to python-dev directly? Does what I'm saying make sense? Does this kind of thing need a PEP? -- Chad Austin http://imvu.com/technology -- http://mail.python.org/mailman/listinfo/python-list
Question about Tkinter MenuOption variable
Is there anyway to set the individual options in Tkinter to a particular variable. For example, I have a menu option(code is below) which has January, February, March and so on, which I would like to have corresponding values of 01, 02, 03 and so on. Can someone please tell me how to do that within the context of the code I have below - or even totally modify it if you must. Label(self, text = "Month" ).grid(row = 5, column = 1, sticky = W) OPTIONS = [ "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"] default_option = StringVar(self) default_option.set(OPTIONS[0]) self.month_option = OptionMenu(self, default_option, *OPTIONS) self.month_option.grid(row = 5, column = 2, sticky = W) -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with the get() method of a Text entry
On Apr 12, 5:03 pm, James Stroud <[EMAIL PROTECTED]> wrote: > James Stroud wrote: > > Chad wrote: > > >> I have a simple little program that brings up asks the user to enter a > >> note, then is supposed to place that note into a text file when the > >> user hits the submit button. However, when the user hits the submit > >> button, absolutely nothing happens. IDLE doesn't give an error > >> message and the note is not entered into the text file. For > >> troubleshooting puposes, I wanted to see if IDLE would at least print > >> the user's input; it doesn't do that either. Can someone please help > >> me? > > >> Here is the code: > > >> from Tkinter import * > > >> class Application(Frame): > >> """ GUI application that creates a story based on user input. """ > >> def __init__(self, master): > >> """ Initialize Frame. """ > >> Frame.__init__(self, master) > >> self.grid() > >> self.create_widgets() > > >> def create_widgets(self): > >> """ Create widgets to get note information. """ > >> # create instruction label and text entry for notes > >> Label(self, > >> text = "Notes" > >> ).grid(row = 0, column = 0, columnspan = 2 ) > > >> self.notes_ent = Text(self, width = 75, height = 10, wrap = > >> WORD) > >> self.notes_ent.grid(row = 2, column = 0 ,columnspan = 7, > >> rowspan = 3, sticky = W) > >> create submit button > >> text1 = StringVar(self) > >> text1 = self.notes_ent.get(1.0, END) > >> self.notes_ent.config(state=NORMAL) > >> Button(self, > >> text = "Add Note", > >> command = self.add_note(text1) > >>).grid(row = 1, column = 0, sticky = W) > > >> def add_note(self, text1): > >> print text1 > >> text_file = open("write_it.txt", "a+") > >> text_file.write(text1) > > >> root = Tk() > >> root.title("Mad Lib") > >> app = Application(root) > >> root.mainloop() > > > On second look, it seems you have deeper problems, some of which are: > > > > text1 = StringVar(self) > > > text1 = self.notes_ent.get(1.0, END) > > > You obviously added the second because the first will never work. Get > > rid of both lines. Even if you intended the second, it immediately > > nullifies the first. Instead of my previous suggestions, do this: > > > 1. delete both "text1 =" lines > > 2. change "command = self.add_note(text1)" to > > "command = self.add_note" > > 3. change "def add_note(self, text1):" to > > "def add_note(self):" > > 4. delete "print text1" > > 5. change "text_file.write(text1)" to > >"text_file.notes_ent.get(1.0, END) > > > James > > Or rather > 5. change "text_file.write(text1)" to > "text_file.write(self.notes_ent.get(1.0, END))" Thank you, that worked very well. -- http://mail.python.org/mailman/listinfo/python-list
Need help with the get() method of a Text entry
I have a simple little program that brings up asks the user to enter a note, then is supposed to place that note into a text file when the user hits the submit button. However, when the user hits the submit button, absolutely nothing happens. IDLE doesn't give an error message and the note is not entered into the text file. For troubleshooting puposes, I wanted to see if IDLE would at least print the user's input; it doesn't do that either. Can someone please help me? Here is the code: from Tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): """ Initialize Frame. """ Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get note information. """ # create instruction label and text entry for notes Label(self, text = "Notes" ).grid(row = 0, column = 0, columnspan = 2 ) self.notes_ent = Text(self, width = 75, height = 10, wrap = WORD) self.notes_ent.grid(row = 2, column = 0 ,columnspan = 7, rowspan = 3, sticky = W) create submit button text1 = StringVar(self) text1 = self.notes_ent.get(1.0, END) self.notes_ent.config(state=NORMAL) Button(self, text = "Add Note", command = self.add_note(text1) ).grid(row = 1, column = 0, sticky = W) def add_note(self, text1): print text1 text_file = open("write_it.txt", "a+") text_file.write(text1) root = Tk() root.title("Mad Lib") app = Application(root) root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads and signals
By writing a little C module I fixed the problem. By simply calling the function in the child thrd's run method, things work as expected. This is all the function (blockall) does: sigset_t omask, nmask; sigfillset(&nmask); sigprocmask(SIG_SETMASK, &nmask, NULL); bash-2.05b# python2.5 ./thrd_test.py Starting up MainThread.run(): 71799 ChildThread.run(): 71799 ChildThread before sleep(10) MainThread before sleep(15) ^CReceived signal 2 flag: True flag: False MainThread after sleep(15) Shutting down bash-2.05b# Chad > I've run into an "opportunity" in a Python application using threads > and signals. Basically, there is a main process that spawns off a child > thread that loops forever. In between iterations, the child > thread sleeps for X seconds. All the while, the main thread loops > forever doing its thing and also sleeps in between iterations (see the code > at > the end this message). Normally the application would > be daemonized before the main process starts up. Hence, during a > system shutdown or stoppage of the daemon, it's desired that the > daemon catch a few signals (TERM/INT) and perform a few cleanup > routines. According to the Python docs, only the main thread will receive > signals. The problem I have, on FreeBSD systems, is that the sleep > function in the child gets interrupted and the signal never gets handled > until the main thread's sleep concludes. It works as expected on a Linux > box (main thrd's sleep is interrupted). Sample output from multiple systems > is directly below. > > Just looking for insight from others in the know. > > Thanks, > Chad > > > Linux 2.6.17 > > test_bed$ python2.5 ./thrd_test.py > Starting up > MainThread.run(): 14332 > MainThread before sleep(15) > ChildThread.run(): 14332 > ChildThread before sleep(10) > Received signal 2<-- Interrupted here (Ctrl-C), correctly > flag: Trueinterrupts sleep in main thread > flag: False > MainThread after sleep(15) > Shutting down > > test_bed$ python2.4 ./thrd_test.py > Starting up > MainThread.run(): 14338 > MainThread before sleep(15) > ChildThread.run(): 14338 > ChildThread before sleep(10) > Received signal 2 <-- Interrupted here (Ctrl-C), correctly > flag: Trueinterrupts sleep in main thread > flag: False > MainThread after sleep(15) > Shutting down > test_bed$ > > FreeBSD 4.11, 6.1, and 6.2 > > bash-2.05b# python2.5 ./thrd_test.py > Starting up > MainThread.run(): 65930 > ChildThread.run(): 65930 > ChildThread before sleep(10) > MainThread before sleep(15) > ^CChildThread after sleep(10) <-- Interrupted here (Ctrl-C), but > ChildThread before sleep(10) interrupts the child thrd's sleep > ChildThread after sleep(10) > ChildThread before sleep(10) > Received signal 2<-- Main sleep concludes and > then > flag: True the signal gets handled > flag: False > MainThread after sleep(15) > Shutting down > bash-2.05b# > > > #--- CODE BEGIN ---# > > #!/usr/bin/env python > > import os > import sys > import time > import signal > import threading > > def sigHandle(signo, stkframe): >print "Received signal ", signo >print "flag: ", mthrd.flag.isSet() >mthrd.flag.clear() >print "flag: ", mthrd.flag.isSet() > > class ChildThread(threading.Thread): > >def __init__(self): >threading.Thread.__init__(self) > >def run(self): >print "ChildThread.run(): ", os.getpid() mymod.blockall() >while (True): >print "ChildThread before sleep(10)" >time.sleep(10) >print "ChildThread after sleep(10)" > > class MainThread(object): > >def __init__(self): >self.flag = threading.Event() >self.cthrd = ChildThread() >self.cthrd.setDaemon(True) > >def run(self): >print "MainThread.run(): ", os.getpid() >self.flag.wait() >self.cthrd.start() >while (self.flag.isSet()): >print "MainThread before sleep(15)" >time.sleep(15) >print "MainThread after sleep(15)" >return# or cleanup routine > > if __name__ == "__main__": > ># Normally, the process is daemonized first. That's been ># left out for testing purposes. > >signal.signal(signal.SIGINT, sigHandle) >signal.signal(signal.SIGQUIT, sigHandle) >signal.signal(signal.SIGTERM, sigHandle) > >mthrd = MainThread() >print "Starting up" >mthrd.flag.set() >mthrd.run() >print "Shutting down" > >sys.exit(0) > > #--- CODE END ---# -- http://mail.python.org/mailman/listinfo/python-list
Threads and signals
I've run into an "opportunity" in a Python application using threads and signals. Basically, there is a main process that spawns off a child thread that loops forever. In between iterations, the child thread sleeps for X seconds. All the while, the main thread loops forever doing its thing and also sleeps in between iterations (see the code at the end this message). Normally the application would be daemonized before the main process starts up. Hence, during a system shutdown or stoppage of the daemon, it's desired that the daemon catch a few signals (TERM/INT) and perform a few cleanup routines. According to the Python docs, only the main thread will receive signals. The problem I have, on FreeBSD systems, is that the sleep function in the child gets interrupted and the signal never gets handled until the main thread's sleep concludes. It works as expected on a Linux box (main thrd's sleep is interrupted). Sample output from multiple systems is directly below. Just looking for insight from others in the know. Thanks, Chad Linux 2.6.17 test_bed$ python2.5 ./thrd_test.py Starting up MainThread.run(): 14332 MainThread before sleep(15) ChildThread.run(): 14332 ChildThread before sleep(10) Received signal 2<-- Interrupted here (Ctrl-C), correctly flag: Trueinterrupts sleep in main thread flag: False MainThread after sleep(15) Shutting down test_bed$ python2.4 ./thrd_test.py Starting up MainThread.run(): 14338 MainThread before sleep(15) ChildThread.run(): 14338 ChildThread before sleep(10) Received signal 2 <-- Interrupted here (Ctrl-C), correctly flag: Trueinterrupts sleep in main thread flag: False MainThread after sleep(15) Shutting down test_bed$ FreeBSD 4.11, 6.1, and 6.2 bash-2.05b# python2.5 ./thrd_test.py Starting up MainThread.run(): 65930 ChildThread.run(): 65930 ChildThread before sleep(10) MainThread before sleep(15) ^CChildThread after sleep(10) <-- Interrupted here (Ctrl-C), but ChildThread before sleep(10) interrupts the child thrd's sleep ChildThread after sleep(10) ChildThread before sleep(10) Received signal 2<-- Main sleep concludes and then the flag: True signal gets handled flag: False MainThread after sleep(15) Shutting down bash-2.05b# #--- CODE BEGIN ---# #!/usr/bin/env python import os import sys import time import signal import threading def sigHandle(signo, stkframe): print "Received signal ", signo print "flag: ", mthrd.flag.isSet() mthrd.flag.clear() print "flag: ", mthrd.flag.isSet() class ChildThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): print "ChildThread.run(): ", os.getpid() while (True): print "ChildThread before sleep(10)" time.sleep(10) print "ChildThread after sleep(10)" class MainThread(object): def __init__(self): self.flag = threading.Event() self.cthrd = ChildThread() self.cthrd.setDaemon(True) def run(self): print "MainThread.run(): ", os.getpid() self.flag.wait() self.cthrd.start() while (self.flag.isSet()): print "MainThread before sleep(15)" time.sleep(15) print "MainThread after sleep(15)" return# or cleanup routine if __name__ == "__main__": # Normally, the process is daemonized first. That's been # left out for testing purposes. signal.signal(signal.SIGINT, sigHandle) signal.signal(signal.SIGQUIT, sigHandle) signal.signal(signal.SIGTERM, sigHandle) mthrd = MainThread() print "Starting up" mthrd.flag.set() mthrd.run() print "Shutting down" sys.exit(0) #--- CODE END ---# -- http://mail.python.org/mailman/listinfo/python-list
Re: clearerr called on NULL FILE* ?
Sorry to respond to myself; I wanted to give an update on this crash. It turns out it's a race condition with multiple threads accessing the same Python file object! http://sourceforge.net/tracker/index.php?func=detail&aid=595601&group_id=5470&atid=105470 Python-dev thread at http://mail.python.org/pipermail/python-dev/2003-June/036537.html I wrote about the experience at http://aegisknight.livejournal.com/128191.html. I agree that our program was incorrect to be writing to a log on one thread while it rotated them on another, but it'd be nice to get an exception that unambiguously shows what's going on rather than having random crashes reported in the field. Chad Chad Austin wrote: > Hi all, > > My first post to the list. :) I'm debugging one of our application > crashes, and I thought maybe one of you has seen something similar > before. Our application is mostly Python, with some work being done in > a native C++ module. Anyway, I'm getting a memory access violation at > the following stack: > > > CRASHING THREAD > EXCEPTION POINTERS: 0x0012e424 > ExceptionRecord: 0x0012e518 > ExceptionCode: 0xc005 EXCEPTION_ACCESS_VIOLATION > ExceptionFlags: 0x > ExceptionAddress: 0x7c901010 > NumberParameters: 2 > ExceptionInformation[0]: 0x > ExceptionInformation[1]: 0x0034 > ExceptionRecord: 0x > > THREAD ID: 10b0frame count: 4 > PYTHON23!0x000baa00 - PyFile_Type > PYTHON23!0x0003ac27 - PyFile_SetEncoding >MSVCRT!0x00030a06 - clearerr > ntdll!0x1010 - RtlEnterCriticalSection > > > Here's my understanding: something is getting called on a PyFileObject > where f_fp is NULL, and clearerr in the multithreaded runtime tries to > enter an invalid critical section. It looks like PyFile_SetEncoding in > the stack, but I can't figure out how in the Python source how > SetEncoding calls clearerr. > > Based on the timing of the crashes, I also think it might have something > to do with log rollovers in RotatingFileHandler. > > Has anyone run into something similar? I don't expect anyone to spend a > lot of time on this, but if there are any quick tips, they would be > greatly appreciated... > > We're using Python 2.3.5 and Visual C++ 6. > > -- > Chad Austin > http://imvu.com/technology > -- http://mail.python.org/mailman/listinfo/python-list
clearerr called on NULL FILE* ?
Hi all, My first post to the list. :) I'm debugging one of our application crashes, and I thought maybe one of you has seen something similar before. Our application is mostly Python, with some work being done in a native C++ module. Anyway, I'm getting a memory access violation at the following stack: CRASHING THREAD EXCEPTION POINTERS: 0x0012e424 ExceptionRecord: 0x0012e518 ExceptionCode: 0xc005 EXCEPTION_ACCESS_VIOLATION ExceptionFlags: 0x ExceptionAddress: 0x7c901010 NumberParameters: 2 ExceptionInformation[0]: 0x ExceptionInformation[1]: 0x0034 ExceptionRecord: 0x THREAD ID: 10b0frame count: 4 PYTHON23!0x000baa00 - PyFile_Type PYTHON23!0x0003ac27 - PyFile_SetEncoding MSVCRT!0x00030a06 - clearerr ntdll!0x1010 - RtlEnterCriticalSection Here's my understanding: something is getting called on a PyFileObject where f_fp is NULL, and clearerr in the multithreaded runtime tries to enter an invalid critical section. It looks like PyFile_SetEncoding in the stack, but I can't figure out how in the Python source how SetEncoding calls clearerr. Based on the timing of the crashes, I also think it might have something to do with log rollovers in RotatingFileHandler. Has anyone run into something similar? I don't expect anyone to spend a lot of time on this, but if there are any quick tips, they would be greatly appreciated... We're using Python 2.3.5 and Visual C++ 6. -- Chad Austin http://imvu.com/technology -- http://mail.python.org/mailman/listinfo/python-list
Re: newb ?
Mensanator, Thanks for your help. That should get me along. I appreciate your time. Chad <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > Chad Everett wrote: >> Hey guys, >> >> I am back. Trying to expand on a program that was given in the book I >> am >> studying. >> >> No I am not a high school or college student. Doing this on my own. and >> having way to much trouble >> >> I am trying to add a hint section to a word jumble program. >> >> I get a traceback error that the word in the jumble is not defined. >> Can anyone help? > > You have several errors. > >> thanks, >> >> import random >> >> # create a sequence of words to choose from >> WORDS = ("python", "easy") >> # pick one word randomly from the sequence >> word = random.choice(WORDS) >> # create a variable to use later to see if the guess is correct >> correct = word >> # create variable to use for hint if needed > > You didn't create a variable here. Something like > > hint = "hint" > > And this is the core of your problems. You are confusing a > variable name with the value assigned to it. > > >> # create a jumbled version of the word >> jumble ="" >> while word: >> position = random.randrange(len(word)) >> jumble += word[position] >> word = word[:position] + word[(position + 1):] >> >> # start the game >> print \ >> """ >>Welcome to Word Jumble! >> >>Unscramble the letters to make a word. >> (Press the enter key at the prompt to quit.) >> """ >> print "The jumble is:", jumble >> print "If you need a hint type 'hint' and Hit enter." > > Here you have specifically told the user that the hint word is "hint". > >> >> guess = raw_input("\nYour guess: ") >> guess = guess.lower() >> while (guess != correct) and (guess != "")and (guess != hint): ##not sure >> about this either## > > It will fail because you did not define the hint variable. > Note you actually don't need a hint variable (because the > hint word never changes), you could have said > > ... and (guess != "hint") > > whereas (guess != correct) needs to compare against a variable > because correct does change. > >> print "Sorry, that's not it." >> guess = raw_input("Your guess: ") >> guess = guess.lower() >> >> >> ###I don"t lnow how to set up this part correct so that when they ask for >> the hint it will give it to them### >> >> >> while word == easy: > > Same problem here, easy is a variable (which you haven't defined). > What you meant to say was > > while word == "easy": > > >> if guess == hint: >> print "not hard but" >> guess = raw_input("Your guess: ") >> guess = guess.lower() >> >> while word == python: > > Ditto. But this is going to get tedious when your word list gets large. > You should have your words and their hints stored in a dictionary: > > hints = {'easy':'not hard but','python':'snake'} > > then you need just a single code block that can print the hint > by using the correct word to look up the hint in the dictionary. > > if guess == hint: > print hints[correct] > guess = raw_input("Your guess: ") > guess = guess.lower() >> >> if guess == correct: >> print "That's it! You guessed it!\n" >> >> print "Thanks for playing." >> >> raw_input("\n\nPress the enter key to exit.") > -- http://mail.python.org/mailman/listinfo/python-list
newb ?
Hey guys, I am back. Trying to expand on a program that was given in the book I am studying. No I am not a high school or college student. Doing this on my own. and having way to much trouble I am trying to add a hint section to a word jumble program. I get a traceback error that the word in the jumble is not defined. Can anyone help? thanks, import random # create a sequence of words to choose from WORDS = ("python", "easy") # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word # create variable to use for hint if needed # create a jumbled version of the word jumble ="" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] # start the game print \ """ Welcome to Word Jumble! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) """ print "The jumble is:", jumble print "If you need a hint type 'hint' and Hit enter." guess = raw_input("\nYour guess: ") guess = guess.lower() while (guess != correct) and (guess != "")and (guess != hint): ##not sure about this either## print "Sorry, that's not it." guess = raw_input("Your guess: ") guess = guess.lower() ###I don"t lnow how to set up this part correct so that when they ask for the hint it will give it to them### while word == easy: if guess == hint: print "not hard but" guess = raw_input("Your guess: ") guess = guess.lower() while word == python: if guess == hint: print "snake" guess = raw_input("Your guess: ") guess = guess.lower() if guess == correct: print "That's it! You guessed it!\n" print "Thanks for playing." raw_input("\n\nPress the enter key to exit.") -- http://mail.python.org/mailman/listinfo/python-list
Socket Error
Does anyone know why you get socket error while trying to run IDLE and the module. Is says something about a Subprocess Startup Error. I know that it always says something about a personal firewall. I have all that shut off. About 50% of the time when I try and test code by running the module it will pop up. Any suggestions? thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: Newb ?
Hey guys, Thanks for the hint. I found that info last night but I could never get it to print more than just the last letter. or it would only print partially. I was using just a single colon, the double colon did it. Thanks "Chad Everett" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hello all, > > Have a problem here with a challenge from a book I am reading. > Any help is much appreciated. > > I am trying to run a program that asks the user for a statement and then > prints it out backwards. > this is what I have. > It does not print anything out. I assume that I have something out of > whack with my high and low statements. > > Thanks for you help. > > > print "\n\nWelcome to the Backwards Message Display." > print > message = raw_input("\nPlease Enter a Message.") > > high = len(message) > low = -len(message) > print > print message[high:low] > print > print raw_input("Please Press Enter to Exit") > -- http://mail.python.org/mailman/listinfo/python-list
Re: Newb ?
"Paul Watson" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Chad Everett wrote: >> Hello all, >> >> Have a problem here with a challenge from a book I am reading. >> Any help is much appreciated. >> >> I am trying to run a program that asks the user for a statement and then >> prints it out backwards. >> this is what I have. >> It does not print anything out. I assume that I have something out of >> whack with my high and low statements. >> >> Thanks for you help. >> >> >> print "\n\nWelcome to the Backwards Message Display." >> print >> message = raw_input("\nPlease Enter a Message.") >> >> high = len(message) >> low = -len(message) >> print >> print message[high:low] >> print >> print raw_input("Please Press Enter to Exit") > > Are you sure that this is not a class assignment? You can search the > messages here for the answer. No, I have been out of school way too long. I am 34 trying to learn a new trade. I searched the group for the term backwards but I did not get any results. -- http://mail.python.org/mailman/listinfo/python-list
Newb ?
Hello all, Have a problem here with a challenge from a book I am reading. Any help is much appreciated. I am trying to run a program that asks the user for a statement and then prints it out backwards. this is what I have. It does not print anything out. I assume that I have something out of whack with my high and low statements. Thanks for you help. print "\n\nWelcome to the Backwards Message Display." print message = raw_input("\nPlease Enter a Message.") high = len(message) low = -len(message) print print message[high:low] print print raw_input("Please Press Enter to Exit") -- http://mail.python.org/mailman/listinfo/python-list
Re: Newb ??
Hey guys, Thanks for your help. I am glad to know there is a community out there willing to put the effort out to help us newbies. I will work on it. Some of the suggestions are things that I have not covered yet but I am sure I will figure it out. Thanks again. I am sure I will be back with more questions before too long. Chad "Chad Everett" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi all, I am new to the group. Trying to learn Python programming on my > own. I am working through Michael Dawson's Book Python Programming for > the absolute beginner. > > I am tring to write a program that is a number guessing game. I want to > be able to give the user 5 tries to guess the number before the program > ends. > > I get the result that I want when the user misses after the 5th try. But > it does not go down to my closing statement to end. Rather is askes for > another guess. > > I appreciate any help you can give. If this is not the correct group for > these types of questions, I apologize and hope that you can direct me to > another NG. > > Thanks, > Chad > > import random > > print "\tWelcome to 'Guess my Number'!" > print "\nI'm Thinking of a Number between 1 and 100." > print "\nTry to Guess it in as few attempts as possible.\n" > > #Set the initial values > the_number = random.randrange(100) + 1 > guess = int(raw_input("Take a guess:")) > tries = 1 > > #Guessing Loop > > while (guess != the_number): >if (guess >the_number): >print "Lower..." >else: >print "Higher..." >guess = int(raw_input("Take another Guess:")) >tries +=1 >if tries == 5: > print "Sorry you lose." > print "The Correct Number was ", the_number > > > print "You guess correctly!!" > print "The number was:", the_number > print "You got it correct in", tries, "tries" > > raw_input("Press Enter to exit the program") > -- http://mail.python.org/mailman/listinfo/python-list
Newb ??
Hi all, I am new to the group. Trying to learn Python programming on my own. I am working through Michael Dawson's Book Python Programming for the absolute beginner. I am tring to write a program that is a number guessing game. I want to be able to give the user 5 tries to guess the number before the program ends. I get the result that I want when the user misses after the 5th try. But it does not go down to my closing statement to end. Rather is askes for another guess. I appreciate any help you can give. If this is not the correct group for these types of questions, I apologize and hope that you can direct me to another NG. Thanks, Chad import random print "\tWelcome to 'Guess my Number'!" print "\nI'm Thinking of a Number between 1 and 100." print "\nTry to Guess it in as few attempts as possible.\n" #Set the initial values the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess:")) tries = 1 #Guessing Loop while (guess != the_number): if (guess >the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take another Guess:")) tries +=1 if tries == 5: print "Sorry you lose." print "The Correct Number was ", the_number print "You guess correctly!!" print "The number was:", the_number print "You got it correct in", tries, "tries" raw_input("Press Enter to exit the program") -- http://mail.python.org/mailman/listinfo/python-list
Class methods
Title: Class methods Is there any way to create a class method? I can create a class variable like this: class Foo: classVariable = None def __init__(self, classVariable): Foo.classVariable = classVariable A = Foo('a') B = Foo('b') Print 'The class variable for A is "%s" and the class variable for B is "%s"'%(a.classVariable,b.classVariable) When you run this, you see the following: The class variable for A is "b" and the class variable for B is "b" This is what I expect. However, I wand to write a function that can be called on a class directly. Lets say the name of the function is bar. This function needs to be callable without an instance. The class will be maintaining a queue, as a class variable, that all instances of that class will use to place data in. When bar is called - perhaps by Foo.bar() - bar will operate on the all of the data provided by its instances. Any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Can't start new thread
Title: Can't start new thread I am trying to understand what is causing python to raise this error when I create a number of threads: thread.error: can't start new thread I have been told that it is due to the default thread size (1 MB), but I have recompiled python defining an alternate threadsize, and I am not seeing any changes. I defined the THREAD_STACK_SIZE in the thread_pthread.h file. Any ideas? Here is the code I am using to test the number of threads I can get running. It maxis out at 1031. I have tested it on two systems, one with 1GB of ram and another with 2GB of RAM. import threading import time class Mythread(threading.Thread): def __init__(self): self.__live = True threading.Thread.__init__(self, target=self.runLoop) def runLoop(self): while self.__live: time.sleep(.1) def stop(self): self.__live = False threads = [] max = raw_input("max: ") if max == 'None': max = None else: max = int(max) while True: print len(threads) t = Mythread() t.start() threads.append(t) if len(threads) == max: break print 'all running' while True: answer = raw_input("stop now? ") if answer in ['Y','y']: break print "stopping" for t in threads: t.stop() print "joining" for t in T: t.join() while True: answer = raw_input("Quit now? ") if answer in ['Y','y']: break print "done" -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with images
"max" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "Chad" <[EMAIL PROTECTED]> wrote in > news:[EMAIL PROTECTED]: > >> I have installed a TWAIN module(from >> http://twainmodule.sourceforge.net) today and figured out how to >> acquire an image. The only problem is that the image is way too >> large in terms of filesize. It is over 1MB. >> >> I can do either one of two things. Try to figure out how to >> manupilate the image with this module(which I am been doing all >> day) or just use a module that can compress jpegs. Can anybody >> help? >> >> > > Check out PIL: > http://www.pythonware.com/products/pil/ > http://www.pythonware.com/library/pil/handbook/ > > > but also be sure to read the "Setting Capababilities" section of this > document: > > http://twainmodule.sourceforge.net/docs/caps.html > > max Max, I have read the document about setting the capabilities. I have also tried the twexplore.exe to see the capabilities of my scanner. The twexplore.exe will give you the option to save the file or "retrieve it natively." On the window where it gives you this option, it also allows you to set attributes like bit size, or compression. No matter how many times I change these options, it still gives an image with the same filesize. The reason, I mentioned that was because those attributes that you can change correlate to the ICAP values. If changing those attributes in twexplore.exe does not do anything, then I am thinking that it probably won't do anything when I write a script either. -- http://mail.python.org/mailman/listinfo/python-list
Help with images
I have installed a TWAIN module(from http://twainmodule.sourceforge.net) today and figured out how to acquire an image. The only problem is that the image is way too large in terms of filesize. It is over 1MB. I can do either one of two things. Try to figure out how to manupilate the image with this module(which I am been doing all day) or just use a module that can compress jpegs. Can anybody help? -- http://mail.python.org/mailman/listinfo/python-list
RE: Database recommendations for Windows app
Firebird is cross platform (you would need the classic server version) look at the following post: http://mail.python.org/pipermail/python-list/2005-June/286366.html Chad -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Will McGugan Sent: Wednesday, June 22, 2005 7:14 AM To: python-list@python.org Subject: Database recommendations for Windows app Hi, I'd like to write a windows app that accesses a locally stored database. There are a number of tables, the largest of which has 455,905 records. Can anyone recommend a database that runs on Windows, is fast / efficient and can be shipped without restrictions or extra downloads? I have googled and found plenty of information on databases, its just that I dont have enough experience with databases to know which one is best for my task! Thanks in advance, Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Python choice of database
One db that is very much worth trying is Firebird. This is an open source Interbase 6.0 (Borland product) compatible db. It is a SourceForge project. There are three versions: the super server which is a client/server db, classic server (the one that I am very familiar with) which is also a client/server db, and the embedded server which is a standalone. In order to access the database you need the open source module KInterbasdb which is also a SourceForge project. KInterbasdb is a Python DB API 2.0 database driver. Firebird has a lot of documentation. Moreover it was made based on the Interbase 6.0, which is was made open source by Borland, so all of Borland's documentation and tools apply as well. Firebird can be found at: http://firebird.sourceforge.net/ KInterbasdb can be found at: http://kinterbasdb.sourceforge.net/ -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Philippe C. Martin Sent: Monday, June 20, 2005 8:19 AM To: python-list@python.org Subject: Python choice of database Hi, I am looking for a stand-alone (not client/server) database solution for Python. 1) speed is not an issue 2) I wish to store less than 5000 records 3) each record should not be larger than 16K As I start with Python objects, I thought of using shelve, but looking at the restrictions (record size + potential collisions) I feel I should study my options a bit further before I get started. Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: how to operate the excel by python?
Title: Message I have posed a more complete answer to your question, however, it is quite a large and It is awaiting approval. For now, xlRight = -4152. You can find this out by opening up Excel and typing the ALT-F11 combination. From there use the ObjectBrowser. For example if you type in the word "xlRight" you will see that it is equal to -4152. Chad -Original Message-From: Kevin P. Coffey [mailto:[EMAIL PROTECTED] Sent: Friday, June 17, 2005 11:28 AMTo: python-list@python.orgSubject: how to operate the excel by python? Question please: In the post, "How to operate the excel by python," where did you find the codes for HorizontalAlignment and VerticalAlignment (Center = -4108 and Bottom = -4107)? I need the code for HorizontalAlignment = xlRight. Is there a table somewhere that shows these codes? Thanks kevin.coffey at ism-corp.us -- http://mail.python.org/mailman/listinfo/python-list
RE: Overcoming herpetophobia (or what's up w/ Python scopes)?
Thanks, I will keep that in mind. Chad -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Steven D'Aprano Sent: Friday, June 17, 2005 11:06 AM To: python-list@python.org Subject: RE: Overcoming herpetophobia (or what's up w/ Python scopes)? On Fri, 17 Jun 2005 10:22:05 -0700, Hughes, Chad O wrote: > Are you sure about the lower-case thing. The original post states > "Perlhead" and there are many instances at www.Perl.com where O'REILLY > spells perl as Perl. I did say "usually" :-) But in fact it seems that the creator of Perl/perl, Larry Wall, now distinguishes between the two spellings. From the FAQs: Q: What's the difference between "perl" and "Perl"? A: One bit. Oh, you weren't talking ASCII? :-) Larry now uses "Perl" to signify the language proper and "perl" the implementation of it, i.e. the current interpreter. Hence Tom's quip that "Nothing but perl can parse Perl." You may or may not choose to follow this usage. For example, parallelism means "awk and perl" and "Python and Perl" look OK, while "awk and Perl" and "Python and perl" do not. But never write "PERL", because perl is not an acronym, apocryphal folklore and post-facto expansions notwithstanding. http://faq.perl.org/perlfaq1.html -- Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Overcoming herpetophobia (or what's up w/ Python scopes)?
Are you sure about the lower-case thing. The original post states "Perlhead" and there are many instances at www.Perl.com where O'REILLY spells perl as Perl. Chad -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Steven D'Aprano Sent: Friday, June 17, 2005 10:02 AM To: python-list@python.org Subject: RE: Overcoming herpetophobia (or what's up w/ Python scopes)? On Fri, 17 Jun 2005 09:36:55 -0700, Hughes, Chad O wrote: > I am very familiar with Python, but I don't know Pearl. The language is *always* spelt without the "a", and usually all in lower-case: perl. Now that I've taught you everything I know about perl, you can be an expert like me -- Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Overcoming herpetophobia (or what's up w/ Python scopes)?
I am very familiar with Python, but I don't know Pearl. In order to answer your question, you will have to tell me about your statement, "I couldn't live without closures and without the fine control over scopes that Pearl provides." I don't know what these things are to Pearl. If you tell me what these features are in Pearl and what you use them for, I can tell you if Python has them as well. Chad -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of kj Sent: Friday, June 17, 2005 9:20 AM To: python-list@python.org Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? I'm a Perlhead (there, I said it). Years ago I made a genuine attempt to learn Python, but my intense disappointed with the way Python deals with scopes ultimately sapped my enthusiasm. I couldn't live without closures and without the fine control over scopes that Perl provides. I've been wanting to make another attempt to (re)learn Python for a while, but this scopes business remained a major damper. What's pushing me over my reluctance is having to work with a large in-house package developed in Python. I am hoping that it may be better this time around. For one thing, like Perl, Python was then (and maybe still is) a "work in progress." So I figure that Python scoping may have improved since then. Even if not, I think that Python is mature enough by now that adequate alternatives must have been devised for the Perlish features that I missed during my first attempt. My question is: is there any tutorial on Python scoping aimed at diehard Perlheads? Thanks! kj -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Finding Word and switch focus to it
Consider reading this post. It highlights how to do what you want: http://mail.python.org/pipermail/python-win32/2002-April/000322.html Chad -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of John Henry Sent: Wednesday, June 15, 2005 3:21 PM To: python-list@python.org Subject: Finding Word and switch focus to it Does anybody know how to find an opened copy of Word and switch focus to it, wait until Word is closed, before continuing my Python script? I tried to search for the answer from Google and nothing stands out. Running under Windows XP. Thanks, -- John -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Finding Word and switch focus to it
The first part is easy. I will have to think about the second part. To find an opened copy of Word and switch focus to it do the following: from win32com.client import Dispatch word = Dispatch('Word.Application') wdWindowStateNormal = 0 if len(word.Documents): word.Activate() if word.WindowState != wdWindowStateNormal: word.WindowState = wdWindowStateNormal -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of John Henry Sent: Wednesday, June 15, 2005 3:21 PM To: python-list@python.org Subject: Finding Word and switch focus to it Does anybody know how to find an opened copy of Word and switch focus to it, wait until Word is closed, before continuing my Python script? I tried to search for the answer from Google and nothing stands out. Running under Windows XP. Thanks, -- John -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Opening a drive folder from Python
I think you are talking about the following: from win32com.client import Dispatch path = raw_input('Type in a path: ') s=Dispatch('WScript.Shell') s.Run('Explorer %s'%path) Chad -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of John Henry Sent: Tuesday, June 14, 2005 4:02 PM To: python-list@python.org Subject: Opening a drive folder from Python Can somebody please tell me how to pop open a drive folder from a Python script? Thanks. -- John -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: [python-win32] NTService detecting if the Windows System is Idle
-Original Message- From: Hughes, Chad O Sent: Monday, June 13, 2005 9:09 AM To: 'Fred Dixon' Subject: RE: [python-win32] NTService detecting if the Windows System is Idle There may be important processes running in the background (headless process with no user interaction) that need resources while the user may or may not be "using" the computer, possible when the user is logged out. I would use the system resource usage itself to define the idleness of your system. There are a great number of things that can be measured and you can even have general system measurements as well as process specific measurements. For example: lets say that you have your thresholds set to some logical value, and you have some process (call it processA) that is important. You can dynamically redefine your thresholds for when processA is running and then dynamically readjust them when it is not. Moreover, you can make your thresholds be a function of your general system usage combined with process specific usage. For example, you can dynamically adjust your thresholds based on linear functions of the usage of a list of processes and your system. This is a very flexible approach. My example is just a starting point. Do you fallow this? -Original Message- From: Fred Dixon [mailto:[EMAIL PROTECTED] Sent: Sunday, June 12, 2005 12:30 PM To: Hughes, Chad O Subject: Re: [python-win32] NTService detecting if the Windows System is Idle why not just run it when the screen saver is active On 6/10/05, Hughes, Chad O <[EMAIL PROTECTED]> wrote: > I think this example is what you want to do. It is not a service, but > you can turn it into one. > > import win32pdh > from time import sleep > import threading > > pdhQuery = win32pdh.OpenQuery(None, 0) > > class PDH_COUNTER_PATH_ELEMENTS(list): > def __init__(self, l = None): > if not l: > l = ['127.0.0.1',None,None,None,-1,None] > list.__init__(self,l) > self.__machineName = self[0] > self.__objectName = self[1] > self.__instanceName = self[2] > self.__parantInstance = self[3] > self.__instanceIndex = self[4] > self.__counterName = self[5] > def __setMachineName(self,value): > self.__machineName = value > self[0] = value > def __setObjectName(self,value): > self.__objectName = value > self[1] = value > def __setInstanceName(self,value): > self.__instanceName = value > self[2] = value > def __setParentInstance(self,value): > self.__parentInstance = value > self[3] = value > def __setInstanceIndex(self,value): > self.__instanceIndex = value > self[4] = value > def __setCounterName(self,value): > self.__counterName = value > self[5] = value > def __getMachineName(self): > return self.__machineName > def __getObjectName(self): > return self.__objectName > def __getInstanceName(self): > return self.__instanceName > def __getParentInstance(self): > return self.__parentInstance > def __getInstanceIndex(self): > return self.__instanceIndex > def __getCounterName(self): > return self.__counterName > machineName = property(__getMachineName, __setMachineName) > objectName = property(__getObjectName, __setObjectName) > instanceName = property(__getInstanceName, __setInstanceName) > instanceIndex = property(__getInstanceIndex, __setInstanceIndex) > parentInstanceIndex = property(__getParentInstance, > __setParentInstance) > counterName = property(__getCounterName, __setCounterName) > def makeCopy(self): > return PDH_COUNTER_PATH_ELEMENTS(self) > def __repr__(self): > return 'machineName = %s\nobjectName = %s\nInstanceName = > %s\nparentInstance = %s\ninstanceIndex = %s\ncounterName = > %s'%tuple(self) > > class WorkerThread(threading.Thread): > def __init__(self): > threading.Thread.__init__(self, target = self.__runLoop) > self.__pauseEvent = threading.Event() > #when wait is called after clear the thread will pause until set > self.__pauseEvent.clear() > self.__stayAlive = True > def stop(self): > self.__stayAlive = False > #loop until runLoop is exited > while self.isAlive(): > self.__pauseEvent.set() > def pause(self): > self.__pauseEvent.clear() > def resume(self): > self.__pauseEvent.set() > def __runLoop(self): > while self.__stayAlive: > self.__pauseEvent.wait() > #do what ever you want to do while the CPU is idle > #example print that cpu is idle > print 'The CPU is idle' > > > #make paths > cpe = PDH_COUNTER_PATH_ELEMENTS(( > '127.0.0.1', > "Processor", >
RE: SMTP Test Rig
Thanks very much it works great and does exactly what I need for a test I have to perform. I started teaching myself the SMTP protocol last night and it does not look to hard. But this saves me a great deal of time an effort. I hope you can find a good place to host it, as it is the only example I have seen yet. Chad -Original Message- From: Tim Williams [mailto:[EMAIL PROTECTED] Sent: Friday, June 10, 2005 5:35 AM To: Hughes, Chad O; Jesse Noller Subject: SMTP Test Rig Chad, Jesse. The SMTP test rig receives SMTP emails and can be configured to write them to the screen, save them to a file - or both. Have fun # """ SMTPRIG.py (SMTP Test Rig) Version 1.0 Copyright (C) Tim Williams ([EMAIL PROTECTED]) 10th June 2005 # # This software is provided "AS IS" without any warranty # explicit or implied. # # Redistribution of this code is allowed provided the # above copyright information remains intact. # # This code was developed out of the need for a very basic # test SMTP server, and later expanded to add logging to # screen and/or the ability to save the email to a text file. # # This server has the bare minimum SMTP functionality required # to impliment the above requirements. It has no error checking # or rfc822 compliance checks, it will receive anything from anyone # no matter how bad their SMTP dialogue is. # # This server has only been tested in a windows environment # # This server can receive multiple concurrent emails (multithreaded inbound) # # This server CAN NOT RELAY email to another server (unless you add that bit yourself) # # Please feel free to send comments or questions to [EMAIL PROTECTED] # """ from socket import * from SocketServer import * from Queue import Queue from random import randrange from os import path, makedirs import thread server_port = 2525 # the port the server will run on file_path = 'txtmails' # path for saved files write_to_screen = 1 # 1 to enable, 0 to disable write_to_file = 1 # 1 to enable, 0 to disable try: makedirs(file_path) except OSError, x: #[Errno 17] File exists: pass q_print = Queue() #queue for printing to console. class SMTPServer(ThreadingMixIn, TCPServer): # other functions exist here in a live server def some_function(self): pass #end of class SMTPServer class SMTPRequestHandler(StreamRequestHandler): global write_to_file, file_path def handle(self): qprint ('*-'*30) self.ip, self.port = self.client_address self.port = str(self.port) self.ip = str(self.ip) qprint ( "<=> Incoming connection from ", self.ip, ' Port:', self.port) self.terminated = 0 self.receiving_data = 0 self.SendResponse('220 ** Welcome **') self.msg = [] self.msg_count = 1 empty_line = 0 self.msg_id() commands={ 'HELO' : self.__OK,# supported commands 'QUIT' : self.__QUIT, 'MAIL' : self.__OK, 'RCPT' : self.__OK, 'NOOP' : self.__OK, 'RSET' : self.__OK, 'HELP' : self.__OK, 'DATA' : self.__DATA, } while not self.terminated: try: self.inputline = self.rfile.readline() self.inputline = self.inputline.rstrip() qprint (self.port + '<== ' + self.inputline ) except: self.inputline = ' ' request = self.inputline.upper().split() if self.receiving_data: self.receive_body() elif request and commands.has_key(request[0]): # eg: if has_key HELO commands[request[0]](request) else: self.SendResponse("500 Unknown Command "+ self.inputline) if self.inputline == '':# empty commandline empty_line += 1 if empty_line > 9: # max empty lines self.SendResponse('550 Too many empty lines') break # end of smtp conversation def receive_body(self): if self.inputline == '.': self.receiving_data = 0 self.msg_count += 1 self.msg_id() if write_to_file: self.write_file() self.SendResponse('250 2.1.0 OK: Data received') else: self.msg.append(self.inputline) def __OK(self,request): self.SendResponse('250 2.1.0 OK') def __DATA(self,request): self.receiving_data = 1 self.SendResponse('35
RE: how to operate the excel by python?
Sorry, I meant to spell check but I did not somehow. Chad -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Hughes, Chad O Sent: Friday, June 10, 2005 10:01 AM To: python-list@python.org Subject: RE: how to operate the excel by python? Here are two scripts that I have had to build for a class that I teach. You will either need to write the constants explicitly, or I can email neet the constans module that I have built, for the second one to work. I will copy it to the very end. If you have any questions, just let me know. Here is a simple one that allows me to interface with my grade book spreadsheet though the command line for taking attendance: from win32com.client import Dispatch import time xl = Dispatch('Excel.Application') wb = xl.Workbooks.Open('C:\\Documents and Settings\\My Documents\\discrete\\GradeBook.xls') ws = wb.Worksheets.Item(1) ws.Activate() i = 1 while True: if ws.Cells(1,i).Text == '': break i += 1 t = time.localtime() d = '%s/%s/%s'%(t.tm_mon,t.tm_mday,t.tm_year) ws.Cells(1,i).FormulaR1C1 = d ws.Cells(2,i).Select() j = 2 while True: name = ws.Cells(j,1).Text if name == '': break name = name.split()[1] here = int(raw_input('%s here? '%name)) ws.Cells(j,i).FormulaR1C1 = here j += 1 wb.Save() The next one is a kluge (spaghetti code), sorry but it is complete. It builds a truth table for evalutating logic expressions: from win32com.client import Dispatch >From officecon.xlcon import * xl = Dispatch('Excel.Application') binary = False # set this to true to use 0 and 1 instead of False and True vars = raw_input("Comma seperate the variables:") headers = raw_input("What other headers do you want, comma seperated?") headers = headers.split(',') vars = vars.split(',') numToAlpha = 'abcdefghijklmnopqrstuvwxyz' if not xl.Visible: xl.Workbooks.Add() xl.Worksheets.Add() for i in range(3): sheet = xl.Worksheets.Item(2) sheet.Delete() xl.ActiveWindow.SelectedSheets.Delete else: xl.Worksheets.Add() sheet = xl.Worksheets.Item(1) if len(headers[-1]) > 30: sheet.name = headers[-1][:27]+'...' elif headers[-1] == '': sheet.name = 'Example' else: sheet.name = headers[-1] xl.Visible = True for i in range(len(vars)): sheet.Range(numToAlpha[i]+'1').FormulaR1C1 = vars[i] sheet.Rows("1:1").Select() xlBottom = -4107 xlCenter = -4108 xl.Selection.NumberFormat = "General" xl.Selection.HorizontalAlignment = xlCenter xl.Selection.VerticalAlignment = xlBottom xl.Selection.Font.name = "Areial" xl.Selection.Font.FontStyle = "Bold" xl.Selection.Font.Size = 12 rows = [] number = 2**len(vars) for i in range(number): row = [] for j in range(len(vars)): row.append((i%(2**(len(vars)-j)))/(2**(len(vars)-j-1))) rows.append(row) for row in range(len(rows)): for column in range(len(rows[row])): if not rows[row][column]: if binary: value = 0 else: value = 'TRUE' else: if binary: value = 1 else: value = 'FALSE' sheet.Range(numToAlpha[column]+`row+2`).FormulaR1C1 = value for i in range(len(headers)): sheet.Range(numToAlpha[i+len(vars)]+'1').FormulaR1C1 = headers[i] sheet.Range(numToAlpha[i+len(vars)]+'1').Select() sheet.Range("A1:"+numToAlpha[len(vars)+len(headers)-1]+`number+1`).Select() xl.Selection.Borders(xlDiagonalDown).LineStyle = xlNone xl.Selection.Borders(xlDiagonalUp).LineStyle = xlNone xl.Selection.Borders(xlEdgeLeft).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeLeft).Weight = xlThick xl.Selection.Borders(xlEdgeLeft).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeTop).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeTop).Weight = xlThick xl.Selection.Borders(xlEdgeTop).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeBottom).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeBottom).Weight = xlThick xl.Selection.Borders(xlEdgeBottom).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeRight).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeRight).Weight = xlThick xl.Selection.Borders(xlEdgeRight).ColorIndex = xlAutomatic xl.Selection.Borders(xlInsideVertical).LineStyle = xlContinuous xl.Selection.Borders(xlInsideVertical).Weight = xlThin xl.Selection.Borders(xlInsideVertical).ColorIndex = xlAutomatic xl.Selection.Borders(xlInsideHorizontal).LineStyle = xlContinuous xl.Selection.Borders(xlInsideHorizontal).Weight = xlThin xl.Selection.Borders(xlInsideHorizontal).ColorIndex = xlAutomatic xl.Range("A1:"+numToAlpha[len(vars)+len(headers)-1]+'2').Select() xl.Selection.Borders(xlInsideHorizontal).Weight = xlThick xl.Range(numToAlpha[len(vars)-1]+'1:'+numToAlpha[len(vars)]+`n
RE: how to operate the excel by python?
Here are two scripts that I have had to build for a class that I teach. You will either need to write the constants explicitly, or I can email neet the constans module that I have built, for the second one to work. I will copy it to the very end. If you have any questions, just let me know. Here is a simple one that allows me to interface with my grade book spreadsheet though the command line for taking attendance: from win32com.client import Dispatch import time xl = Dispatch('Excel.Application') wb = xl.Workbooks.Open('C:\\Documents and Settings\\My Documents\\discrete\\GradeBook.xls') ws = wb.Worksheets.Item(1) ws.Activate() i = 1 while True: if ws.Cells(1,i).Text == '': break i += 1 t = time.localtime() d = '%s/%s/%s'%(t.tm_mon,t.tm_mday,t.tm_year) ws.Cells(1,i).FormulaR1C1 = d ws.Cells(2,i).Select() j = 2 while True: name = ws.Cells(j,1).Text if name == '': break name = name.split()[1] here = int(raw_input('%s here? '%name)) ws.Cells(j,i).FormulaR1C1 = here j += 1 wb.Save() The next one is a kluge (spaghetti code), sorry but it is complete. It builds a truth table for evalutating logic expressions: from win32com.client import Dispatch >From officecon.xlcon import * xl = Dispatch('Excel.Application') binary = False # set this to true to use 0 and 1 instead of False and True vars = raw_input("Comma seperate the variables:") headers = raw_input("What other headers do you want, comma seperated?") headers = headers.split(',') vars = vars.split(',') numToAlpha = 'abcdefghijklmnopqrstuvwxyz' if not xl.Visible: xl.Workbooks.Add() xl.Worksheets.Add() for i in range(3): sheet = xl.Worksheets.Item(2) sheet.Delete() xl.ActiveWindow.SelectedSheets.Delete else: xl.Worksheets.Add() sheet = xl.Worksheets.Item(1) if len(headers[-1]) > 30: sheet.name = headers[-1][:27]+'...' elif headers[-1] == '': sheet.name = 'Example' else: sheet.name = headers[-1] xl.Visible = True for i in range(len(vars)): sheet.Range(numToAlpha[i]+'1').FormulaR1C1 = vars[i] sheet.Rows("1:1").Select() xlBottom = -4107 xlCenter = -4108 xl.Selection.NumberFormat = "General" xl.Selection.HorizontalAlignment = xlCenter xl.Selection.VerticalAlignment = xlBottom xl.Selection.Font.name = "Areial" xl.Selection.Font.FontStyle = "Bold" xl.Selection.Font.Size = 12 rows = [] number = 2**len(vars) for i in range(number): row = [] for j in range(len(vars)): row.append((i%(2**(len(vars)-j)))/(2**(len(vars)-j-1))) rows.append(row) for row in range(len(rows)): for column in range(len(rows[row])): if not rows[row][column]: if binary: value = 0 else: value = 'TRUE' else: if binary: value = 1 else: value = 'FALSE' sheet.Range(numToAlpha[column]+`row+2`).FormulaR1C1 = value for i in range(len(headers)): sheet.Range(numToAlpha[i+len(vars)]+'1').FormulaR1C1 = headers[i] sheet.Range(numToAlpha[i+len(vars)]+'1').Select() sheet.Range("A1:"+numToAlpha[len(vars)+len(headers)-1]+`number+1`).Select() xl.Selection.Borders(xlDiagonalDown).LineStyle = xlNone xl.Selection.Borders(xlDiagonalUp).LineStyle = xlNone xl.Selection.Borders(xlEdgeLeft).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeLeft).Weight = xlThick xl.Selection.Borders(xlEdgeLeft).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeTop).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeTop).Weight = xlThick xl.Selection.Borders(xlEdgeTop).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeBottom).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeBottom).Weight = xlThick xl.Selection.Borders(xlEdgeBottom).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeRight).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeRight).Weight = xlThick xl.Selection.Borders(xlEdgeRight).ColorIndex = xlAutomatic xl.Selection.Borders(xlInsideVertical).LineStyle = xlContinuous xl.Selection.Borders(xlInsideVertical).Weight = xlThin xl.Selection.Borders(xlInsideVertical).ColorIndex = xlAutomatic xl.Selection.Borders(xlInsideHorizontal).LineStyle = xlContinuous xl.Selection.Borders(xlInsideHorizontal).Weight = xlThin xl.Selection.Borders(xlInsideHorizontal).ColorIndex = xlAutomatic xl.Range("A1:"+numToAlpha[len(vars)+len(headers)-1]+'2').Select() xl.Selection.Borders(xlInsideHorizontal).Weight = xlThick xl.Range(numToAlpha[len(vars)-1]+'1:'+numToAlpha[len(vars)]+`number+1`).Select() xl.Selection.Borders(xlInsideVertical).LineStyle = xlDouble xl.Range(numToAlpha[len(vars)+len(headers)-1]+'1:'+numToAlpha[len(vars)+len(headers)-1]+`number+1`).Select() xl.Selection.Borders(xlEdgeLeft).LineStyle = xlDashDotDot xl.Selection.Interior.ColorIndex = 20 xl.Selection.Interior.Pattern = xlSolid #xl.Selection.Borders(xlEdgeLeft).Weight = xlThick #xl.Selection.Borders(xlEdgeTop).Weight = xlThick #xl.Selection.Borders(xlEdgeBottom).Weight = xlThick xl.Selection.Borders(xlEdgeRight).Weight = xlThick #xl.Selection.Borders(xlInsideVertical).Weight = xlThin #xl.Selec
RE: smtpd module
No, I know how to use the smtplib module and I can send email through that. However what I want is a the ability to set up a very simple mail server with python, for some tests that I need to run that just prints out the message to the standard out and disregards the message. The smtpd module seems to provide this ability via the DebuggingServer. According to the documentation that is provided with python the: class DebuggingServer( localaddr, remoteaddr) Create a new debugging server. Arguments are as per SMTPServer. Messages will be discarded, and printed on stdout. Unfortunately, this does not tell me how to use it. I cannot find any examples on the web. For that matter, I cannot find any other documentation anywhere. Has anyone ever used ether the SMTPServer object or the DebuggingServer object? If so, I would appreciate very much an example use case. Thanks, Chad -Original Message- From: Ivan Shevanski [mailto:[EMAIL PROTECTED] Sent: Thursday, June 09, 2005 2:03 PM To: python-list@python.org Cc: Hughes, Chad O Subject: RE: smtpd module So youre wondering how to send mail in python? I have a lot of examples if you want the smtp module. I don't have anything for anything other than the smtp module. -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
smtpd module
Title: smtpd module Does anyone know of any documentation on how to use the smtpd module, either the SMTPServer or the DebuggingServer? I cannot find any usage cases or examples anywhere. I can find examples of using the smtplib module but not the smtpd module. Thanks, Chad -- http://mail.python.org/mailman/listinfo/python-list
Posting a reply to a post in an existing thread
Title: Posting a reply to a post in an existing thread This may be a dumb question. I am new to using this list, and I cannot figure out how to send a reply to a message that has been posed in a thread without creating a new thread. Let me rephrase my question. The instructions for posting to the list is to send a message to [EMAIL PROTECTED] There are no instructions for posting a reply. What I need to know is, what do I put in either the TO field, the CC field, or the SUBJECT field for the list to see my message as a reply to an existing post in a thread and not a new thread. When I use RE: in front of the reply and put python-list@python.org in the TO field, my reply ends up as the start of a new thread. Is this supposed to be the procedure? Thanks, Chad -- http://mail.python.org/mailman/listinfo/python-list
RE: EnumKey vs EnumValue
EnumKey enumerates subkeys which are equivalent to the folders in regedit. EnumValue enumerates values only. The reason your script is not printing anything must be due to the fact that you are passing in a registry path that contains only subkeys and no values. As I mentioned before, the folders are the subkeys, but the values are the name, type, data tuple in a given key. Some loosely call the values keys, but technically, the keys are the folders and the values are the names. The names can be set to a specific data item. Hence the data column in regedit. The type is obviously the data type of the data that is associated with a given value (name). So, to summarize, keys are the folders that hold values that are set to data of a specific type. Keys are equivalent to the path, values are equivalent to the name in regedit. That value is assigned a date item of a specific type. This can get confusing because people commonly referred to the values as keys when keys are actually the folders. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Pykid Sent: Monday, June 06, 2005 1:07 PM To: python-list@python.org Subject: EnumKey vs EnumValue I'm having trouble getting any responses back from the following snippet, where I am just trying to read some data from the Windows Registry. I intend to do a little bit more with this but will work on that later, but I think I can get more data back from EnumValue, I'd like to see the differences between them. I am running Python 2.3 on XP and can get a response from EnumKey, but EnumValue returns nothing at all; the key listing even returns 0 keys when it prints out the status. But EnumKey returns the right number and even prints out the keys I expect, I copied some of this from the Cookbook and can't tell what might be the problem. Thanks for any help. - M - from _winreg import * findkey = raw_input("What key do you want to look for? ") key = "SOFTWARE\\"+findkey machine = ConnectRegistry(None,HKEY_LOCAL_MACHINE) regpath = OpenKey(machine,key) print "Looking for",key for i in range(25): try: regEndeca = EnumKey(regpath,i) print regEndeca except EnvironmentError: print "There are", i,"keys under",key break print "That was using EnumKey." for j in range(25): try: regstr,value,type = EnumValue(regpath,j) print regstr,value,type except EnvironmentError: print "There are", j,"keys under",key break print "That was using EnumValue." -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Thread Stack Size
Title: Thread Stack Size I am using the threading module to create a great deal of threads. Is there any way to set the thread stack size? It looks like each thread is being given a default stack size of 1MB. I have looked all over and I cannot find a way to shrink the stack to a few KB. When I try to create a large number of threads (say 1000 of them) I run into trouble, due to the fact that I have one Gig of memory. -- http://mail.python.org/mailman/listinfo/python-list
Re: parse tree has symbols not in the grammar?
Terry, Thanks for the reply. Did you not find them in grammar.txt, which you referenced, or Grammar/Grammar is the source, which you did not. I didn't find them in grammar.txt. I didn't find Grammar/Grammar because I was looking in an installed Python rather than the source (my mistake; I've found it now). I assumed that the two would the same. Guido has said that the grammar in the ref manual, meant for human consumption, is equivalent to but not quite the same as the grammar used to generate the parser, which has to meet LL1 constraints. Ok, thanks for the info. While I found a comment re: the ref manual being for human consumption[1], I didn't take this to mean that its grammar was actually not the same as the implementation grammar, only that it was set forth in English (hence, my assumption above). Would there be any value, I wonder, in posting Grammar/Grammar with the rest of the docs, e.g., at doc/ref/grammar-parser.txt? Thanks again for the sanity check! chad -- [1] http://python.org/doc/ref/introduction.html -- http://mail.python.org/mailman/listinfo/python-list
parse tree has symbols not in the grammar?
Hey all, I've been playing around with the parser module, and based on the documentation I would expect all symbols in a parse tree to be part of the grammar.[1] For example, I find this line in the symbol module docs: Refer to the file Grammar/Grammar in the Python distribution for the definitions of the names in the context of the language grammar.[2] However, the program below gives me a human-readable parse tree (also below) that contains symbols that don't seem to be in the grammar, e.g., small_stmt, expr_stmt, factor. Is my expectation wrong? Thanks. chad -- [1] http://python.org/doc/ref/grammar.txt [2] http://python.org/doc/lib/module-symbol.html # A PROGRAM # #!/usr/bin/env python """print out a human-readable parse tree for a simple code block """ import parser, symbol, token from pprint import pprint def experiment(block): """experimenting, like the man said """ ast = parser.suite(block) raw = ast.tolist() def interp(x): """given an int or a string, return a symbol, token, or other string """ if type(x) is type(0): if x < 256: return token.tok_name[x] else: return symbol.sym_name[x] return x def process(raw): """recursively convert a raw parse tree into something readable """ for node in raw: if type(node) is type([]): process(node) else: raw[raw.index(node)] = interp(node) process(raw) pprint(raw) experiment("""\ x = 3 for y in range(10): y == x """) # ITS OUTPUT # ['file_input', ['stmt', ['simple_stmt', ['small_stmt', ['expr_stmt', ['testlist', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'x']]], ['EQUAL', '='], ['testlist', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NUMBER', '3'], ['NEWLINE', '']]], ['stmt', ['compound_stmt', ['for_stmt', ['NAME', 'for'], ['exprlist', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'y']]], ['NAME', 'in'], ['testlist', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'range']], ['trailer', ['LPAR', '('], ['arglist', ['argument', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NUMBER', '10', ['RPAR', ')']]], ['COLON', ':'], ['suite', ['NEWLINE', ''], ['INDENT', ''], ['stmt', ['simple_stmt', ['small_stmt', ['expr_stmt', ['testlist', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'y']], ['comp_op', ['EQEQUAL', '==']], ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'x'], ['NEWLINE', '']]], ['DEDENT', ''], ['NEWLINE', ''], ['ENDMARKER', '']] -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help
I got it, thanks for the help. Chad "Michael Hartl" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Sorry about the code: Google Groups screwed up the formatting, but I > hope you get the picture. > -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help
No problem, I need all the help and insruction I can get. Thanks, Chad "Kent Johnson" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Kent Johnson wrote: >> You might be interested in the Python tutor mailing list which is >> specifically intended for beginners. >> http://mail.python.org/mailman/listinfo/tutor > > Ah, I don't mean to imply that this list is unfriendly to beginners, or > that you are not welcome here! Just pointing out another resource. > > Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help
Nope, I am trying to learn it on my own. I am using the book by Michael Dawson. Thanks, "Francis Girard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Mmm. This very much look like a homework from school. Right ? Francis Girard Le lundi 14 Février 2005 04:03, Chad Everett a écrit : > Hey guys, > > Hope you can help me again with another problem. I am trying to learn > Python on my own and need some help with the following. > > I am writing a program that lets has the pc pick a number and the user > has five guess to get the number. > 1. BUG: If the number is say 35 and I guess 41 the program tells me > that I guessed the correct number and tells me I guessed 31. > > 2.When I do get the correct number I can not get the program to stop > asking me for the number. > > > Your help is greatly appreciated. > > Chad > > # Five Tries to Guess My Number > # > # The computer picks a random number between 1 and 100 > # The player gets Five tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > # > # Chad Everett 2/10/2005 > > import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 100." > print "You Only Have Five Guesses.\n" > > # set the initial values > number = random.randrange(100) + 1 > guess = int(raw_input("Go Ahead and Take a guess: ")) > tries = 1 > > > # guessing loop > > > while guess != number: > > if (guess > number): > print "Guess Lower..." > else: > print "Guess Higher..." > > guess = int(raw_input("Take Another guess: ")) > tries += 1 > > print "You guessed it! The number was", number > print "And it only took you", tries, "tries!\n" > > if tries == 5: > print "Sorry You Lose" > print "The Number was ", number > > raw_input("\n\nPress the enter key to exit.") > > THIS IS WHAT THE RESULTS LOOKS LIKE WHEN I RUN THE PROGRAM > > Welcome to 'Guess My Number'! > > I'm thinking of a number between 1 and 100. > You Only Have Five Guesses. > > Go Ahead and Take a guess: 99 > Guess Lower... > Take Another guess: 98 > You guessed it! The number was 85 > And it only took you 2 tries! > > Guess Lower... > Take Another guess: 44 > You guessed it! The number was 85 > And it only took you 3 tries! > > Guess Higher... > Take Another guess: 55 > You guessed it! The number was 85 > And it only took you 4 tries! > > Guess Higher... > Take Another guess: 33 > You guessed it! The number was 85 > And it only took you 5 tries! > > Sorry You Lose > The Number was 85 > Guess Higher... > Take Another guess: -- http://mail.python.org/mailman/listinfo/python-list
Newbie help
Hey guys, Hope you can help me again with another problem. I am trying to learn Python on my own and need some help with the following. I am writing a program that lets has the pc pick a number and the user has five guess to get the number. 1. BUG: If the number is say 35 and I guess 41 the program tells me that I guessed the correct number and tells me I guessed 31. 2.When I do get the correct number I can not get the program to stop asking me for the number. Your help is greatly appreciated. Chad # Five Tries to Guess My Number # # The computer picks a random number between 1 and 100 # The player gets Five tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money # # Chad Everett 2/10/2005 import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "You Only Have Five Guesses.\n" # set the initial values number = random.randrange(100) + 1 guess = int(raw_input("Go Ahead and Take a guess: ")) tries = 1 # guessing loop while guess != number: if (guess > number): print "Guess Lower..." else: print "Guess Higher..." guess = int(raw_input("Take Another guess: ")) tries += 1 print "You guessed it! The number was", number print "And it only took you", tries, "tries!\n" if tries == 5: print "Sorry You Lose" print "The Number was ", number raw_input("\n\nPress the enter key to exit.") THIS IS WHAT THE RESULTS LOOKS LIKE WHEN I RUN THE PROGRAM Welcome to 'Guess My Number'! I'm thinking of a number between 1 and 100. You Only Have Five Guesses. Go Ahead and Take a guess: 99 Guess Lower... Take Another guess: 98 You guessed it! The number was 85 And it only took you 2 tries! Guess Lower... Take Another guess: 44 You guessed it! The number was 85 And it only took you 3 tries! Guess Higher... Take Another guess: 55 You guessed it! The number was 85 And it only took you 4 tries! Guess Higher... Take Another guess: 33 You guessed it! The number was 85 And it only took you 5 tries! Sorry You Lose The Number was 85 Guess Higher... Take Another guess: -- http://mail.python.org/mailman/listinfo/python-list
newbie: Syntax error
Hi Everyone, I am new to Python and programming in general. I bought the book "Python Programming for the Absolute Beginner" by michael Dawson. I have been working through it but am having trouble. I am trying to make a coin flip program and keep geting a Synax Error "invalid syntax". If anyone has a moment could you please look at it and tell me what I am doing wrong. thanks for your time and patience. Chad # Coin Flip Program # This program flips a coin 100 times and tells the number of heads and tails. # Chad Everett 2/3/2005 print "\t\tCoin Flip Game*\n" import random # heads = 1 # tails = 2 tries = random.randrange(2) + 1 count = 1 while count != 100: if tries == 1: heads = 1 count += 1 else tries == 2: # I AM GETTING THE SYNTAX ERROR HERE tails = 1 count += 1 print "heads: " + heads print "tails: " + tails raw_input("Press enter to quit") -- http://mail.python.org/mailman/listinfo/python-list