Re: [Tutor] Remote Directory Reading
Daniel Watkins wrote: > I've run into a bit of trouble with my spider script. Thus far, it is > able to retrieve all of the data off the website that is contained > within standard HTML, downloading jpg, gif and bmp images that are > related to the files (this restriction only being set by a lack of > further definitions by myself). However, I have run into a problem with > one link that simply points to a folder (www.aehof.org.uk/forum) within > which is contained a phpBB forum. It seems to me this page is no different from any other - it has a bunch of links that you can follow to get the content. I'm not sure why you want to handle it specially? Except maybe to ignore some of the links, which you will have to write into your program. > I've attempted to use 'dircache' but couldn't find a way for it to > understand web addresses. However, I may not have hit upon the right > combination of syntax, so may be mistaken. I also considered 'os' but it > appears to require definition of a particular operating system, which is > a direction I'd prefer not to take unless I have to. In addition, the > error messages I received from using 'dircache' traced back into 'os' so > it is unlikely it would have been suitable for the purpose. The os module actually hides the differences between operating systems pretty well. It has implementations for many os's but the interface you see is os-independent. The choice of the correct implementation happens under the hood, it is not something you need to be concerned with. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beautiful Soup / Unicode problem?
grouchy wrote: > Hi, > > I'm having bang-my-head-against-a-wall moments trying to figure all of this > out. > from BeautifulSoup import BeautifulSoup >>> file = urllib.urlopen("http://www.google.com/search?q=beautifulsoup";) file = file.read().decode("utf-8") soup = BeautifulSoup(file) results = soup('p','g') x = results[1].a.renderContents() type(x) > > > print x > > Matt Croydon::Postneo 2.0 » Blog Archive » Mobile Screen Scraping ... > > So far so good. But what I really want is just the text, so I try > something like: > > y = results[1].a.fetchText(re.compile('.+')) > > Traceback (most recent call last): > File "", line 1, in ? > File "BeautifulSoup.py", line 466, in fetchText > return self.fetch(recursive=recursive, text=text, limit=limit) > File "BeautifulSoup.py", line 492, in fetch > return self._fetch(name, attrs, text, limit, generator) > File "BeautifulSoup.py", line 194, in _fetch > if self._matches(i, text): > File "BeautifulSoup.py", line 252, in _matches > chunk = str(chunk) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in > position 26: ordinal not in range(128) > > Is this a bug? Come to think of it, I'm not even sure how printing x > worked, since it printed non-ascii characters. This is the first question in the BeautifulSoup FAQ at http://www.crummy.com/software/BeautifulSoup/FAQ.html Unfortunately the author of BS considers this a problem with your Python installation! So it seems he doesn't have a good understanding of Python and Unicode. (OK, I can forgive him that, I think there are only a handful of people who really do understand it completely.) The first fix given doesn't work. The second fix works but it is not a good idea to change the default encoding for your Python install. There is a hack you can use to change the default encoding just for one program; in your program put reload(sys); sys.setdefaultencoding('utf-8') This seems to fix the problem you are having. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with files
> > basically I took the idea and the code example given and wrote this > little function, i stuck vars in this html page like #email# and > just used it like this, " insertdata('#email#','[EMAIL PROTECTED]') > > works perfect! ARe you sure? The problem using seek and write is that if the data you are inserting is bigger than your marker you will overwrite the data following the marker. Thus if your marker were in a table like: #email#Scott's email And you overwrite the #mail# with [EMAIL PROTECTED] You will end up with: [EMAIL PROTECTED]'s email Which will not display the way you want! > def insertdata(name, data): >file = open('template.html', 'r+') >contents = file.read() >pos = contents.index(name) >file.seek(pos) >file.write(data) This does not insert it overwrites. You are better to insert the content into contents and then just write it all back to the file in one move. >file.write(contents[pos + len(name):]) >file.close() HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Instance attribute as a parameter's default value
Hi, I need to use an instance attribute as the default value for a parameter to a method. This obviously won't work: page.Children() def Children(self, id=self.id, level=2): How can I get the id parameter to use the attribute page.id? I know I could simply use the method call page.Children(id=page.id) but I thought it is much more elegant to use a default value here. Is it possible? TIA, Jan -- The day Microsoft makes something that doesn't suck is the day they start selling vacuum cleaners. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Instance attribute as a parameter's default value
Hi, Jan Eden wrote on 26.08.2005: >Hi, > >I need to use an instance attribute as the default value for a parameter to a >method. > >This obviously won't work: > >page.Children() > >def Children(self, id=self.id, level=2): > >How can I get the id parameter to use the attribute page.id? I know I could >simply use the method call > >page.Children(id=page.id) > >but I thought it is much more elegant to use a default value here. > >Is it possible? Addition: I do use def Children(self, id=0, level=2): if not id: id = self.id right now. But still - there has to be a smarter way. Thanks, Jan -- Any sufficiently advanced technology is insufficiently documented. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Instance attribute as a parameter's default value
Jan Eden a écrit : > Hi, > > Jan Eden wrote on 26.08.2005: > > >>Hi, >> >>I need to use an instance attribute as the default value for a parameter to a >>method. >> >>This obviously won't work: >> >>page.Children() >> >>def Children(self, id=self.id, level=2): >> >>How can I get the id parameter to use the attribute page.id? I know I could >>simply use the method call >> >>page.Children(id=page.id) >> >>but I thought it is much more elegant to use a default value here. >> >>Is it possible? > > > Addition: I do use > > def Children(self, id=0, level=2): > if not id: id = self.id > > right now. But still - there has to be a smarter way. Well, I prefer the use of "None" for that, as it cannot be mixed up with any other value: def Children(self, id=None, level=2): if id is None: id = self.id Another possibility (mainly if you have many such arguments) is the use of something like: def Children(self, **kwords): id = kwords.pop("id", None) level = kwords.pop("level", 2) Although it is not equivalent ! In the second cases, you have to name the parameter to set it ! But I sometimes find this A Good Thing (tm) when no argument order is better ... Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with files
Alan G wrote: > ARe you sure? The problem using seek and write is that if the data > you are inserting is bigger than your marker you will overwrite the > data following the marker. Alan, you missed the last part of the code - he writes the rest of the data following the match into the file. This is an innovative approach which may have some benefit over the usual / read the whole file / change the data in memory / write the whole file / method as it avoids re-writing the part of the file before the change. It also avoids making a new string with the modified data. These could be significant benefits if the data is very large. > This does not insert it overwrites. > You are better to insert the content into contents and > then just write it all back to the file in one move. > > >> file.write(contents[pos + len(name):]) >> file.close() This is the piece you missed. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Instance attribute as a parameter's default value
Jan Eden wrote: > Hi, > > Jan Eden wrote on 26.08.2005: > > >>Hi, >> >>I need to use an instance attribute as the default value for a parameter to a >>method. >> >>This obviously won't work: >> >>page.Children() >> >>def Children(self, id=self.id, level=2): >> >>How can I get the id parameter to use the attribute page.id? I know I could >>simply use the method call >> >>page.Children(id=page.id) >> >>but I thought it is much more elegant to use a default value here. >> >>Is it possible? > > > Addition: I do use > > def Children(self, id=0, level=2): > if not id: id = self.id > > right now. But still - there has to be a smarter way. Other than using None instead of 0 as Pierre suggests, this is the best way. The problem is that the default argument is bound when the function definition is executed, so the value has to be defined at that time and it is then fixed. To use a (changeable) attribute as the default you have to read it when the function body is executed. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Generate 8 digit random number
Hi everyone I need to generate a password..It has to be an 8 digit number and it has to be random The code I've been trying is the following: import random random.randrange(,) The code works but sometimes it picks a number with 7 digits. Is there any way that I can tell him to select always a random number with 8 digits? Thanks in advanced Alberto ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(,) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? random.randrange(1000,) ?? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Is "0" a valid digit for your password ? If the answer is "YES" then, remember that the "0" at the left of a number are juste removed ! In that case, try writing your password with : "%08d" % password Pierre Alberto Troiano a écrit : > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(,) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Hi Kent Nope... Not workingI'm still getting 7 even 6 digits number Any other idea? Thanks Alberto >From: Kent Johnson <[EMAIL PROTECTED]> >CC: tutor@python.org >Subject: Re: [Tutor] Generate 8 digit random number >Date: Fri, 26 Aug 2005 10:00:50 -0400 > >Alberto Troiano wrote: > > Hi everyone > > > > I need to generate a password..It has to be an 8 digit number and it has >to > > be random > > > > The code I've been trying is the following: > > > > > > import random > > random.randrange(,) > > > > The code works but sometimes it picks a number with 7 digits. Is there >any > > way that I can tell him to select always a random number with 8 digits? > >random.randrange(1000,) ?? > >Kent > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
On Fri, Aug 26, 2005 at 01:50:04PM +, Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(,) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced Hi, The following code seeems to work. from random import choice lnd='0123456789' print ''.join(map(lambda x,y=lnd: choice(y), range(8))) Bye -- The Old Man and the Sea LITE(tm) -- by Ernest Hemingway 'An old man goes fishing, but doesn't have much luck.' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Alberto Troiano wrote: > Hi Kent > > Nope... > Not workingI'm still getting 7 even 6 digits number Are you sure? It works for me: >>> import random >>> random.randrange(1000,) 42247129 >>> for i in range(1000): ... x = random.randrange(1000,) ... if len(str(x)) < 8: ... print x ... >>> (prints nothing - they are all 8 digits) Kent > > Any other idea? > > Thanks > > Alberto > >> From: Kent Johnson <[EMAIL PROTECTED]> >> CC: tutor@python.org >> Subject: Re: [Tutor] Generate 8 digit random number >> Date: Fri, 26 Aug 2005 10:00:50 -0400 >> >> Alberto Troiano wrote: >> > Hi everyone >> > >> > I need to generate a password..It has to be an 8 digit number and it >> has to >> > be random >> > >> > The code I've been trying is the following: >> > >> > >> > import random >> > random.randrange(,) >> > >> > The code works but sometimes it picks a number with 7 digits. Is >> there any >> > way that I can tell him to select always a random number with 8 digits? >> >> random.randrange(1000,) ?? >> >> Kent >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Hey ALL The code Kent sent might work ok but I didn't see it because of what Pierre said about the left 0's I think I will go with Pietro's approach. I think is neater and shorter than the randrange approach Thanks to all that helped Best Regards Alberto >From: Kent Johnson <[EMAIL PROTECTED]> >CC: tutor@python.org >Subject: Re: [Tutor] Generate 8 digit random number >Date: Fri, 26 Aug 2005 10:16:37 -0400 > >Alberto Troiano wrote: > > Hi Kent > > > > Nope... > > Not workingI'm still getting 7 even 6 digits number > >Are you sure? It works for me: > >>> import random > >>> random.randrange(1000,) >42247129 > >>> for i in range(1000): > ... x = random.randrange(1000,) > ... if len(str(x)) < 8: > ... print x > ... > >>> (prints nothing - they are all 8 digits) > >Kent > > > > Any other idea? > > > > Thanks > > > > Alberto > > > >> From: Kent Johnson <[EMAIL PROTECTED]> > >> CC: tutor@python.org > >> Subject: Re: [Tutor] Generate 8 digit random number > >> Date: Fri, 26 Aug 2005 10:00:50 -0400 > >> > >> Alberto Troiano wrote: > >> > Hi everyone > >> > > >> > I need to generate a password..It has to be an 8 digit number and it > >> has to > >> > be random > >> > > >> > The code I've been trying is the following: > >> > > >> > > >> > import random > >> > random.randrange(,) > >> > > >> > The code works but sometimes it picks a number with 7 digits. Is > >> there any > >> > way that I can tell him to select always a random number with 8 >digits? > >> > >> random.randrange(1000,) ?? > >> > >> Kent > >> > >> ___ > >> Tutor maillist - Tutor@python.org > >> http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] find() function an Tupel. Always returns -1.
hi there, i got a problem with Tupel and the find() function. I know in the document are this Keywords which i am looking for but find() always returns -1. Thanks for the help. fedora_user #!/usr/bin/python # -*- coding: utf_8 -*- import string import sys import os import urllib anf_bez = ('Startpreis:','Restzeit:','Angebotsbeginn:','Übersicht:','Artikelstandort:','Versand nach:', 'Artikelnummer:','Kategorie') end_bez = ('','MESZ','MESZ','Gebote','','','','') # Artikelnummer von dem die Infos gespeichert werden artikelno = `sys.argv[1:2]` artikelno = artikelno[2:-2] if len(artikelno) != 0: TARGET_DIR = "/opt/internet/eBay/" EBAY_HTTP = "http://cgi.ebay.de/ws/eBayISAPI.dll?ViewItem&item="; EBAY_PAGE = EBAY_HTTP + artikelno SAVE_PAGE = "" SAVE_PAGE = SAVE_PAGE + "eBay-artikel" + artikelno + ".html" SAVE_PAGE = os.path.join(TARGET_DIR,SAVE_PAGE) # webSite laden und speichern urllib.urlretrieve(EBAY_PAGE,SAVE_PAGE) # webSite öffnen und absuchen file = open(SAVE_PAGE,"rt") for a in file: asi = 0 # Suchindex für 'anf_bez' esi = 0 # Suchindex für 'end_bez' while asi < 8: anf = -1 end = -1 anf = a.find( anf_bez[asi] ) # < always returns -1, never find anything ? - if anf != -1: end = a[anf].find( end_bez[esi] ) if end != -1: print a[anf:end] asi = asi+1 esi = esi+1 print asi,esi print EBAY_PAGE print SAVE_PAGE else: print "Artikelnummer als Argument übergeben." ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beautiful Soup / Unicode problem?
> Here you go: > > >>> import types > >>> print types.StringTypes > (, ) > >>> import sys > >>> print sys.version > 2.3.4 (#2, May 29 2004, 03:31:27) > [GCC 3.3.3 (Debian 20040417)] > >>> print type(u'hello' in types.StringTypes > True > >>>sys.getdefaultencoding() > 'ascii' [CCing Leonard Richardson: we found a bug and a correction to the code. See below.] Ok, this is officially a mystery. *grin* Let me try some tests too. ## >>> import BeautifulSoup >>> soup = BeautifulSoup.BeautifulSoup(u"\xbb") >>> import re >>> result = soup.fetchText(re.compile('.*')) Traceback (most recent call last): File "", line 1, in ? File "BeautifulSoup.py", line 465, in fetchText return self.fetch(recursive=recursive, text=text, limit=limit) File "BeautifulSoup.py", line 491, in fetch return self._fetch(name, attrs, text, limit, generator) File "BeautifulSoup.py", line 193, in _fetch if self._matches(i, text): File "BeautifulSoup.py", line 251, in _matches chunk = str(chunk) UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in position 0: ordinal not in range(128) ## Gaaa! Ok, that's not right. Well, at least I'm seeing the same results as you. *grin* This seems like a bug in BeautifulSoup; let me look at the flow of values again... ah! I see. That was silly. The problem is that 'chunk' can be a NavigableString or a NavigatableUnicodeString, and neither of those types are in types.StringType. So the bit of code here: if not type(chunk) in types.StringTypes: never worked properly. *grin* A possible fix to this is to change the check for direct types into a check for subclass or isinstance; we can to change the line in BeautifulSoup.py:250 from: if not type(chunk) in types.StringTypes: to: if not isinstance(chunk, basestring): Testing the change now... ## >>> soup = BeautifulSoup.BeautifulSoup(u"\xbb") >>> result = soup.fetchText(re.compile('.*')) >>> result [u'\xbb'] ## Ah, better. *grin* One other problem is the implementation of __repr__(); I know it's convenient for it to delegate to str(), but that poses a problem: ## >>> soup = BeautifulSoup.BeautifulSoup(u"\xbb") >>> soup Traceback (most recent call last): File "", line 1, in ? File "BeautifulSoup.py", line 374, in __repr__ return str(self) UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in position 6: ordinal not in range(128) ## repr() should never fail like this, regardless of our default encoding. The cheap way out might be to just not implement repr(), but that's probably not so nice. *grin* I'd have to look at the implementation of __str__() some more and see if there's a good general way to fix this. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beautiful Soup / Unicode problem?
Hi Danny, > If you have a moment, do you mind doing this on your system? > Here you go: >>> import types >>> print types.StringTypes (, ) >>> import sys >>> print sys.version 2.3.4 (#2, May 29 2004, 03:31:27) [GCC 3.3.3 (Debian 20040417)] >>> print type(u'hello' in types.StringTypes True >>>sys.getdefaultencoding() 'ascii' I have a second machine running XP and Activestate 2.4.1, I get the same results with the exception of: >>> sys.version '2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)]' Today I tried changing my default encoding to uft8, and the error went away. I have no idea -why- it would go away, and it feels like a hacky solution. And confusing, because I wasn't trying to print anything to the screen, so why would python care or complain? Almost forgot, I tried the included Beautiful Soup tests on both machines and got an error on both: # python BeautifulSoupTests.py ...E == ERROR: testBasicUnicode (__main__.UnicodeRed) -- Traceback (most recent call last): File "BeautifulSoupTests.py", line 209, in testBasicUnicode self.assertEqual(type(str(self.soup)), sType) UnicodeEncodeError: 'ascii' codec can't encode character u'\xc8' in position 13: ordinal not in range(128) So there may be a bug, but I don't know if it's my problem It's strange that the tests fail on two different computers running two versions of python, however. > > and show us what comes up? > > > > Good luck to you! > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Beautiful Soup / Unicode problem?
>This is the first question in the BeautifulSoup FAQ at >http://www.crummy.com/software/BeautifulSoup/FAQ.html >Unfortunately the author of BS considers this a problem with your Python installation! So it >seems he doesn't have a good understanding of Python and Unicode. (OK, I can forgive him >that, I think there are only a handful of people who really do understand it completely.) >The first fix given doesn't work. The second fix works but it is not a good idea to change the >default encoding for your Python install. There is a hack you can use to change the default >encoding just for one program; in your program put > reload(sys); sys.setdefaultencoding('utf-8') >This seems to fix the problem you are having. >Kent Hi Kent, I did read the FAQ before posting, honest :) But it does seem to be addressing a different issue. He says to try: >>> latin1word = 'Sacr\xe9 bleu!' >>> unicodeword = unicode(latin1word, 'latin-1') >>> print unicodeword Sacré bleu! Which worked fine for me. And then he gives a solution for fixing -display- problems on the terminal. For instance, his first solution was : "The easy way is to remap standard output to a converter that's not afraid to send ISO-Latin-1 or UTF-8 characters to the terminal." But I avoided displaying anything in my original example, because I didn't want to confuse the issue. It's also why I didn't mention the damning FAQ entry: >>> y = results[1].a.fetchText(re.compile('.+')) Is all I am trying to do. I don't expect non-ASCII characters to display correctly, however I was suprised when I tried "print x" in my original example, and it printed. I would have expected to have to do something like: >>> print x.encode("utf8") Matt Croydon::Postneo 2.0 » Blog Archive » Mobile Screen Scraping ... I've just looked, and I have to do this explicit encoding under python 2.3.4, but not under 2.4.1. So perhaps 2.4 is less afraid/smarter about converting and displaying non-ascii characters to the terminal. Either way, I don't -think- that's my problem with Beautiful Soup. Changing my default encoding does indeed fix it, but it may be a reflection of the author making bad assumptions because his default was set to utf-8. I'm not really experienced enough to tell what is going on in his code, but I've been trying. Does seem to defeat the point of unicode, however. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Hi Alberto, Here's how to do it: --- import random def generateKey(): nums = "0123456789" strNumber = "" count = 0 while (count < 8): strNumber += nums[random.randrange(len(nums))] count += 1 print strNumber # A quick test... count = 0 while (count < 1): generateKey() count += 1 --- Byron :-) --- Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(,) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Alberto If you don't mind having leading 0 then you could just do the random like you did then format it to 9 digits. You could give this a try num = random.randrange(,) num8 = "%09i" % num John Ertl -Original Message- From: Byron [mailto:[EMAIL PROTECTED] Sent: Friday, August 26, 2005 1:50 PM To: Alberto Troiano; tutor@python.org Subject:Re: [Tutor] Generate 8 digit random number Hi Alberto, Here's how to do it: --- import random def generateKey(): nums = "0123456789" strNumber = "" count = 0 while (count < 8): strNumber += nums[random.randrange(len(nums))] count += 1 print strNumber # A quick test... count = 0 while (count < 1): generateKey() count += 1 --- Byron :-) --- Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(,) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Sorry for that you will have to change the %09 to a %08 to get 8 digits. I got a bit to fixated on the John Ertl -Original Message- From: Ertl, John Sent: Friday, August 26, 2005 2:23 PM To: Alberto Troiano; tutor@python.org Subject:RE: [Tutor] Generate 8 digit random number Alberto If you don't mind having leading 0 then you could just do the random like you did then format it to 9 digits. You could give this a try num = random.randrange(,) num8 = "%09i" % num John Ertl -Original Message- From: Byron [mailto:[EMAIL PROTECTED] Sent: Friday, August 26, 2005 1:50 PM To: Alberto Troiano; tutor@python.org Subject:Re: [Tutor] Generate 8 digit random number Hi Alberto, Here's how to do it: --- import random def generateKey(): nums = "0123456789" strNumber = "" count = 0 while (count < 8): strNumber += nums[random.randrange(len(nums))] count += 1 print strNumber # A quick test... count = 0 while (count < 1): generateKey() count += 1 --- Byron :-) --- Alberto Troiano wrote: > Hi everyone > > I need to generate a password..It has to be an 8 digit number and it has to > be random > > The code I've been trying is the following: > > > import random > random.randrange(,) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? > > Thanks in advanced > > Alberto > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with files
> Alan, you missed the last part of the code - he writes the rest of > the data following the match into the file. I didn't miss it but I did misread it! :-) >file.write(contents[pos + len(name):]) I assumed 'name' was here referring to the actual value inserted. But of course that would have been a different bug to the one I described. > This is an innovative approach which may have some benefit over the > usual / read the whole file / change the data in memory / write the > whole file / method as it avoids re-writing the part of the file > before the change. Yes indeed, now that I actually see what's happening it's quite cute! > It also avoids making a new string with the modified data. True but it does involve a new string fom the slice, so I wouldn't expect a huge saving there. But the random file access should be faster than a full rewrite operation. Thanks for pointing out my mistake and my compliments to the OP! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
> I need to generate a password..It has to be an 8 digit number and it > has to be random I assume you mean a string representing an 8 digit random number? If so... > import random > random.randrange(,) > > The code works but sometimes it picks a number with 7 digits. Is > there any way that I can tell him to select always a random number > with 8 digits? Eventually it will generate a single digit number if its truly random! But when you convert it to a string (see assumption above!) you can pad it with zeros passString = "%08d" % random.randrange(0,) Is that what you want? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
On Fri, 26 Aug 2005, Alberto Troiano wrote: > I need to generate a password..It has to be an 8 digit number and it has > to be random > > import random > random.randrange(,) > > The code works but sometimes it picks a number with 7 digits. Is there any > way that I can tell him to select always a random number with 8 digits? well, you've gotten a lot of good answers, so let me chime in with a really ugly one: >>> ''.join(['000',str(random.randrange(,))])[-8:] '00101381' (I don't really recommend this, but this is pretty much akin to the prefered way in IBM's EXEC2 language as I used to use it some 25 years ago!) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
On 8/26/05, Alberto Troiano <[EMAIL PROTECTED]> wrote: Hi everyoneI need to generate a password..It has to be an 8 digit number and it has tobe randomThe code I've been trying is the following:import randomrandom.randrange(,) The code works but sometimes it picks a number with 7 digits. Is there anyway that I can tell him to select always a random number with 8 digits?Thanks in advancedAlberto Along with everyone else's solutions, I'll throw out: str(random.randrange()).zfill(8) -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Strange XP stdin behaviour.
Hi gang, a strange one uncovered by a student of my tutorial. If you create the following example program, lets call it intest.py: ### intest.py # inp = raw_input()while inp != '': print inp inp = raw_input() ### And the following data file Not part of in.txt - 6 7 8 Not part of in.txt - Then run Python from a DOS prompt like so: C:\somepath> pythopn intest.py < in.txt The file content is echo'd as expected. But if you start it: C:\somepath> intest.py < in.txt There is no output! In fact, I get an error: E:\PROJECTS\Python>intest.py < in.txtTraceback (most recent call last): File "E:\PROJECTS\Python\intest.py", line 2, in ? inp = raw_input()EOFError: EOF when reading a line And if you run C:\somepath> intest.py You get the interactive version as expected. Why the difference with the redirected file? I am confused. What am I missing? XP seems to have a different runtime environment depending on how the script is run... BTW This also happens under cygwin. Alan GAuthor of the Learn to Program web tutorhttp://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Strange XP stdin behaviour.
> C:\somepath> intest.py < in.txt > > There is no output! > In fact, I get an error: > > E:\PROJECTS\Python>intest.py < in.txt > Traceback (most recent call last): > File "E:\PROJECTS\Python\intest.py", line 2, in ? > inp = raw_input() > EOFError: EOF when reading a line Hi Alan, Yes, this is a Windows-specific thing. Unfortunately, Windows's treatment of shell scripts is slightly inconsistant. However, there are workarounds by making a '.CMD' file. See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366355 for details. Hope this helps! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Strange XP stdin behaviour.
>> C:\somepath> intest.py < in.txt >> >> There is no output! >> In fact, I get an error: > > Yes, this is a Windows-specific thing. Unfortunately, Windows's > treatment > of shell scripts is slightly inconsistant. However, there are > workarounds > by making a '.CMD' file. See: > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366355 > Thanks Danny, interesting link in that it shows a solution I didn't know about in the one-liner at the bottom of the discussion. But really I was hoping someone could explain *why* there is a difference. If PATHEXT can detect that intest.py needs to be run through Python why doesn't redirection work as expected? What is happening to stdin/stdout in this case? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor