From bob.nienhuis at gmail.com Mon Oct 1 01:05:48 2007 From: bob.nienhuis at gmail.com (Bob Nienhuis) Date: Sun, 30 Sep 2007 15:05:48 -0800 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> Message-ID: <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> BTW, GMail brings up some interesting sponsored links when the subject line has string.strip in it ( :-0) On 9/30/07, Alan Gauld wrote: > > > "wesley chun" wrote in message > news:78b3a9580709300102x12cbe392uebb988ed965c7202 at mail.gmail.com... > >> > I'm not sure how to proceed. My biggest stumbling > >> > block is how to detect the leading and trailing > >> > whitespace. > >> > >> Use indexing. > >> Try using a while loop. > >> Or maybe two? > >> > >> And strings have an isspace method... > > > > unfortunately, the isspace() string method only returns True if all > > chars in the string are whitespace chars and False otherwise, so > > that's a bummer. > > But the string can be one character long: > > s = 'fred\n' > print s[-1].isspace() # --> True > > :-) > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070930/c8a1d7ee/attachment-0001.htm From mwalsh at groktech.org Mon Oct 1 02:44:35 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 30 Sep 2007 19:44:35 -0500 Subject: [Tutor] CGI File Woes In-Reply-To: <939808.45127.qm@web32411.mail.mud.yahoo.com> References: <939808.45127.qm@web32411.mail.mud.yahoo.com> Message-ID: <470042F3.6030108@groktech.org> wormwood_3 wrote: > Those examples were a lot of help Martin. Turned out the only issue was that I did not have this line right: > > print "Content-type: text/html\n\n" Sam, Glad the examples helped. I should probably fess up and point out that I mistakenly added an additional newline to that print statement. You only need one, as the print itself will append an extra. So by adding the addition \n, a blank line will be sent to the browser as part of the page content, which shouldn't be a problem for text/html content-types. But as soon as you want to serve up another content-type (eg. image/png) you may run into odd problems. So, the corrected print statement should look like this: print "Content-type: text/html\n" or as described in the docs, http://docs.python.org/lib/cgi-intro.html print "Content-type: text/html" print HTH, Marty > > With that form, it loaded just fine. It had been running fine from the terminal, but without this line being right, Apache did not know what to do with it. > > I had spoken with my web-hosting provider, but since I had a shared account I was unable to view the server logs. And the person helping me knew nothing about Python (he kept slipping and calling it PHP actually, to my dismay and chagrin:-) ). > > Thanks for all the help, Alan and Martin. > > -Sam > > _________________ > ----- Original Message ---- > From: Martin Walsh > To: tutor at python.org > Sent: Sunday, September 30, 2007 1:07:02 PM > Subject: Re: [Tutor] CGI File Woes > > No doubt cgitb is a great tool for debugging cgi, but IIUC there are at > least two instances when you will not get the pretty printed tracebacks > in the browser when using cgitb. One is after, what I would call, a > 'compile time' exception such as SyntaxError, in your python code. The > other is when the python code runs without exception, but you have not > separated the header and the document content with a newline. At least, > I have found these to be true when using apache-cgi. > > Consider the following examples: > > #!/usr/bin/env python > # raises a SyntaxError > > import cgi > import cgitb; cgitb.enable() > > print "Content-type: text/html\n\n" > # NOTE: purposeful misspelling of the print statement > prin "

Hello, world!

" > > # the code above will produce a server 500, with apache > # complaining about "premature end of script headers" From varsha.purohit at gmail.com Mon Oct 1 03:38:57 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 30 Sep 2007 18:38:57 -0700 Subject: [Tutor] [tutor] printing bitmap image dynamically reading data in wxpython Message-ID: Hello All, I want to create a wxpython program where i am reading a list having integer values like [1,2,3,4]. and i need to display the output value as bitmap image which shd be coloured after reading the values. Like 1=red, 2=yellow, 3=orange etc and it displays the output in colours at proper coordinates by matching values of the array. I need to make a script file for arcgis tool which converts the ascii data to a coloured bitmap image at given coordinates. thanks, -- Varsha Purohit, Graduate Student, San Diego State University -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070930/801bac5f/attachment.htm From varsha.purohit at gmail.com Mon Oct 1 04:46:16 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 30 Sep 2007 19:46:16 -0700 Subject: [Tutor] [tutor] creating image from a given data in wxpython Message-ID: Hi All, I basically wanna create a bitmap image in python. This will be basically in pixels. X and y coordinates will be specified in the program and python should create an image by matching the colours. I came across a function called wx.ImageFromData which book claims that it creates a bitmap image in pixels. But i am not getting proper implementation of this function on net... thanks,, Varsha On 9/30/07, Varsha Purohit wrote: > > Hello All, > > I want to create a wxpython program where i am reading a list having > integer values like [1,2,3,4]. and i need to display the output value as > bitmap image which shd be coloured after reading the values. Like 1=red, > 2=yellow, 3=orange etc and it displays the output in colours at proper > coordinates by matching values of the array. I need to make a script file > for arcgis tool which converts the ascii data to a coloured bitmap image at > given coordinates. > > thanks, > -- > Varsha Purohit, > Graduate Student, > San Diego State University -- Varsha Purohit, Graduate Student, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070930/a35dc421/attachment.htm From witham.ian at gmail.com Mon Oct 1 05:05:36 2007 From: witham.ian at gmail.com (Ian Witham) Date: Mon, 1 Oct 2007 15:05:36 +1200 Subject: [Tutor] [tutor] creating image from a given data in wxpython In-Reply-To: References: Message-ID: On 10/1/07, Varsha Purohit wrote: > > Hi All, > I basically wanna create a bitmap image in python. This will be > basically in pixels. X and y coordinates will be specified in the program > and python should create an image by matching the colours. I came across a > function called wx.ImageFromData which book claims that it creates a > bitmap image in pixels. But i am not getting proper implementation of this > function on net... Hi Varsha, I have not delved too deeply into WX, but I have made bitmaps from data using TKinter's canvas. I found it to be a very slow way to do things (both in programming and in execution speed) and I ended up using the Python Image Library (PIL) instead. If you don't really need the GUI capabilities of WX for this project then PIL is probably a better tool for the job. Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071001/8fd7cfaa/attachment.htm From linpeiheng at 163.com Mon Oct 1 04:52:37 2007 From: linpeiheng at 163.com (=?gb2312?B?wdbF4Lrj?=) Date: Mon, 1 Oct 2007 10:52:37 +0800 Subject: [Tutor] How to Practice Python?(Linpeiheng) Message-ID: <47006476.08ADDF.17520@m5-84.163.com> I am learning Python. Do you know somewhere I can practice Python? I means some sites where have exercises I can try solving. And there should be standard answer or other people's answer that can be refered. From wormwood_3 at yahoo.com Mon Oct 1 05:20:00 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 30 Sep 2007 20:20:00 -0700 (PDT) Subject: [Tutor] Really basic web templating Message-ID: <300093.45498.qm@web32406.mail.mud.yahoo.com> Hello all, I am trying to think of a way to make this happen, but it may not be at all possible:-) I would like to use Python to generate pages on demand for my website. By this I mean, when someone hits www.mysite.com/pagex.html, I want to generate the page pagex.html via a Python script. I have a script setup that can generate a page from a template file and a file with the body and title of the page in particular I want to generate. Now from this, I need to somehow be able to respond to requests, and then generate the page based on the page requested. I want to do this because my site is on a shared hosting account, so I cannot install a web framework like Django, and the site's pages will be rather simple. At the same time, I would like to use templating, so I do not have repeated identical code between the pages. Any ideas on this? Thanks, Sam From witham.ian at gmail.com Mon Oct 1 05:52:38 2007 From: witham.ian at gmail.com (Ian Witham) Date: Mon, 1 Oct 2007 15:52:38 +1200 Subject: [Tutor] Really basic web templating In-Reply-To: <300093.45498.qm@web32406.mail.mud.yahoo.com> References: <300093.45498.qm@web32406.mail.mud.yahoo.com> Message-ID: On 10/1/07, wormwood_3 wrote: > > Hello all, > > I am trying to think of a way to make this happen, but it may not be at > all possible:-) I would like to use Python to generate pages on demand for > my website. By this I mean, when someone hits www.mysite.com/pagex.html, I > want to generate the page pagex.html via a Python script. > > I have a script setup that can generate a page from a template file and a > file with the body and title of the page in particular I want to generate. > Now from this, I need to somehow be able to respond to requests, and then > generate the page based on the page requested. I want to do this because my > site is on a shared hosting account, so I cannot install a web framework > like Django, and the site's pages will be rather simple. At the same time, I > would like to use templating, so I do not have repeated identical code > between the pages. > > Any ideas on this? It sounds like you want to use CGI. I think virtually all web servers support it and there are a ton of CGI tutorials on the web Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071001/36af6e02/attachment.htm From wormwood_3 at yahoo.com Mon Oct 1 06:05:39 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 30 Sep 2007 21:05:39 -0700 (PDT) Subject: [Tutor] Really basic web templating Message-ID: <595371.22030.qm@web32407.mail.mud.yahoo.com> Well yes and no:-) This sort of application would fall under the sprawling category of CGI, yes, and I can use Python scripts on my web server, so it is supported. But nearly every tutorial I have seen regarding Python and CGI only have to do with form submissions, doing calculations and other things with data sent from webpages to Python scripts. But that is not really what I want to do. I am wondering what a script would need to do to take requests for pages on my site, and generate them from templates. I am not sure if I can do this without having access to Apache rewrite rules, etc. Perhaps this is just another area of CGI that I missed and have not seen tutorials on. If it is and you have seen some, please share! -Sam ________________ ----- Original Message ---- From: Ian Witham To: wormwood_3 Cc: Python Tutorlist Sent: Sunday, September 30, 2007 11:52:38 PM Subject: Re: [Tutor] Really basic web templating On 10/1/07, wormwood_3 wrote: Hello all, I am trying to think of a way to make this happen, but it may not be at all possible:-) I would like to use Python to generate pages on demand for my website. By this I mean, when someone hits www.mysite.com/pagex.html, I want to generate the page pagex.html via a Python script. I have a script setup that can generate a page from a template file and a file with the body and title of the page in particular I want to generate. Now from this, I need to somehow be able to respond to requests, and then generate the page based on the page requested. I want to do this because my site is on a shared hosting account, so I cannot install a web framework like Django, and the site's pages will be rather simple. At the same time, I would like to use templating, so I do not have repeated identical code between the pages. Any ideas on this? It sounds like you want to use CGI. I think virtually all web servers support it and there are a ton of CGI tutorials on the web Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070930/7b14f42c/attachment-0001.htm From steve at alchemy.com Mon Oct 1 06:41:12 2007 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 30 Sep 2007 21:41:12 -0700 Subject: [Tutor] Really basic web templating In-Reply-To: <595371.22030.qm@web32407.mail.mud.yahoo.com> References: <595371.22030.qm@web32407.mail.mud.yahoo.com> Message-ID: <47007A68.9000006@alchemy.com> wormwood_3 wrote: > Well yes and no:-) This sort of application would fall under the > sprawling category of CGI, yes, and I can use Python scripts on my web > server, so it is supported. But nearly every tutorial I have seen > regarding Python and CGI only have to do with form submissions, doing > calculations and other things with data sent from webpages to Python > scripts. But that is not really what I want to do. I am wondering what a > script would need to do to take requests for pages on my site, and > generate them from templates. I am not sure if I can do this without > having access to Apache rewrite rules, etc. > > Perhaps this is just another area of CGI that I missed and have not seen > tutorials on. If it is and you have seen some, please share! > Yes, it's just another area of CGI that you missed. Things like wikis do this, for one example. If you request a URL you get a script which serves the page if it exists, or creates a blank one if it doesn't. You can use Python's string template module as an easy way to format up variable text into style templates you set up as text files, or use a database backend, or whatever. --steve > -Sam > > ________________ > ----- Original Message ---- > From: Ian Witham > To: wormwood_3 > Cc: Python Tutorlist > Sent: Sunday, September 30, 2007 11:52:38 PM > Subject: Re: [Tutor] Really basic web templating > > > > On 10/1/07, *wormwood_3* > wrote: > > Hello all, > > I am trying to think of a way to make this happen, but it may not be > at all possible:-) I would like to use Python to generate pages on > demand for my website. By this I mean, when someone hits > www.mysite.com/pagex.html , I want > to generate the page pagex.html via a Python script. > > I have a script setup that can generate a page from a template file > and a file with the body and title of the page in particular I want > to generate. Now from this, I need to somehow be able to respond to > requests, and then generate the page based on the page requested. I > want to do this because my site is on a shared hosting account, so I > cannot install a web framework like Django, and the site's pages > will be rather simple. At the same time, I would like to use > templating, so I do not have repeated identical code between the pages. > > Any ideas on this? > > > It sounds like you want to use CGI. I think virtually all web servers > support it and there are a ton of CGI tutorials on the web > > Ian. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From gtxy20 at gmail.com Mon Oct 1 07:35:02 2007 From: gtxy20 at gmail.com (GTXY20) Date: Mon, 1 Oct 2007 01:35:02 -0400 Subject: [Tutor] Dictionary - count values where values are stored as a list Message-ID: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> Hello, Any way to display the count of the values in a dictionary where the values are stored as a list? here is my dictionary: {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': ['a', 'c']} I would like to display count as follows and I would not know all the value types in the values list: Value QTY a 4 b 3 c 4 Also is there anyway to display the count of the values list combinations so here again is my dictionary: {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': ['a', 'c']} And I would like to display as follows QTY Value List Combination 3 a,b,c 1 a,c Once again all help is much appreciated. M. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071001/13e41d51/attachment.htm From mail at timgolden.me.uk Mon Oct 1 09:02:29 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 01 Oct 2007 08:02:29 +0100 Subject: [Tutor] Disable keyboard/mouse input on windows? In-Reply-To: <61872.68.191.136.241.1191107303.squirrel@webmail.opmstech.org> References: <61872.68.191.136.241.1191107303.squirrel@webmail.opmstech.org> Message-ID: <47009B85.6060509@timgolden.me.uk> Trey Keown wrote: > Hey everybody, > I was wondering, how could I disable all keyboard/mouse input for the > whole windows system while I have a video playing? So the user can't > press, for example, the super key [one with windows logo on it], and have > the windows menu pop up? > Could this be accomplished somehow through system hooks? In the final analysis, I imagine you *could* do this by digging hard enough. But (a) it won't be easy to do it in a robust way which takes account of all possibilities, and (b) I think any program which acted in this way (locking out all others) would be *very* ill-considered. If you're really set on this, it's probably worth looking for kiosk-mode / internet cafe setups as they presumably do things like this, so maybe Googling for those terms might throw up a solution. TJG From alan.gauld at btinternet.com Mon Oct 1 09:33:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 08:33:40 +0100 Subject: [Tutor] How to Practice Python?(Linpeiheng) References: <47006476.08ADDF.17520@m5-84.163.com> Message-ID: "???" wrote > I am learning Python. Do you know somewhere I can practice Python? > I means some sites where have exercises I can try solving. The Useless Python website has some exercises and other small projects. Some have solutions some don't. Also the Python Challenge web site offers a "Game" where you navigate through the lasyers by solving Python puzzles, each using a new feature of Python. > And there should be standard answer or other people's > answer that can be refered. This is harder. There are solutions around for spome of them but not "standard solutions" - I'm not sure what such a thing would look like in a programming context. There are no such things as standard solutions to programming problems, its not like doing math! Some solutions are nicer than othes but each usually has some merit. HTH, Alan G From alan.gauld at btinternet.com Mon Oct 1 09:41:02 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 08:41:02 +0100 Subject: [Tutor] Really basic web templating References: <595371.22030.qm@web32407.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > ...nearly every tutorial I have seen regarding Python and CGI only > have to do with form submissions, Thats the most common use of CGI but really a form submission is just a standard HTTP GET/POST request with some predefined variables. In reality the user requests your python script and whatever the script sends to stdout goes to the browser So all you have to do is read in your header, body and footer and stitch them together then send them to stdout. If you want richer functionality you can use templating engines from the frameworks without the framework being present. For example the kid system used in TurboGears can be used standalone to give sophistoicated templating without anything special being done to the web server. Indeed it can even be used outside a web server context. But from your description simple CGI and Python may be all you need. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Oct 1 09:46:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 08:46:35 +0100 Subject: [Tutor] Disable keyboard/mouse input on windows? References: <61872.68.191.136.241.1191107303.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > I was wondering, how could I disable all keyboard/mouse input for > the > whole windows system while I have a video playing? So the user can't > press, for example, the super key [one with windows logo on it], and > have > the windows menu pop up? > Could this be accomplished somehow through system hooks? Yes it can be done using the low level Windows API calls. You could do that from Python using ctypes. But you really shouldn't! It's very easy to lock up a PC completely if you do that and many users get very cross whem they run a program which completely locks their machine and prevents them using it for other things. After all they paid for a multi-tasking OS why should applications prevent them from using it?! >From a video playing perspective consider too how you might get rid of a warning dialog that Windows (or your anti-virus scanner etc) decides to pop onto the screen while watching the video? You are stuck with a dialog blocking the view which you can't get rid of till the video ends! Alan G From alan.gauld at btinternet.com Mon Oct 1 09:53:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 08:53:30 +0100 Subject: [Tutor] [tutor] creating image from a given data in wxpython References: Message-ID: "Ian Witham" wrote >> I basically wanna create a bitmap image in python. This will be >> basically in pixels. X and y coordinates will be specified in the >> program >> and python should create an image by matching the colours. > I found it to be a very slow way to do things (both in programming > and in > execution speed) and I ended up using the Python Image Library (PIL) > instead. > > If you don't really need the GUI capabilities of WX for this project > then > PIL is probably a better tool for the job. Avtually I'd recommend PIL even if you do need the wxPython GUI capabilities. wxPython will happily display bitmapps created in PIL. Alan G. From alan.gauld at btinternet.com Mon Oct 1 09:50:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 08:50:31 +0100 Subject: [Tutor] [tutor] printing bitmap image dynamically reading data inwxpython References: Message-ID: "Varsha Purohit" wrote > I want to create a wxpython program where i am reading a list > having > integer values like [1,2,3,4]. and i need to display the output > value as > bitmap image which shd be coloured after reading the values. Like > 1=red, > 2=yellow, 3=orange etc and it displays the output in colours at > proper > coordinates by matching values of the array. Sounds like a fun project. Have you any plans on how to go about it? Are you having problems? Or are you just sharing your excitement at the challenge? > I need to make a script file for arcgis tool which converts the > ascii data to a coloured bitmap image at given coordinates. I dunno much about arcgis but again it sounds like a reasonable thing to do. Let us know how you get on. If you run into problems ask questions we might be able to help. However since it seems to be a homework type exercise we can't solve it for you. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Oct 1 09:58:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 08:58:48 +0100 Subject: [Tutor] Dictionary - count values where values are stored as a list References: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> Message-ID: "GTXY20" wrote > Any way to display the count of the values in a dictionary where the > values > are stored as a list? here is my dictionary: > > {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], > '4': > ['a', 'c']} > > I would like to display count as follows and I would not know all > the value > types in the values list: > > Value QTY > a 4 > b 3 > c 4 Try a list comprehension: data = [(key, len(D[key]) for key in D] Printing that out becomes a simple loop: print "Value\tQTY" for tup in data: print "%s\t%s" % tup > Also is there anyway to display the count of the values list > combinations so > here again is my dictionary: > {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], > '4': > ['a', 'c']} > The same approach should work except you change the tuple values: data = [(len(D[key]), D[key]) for key in D] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mwalsh at groktech.org Mon Oct 1 10:32:07 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Mon, 01 Oct 2007 03:32:07 -0500 Subject: [Tutor] Really basic web templating In-Reply-To: <595371.22030.qm@web32407.mail.mud.yahoo.com> References: <595371.22030.qm@web32407.mail.mud.yahoo.com> Message-ID: <4700B087.9030603@groktech.org> wormwood_3 wrote: > Well yes and no:-) This sort of application would fall under the > sprawling category of CGI, yes, and I can use Python scripts on my web > server, so it is supported. But nearly every tutorial I have seen > regarding Python and CGI only have to do with form submissions, doing > calculations and other things with data sent from webpages to Python > scripts. But that is not really what I want to do. I am wondering what a > script would need to do to take requests for pages on my site, and > generate them from templates. I am not sure if I can do this without > having access to Apache rewrite rules, etc. I am going to assume from your description that you are looking for a way to use a *single* cgi script to handle all page requests to your site, and respond with the appropriate template based on the requested url. If I have assumed incorrectly then you can safely ignore the rest of this message. :) Some mod_rewrite directives are available to .htaccess, IIRC -- so that may be a valid option, only if your webhost has enabled mod_rewrite of course, and they allow overrides with htaccess. Otherwise, this is a fairly simple task if you are content with "ugly" urls. For example, given a url something like http://mysite.com/mycgi.py?page=index.html, a very basic cgi implementation might look like this: #!/usr/bin/env python import cgi form = cgi.FieldStorage() print "Content-type: text/html\n" try: page = form["page"] except KeyError: print file('custom404error.html').read() else: content = file(page.value).read() # ... do something with content ... print content --- If your webhost has enabled mod_actions (I suppose this is unlikely), you can also do the following in .htaccess (again, only if they allow override): AddHandler my-python-handler .html Action my-python-handler /cgi-bin/handler.py which should force apache to set an environment variable named 'PATH_TRANSLATED' with the value of the requested url, and call 'handler.py' for any requested file with an .html extension (that exists) in that directory -- honestly, I've never attempted this myself -- and there is probably a better way, but it's all I can think of ATM. If the file doesn't exist apache returns a 404, which is only desirable if you plan to store your templates on the filesystem. And you can use the os module to access the cgi environment variables: #!/usr/bin/env python import os print "Content-type: text/plain\n" try: path = os.environ["PATH_TRANSLATED"] except: path = 'PATH_TRANSLATED is not defined.' print "The requested url is:", path --- Perhaps you could convince your webhost to install mod_python, if they haven't already. It's fairly trivial to write a simple mod_python handler to accomplish exactly what you are trying to do. HTH, Marty From aijames at exemail.com.au Mon Oct 1 02:23:16 2007 From: aijames at exemail.com.au (Andrew James) Date: Mon, 01 Oct 2007 10:23:16 +1000 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> Message-ID: <47003DF4.2020903@exemail.com.au> I've gone ahead and created a script that does this, however it also strips punctuation. I was originally just comparing each character to a string containing a single space ' ' but even using s[-1].isspace() I lose punctuation marks. Any idea why that's happening? (Not the OP, I just thought this would be interesting to do) Bob Nienhuis wrote: > BTW, GMail brings up some interesting sponsored links when the subject > line > has string.strip in it ( :-0) > > On 9/30/07, *Alan Gauld* < alan.gauld at btinternet.com > > wrote: > > > "wesley chun" < wescpy at gmail.com > wrote > in message > news:78b3a9580709300102x12cbe392uebb988ed965c7202 at mail.gmail.com... > >> > I'm not sure how to proceed. My biggest stumbling > >> > block is how to detect the leading and trailing > >> > whitespace. > >> > >> Use indexing. > >> Try using a while loop. > >> Or maybe two? > >> > >> And strings have an isspace method... > > > > unfortunately, the isspace() string method only returns True if all > > chars in the string are whitespace chars and False otherwise, so > > that's a bummer. > > But the string can be one character long: > > s = 'fred\n' > print s[-1].isspace() # --> True > > :-) > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------------------------------------------------ > > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.5.488 / Virus Database: 269.13.35 - Release Date: 29/09/2007 12:00 AM > From kent37 at tds.net Mon Oct 1 12:44:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 06:44:45 -0400 Subject: [Tutor] Really basic web templating In-Reply-To: <300093.45498.qm@web32406.mail.mud.yahoo.com> References: <300093.45498.qm@web32406.mail.mud.yahoo.com> Message-ID: <4700CF9D.1020404@tds.net> wormwood_3 wrote: > I want > to do this because my site is on a shared hosting account, so I cannot > install a web framework like Django Another option is to switch to a hosting account that supports Python. I have been working with WebFaction and I'm very happy with them; an account with Django support is available for less than $10/month. Kent From kent37 at tds.net Mon Oct 1 13:17:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 07:17:13 -0400 Subject: [Tutor] Dictionary - count values where values are stored as a list In-Reply-To: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> References: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> Message-ID: <4700D739.7080506@tds.net> GTXY20 wrote: > Hello, > > Any way to display the count of the values in a dictionary where the > values are stored as a list? here is my dictionary: > > {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': > ['a', 'c']} > > I would like to display count as follows and I would not know all the > value types in the values list: > > Value QTY > a 4 > b 3 > c 4 You need two nested loops - one to loop over the dictionary values and one to loop over the individual lists. collections.defaultdict is handy for accumulating the counts but you could use a regular dict also: In [4]: d={'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': ['a', 'c']} In [5]: from collections import defaultdict In [6]: counts=defaultdict(int) In [7]: for lst in d.values(): ...: for item in lst: ...: counts[item] += 1 ...: In [8]: counts Out[8]: defaultdict(, {'a': 4, 'c': 4, 'b': 3}) In [10]: for k, v in sorted(counts.items()): ....: print k,v ....: ....: a 4 b 3 c 4 > Also is there anyway to display the count of the values list > combinations so here again is my dictionary: > > {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': > ['a', 'c']} > > > And I would like to display as follows > > QTY Value List Combination > 3 a,b,c > 1 a,c Again you can use a defaultdict to accumulate counts. You can't use a mutable object (such as a list) as a dict key so you have to convert it to a tuple: In [11]: c2=defaultdict(int) In [13]: for v in d.values(): ....: c2[tuple(v)] += 1 ....: In [14]: c2 Out[14]: defaultdict(, {('a', 'b', 'c'): 3, ('a', 'c'): 1}) Printing in order of count requires switching the order of the (key, value) pairs: In [15]: for count, items in sorted( ((v, k) for k, v in c2.items()), reverse=True): ....: print count, ', '.join(items) ....: 3 a, b, c 1 a, c or using a sort key: In [16]: from operator import itemgetter In [17]: for items, count in sorted(c2.items(), key=itemgetter(1), reverse=True): ....: print count, ', '.join(items) ....: 3 a, b, c 1 a, c Kent From alan.gauld at btinternet.com Mon Oct 1 13:20:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 12:20:05 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> Message-ID: "Andrew James" wrote > string containing a single space ' ' but even using s[-1].isspace() > I > lose punctuation marks. Any idea why that's happening? care to show us what you are doing? >>> ';'.isspace() False So puntuation should not show up as true... Alan G. From kent37 at tds.net Mon Oct 1 13:22:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 07:22:25 -0400 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <47003DF4.2020903@exemail.com.au> References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> Message-ID: <4700D871.60202@tds.net> Andrew James wrote: > I've gone ahead and created a script that does this, however it also > strips punctuation. I was originally just comparing each character to a > string containing a single space ' ' but even using s[-1].isspace() I > lose punctuation marks. Any idea why that's happening? Hmmm, I seem to have misplaced my glasses of distant screen reading +3 Australia is a bit far for me to look over you shoulder. Maybe you should just post your code here so we can take a look. Kent From wormwood_3 at yahoo.com Mon Oct 1 14:24:49 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 1 Oct 2007 05:24:49 -0700 (PDT) Subject: [Tutor] Really basic web templating Message-ID: <678775.64655.qm@web32404.mail.mud.yahoo.com> My host actually does support Python. But I don't have access to Apache rules nor the level of access to install apps like Django, so I am limited to just scripts I write. But for that price, i will definitely check out WebFaction! -Sam ----- Original Message ---- From: Kent Johnson To: wormwood_3 Cc: Python Tutorlist Sent: Monday, October 1, 2007 6:44:45 AM Subject: Re: [Tutor] Really basic web templating wormwood_3 wrote: > I want > to do this because my site is on a shared hosting account, so I cannot > install a web framework like Django Another option is to switch to a hosting account that supports Python. I have been working with WebFaction and I'm very happy with them; an account with Django support is available for less than $10/month. Kent From kent37 at tds.net Mon Oct 1 14:36:03 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 08:36:03 -0400 Subject: [Tutor] Really basic web templating In-Reply-To: <678775.64655.qm@web32404.mail.mud.yahoo.com> References: <678775.64655.qm@web32404.mail.mud.yahoo.com> Message-ID: <4700E9B3.3070605@tds.net> wormwood_3 wrote: > My host actually does support Python. But I don't have access to > Apache rules nor the level of access to install apps like Django, so > I am limited to just scripts I write. Webfaction gives you both - you can install anything you like as long as it doesn't require superuser privileges and you have your own Apache instance that you can tweak any way you like. Kent From janos.juhasz at VELUX.com Mon Oct 1 16:51:53 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 1 Oct 2007 16:51:53 +0200 Subject: [Tutor] using **kwargs in __init__() as attributes Message-ID: Dear Tutors, I would like to make a new class instance, where the intance attributes coming from the kwargs hash. class ADUser: def __init__(self, **kwargs): for key in kwargs.keys(): self.key = kwargs[k] a = ADUser(name='papa') It isn't working :( Yours sincerely, ______________________________ Janos Juhasz From kent37 at tds.net Mon Oct 1 17:06:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 11:06:23 -0400 Subject: [Tutor] using **kwargs in __init__() as attributes In-Reply-To: References: Message-ID: <47010CEF.8020808@tds.net> J?nos Juh?sz wrote: > Dear Tutors, > > I would like to make a new class instance, where > the intance attributes coming from the kwargs hash. > > class ADUser: > def __init__(self, **kwargs): > for key in kwargs.keys(): > self.key = kwargs[k] This sets the 'key' attribute of self to the value of the keyword. You want to use the value of of key as the attribute name. You can do this with setattr(): setattr(self, key, kwargs[k]) You can also update all the kwargs at once with self.__dict__.update(kwargs) > It isn't working :( A more specific description of the problem is often helpful; for best results copy and paste the exact error message, including the traceback, into your email. Kent From dkuhlman at rexx.com Mon Oct 1 17:21:14 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 1 Oct 2007 08:21:14 -0700 Subject: [Tutor] using **kwargs in __init__() as attributes In-Reply-To: References: Message-ID: <20071001152114.GA47826@cutter.rexx.com> On Mon, Oct 01, 2007 at 04:51:53PM +0200, J?nos Juh?sz wrote: > Dear Tutors, > > I would like to make a new class instance, where > the intance attributes coming from the kwargs hash. > > class ADUser: > def __init__(self, **kwargs): > for key in kwargs.keys(): > self.key = kwargs[k] > You are asking a more sophisticated form of a question that has been asked on this list several times before: "How do I create names in a namespace from string values?" It's likely that you do not really want (or need) to do this. Try the following instead: def __init__(self, **kwargs): self.values = kwargs Then access the values with: x = self.values['name'] or, safer: x = self.values.get('name', '') If you are determined to create names in a namespace, on the fly, look at the "exec" command (http://docs.python.org/ref/exec.html). But, that's a dangerous way to code. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From mail at timgolden.me.uk Mon Oct 1 17:34:15 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 01 Oct 2007 16:34:15 +0100 Subject: [Tutor] using **kwargs in __init__() as attributes In-Reply-To: <20071001152114.GA47826@cutter.rexx.com> References: <20071001152114.GA47826@cutter.rexx.com> Message-ID: <47011377.1020507@timgolden.me.uk> Dave Kuhlman wrote: > On Mon, Oct 01, 2007 at 04:51:53PM +0200, J?nos Juh?sz wrote: >> Dear Tutors, >> >> I would like to make a new class instance, where >> the intance attributes coming from the kwargs hash. >> >> class ADUser: >> def __init__(self, **kwargs): >> for key in kwargs.keys(): >> self.key = kwargs[k] >> > > You are asking a more sophisticated form of a question that has > been asked on this list several times before: > > "How do I create names in a namespace from string values?" > > It's likely that you do not really want (or need) to do this. Also, on the off-chance (from the name of the class) that you're implementing a wrapper around Active Directory, have a look at: http://tgolden.sc.sabren.com/python/active_directory.html to see if it meets your needs already or is at least a starting point. TJG From kent37 at tds.net Mon Oct 1 17:58:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 11:58:04 -0400 Subject: [Tutor] using **kwargs in __init__() as attributes In-Reply-To: <20071001152114.GA47826@cutter.rexx.com> References: <20071001152114.GA47826@cutter.rexx.com> Message-ID: <4701190C.8040907@tds.net> Dave Kuhlman wrote: > On Mon, Oct 01, 2007 at 04:51:53PM +0200, J?nos Juh?sz wrote: >> Dear Tutors, >> >> I would like to make a new class instance, where >> the intance attributes coming from the kwargs hash. >> >> class ADUser: >> def __init__(self, **kwargs): >> for key in kwargs.keys(): >> self.key = kwargs[k] >> > > You are asking a more sophisticated form of a question that has > been asked on this list several times before: > > "How do I create names in a namespace from string values?" > > It's likely that you do not really want (or need) to do this. Getting and setting attribute values by name is easy and well supported using getattr() and setattr(). IMO this is not in the same category as setting a variable name in the local or global namespace. The self.__dict__.update(kwargs) method is from a recipe by none other than Alex Martelli: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 > If you are determined to create names in a namespace, on the fly, > look at the "exec" command (http://docs.python.org/ref/exec.html). > But, that's a dangerous way to code. In this case setattr() is all that is needed and it is safe. Kent From roychenlei at gmail.com Mon Oct 1 18:07:09 2007 From: roychenlei at gmail.com (Roy Chen) Date: Tue, 2 Oct 2007 00:07:09 +0800 Subject: [Tutor] Location of modules in Mac OS X Message-ID: Hello all, I'm using MacPython 2.5 on OS X 10.4. I was just wondering if all the Python modules are contained in this directory: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ Also, I've installed the Python Image Library (PIL), and it seems to be installed in this folder: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/PIL/ Are all external Python modules installed guaranteed to be in this folder? Thanks :) From agunnerson at gmail.com Mon Oct 1 18:14:20 2007 From: agunnerson at gmail.com (Andy) Date: Mon, 1 Oct 2007 10:14:20 -0600 Subject: [Tutor] How to Practice Python?(Linpeiheng) In-Reply-To: References: <47006476.08ADDF.17520@m5-84.163.com> Message-ID: <26e972870710010914j50da07c5id79908fe4b1f3e18@mail.gmail.com> While not Python specific you could to the Ruby quizzes (http://www.rubyquiz.com/). Just look at the problems and write a solution in Python. On 10/1/07, Alan Gauld wrote: > > "???" wrote > > > I am learning Python. Do you know somewhere I can practice Python? > > I means some sites where have exercises I can try solving. > > The Useless Python website has some exercises and other small > projects. > Some have solutions some don't. > > Also the Python Challenge web site offers a "Game" where you > navigate through the lasyers by solving Python puzzles, each > using a new feature of Python. > > > And there should be standard answer or other people's > > answer that can be refered. > > This is harder. There are solutions around for spome of them > but not "standard solutions" - I'm not sure what such a thing would > look like in a programming context. There are no such things > as standard solutions to programming problems, its not like > doing math! > > Some solutions are nicer than othes but each usually has some merit. > > HTH, > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -Andy "I have a great faith in fools; self-confidence my friends call it." ? Edgar Allen Poe From gtxy20 at gmail.com Mon Oct 1 18:21:22 2007 From: gtxy20 at gmail.com (GTXY20) Date: Mon, 1 Oct 2007 12:21:22 -0400 Subject: [Tutor] Dictionary - count values where values are stored as a list In-Reply-To: <4700D739.7080506@tds.net> References: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> <4700D739.7080506@tds.net> Message-ID: <39cb7e5d0710010921i526314fesc3c68d92d7f0b1f2@mail.gmail.com> This works perfectly. However I will be dealing with an import of a very large dictionary - if I call the commands at command line this seems to be very taxing on the CPU and memory and will take a long time. I was thinking of creating each as a fucntion whereby python would just to write to a file instead of calling within a python shell do you think that this would speed up the process? All in total I will probably be looking at about 2 million dictionary keys with assorted value quantities. M. On 10/1/07, Kent Johnson wrote: > > GTXY20 wrote: > > Hello, > > > > Any way to display the count of the values in a dictionary where the > > values are stored as a list? here is my dictionary: > > > > {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': > > ['a', 'c']} > > > > I would like to display count as follows and I would not know all the > > value types in the values list: > > > > Value QTY > > a 4 > > b 3 > > c 4 > > You need two nested loops - one to loop over the dictionary values and > one to loop over the individual lists. collections.defaultdict is handy > for accumulating the counts but you could use a regular dict also: > > In [4]: d={'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', > 'c'], '4': ['a', 'c']} > In [5]: from collections import defaultdict > In [6]: counts=defaultdict(int) > In [7]: for lst in d.values(): > ...: for item in lst: > ...: counts[item] += 1 > ...: > In [8]: counts > Out[8]: defaultdict(, {'a': 4, 'c': 4, 'b': 3}) > > In [10]: for k, v in sorted(counts.items()): > ....: print k,v > ....: > ....: > a 4 > b 3 > c 4 > > > > Also is there anyway to display the count of the values list > > combinations so here again is my dictionary: > > > > {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': > > ['a', 'c']} > > > > > > And I would like to display as follows > > > > QTY Value List Combination > > 3 a,b,c > > 1 a,c > > Again you can use a defaultdict to accumulate counts. You can't use a > mutable object (such as a list) as a dict key so you have to convert it > to a tuple: > > In [11]: c2=defaultdict(int) > In [13]: for v in d.values(): > ....: c2[tuple(v)] += 1 > ....: > In [14]: c2 > Out[14]: defaultdict(, {('a', 'b', 'c'): 3, ('a', 'c'): 1}) > > Printing in order of count requires switching the order of the (key, > value) pairs: > > In [15]: for count, items in sorted( ((v, k) for k, v in c2.items()), > reverse=True): > ....: print count, ', '.join(items) > ....: > 3 a, b, c > 1 a, c > > or using a sort key: > In [16]: from operator import itemgetter > In [17]: for items, count in sorted(c2.items(), key=itemgetter(1), > reverse=True): > ....: print count, ', '.join(items) > ....: > 3 a, b, c > 1 a, c > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071001/ae0da57b/attachment.htm From kent37 at tds.net Mon Oct 1 18:32:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 12:32:54 -0400 Subject: [Tutor] Dictionary - count values where values are stored as a list In-Reply-To: <39cb7e5d0710010921i526314fesc3c68d92d7f0b1f2@mail.gmail.com> References: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> <4700D739.7080506@tds.net> <39cb7e5d0710010921i526314fesc3c68d92d7f0b1f2@mail.gmail.com> Message-ID: <47012136.2040908@tds.net> GTXY20 wrote: > > This works perfectly. > > However I will be dealing with an import of a very large dictionary - if > I call the commands at command line this seems to be very taxing on the > CPU and memory and will take a long time. > > I was thinking of creating each as a fucntion whereby python would just > to write to a file instead of calling within a python shell do you think > that this would speed up the process? I don't understand what you are suggesting. Both of your requirements just need the values of the dict. If the dict is being created from a file, you could probably build the count dicts on the fly as you read the values without ever creating the dict with all the items in it. Kent > > All in total I will probably be looking at about 2 million dictionary > keys with assorted value quantities. From timmichelsen at gmx-topmail.de Mon Oct 1 18:37:59 2007 From: timmichelsen at gmx-topmail.de (Tim) Date: Mon, 1 Oct 2007 16:37:59 +0000 (UTC) Subject: [Tutor] function for removing all white spaces from a string Message-ID: Hello, after reading the responses to athread in 2004 [1] I am wondering why there is no easy function in python to remove all white spaces from a string. Like: " i am very fine " to "iamveryfine" In IDL there's just one simple function which does this: STRCOMPRESS [2]. Is there really not yet such a function in Python? If not I created it: a = " i am very fine " def strcompress(mystring): ... mystring_compressed = ''.join(mystring.split()) ... return mystring_compressed strcompress(a) 'iamveryfine' Thanks for your input, Timmie [1] Re: how to strip whitespaces from a string. http://article.gmane.org/gmane.comp.python.tutor/18622 [2] STRCOMPRESS http://idlastro.gsfc.nasa.gov/idl_html_help/STRCOMPRESS.html From varsha.purohit at gmail.com Mon Oct 1 19:58:20 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Mon, 1 Oct 2007 10:58:20 -0700 Subject: [Tutor] [tutor] printing bitmap image dynamically reading data inwxpython In-Reply-To: References: Message-ID: Hi Alan, Thanks for the response. Its not a home work problem its actually a task i need to complete as i am tryin to make some tool which will be helpful to use as a script in arcgis. i kinda got some clue will surely ask help if i get stuck somewhere coz i know its difficult to put down in words of what i wanna do.... :( thanks, Varsha On 10/1/07, Alan Gauld wrote: > > "Varsha Purohit" wrote > > > I want to create a wxpython program where i am reading a list > > having > > integer values like [1,2,3,4]. and i need to display the output > > value as > > bitmap image which shd be coloured after reading the values. Like > > 1=red, > > 2=yellow, 3=orange etc and it displays the output in colours at > > proper > > coordinates by matching values of the array. > > Sounds like a fun project. > Have you any plans on how to go about it? > Are you having problems? Or are you just sharing your excitement > at the challenge? > > > I need to make a script file for arcgis tool which converts the > > ascii data to a coloured bitmap image at given coordinates. > > I dunno much about arcgis but again it sounds like a reasonable > thing to do. > > Let us know how you get on. If you run into problems ask > questions we might be able to help. However since it seems > to be a homework type exercise we can't solve it for you. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071001/14d18635/attachment.htm From alan.gauld at btinternet.com Mon Oct 1 19:59:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 18:59:03 +0100 Subject: [Tutor] Location of modules in Mac OS X References: Message-ID: "Roy Chen" wrote > I'm using MacPython 2.5 on OS X 10.4. > > I was just wondering if all the Python modules are contained in this > directory: > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ The standard library modules are. Any custom moidules could be almost anywhere! > Also, I've installed the Python Image Library (PIL), and it seems to > be installed in this folder: > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > packages/PIL/ > > Are all external Python modules installed guaranteed to be in this > folder? site-packages is the usual place but some authors don't provide an install script so they could be anywhere that you unpack them. A few others write unconventional scripts and put them someplace else (maybe inside their own applications area). Welcome to the world of Opensource where rules are "flexible" But mostly they are followed OK. :-) BTW ISTR that a few Mac specific packages found thir way someplace else, but I can't recall which ones. Sherlock found them for me... Alan G. From alan.gauld at btinternet.com Mon Oct 1 20:02:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 19:02:03 +0100 Subject: [Tutor] function for removing all white spaces from a string References: Message-ID: "Tim" wrote > after reading the responses to athread in 2004 [1] I am wondering > why there is > no easy function in python to remove all white spaces from a string. > > " i am very fine " > to > "iamveryfine" You can use string.replace. >>> 'I am very fine'.replace(' ','') 'Iamveryfine' >>> But you need to apply several times if you want more than simple spaces removed. Or you can use regexs. (Or the translate function might work too, but i haven't tried it for this) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Oct 1 20:04:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Oct 2007 19:04:22 +0100 Subject: [Tutor] using **kwargs in __init__() as attributes References: Message-ID: "J?nos Juh?sz" wrote > class ADUser: > def __init__(self, **kwargs): > for key in kwargs.keys(): > self.key = kwargs[k] > > a = ADUser(name='papa') > > > It isn't working :( Try using setattr instead of self.key assignment. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From noufal at airtelbroadband.in Mon Oct 1 20:18:37 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Mon, 01 Oct 2007 23:48:37 +0530 Subject: [Tutor] using **kwargs in __init__() as attributes In-Reply-To: References: Message-ID: <470139FD.2030009@airtelbroadband.in> J?nos Juh?sz wrote: > Dear Tutors, > > I would like to make a new class instance, where > the intance attributes coming from the kwargs hash. > > class ADUser: > def __init__(self, **kwargs): > for key in kwargs.keys(): > self.key = kwargs[k] > > a = ADUser(name='papa') > Your snippet above will set the attribute "key" to kwargs[k] (it will overwrite the values for the previous keys so you won't get anywhere). You need to use setattr to do this since the names of the attributes are available as strings. Here's an example. >>> class Foo(object): ... def __init__(self,**d): ... for i in d: ... setattr(self,i,d[i]) ... >>> >>> >>> x= Foo(name="Papa") >>> x.name 'Papa' >>> -- ~noufal http://nibrahim.net.in/ From kent37 at tds.net Mon Oct 1 20:28:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 14:28:25 -0400 Subject: [Tutor] Location of modules in Mac OS X In-Reply-To: References: Message-ID: <47013C49.6010309@tds.net> Roy Chen wrote: > Hello all, > > I'm using MacPython 2.5 on OS X 10.4. > > I was just wondering if all the Python modules are contained in this > directory: > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ Try import sys sys.path That will give you a list of all the places Python will search for modules. There are several ways this list can be customized, including PYTHONPATH environment variables .pth files site-customize.py modifying sys.path in a program so you shouldn't treat this as a final definitive list, rather it is a snapshot of current usage. Kent From wormwood_3 at yahoo.com Mon Oct 1 20:40:17 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 1 Oct 2007 11:40:17 -0700 (PDT) Subject: [Tutor] Really basic web templating Message-ID: <165187.79145.qm@web32414.mail.mud.yahoo.com> There was another host that I wanted to mention along these lines (for Python sites) that I think is even better: VPSLink (http://www.vpslink.com). They allow root SSH access, and can install your choice of OS (lots of linux flavors, ubuntu, SUSE, CentOS, etc) from a control panel. Aside from that they are similar to WebFaction, but having that much flexibility, with the base plan only ~$8/month, is pretty awesome. -Sam ----- Original Message ---- From: Kent Johnson To: wormwood_3 Cc: Python Tutorlist Sent: Monday, October 1, 2007 8:36:03 AM Subject: Re: [Tutor] Really basic web templating wormwood_3 wrote: > My host actually does support Python. But I don't have access to > Apache rules nor the level of access to install apps like Django, so > I am limited to just scripts I write. Webfaction gives you both - you can install anything you like as long as it doesn't require superuser privileges and you have your own Apache instance that you can tweak any way you like. Kent From finalyugi at sapo.pt Mon Oct 1 21:57:15 2007 From: finalyugi at sapo.pt (Rolando Pereira) Date: Mon, 01 Oct 2007 20:57:15 +0100 Subject: [Tutor] How to Practice Python?(Linpeiheng) In-Reply-To: References: <47006476.08ADDF.17520@m5-84.163.com> Message-ID: <4701511B.9040500@sapo.pt> Alan Gauld wrote: > There are no such things > as standard solutions to programming problems, its not like > doing math! But usually there is "The Right Way". I think... -- _ ASCII ribbon campaign ( ) - against HTML email X & vCards / \ From mlangford.cs03 at gtalumni.org Mon Oct 1 22:09:52 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 1 Oct 2007 16:09:52 -0400 Subject: [Tutor] Really basic web templating In-Reply-To: <300093.45498.qm@web32406.mail.mud.yahoo.com> References: <300093.45498.qm@web32406.mail.mud.yahoo.com> Message-ID: <82b4f5810710011309j36fd4a48kf0126422de118804@mail.gmail.com> Check to see if mod_python is installed/installable. It would quite easily give you a very simple interface to do what you're looking for. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ On 9/30/07, wormwood_3 wrote: > Hello all, > > I am trying to think of a way to make this happen, but it may not be at all possible:-) I would like to use Python to generate pages on demand for my website. By this I mean, when someone hits www.mysite.com/pagex.html, I want to generate the page pagex.html via a Python script. > > I have a script setup that can generate a page from a template file and a file with the body and title of the page in particular I want to generate. Now from this, I need to somehow be able to respond to requests, and then generate the page based on the page requested. I want to do this because my site is on a shared hosting account, so I cannot install a web framework like Django, and the site's pages will be rather simple. At the same time, I would like to use templating, so I do not have repeated identical code between the pages. > > Any ideas on this? > > Thanks, > Sam > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bill at celestial.net Mon Oct 1 22:47:55 2007 From: bill at celestial.net (Bill Campbell) Date: Mon, 1 Oct 2007 13:47:55 -0700 Subject: [Tutor] function for removing all white spaces from a string In-Reply-To: References: Message-ID: <20071001204755.GA27259@ayn.mi.celestial.com> On Mon, Oct 01, 2007, Alan Gauld wrote: > >"Tim" wrote > >> after reading the responses to athread in 2004 [1] I am wondering >> why there is >> no easy function in python to remove all white spaces from a string. >> >> " i am very fine " >> to >> "iamveryfine" > >You can use string.replace. > >>>> 'I am very fine'.replace(' ','') >'Iamveryfine' >>>> > >But you need to apply several times if you want more than simple >spaces removed. > >Or you can use regexs. (Or the translate function might work too, but >i haven't >tried it for this) import re whitespace = re.compile(r'\s+') cleanstring = whitespace.sub('', dirtystring) Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 Marijuana will be legal some day, because the many law students who now smoke pot will someday become congressmen and legalize it in order to protect themselves. -- Lenny Bruce From ricaraoz at gmail.com Mon Oct 1 15:25:06 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 01 Oct 2007 10:25:06 -0300 Subject: [Tutor] Dictionary - count values where values are stored as a list In-Reply-To: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> References: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> Message-ID: <4700F532.9020006@bigfoot.com> GTXY20 wrote: > Hello, > > Any way to display the count of the values in a dictionary where the > values are stored as a list? here is my dictionary: > > {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': > ['a', 'c']} > > I would like to display count as follows and I would not know all the > value types in the values list: > > Value QTY > a 4 > b 3 > c 4 > > Also is there anyway to display the count of the values list > combinations so here again is my dictionary: > > {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': > ['a', 'c']} > > > And I would like to display as follows > > QTY Value List Combination > 3 a,b,c > 1 a,c > > Once again all help is much appreciated. > > M. > >>> D = {'1':['a', 'b', 'c'], '3':['a', 'b', 'c'], '2':['a', 'b', 'c'], '4':['a', 'c'] } >>> d = {} >>> for v in reduce(lambda x, y: x+y, [b for a,b in D.iteritems()]): ... d[v] = d.setdefault(v, 0) + 1 ... >>> for k, v in d.iteritems(): ... print k, v ... a 4 c 4 b 3 >>> ld = {} >>> for v in [''.join(b) for a,b in D.iteritems()]: ... d[v] = d.setdefault(v, 0) + 1 ... >>> for k, v in d.iteritems(): ... print v, list(k) ... 1 ['a', 'c'] 3 ['a', 'b', 'c'] HTH From gtxy20 at gmail.com Tue Oct 2 00:12:53 2007 From: gtxy20 at gmail.com (GTXY20) Date: Mon, 1 Oct 2007 18:12:53 -0400 Subject: [Tutor] Dictionary - count values where values are stored as a list In-Reply-To: <47012136.2040908@tds.net> References: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> <4700D739.7080506@tds.net> <39cb7e5d0710010921i526314fesc3c68d92d7f0b1f2@mail.gmail.com> <47012136.2040908@tds.net> Message-ID: <39cb7e5d0710011512v25c47a0ara109375dd87f1b72@mail.gmail.com> Thanks again I have worked that issue out. However I have the following function and it is throwing this error: FEXpython_v2.py", line 32, in UnitHolderDistributionqty count[item]+=1 KeyError: 3 This is the function: def Distributionqty(dictionary): holder=list() held=list() distqtydic={} count={} for key in sorted(dictionary.keys()): holder.append(key) held.append(len(dictionary[key])) for (key, value) in map(None, holder, held): distqtydic[key]=value for item in distqtydic.values(): count[item]+=1 for k,v in sorted(count.items()): fdist=k qty=v print fdist,qty Not sure... M. On 10/1/07, Kent Johnson wrote: > > GTXY20 wrote: > > > > This works perfectly. > > > > However I will be dealing with an import of a very large dictionary - if > > > I call the commands at command line this seems to be very taxing on the > > CPU and memory and will take a long time. > > > > I was thinking of creating each as a fucntion whereby python would just > > to write to a file instead of calling within a python shell do you think > > that this would speed up the process? > > I don't understand what you are suggesting. > > Both of your requirements just need the values of the dict. If the dict > is being created from a file, you could probably build the count dicts > on the fly as you read the values without ever creating the dict with > all the items in it. > > Kent > > > > > All in total I will probably be looking at about 2 million dictionary > > keys with assorted value quantities. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071001/a0f59ef5/attachment-0001.htm From ricaraoz at gmail.com Tue Oct 2 00:47:40 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 01 Oct 2007 19:47:40 -0300 Subject: [Tutor] function for removing all white spaces from a string In-Reply-To: References: Message-ID: <4701790C.10600@bigfoot.com> Tim wrote: > Hello, > after reading the responses to athread in 2004 [1] I am wondering why there is > no easy function in python to remove all white spaces from a string. > > Like: > > " i am very fine " > to > "iamveryfine" > > In IDL there's just one simple function which does this: STRCOMPRESS [2]. > > Is there really not yet such a function in Python? > > If not I created it: > > a = " i am very fine " > > > def strcompress(mystring): > ... mystring_compressed = ''.join(mystring.split()) > ... return mystring_compressed > > strcompress(a) > 'iamveryfine' > > Thanks for your input, > Timmie > > [1] Re: how to strip whitespaces from a string. > http://article.gmane.org/gmane.comp.python.tutor/18622 > > [2] STRCOMPRESS http://idlastro.gsfc.nasa.gov/idl_html_help/STRCOMPRESS.html ''.join(c for c in a if not c.isspace()) From kent37 at tds.net Tue Oct 2 01:01:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 19:01:16 -0400 Subject: [Tutor] Dictionary - count values where values are stored as a list In-Reply-To: <39cb7e5d0710011512v25c47a0ara109375dd87f1b72@mail.gmail.com> References: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> <4700D739.7080506@tds.net> <39cb7e5d0710010921i526314fesc3c68d92d7f0b1f2@mail.gmail.com> <47012136.2040908@tds.net> <39cb7e5d0710011512v25c47a0ara109375dd87f1b72@mail.gmail.com> Message-ID: <47017C3C.5000608@tds.net> GTXY20 wrote: > > Thanks again I have worked that issue out. > > However I have the following function and it is throwing this error: > > FEXpython_v2.py", line 32, in UnitHolderDistributionqty > count[item]+=1 > KeyError: 3 > > This is the function: > > def Distributionqty(dictionary): > holder=list() > held=list() > distqtydic={} > for key in sorted(dictionary.keys()): > holder.append(key) > held.append(len(dictionary[key])) > for (key, value) in map(None, holder, held): > distqtydic[key]=value Unless you need holder and held for something else, all of the above can be replaced with distqtydic = dict( (key, len(value)) for key, value in sorted(dictionary.items()) > count={} > for item in distqtydic.values(): > count[item]+=1 The problem is that you are trying to add 1 to a value that is not defined yet. You can either make count=defaultdict(int) or write count[item] = count.get(item, 0) + 1 If this is the only use of distqtydic then even the shortened code above is more than you need, you could just write for item in dictionary.values(): count[len(item)] += 1 # assuming defaultdict Kent > for k,v in sorted(count.items()): > fdist=k > qty=v > print fdist,qty for fdist,qty in sorted(count.items()): print fdist, qty No need for the intermediate k, v; just use the names you like. Kent From gtxy20 at gmail.com Tue Oct 2 01:25:17 2007 From: gtxy20 at gmail.com (GTXY20) Date: Mon, 1 Oct 2007 19:25:17 -0400 Subject: [Tutor] Dictionary - count values where values are stored as a list In-Reply-To: <39cb7e5d0710011512v25c47a0ara109375dd87f1b72@mail.gmail.com> References: <39cb7e5d0709302235w3d5e8702x50c938a013b8e737@mail.gmail.com> <4700D739.7080506@tds.net> <39cb7e5d0710010921i526314fesc3c68d92d7f0b1f2@mail.gmail.com> <47012136.2040908@tds.net> <39cb7e5d0710011512v25c47a0ara109375dd87f1b72@mail.gmail.com> Message-ID: <39cb7e5d0710011625g40871fd0i71b5db4818eefdb5@mail.gmail.com> Thanks so much I changed to the following and this worked: def HolderDistributionqty(dictionary): from collections import defaultdict count=defaultdict(int) for item in dictionary.values(): count[len(item)]+=1 for k,v in sorted(count.items()): fdist=k qty=v print fdist,qty M. On 10/1/07, GTXY20 wrote: > > > Thanks again I have worked that issue out. > > However I have the following function and it is throwing this error: > > FEXpython_v2.py", line 32, in UnitHolderDistributionqty > count[item]+=1 > KeyError: 3 > > This is the function: > > def Distributionqty(dictionary): > holder=list() > held=list() > distqtydic={} > count={} > for key in sorted(dictionary.keys()): > holder.append(key) > held.append(len(dictionary[key])) > for (key, value) in map(None, holder, held): > distqtydic[key]=value > for item in distqtydic.values(): > count[item]+=1 > for k,v in sorted(count.items()): > fdist=k > qty=v > print fdist,qty > > Not sure... > > M. > > > > On 10/1/07, Kent Johnson wrote: > > > > GTXY20 wrote: > > > > > > This works perfectly. > > > > > > However I will be dealing with an import of a very large dictionary - > > if > > > I call the commands at command line this seems to be very taxing on > > the > > > CPU and memory and will take a long time. > > > > > > I was thinking of creating each as a fucntion whereby python would > > just > > > to write to a file instead of calling within a python shell do you > > think > > > that this would speed up the process? > > > > I don't understand what you are suggesting. > > > > Both of your requirements just need the values of the dict. If the dict > > is being created from a file, you could probably build the count dicts > > on the fly as you read the values without ever creating the dict with > > all the items in it. > > > > Kent > > > > > > > > All in total I will probably be looking at about 2 million dictionary > > > keys with assorted value quantities. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071001/1b8a8e96/attachment.htm From speel at energy.com.au Tue Oct 2 03:31:41 2007 From: speel at energy.com.au (Suzanne Peel) Date: Tue, 2 Oct 2007 11:31:41 +1000 Subject: [Tutor] A simple Question... Message-ID: Hi, I have a very simple question that I cannot find the answer to ... if I knew the correct question to ask it would be simple. I am trying to find the name of the file I am currently running (please don't laugh at me I know it's simple but I cannot figure it out). I want to know where my errors are occurring so if I print out the name of the file (or script) when it starts that should help me I have tried os.listpath os.path and get lists of files and directories but no matter how much searching (through Python help and Dive into python) I cannot figure out how to find the current file name. Any help will be more than welcome!!! Suzanne ---------------------------------------------------------------------------------------- This e-mail may contain confidential or privileged information. If you have received it in error, please notify the sender immediately via return e-mail and then delete the original e-mail. EnergyAustralia has collected your business contact details for dealing with you in your business capacity. More information about how we handle your personal information, including your right of access is contained at http://www.energy.com.au. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/980e43bb/attachment.htm From john at fouhy.net Tue Oct 2 04:00:09 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 2 Oct 2007 14:00:09 +1200 Subject: [Tutor] A simple Question... In-Reply-To: References: Message-ID: <5e58f2e40710011900j6385edcw3c568fa29b4ac5dc@mail.gmail.com> On 02/10/2007, Suzanne Peel wrote: > I am trying to find the name of the file I am currently running (please don't laugh at me I know it's simple but I cannot figure it out). Have a look at sys.argv[0] :-) -- John. From kent37 at tds.net Tue Oct 2 04:06:41 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 01 Oct 2007 22:06:41 -0400 Subject: [Tutor] A simple Question... In-Reply-To: References: Message-ID: <4701A7B1.7050300@tds.net> Suzanne Peel wrote: > > Hi, > > I have a very simple question that I cannot find the answer to ... if I > knew the correct question to ask it would be simple. > > I am trying to find the name of the file I am currently running (please > don't laugh at me I know it's simple but I cannot figure it out). __file__ is the name of the current module. > > I want to know where my errors are occurring so if I print out the name > of the file (or script) when it starts that should help me What kind of errors are you getting? If they are exceptions you should be able to get a traceback easily with traceback.print_exc(). You can also print out a full stack trace at any time with traceback.print_stack(). Kent From cspears2002 at yahoo.com Tue Oct 2 06:36:06 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 1 Oct 2007 21:36:06 -0700 (PDT) Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> Message-ID: <999472.94373.qm@web51604.mail.re2.yahoo.com> I was looking for the source code for the strip functions at python.org. I didn't find anything. Do you or someone else know where the source code is posted? I tried to find python on my workstation, but I'm not sure where the sys admin installed it. From mwalsh at groktech.org Tue Oct 2 07:01:07 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Tue, 02 Oct 2007 00:01:07 -0500 Subject: [Tutor] OT: webhosting In-Reply-To: <165187.79145.qm@web32414.mail.mud.yahoo.com> References: <165187.79145.qm@web32414.mail.mud.yahoo.com> Message-ID: <4701D093.2040902@groktech.org> wormwood_3 wrote: > There was another host that I wanted to mention along these lines (for Python sites) that I think is even better: VPSLink (http://www.vpslink.com). They allow root SSH access, and can install your choice of OS (lots of linux flavors, ubuntu, SUSE, CentOS, etc) from a control panel. Aside from that they are similar to WebFaction, but having that much flexibility, with the base plan only ~$8/month, is pretty awesome. > > -Sam Running the risk of taking this tread in an inappropriate direction, I feel compelled to mention http://openhosting.com, founded by Gregory Trubetskoy the author of mod_python. Aside from the pleasant opportunity to name-drop :) I have found their service, up-time, and support to be phenomenal -- while not the cheapest vps on the block. I think their service plans start at around $20 US a month. > > ----- Original Message ---- > From: Kent Johnson > > Webfaction gives you both - you can install anything you like as long as > it doesn't require superuser privileges and you have your own Apache > instance that you can tweak any way you like. > > Kent From gtxy20 at gmail.com Tue Oct 2 07:56:48 2007 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 2 Oct 2007 01:56:48 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary Message-ID: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> Hello all, Let's say I have the following dictionary: {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} I also have another dictionary for new value association: {a:1, b:2, c:3} How should I approach if I want to modify the first dictionary to read: {1:(1,2,3), 2:(1,3), 3:(2,3), 4:(1,d)} There is the potential to have a value in the first dictionary that will not have an update key in the second dictionary hence in the above dictionary for key=4 I still have d listed as a value. As always all help is appreciated. M. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/47d72599/attachment-0001.htm From john at fouhy.net Tue Oct 2 08:05:38 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 2 Oct 2007 18:05:38 +1200 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> Message-ID: <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> On 02/10/2007, GTXY20 wrote: > Hello all, > > Let's say I have the following dictionary: > > {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} > > I also have another dictionary for new value association: > > {a:1, b:2, c:3} > > How should I approach if I want to modify the first dictionary to read: > > {1:(1,2,3), 2:(1,3), 3:(2,3), 4:(1,d)} > > There is the potential to have a value in the first dictionary that will not > have an update key in the second dictionary hence in the above dictionary > for key=4 I still have d listed as a value. You could use the map function... Let's say we have something like: transDict = { 'a':1, 'b':2, 'c':3 } We could define a function that mirrors this: def transFn(c): try: return transDict[c] except KeyError: return c Then if you have your data: data = { 1:('a','b','c'), 2:('a','c'), 3:('b','c'), 4:('a','d')} You can translate it as: for key in data.keys(): data[key] = map(transFn, data[key]) HTH! -- John. From speel at energy.com.au Tue Oct 2 08:22:11 2007 From: speel at energy.com.au (Suzanne Peel) Date: Tue, 2 Oct 2007 16:22:11 +1000 Subject: [Tutor] A simple Question... Message-ID: Thankyou for your help, However both suggestions will only give me that name of the 1st file executed eg when I use execfile('EA_Owner.py') the name returned when the __file__ or sys.argv[0] is executed always EA_Owner.py . The Traceback feature is an excellent resource however the errors I am trying to follow are not python errors but come from the data I am manipulating - I cannot remember off-the-top-of-my-head what order each file is called so I resort to opening the main file to figure it out - it would be nice if I could write out the name whenever the script runs the I just look for the name... I do realise I could hardcode the names I was just looking for a more elegant solution that I can put in all my scripts identifying which one is executing. The trace-back feature provides this - can I force an error of sorts that will not suspend programming but will report the file/module/script that it is running ??? (Probably a bit dramatic but I am at a loss..) Regards, Suzanne Peel Engineer - Subtransmission Planning, Sydney EnergyAustralia ____________________________________ Level 3, 570 George St, Sydney NSW 2000 T. 612 9269 4659 (Extn 34659) F. 612 9269 4690 (Extn 34690) speel at energy.com.au ____________________________________ ---------------------------------------------------------------------------------------- This e-mail may contain confidential or privileged information. If you have received it in error, please notify the sender immediately via return e-mail and then delete the original e-mail. EnergyAustralia has collected your business contact details for dealing with you in your business capacity. More information about how we handle your personal information, including your right of access is contained at http://www.energy.com.au. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/0505ed63/attachment.htm From aijames at exemail.com.au Tue Oct 2 09:01:25 2007 From: aijames at exemail.com.au (Andrew James) Date: Tue, 02 Oct 2007 17:01:25 +1000 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <4701EB7E.5080801@exemail.com.au> References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> Message-ID: <4701ECC5.9000009@exemail.com.au> Helps if I send it to the group... And Kent, I didn't post it originally because I figured the other guy was still working on his script. Besides, I didn't think it'd be that far fetched for you to assume I was using something like "while s[0] == ' ':" Andrew James wrote: > I'm always nervous about sharing my code... It's like being back in > high school, I don't want the other kids to laugh at me. Anyway, > running that in IDLE with a string such as ' > testing. ' Will print ' testing' at the > end of the first (second, really) loop. > > def strip(s): > while s[0].isspace() == True: > while s[-1].isspace() == True: > s = s[:-2] > print s > s = s[1:] > print s > > test = raw_input('Enter a string with plenty of leading and trailing > whitespace:') > > strip(test) > > Alan Gauld wrote: >> "Andrew James" wrote >> >> >>> string containing a single space ' ' but even using s[-1].isspace() I >>> lose punctuation marks. Any idea why that's happening? >>> >> >> care to show us what you are doing? >> >> >>>>> ';'.isspace() >>>>> >> False >> >> So puntuation should not show up as true... >> >> Alan G. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > From aijames at exemail.com.au Tue Oct 2 09:04:54 2007 From: aijames at exemail.com.au (Andrew James) Date: Tue, 02 Oct 2007 17:04:54 +1000 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <4701ECC5.9000009@exemail.com.au> References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au> Message-ID: <4701ED96.4000307@exemail.com.au> And as soon as I send it again I realise a pretty stupid error. The two loops shouldn't be nested. Andrew James wrote: > Helps if I send it to the group... > > And Kent, I didn't post it originally because I figured the other guy > was still working on his script. Besides, I didn't think it'd be that > far fetched for you to assume I was using something like "while s[0] > == ' ':" > > Andrew James wrote: >> I'm always nervous about sharing my code... It's like being back in >> high school, I don't want the other kids to laugh at me. Anyway, >> running that in IDLE with a string such as ' >> testing. ' Will print ' testing' at the >> end of the first (second, really) loop. >> >> def strip(s): >> while s[0].isspace() == True: >> while s[-1].isspace() == True: >> s = s[:-2] >> print s >> s = s[1:] >> print s >> >> test = raw_input('Enter a string with plenty of leading and trailing >> whitespace:') >> >> strip(test) >> >> Alan Gauld wrote: >>> "Andrew James" wrote >>> >>> >>>> string containing a single space ' ' but even using s[-1].isspace() I >>>> lose punctuation marks. Any idea why that's happening? >>>> >>> >>> care to show us what you are doing? >>> >>> >>>>>> ';'.isspace() >>>>>> >>> False >>> >>> So puntuation should not show up as true... >>> >>> Alan G. >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> > From aijames at exemail.com.au Tue Oct 2 09:07:17 2007 From: aijames at exemail.com.au (Andrew James) Date: Tue, 02 Oct 2007 17:07:17 +1000 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <4701ED96.4000307@exemail.com.au> References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au> <4701ED96.4000307@exemail.com.au> Message-ID: <4701EE25.4050908@exemail.com.au> *headbang* I'm an idiot. s=s[:-2] should be s=s[:-1]. Andrew James wrote: > And as soon as I send it again I realise a pretty stupid error. The > two loops shouldn't be nested. > > Andrew James wrote: >> Helps if I send it to the group... >> >> And Kent, I didn't post it originally because I figured the other guy >> was still working on his script. Besides, I didn't think it'd be that >> far fetched for you to assume I was using something like "while s[0] >> == ' ':" >> >> Andrew James wrote: >>> I'm always nervous about sharing my code... It's like being back in >>> high school, I don't want the other kids to laugh at me. Anyway, >>> running that in IDLE with a string such as ' >>> testing. ' Will print ' testing' at the >>> end of the first (second, really) loop. >>> >>> def strip(s): >>> while s[0].isspace() == True: >>> while s[-1].isspace() == True: >>> s = s[:-2] >>> print s >>> s = s[1:] >>> print s >>> >>> test = raw_input('Enter a string with plenty of leading and trailing >>> whitespace:') >>> >>> strip(test) >>> >>> Alan Gauld wrote: >>>> "Andrew James" wrote >>>> >>>> >>>>> string containing a single space ' ' but even using s[-1].isspace() I >>>>> lose punctuation marks. Any idea why that's happening? >>>>> >>>> >>>> care to show us what you are doing? >>>> >>>> >>>>>>> ';'.isspace() >>>>>>> >>>> False >>>> >>>> So puntuation should not show up as true... >>>> >>>> Alan G. >>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>> >> > From gtxy20 at gmail.com Tue Oct 2 10:07:24 2007 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 2 Oct 2007 04:07:24 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> Message-ID: <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> I seem to be encountering a problem and I think it is because I actually have my data as follows: data = {1:[a,b,c], 2:[a,c], 3:[b,c], 4:[a,d]} not as previously mentioned: data = {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} So the values are actually stored as a list. I am trying to adjust so that data ends up being: {1:[1,2,3], 2:[1,3], 3:[2,3], 4:[1,d]} right now I am getting: {1:[[1],[2],[3]], 2:[[1],[3]], 3:[[2],[3]], 4:[[1],d]} which is problmatic for other things I am trying to do - it is indicating that the values are not hashable. On 10/2/07, John Fouhy wrote: > > On 02/10/2007, GTXY20 wrote: > > Hello all, > > > > Let's say I have the following dictionary: > > > > {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} > > > > I also have another dictionary for new value association: > > > > {a:1, b:2, c:3} > > > > How should I approach if I want to modify the first dictionary to read: > > > > {1:(1,2,3), 2:(1,3), 3:(2,3), 4:(1,d)} > > > > There is the potential to have a value in the first dictionary that will > not > > have an update key in the second dictionary hence in the above > dictionary > > for key=4 I still have d listed as a value. > > You could use the map function... > > Let's say we have something like: > > transDict = { 'a':1, 'b':2, 'c':3 } > > We could define a function that mirrors this: > > def transFn(c): > try: > return transDict[c] > except KeyError: > return c > > Then if you have your data: > > data = { 1:('a','b','c'), 2:('a','c'), 3:('b','c'), 4:('a','d')} > > You can translate it as: > > for key in data.keys(): > data[key] = map(transFn, data[key]) > > HTH! > > -- > John. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/a54c9e21/attachment.htm From gtxy20 at gmail.com Tue Oct 2 10:15:43 2007 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 2 Oct 2007 04:15:43 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> Message-ID: <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> Sorry - solved my own problem - it was the way I was creating my dictionary and assigning the value as a list. I will post my final working code shortly. M. On 10/2/07, GTXY20 wrote: > > I seem to be encountering a problem and I think it is because I actually > have my data as follows: > > data = {1:[a,b,c], 2:[a,c], 3:[b,c], 4:[a,d]} > > not as previously mentioned: > > data = {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} > > So the values are actually stored as a list. > > I am trying to adjust so that data ends up being: > > {1:[1,2,3], 2:[1,3], 3:[2,3], 4:[1,d]} > > right now I am getting: > > {1:[[1],[2],[3]], 2:[[1],[3]], 3:[[2],[3]], 4:[[1],d]} > > which is problmatic for other things I am trying to do - it is indicating > that the values are not hashable. > > > > > > On 10/2/07, John Fouhy wrote: > > > > On 02/10/2007, GTXY20 < gtxy20 at gmail.com> wrote: > > > Hello all, > > > > > > Let's say I have the following dictionary: > > > > > > {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} > > > > > > I also have another dictionary for new value association: > > > > > > {a:1, b:2, c:3} > > > > > > How should I approach if I want to modify the first dictionary to > > read: > > > > > > {1:(1,2,3), 2:(1,3), 3:(2,3), 4:(1,d)} > > > > > > There is the potential to have a value in the first dictionary that > > will not > > > have an update key in the second dictionary hence in the above > > dictionary > > > for key=4 I still have d listed as a value. > > > > You could use the map function... > > > > Let's say we have something like: > > > > transDict = { 'a':1, 'b':2, 'c':3 } > > > > We could define a function that mirrors this: > > > > def transFn(c): > > try: > > return transDict[c] > > except KeyError: > > return c > > > > Then if you have your data: > > > > data = { 1:('a','b','c'), 2:('a','c'), 3:('b','c'), 4:('a','d')} > > > > You can translate it as: > > > > for key in data.keys(): > > data[key] = map(transFn, data[key]) > > > > HTH! > > > > -- > > John. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/a1fb8266/attachment-0001.htm From alan.gauld at btinternet.com Tue Oct 2 10:19:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Oct 2007 09:19:56 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au><4701ECC5.9000009@exemail.com.au> <4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au> Message-ID: "Andrew James" wrote > *headbang* > > I'm an idiot. s=s[:-2] should be s=s[:-1]. > > Andrew James wrote: >> And as soon as I send it again I realise a pretty stupid error. The >> two loops shouldn't be nested. >> >> Andrew James wrote: >>> Helps if I send it to the group... See the benefits of posting the code? Nobody said a world and already you fixed it! :-) Alan G. From alan.gauld at btinternet.com Tue Oct 2 10:22:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Oct 2007 09:22:40 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <999472.94373.qm@web51604.mail.re2.yahoo.com> Message-ID: "Christopher Spears" wrote >I was looking for the source code for the strip > functions at python.org. I didn't find anything. Do > you or someone else know where the source code is > posted? I tried to find python on my workstation, but > I'm not sure where the sys admin installed it. Which OS? Windows its likely to be C:\python25 or similar On Linux the libraries will be in a different place to the executable... On a Mac see a recent thread... The source for strip is will be in C rather than Python because the string code is part of the built-in capabilities. HTH, Alan G. From alan.gauld at btinternet.com Tue Oct 2 10:32:47 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Oct 2007 09:32:47 +0100 Subject: [Tutor] A simple Question... References: Message-ID: "Suzanne Peel" wrote > However both suggestions will only give me that name of the 1st file > executed eg when I use execfile('EA_Owner.py') the name returned > when > the __file__ or sys.argv[0] is executed always EA_Owner.py . You didn't mention you were doing wacky stuff like using execfile... That makes it a bit more challenging. Is there any reason why you need to use execfile rather than just importing the file? execfile acts as if another interpreter session was running so its quite tricky to find out the name of the file that the original interpreter was running. You might be able to do it by setting a global variable to the current __file__ before calling execfile... > The trace-back feature provides this - can I force an error of sorts > that > will not suspend programming but will report the file/module/script > that > it is running ??? (Probably a bit dramatic but I am at a loss..) Look at the traceback module. I think its possible but messy. It would be better if you can find a way to avoid using execfile. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From gtxy20 at gmail.com Tue Oct 2 10:31:15 2007 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 2 Oct 2007 04:31:15 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> Message-ID: <39cb7e5d0710020131j6bc8abei8a2a3b65e3a57834@mail.gmail.com> This seemed to work: def transFn(c): transfile = open('translate.txt', 'r') records = transfile.read() transfile.close() lines = records.split() transDict = {} for line in lines: key, value = line.split(',') transDict[key] = value try: return transDict[c] except KeyError: return c for key in data.keys(): data[key] = map(transFn, data[key]) On 10/2/07, GTXY20 wrote: > > > Sorry - solved my own problem - it was the way I was creating my > dictionary and assigning the value as a list. > > I will post my final working code shortly. > > M. > > On 10/2/07, GTXY20 wrote: > > > > I seem to be encountering a problem and I think it is because I actually > > have my data as follows: > > > > data = {1:[a,b,c], 2:[a,c], 3:[b,c], 4:[a,d]} > > > > not as previously mentioned: > > > > data = {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} > > > > So the values are actually stored as a list. > > > > I am trying to adjust so that data ends up being: > > > > {1:[1,2,3], 2:[1,3], 3:[2,3], 4:[1,d]} > > > > right now I am getting: > > > > {1:[[1],[2],[3]], 2:[[1],[3]], 3:[[2],[3]], 4:[[1],d]} > > > > which is problmatic for other things I am trying to do - it is > > indicating that the values are not hashable. > > > > > > > > > > > > On 10/2/07, John Fouhy wrote: > > > > > > On 02/10/2007, GTXY20 < gtxy20 at gmail.com> wrote: > > > > Hello all, > > > > > > > > Let's say I have the following dictionary: > > > > > > > > {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} > > > > > > > > I also have another dictionary for new value association: > > > > > > > > {a:1, b:2, c:3} > > > > > > > > How should I approach if I want to modify the first dictionary to > > > read: > > > > > > > > {1:(1,2,3), 2:(1,3), 3:(2,3), 4:(1,d)} > > > > > > > > There is the potential to have a value in the first dictionary that > > > will not > > > > have an update key in the second dictionary hence in the above > > > dictionary > > > > for key=4 I still have d listed as a value. > > > > > > You could use the map function... > > > > > > Let's say we have something like: > > > > > > transDict = { 'a':1, 'b':2, 'c':3 } > > > > > > We could define a function that mirrors this: > > > > > > def transFn(c): > > > try: > > > return transDict[c] > > > except KeyError: > > > return c > > > > > > Then if you have your data: > > > > > > data = { 1:('a','b','c'), 2:('a','c'), 3:('b','c'), 4:('a','d')} > > > > > > You can translate it as: > > > > > > for key in data.keys(): > > > data[key] = map(transFn, data[key]) > > > > > > HTH! > > > > > > -- > > > John. > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/d969b949/attachment.htm From brunson at brunson.com Tue Oct 2 10:42:52 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 02 Oct 2007 02:42:52 -0600 Subject: [Tutor] A simple Question... In-Reply-To: References: Message-ID: <4702048C.6060105@brunson.com> Alan Gauld wrote: > "Suzanne Peel" wrote > > >> However both suggestions will only give me that name of the 1st file >> executed eg when I use execfile('EA_Owner.py') the name returned >> when >> the __file__ or sys.argv[0] is executed always EA_Owner.py . >> > > You didn't mention you were doing wacky stuff like using execfile... > That makes it a bit more challenging. Is there any reason why you > need to use execfile rather than just importing the file? > > execfile acts as if another interpreter session was running so its > quite tricky to find out the name of the file that the original > interpreter > was running. You might be able to do it by setting a global variable > to the current __file__ before calling execfile... > I agree with Alan that execfile can usually be replaced with a more elegant solution. But if you're not looking to rearchitect the code and are looking for the least amount of work, you could try wrapping or decorating the execfile function. Possibly something like this (off-the-top-of-my-head and untested): create a module, say, myExec.py: def myExecfile( filename ): doSomeLoggingOn( filename ) return execfile( filename ) Then, in your code: from myExec import myExecfile as execfile No other code should have to change. > >> The trace-back feature provides this - can I force an error of sorts >> that >> will not suspend programming but will report the file/module/script >> that >> it is running ??? (Probably a bit dramatic but I am at a loss..) >> > > Look at the traceback module. I think its possible but messy. > It would be better if you can find a way to avoid using execfile. > > HTH, > From alan.gauld at btinternet.com Tue Oct 2 10:44:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Oct 2007 09:44:51 +0100 Subject: [Tutor] Update values stored as a list in a dictionary with valuesfrom another dictionary References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> Message-ID: "GTXY20" wrote > Let's say I have the following dictionary: > > {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} > > I also have another dictionary for new value association: > > {a:1, b:2, c:3} I assume the keys should be strings: 'a','b','c'? Not the variable names a,b,c? > How should I approach if I want to modify the first dictionary to > read: > > {1:(1,2,3), 2:(1,3), 3:(2,3), 4:(1,d)} Lets make life easier by naming the dicts d1,d2 and d3 respectively. So you want d3 to hold 1: (d2[d1[1][0]], d2[d1[1][1]],d2[d1[1][2]]), 2: (d2[d1[2][0]], d2[d1[2][1]]), 3: (d2[d1[3][0]], d2[d1[3],[1]]) Do you see a pattern? d3[key] = d2[d1[key][0...len(d1[key])-1] > There is the potential to have a value in the first dictionary that > will not > have an update key in the second dictionary hence in the above > dictionary > for key=4 I still have d listed as a value. Look at the get() method of dictionaries to deal with that issue. You still need to resolve the problem of inconsistent keys if the d2 keys and d1 values are not strings. That is more tricky! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Oct 2 12:48:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 06:48:13 -0400 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <999472.94373.qm@web51604.mail.re2.yahoo.com> References: <999472.94373.qm@web51604.mail.re2.yahoo.com> Message-ID: <470221ED.3050701@tds.net> Christopher Spears wrote: > I was looking for the source code for the strip > functions at python.org. I didn't find anything. Do > you or someone else know where the source code is > posted? I tried to find python on my workstation, but > I'm not sure where the sys admin installed it. The source for the portion of Python written in C is not installed with the regular Python installer on Mac or Windows (don't know about Linux). You can download it here - get the "Python 2.5.1 compressed source tarball": http://www.python.org/download/ Kent From kent37 at tds.net Tue Oct 2 12:49:43 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 06:49:43 -0400 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <4701ECC5.9000009@exemail.com.au> References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au> Message-ID: <47022247.8070100@tds.net> Andrew James wrote: > Helps if I send it to the group... > > And Kent, I didn't post it originally because I figured the other guy > was still working on his script. Besides, I didn't think it'd be that > far fetched for you to assume I was using something like "while s[0] == > ' ':" Actually I saw that the snippet you posted was fine and assumed that the error must be somewhere else :-) Kent From kent37 at tds.net Tue Oct 2 13:24:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 07:24:53 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> Message-ID: <47022A85.9040305@tds.net> John Fouhy wrote: > You could use the map function... > > Let's say we have something like: > > transDict = { 'a':1, 'b':2, 'c':3 } > > We could define a function that mirrors this: > > def transFn(c): > try: > return transDict[c] > except KeyError: > return c This could be written more simply as return transDict.get(c, c) > Then if you have your data: > > data = { 1:('a','b','c'), 2:('a','c'), 3:('b','c'), 4:('a','d')} > > You can translate it as: > > for key in data.keys(): > data[key] = map(transFn, data[key]) I would use a list comprehension and dict.get(): for key, value in data.items(): data[key] = [ transDict.get(i, i) for i in value ] Kent From kent37 at tds.net Tue Oct 2 13:26:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 07:26:05 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <39cb7e5d0710020131j6bc8abei8a2a3b65e3a57834@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> <39cb7e5d0710020131j6bc8abei8a2a3b65e3a57834@mail.gmail.com> Message-ID: <47022ACD.30008@tds.net> GTXY20 wrote: > > This seemed to work: > > def transFn(c): > transfile = open('translate.txt', 'r') > records = transfile.read() > transfile.close() > lines = records.split() > transDict = {} > for line in lines: > key, value = line.split(',') > transDict[key] = value > try: > return transDict[c] > except KeyError: > return c Yikes! This is re-reading translate.txt every time transFn() is called, i.e. once for every key in data! Kent > > for key in data.keys(): > data[key] = map(transFn, data[key]) From kent37 at tds.net Tue Oct 2 13:30:55 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 07:30:55 -0400 Subject: [Tutor] A simple Question... In-Reply-To: References: Message-ID: <47022BEF.4010703@tds.net> Suzanne Peel wrote: > > Thankyou for your help, > > However both suggestions will only give me that name of the 1st file > executed eg when I use *execfile('EA_Owner.py')* the name returned > when the __file__ or sys.argv[0] is executed always EA_Owner.py . > > The Traceback feature is an excellent resource however the errors I am > trying to follow are not python errors but come from the data I am > manipulating - I cannot remember off-the-top-of-my-head what order each > file is called so I resort to opening the main file to figure it out - > it would be nice if I could write out the name whenever the script runs > the I just look for the name... I do realise I could hardcode the names > I was just looking for a more elegant solution that I can put in all my > scripts identifying which one is executing. I am having a hard time understanding what you are doing, what kind of errors you are getting, and what information you want to print out. Can you show some of your code, or perhaps a simple example of what you are doing, together with some indication of what you want to print out? > The trace-back feature provides this - can I force an error of sorts > that will not suspend programming but will report the file/module/script > that it is running ??? (Probably a bit dramatic but I am at a loss..) traceback.print_stack() prints the stack trace to the current point of execution. No forced error or drama needed :-) Kent From bhaaluu at gmail.com Tue Oct 2 13:54:59 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 2 Oct 2007 07:54:59 -0400 Subject: [Tutor] A simple Question... In-Reply-To: <47022BEF.4010703@tds.net> References: <47022BEF.4010703@tds.net> Message-ID: On 10/2/07, Kent Johnson wrote: > > traceback.print_stack() prints the stack trace to the current point of > execution. No forced error or drama needed :-) > > Kent Exactly how is this used, please? Traceback (most recent call last): File "print_stack.py", line 160, in ? print traceback.print_stack() NameError: name 'traceback' is not defined It seems I should be able to insert a line, something like print traceback.print_stack() in my code wherever I want to print the stack trace? -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From kent37 at tds.net Tue Oct 2 13:59:12 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 07:59:12 -0400 Subject: [Tutor] A simple Question... In-Reply-To: References: <47022BEF.4010703@tds.net> Message-ID: <47023290.2070402@tds.net> bhaaluu wrote: > On 10/2/07, Kent Johnson wrote: >> traceback.print_stack() prints the stack trace to the current point of >> execution. No forced error or drama needed :-) >> >> Kent > > Exactly how is this used, please? > > Traceback (most recent call last): > File "print_stack.py", line 160, in ? > print traceback.print_stack() > NameError: name 'traceback' is not defined import traceback traceback.print_stack() Kent From gtxy20 at gmail.com Tue Oct 2 16:59:01 2007 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 2 Oct 2007 10:59:01 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <47022ACD.30008@tds.net> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> <39cb7e5d0710020131j6bc8abei8a2a3b65e3a57834@mail.gmail.com> <47022ACD.30008@tds.net> Message-ID: <39cb7e5d0710020759n697ba73agf0b0e1d3ef839f4c@mail.gmail.com> I adjusted so that I get the following so if I do not need to translate a dictionary I do not call the function transFn: def transFn(translatefile): transfile = open(translatefile, 'r') records = transfile.read() transfile.close() lines = records.split() transDict = {} for line in lines: key, value = line.split(',') transDict[key] = value for key, value in Data.items(): Data[key] = [ transDict.get(i, i) for i in value ] At this point can anyone recommend any python modules that helps to create reporting and graphing? On 10/2/07, Kent Johnson wrote: > > GTXY20 wrote: > > > > This seemed to work: > > > > def transFn(c): > > transfile = open('translate.txt', 'r') > > records = transfile.read() > > transfile.close() > > lines = records.split() > > transDict = {} > > for line in lines: > > key, value = line.split(',') > > transDict[key] = value > > try: > > return transDict[c] > > except KeyError: > > return c > > Yikes! This is re-reading translate.txt every time transFn() is called, > i.e. once for every key in data! > > Kent > > > > > for key in data.keys(): > > data[key] = map(transFn, data[key]) > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/29dd26ba/attachment.htm From dkuhlman at rexx.com Tue Oct 2 18:32:47 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 2 Oct 2007 09:32:47 -0700 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <470221ED.3050701@tds.net> References: <999472.94373.qm@web51604.mail.re2.yahoo.com> <470221ED.3050701@tds.net> Message-ID: <20071002163247.GA42774@cutter.rexx.com> On Tue, Oct 02, 2007 at 06:48:13AM -0400, Kent Johnson wrote: > Christopher Spears wrote: > > I was looking for the source code for the strip > > functions at python.org. I didn't find anything. Do > > you or someone else know where the source code is > > posted? I tried to find python on my workstation, but > > I'm not sure where the sys admin installed it. > > The source for the portion of Python written in C is not installed with > the regular Python installer on Mac or Windows (don't know about Linux). > You can download it here - get the "Python 2.5.1 compressed source tarball": > http://www.python.org/download/ > If you decide to look at the source, look for the strip function/method in the following files: Objects/stringobject.c Modules/stropmodule.c The first contains the implementation of the method on string objects. The second is the implementation of the function that you get by doing "import string". As an advanced exercise, install Pyrex/Cython, then implement the strip function using that. For more on Cython/Pyrex, see: http://wiki.cython.org/. Cython/Pyrex is a Python-like language for writing Python C extensions in a Python-like language. Pyrex/Cython gets you much closer to C code than Python. Question: Someday will all the Python built-ins be implemented in Cython/Pyrex. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From gtxy20 at gmail.com Tue Oct 2 18:35:12 2007 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 2 Oct 2007 12:35:12 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <39cb7e5d0710020759n697ba73agf0b0e1d3ef839f4c@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> <39cb7e5d0710020131j6bc8abei8a2a3b65e3a57834@mail.gmail.com> <47022ACD.30008@tds.net> <39cb7e5d0710020759n697ba73agf0b0e1d3ef839f4c@mail.gmail.com> Message-ID: <39cb7e5d0710020935jac8193al6910be07bba87b1e@mail.gmail.com> Here's an interesting question: Can I use the transFn function to remove items in the value list. Can this be done by simple assigning the current value a value of null in the translate file? M. On 10/2/07, GTXY20 wrote: > I adjusted so that I get the following so if I do not need to translate a > dictionary I do not call the function transFn: > > def transFn(translatefile): > transfile = open(translatefile, 'r') > records = transfile.read() > transfile.close() > lines = records.split() > transDict = {} > for line in lines: > key, value = line.split(',') > transDict[key] = value > > for key, value in Data.items(): > Data[key] = [ transDict.get(i, i) for i in value ] > > At this point can anyone recommend any python modules that helps to create > reporting and graphing? > > On 10/2/07, Kent Johnson wrote: > > > > GTXY20 wrote: > > > > > > This seemed to work: > > > > > > def transFn(c): > > > transfile = open('translate.txt', 'r') > > > records = transfile.read() > > > transfile.close() > > > lines = records.split() > > > transDict = {} > > > for line in lines: > > > key, value = line.split(',') > > > transDict[key] = value > > > try: > > > return transDict[c] > > > except KeyError: > > > return c > > > > Yikes! This is re-reading translate.txt every time transFn() is called, > > i.e. once for every key in data! > > > > Kent > > > > > > > > for key in data.keys(): > > > data[key] = map(transFn, data[key]) > > > > > From kent37 at tds.net Tue Oct 2 19:00:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 13:00:39 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <39cb7e5d0710020935jac8193al6910be07bba87b1e@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> <39cb7e5d0710020131j6bc8abei8a2a3b65e3a57834@mail.gmail.com> <47022ACD.30008@tds.net> <39cb7e5d0710020759n697ba73agf0b0e1d3ef839f4c@mail.gmail.com> <39cb7e5d0710020935jac8193al6910be07bba87b1e@mail.gmail.com> Message-ID: <47027937.4050604@tds.net> GTXY20 wrote: > Here's an interesting question: > > Can I use the transFn function to remove items in the value list. > > Can this be done by simple assigning the current value a value of null > in the translate file? No, that will make the translated value be None (I guess that is what you mean by null). You could then filter for these, for example for key, value in Data.items(): Data[key] = [ transDict.get(i, i) for i in value if transDict.get(i, i) is not None] If you want to avoid double-fetching from transDict (if Data is huge this might matter) then you could write out the loop or possibly use something like Data[key] = [ x for x in (transDict.get(i, i) for i in value) if x is not None] which makes an intermediate generator and filters that. Kent > > M. > > > > On 10/2/07, GTXY20 wrote: >> I adjusted so that I get the following so if I do not need to translate a >> dictionary I do not call the function transFn: >> >> def transFn(translatefile): >> transfile = open(translatefile, 'r') >> records = transfile.read() >> transfile.close() >> lines = records.split() >> transDict = {} >> for line in lines: >> key, value = line.split(',') >> transDict[key] = value >> >> for key, value in Data.items(): >> Data[key] = [ transDict.get(i, i) for i in value ] From kent37 at tds.net Tue Oct 2 19:16:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 13:16:58 -0400 Subject: [Tutor] Cython/Pyrex In-Reply-To: <20071002163247.GA42774@cutter.rexx.com> References: <999472.94373.qm@web51604.mail.re2.yahoo.com> <470221ED.3050701@tds.net> <20071002163247.GA42774@cutter.rexx.com> Message-ID: <47027D0A.8050805@tds.net> Dave Kuhlman wrote: > Question: Someday will all the Python built-ins be implemented in > Cython/Pyrex. I would bet on RPython against Pyrex: http://codespeak.net/pypy/dist/pypy/doc/extcompiler.html Kent From noufal at airtelbroadband.in Tue Oct 2 20:43:45 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 03 Oct 2007 00:13:45 +0530 Subject: [Tutor] A simple Question... In-Reply-To: References: <47022BEF.4010703@tds.net> Message-ID: <47029161.40105@airtelbroadband.in> bhaaluu wrote: > On 10/2/07, Kent Johnson wrote: >> traceback.print_stack() prints the stack trace to the current point of >> execution. No forced error or drama needed :-) >> >> Kent > > Exactly how is this used, please? > > Traceback (most recent call last): > File "print_stack.py", line 160, in ? > print traceback.print_stack() > NameError: name 'traceback' is not defined > > It seems I should be able to insert a line, something like > print traceback.print_stack() > in my code wherever I want to print the stack trace? Make sure you import the traceback module before you do anything. >>> >>> >>> import traceback >>> def foo(): ... traceback.print_stack() ... >>> >>> foo() File "", line 1, in File "", line 2, in foo >>> -- ~noufal http://nibrahim.net.in/ From gtxy20 at gmail.com Tue Oct 2 21:42:00 2007 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 2 Oct 2007 15:42:00 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <47027937.4050604@tds.net> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> <39cb7e5d0710020131j6bc8abei8a2a3b65e3a57834@mail.gmail.com> <47022ACD.30008@tds.net> <39cb7e5d0710020759n697ba73agf0b0e1d3ef839f4c@mail.gmail.com> <39cb7e5d0710020935jac8193al6910be07bba87b1e@mail.gmail.com> <47027937.4050604@tds.net> Message-ID: <39cb7e5d0710021242u6554bcfau69a3c1ddfafb6ed8@mail.gmail.com> I have the transFn function as follows: def transFn(translatefile): transfile = open(translatefile, 'r') records = transfile.read() transfile.close() lines = records.split() transDict = {} for line in lines: key, value = line.split(',') transDict[key] = value for key, value in data.items(): data[key] = [ x for x in (transDict.get(i, i) for i in value) if x is not None] my original data is: data = {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4': ['a', 'c']} my transDict is: transDict = {'a': '1', 'b': '2'} However when I run transFn my data is: data = {'1': ['1', '2', 'c'], '3': ['1', '2', 'c'], '2': ['1', '2', 'c'], '4': ['1', 'c']} I was expecting: {'1': ['1', '2'], '3': ['1', '2'], '2': ['1', '2'], '4': ['1']} I will see if I can work with a remove command?? M. On 10/2/07, Kent Johnson wrote: > > GTXY20 wrote: > > Here's an interesting question: > > > > Can I use the transFn function to remove items in the value list. > > > > Can this be done by simple assigning the current value a value of null > > in the translate file? > > No, that will make the translated value be None (I guess that is what > you mean by null). You could then filter for these, for example > > for key, value in Data.items(): > Data[key] = [ transDict.get(i, i) for i in value if > transDict.get(i, i) is not None] > > If you want to avoid double-fetching from transDict (if Data is huge > this might matter) then you could write out the loop or possibly use > something like > Data[key] = [ x for x in (transDict.get(i, i) for i in value) if x is > not None] > > which makes an intermediate generator and filters that. > > Kent > > > > > M. > > > > > > > > On 10/2/07, GTXY20 wrote: > >> I adjusted so that I get the following so if I do not need to translate > a > >> dictionary I do not call the function transFn: > >> > >> def transFn(translatefile): > >> transfile = open(translatefile, 'r') > >> records = transfile.read() > >> transfile.close() > >> lines = records.split() > >> transDict = {} > >> for line in lines: > >> key, value = line.split(',') > >> transDict[key] = value > >> > >> for key, value in Data.items(): > >> Data[key] = [ transDict.get(i, i) for i in value ] > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/814dbc24/attachment.htm From kent37 at tds.net Tue Oct 2 21:47:06 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 15:47:06 -0400 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <39cb7e5d0710021242u6554bcfau69a3c1ddfafb6ed8@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> <39cb7e5d0710020107r9dc674frfcb4477f417a0236@mail.gmail.com> <39cb7e5d0710020115j33268fa9y85f38dc603375a17@mail.gmail.com> <39cb7e5d0710020131j6bc8abei8a2a3b65e3a57834@mail.gmail.com> <47022ACD.30008@tds.net> <39cb7e5d0710020759n697ba73agf0b0e1d3ef839f4c@mail.gmail.com> <39cb7e5d0710020935jac8193al6910be07bba87b1e@mail.gmail.com> <47027937.4050604@tds.net> <39cb7e5d0710021242u6554bcfau69a3c1ddfafb6ed8@mail.gmail.com> Message-ID: <4702A03A.5080302@tds.net> GTXY20 wrote: > > I have the transFn function as follows: > > def transFn(translatefile): > transfile = open(translatefile, 'r') > records = transfile.read() > transfile.close() > lines = records.split() > transDict = {} > for line in lines: > key, value = line.split(',') > transDict[key] = value > > for key, value in data.items(): > data[key] = [ x for x in (transDict.get (i, i) for i in value) if > x is not None] > > my original data is: > > data = {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', > 'c'], '4': ['a', 'c']} > > my transDict is: > > transDict = {'a': '1', 'b': '2'} > > However when I run transFn my data is: > > data = {'1': ['1', '2', 'c'], '3': ['1', '2', 'c'], '2': ['1', '2', > 'c'], '4': ['1', 'c']} > > I was expecting: > > {'1': ['1', '2'], '3': ['1', '2'], '2': ['1', '2'], '4': ['1']} Well you said you would assign null to the value in transDict and you did not do that. I fear I am giving you too much code and not enough understanding. You should be figuring some of this stuff out yourself. Look at the docs for dict.get() and see if you can change your code to do what you want. Kent From carroll at tjc.com Tue Oct 2 22:14:37 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 2 Oct 2007 13:14:37 -0700 (PDT) Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: Message-ID: Ian, thanks for cleaning this up and submitting it. I was curious what its performance would be. On Wed, 26 Sep 2007, Ian Witham wrote: > while count > 0: > fivecount += count > count /= 5 This is a great improvement, and I'm embarrased that I didn't think of it myself! From ricaraoz at gmail.com Tue Oct 2 15:03:19 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 02 Oct 2007 10:03:19 -0300 Subject: [Tutor] Update values stored as a list in a dictionary with values from another dictionary In-Reply-To: <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> References: <39cb7e5d0710012256q3ae74063scf24558a36ccc5e6@mail.gmail.com> <5e58f2e40710012305o3490616ag1f192245eaab695e@mail.gmail.com> Message-ID: <47024197.2040808@bigfoot.com> John Fouhy wrote: > On 02/10/2007, GTXY20 wrote: >> Hello all, >> >> Let's say I have the following dictionary: >> >> {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)} >> >> I also have another dictionary for new value association: >> >> {a:1, b:2, c:3} >> >> How should I approach if I want to modify the first dictionary to read: >> >> {1:(1,2,3), 2:(1,3), 3:(2,3), 4:(1,d)} >> >> There is the potential to have a value in the first dictionary that will not >> have an update key in the second dictionary hence in the above dictionary >> for key=4 I still have d listed as a value. > > You could use the map function... > > Let's say we have something like: > > transDict = { 'a':1, 'b':2, 'c':3 } > > We could define a function that mirrors this: > > def transFn(c): > try: > return transDict[c] > except KeyError: > return c > > Then if you have your data: > > data = { 1:('a','b','c'), 2:('a','c'), 3:('b','c'), 4:('a','d')} > > You can translate it as: > > for key in data.keys(): > data[key] = map(transFn, data[key]) > > HTH! > Or without defining a function : for k in data : data[k] = map(transDict.get, data[k], data[k]) From ricaraoz at gmail.com Tue Oct 2 15:46:33 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 02 Oct 2007 10:46:33 -0300 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <4701EE25.4050908@exemail.com.au> References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au> <4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au> Message-ID: <47024BB9.1000800@bigfoot.com> Andrew James wrote: > *headbang* > > I'm an idiot. s=s[:-2] should be s=s[:-1]. > > Andrew James wrote: >> And as soon as I send it again I realise a pretty stupid error. The >> two loops shouldn't be nested. >> >> Andrew James wrote: >>> Helps if I send it to the group... >>> >>> And Kent, I didn't post it originally because I figured the other guy >>> was still working on his script. Besides, I didn't think it'd be that >>> far fetched for you to assume I was using something like "while s[0] >>> == ' ':" >>> >>> Andrew James wrote: >>>> I'm always nervous about sharing my code... It's like being back in >>>> high school, I don't want the other kids to laugh at me. Anyway, >>>> running that in IDLE with a string such as ' >>>> testing. ' Will print ' testing' at the >>>> end of the first (second, really) loop. >>>> >>>> def strip(s): >>>> while s[0].isspace() == True: >>>> while s[-1].isspace() == True: >>>> s = s[:-2] >>>> print s >>>> s = s[1:] >>>> print s >>>> >>>> test = raw_input('Enter a string with plenty of leading and trailing >>>> whitespace:') >>>> >>>> strip(test) >>>> >>>> Alan Gauld wrote: >>>>> "Andrew James" wrote >>>>> >>>>> >>>>>> string containing a single space ' ' but even using s[-1].isspace() I >>>>>> lose punctuation marks. Any idea why that's happening? >>>>>> >>>>> care to show us what you are doing? >>>>> >>>>> >>>>>>>> ';'.isspace() >>>>>>>> >>>>> False >>>>> >>>>> So puntuation should not show up as true... >>>>> >>>>> Alan G. >>>>> So as not to copy strings many times : while s[0].isspace() : while s[-1].isspace() : del s[-1] del s[0] From alan.gauld at btinternet.com Wed Oct 3 01:29:07 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 3 Oct 2007 00:29:07 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au><4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au> <47024BB9.1000800@bigfoot.com> Message-ID: "Ricardo Ar?oz" wrote > > So as not to copy strings many times : > > while s[0].isspace() : > while s[-1].isspace() : > del s[-1] > del s[0] Sorry, it won;t work. Strings are immutable. However you can keep a track of the indexes of the first and last non space characers and use slicing if the copying seems to be a problem... first,last = 0,-1 while s[first].isspace(): first += 1 while s[last].isspace() last -= 1 return s[first:last] There might be an off-by-one error in the slice, its untested... Alan g. From ricaraoz at gmail.com Wed Oct 3 02:29:19 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 02 Oct 2007 21:29:19 -0300 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au><4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au> <47024BB9.1000800@bigfoot.com> Message-ID: <4702E25F.9090906@bigfoot.com> Alan Gauld wrote: > "Ricardo Ar?oz" wrote > >> So as not to copy strings many times : >> >> while s[0].isspace() : >> while s[-1].isspace() : >> del s[-1] >> del s[0] > > Sorry, it won;t work. Strings are immutable. > However you can keep a track of the indexes of the > first and last non space characers and use slicing > if the copying seems to be a problem... > > first,last = 0,-1 > > while s[first].isspace(): > first += 1 > while s[last].isspace() > last -= 1 > return s[first:last] > > There might be an off-by-one error in the slice, its untested... > > Alan g. > sorry, forgot a piece of the code : s = list(s) while s[0].isspace() : while s[-1].isspace() : del s[-1] del s[0] s = ''.join(s) You only copy the string twice. From cuongvt at fpt.vn Wed Oct 3 02:15:14 2007 From: cuongvt at fpt.vn (cuongvt) Date: Tue, 2 Oct 2007 17:15:14 -0700 (PDT) Subject: [Tutor] newbie: Django suited for database driven web application? Message-ID: <13010754.post@talk.nabble.com> Hello I'm new to both Django and Python. I'm mainly developing on PHP. I tend to move to Django. But I want to confirm as below: I heard that Django is mainly used for something like content management, CMS or something like that and Rails is mainly for web applications. So my question: is it true or not? For rapid web application development, can I use Django to create intranet database web driven application in my company for example: empoyees time management, goods import/export management, salary management etc? Tnx in advance. -- View this message in context: http://www.nabble.com/newbie%3A-Django-suited-for-database-driven-web-application--tf4559119.html#a13010754 Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Wed Oct 3 04:40:32 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 02 Oct 2007 22:40:32 -0400 Subject: [Tutor] newbie: Django suited for database driven web application? In-Reply-To: <13010754.post@talk.nabble.com> References: <13010754.post@talk.nabble.com> Message-ID: <47030120.5040905@tds.net> cuongvt wrote: > Hello > I'm new to both Django and Python. I'm mainly developing on PHP. > I tend to move to Django. But I want to confirm as below: > I heard that Django is mainly used for something like content management, > CMS or something > like that and Rails is mainly for web applications. > So my question: is it true or not? No. > For rapid web application development, can I use Django to create intranet > database web driven > application in my company for example: empoyees time management, goods > import/export management, > salary management etc? I don't know why not! Look here for many examples of Django sites: http://www.djangosites.org/latest/ Here is the one I work on: http://blogcosm.com Here is a small catalog site: http://www.americanpersonalizedproducts.com/ Kent From srikanth007m at gmail.com Wed Oct 3 05:45:24 2007 From: srikanth007m at gmail.com (chinni) Date: Wed, 3 Oct 2007 09:15:24 +0530 Subject: [Tutor] xml parsing Message-ID: Hi, I am working on MAC and my App was based on Xml file.If any updates r any changes in the xml file my app will load that changes. as i am new to python.i want to automate that one. there will be one URL and size will mention in that Xml file.i want to write a script so that it will download the file and have to check the size with my Xml file and downloaded file size.if size mismatch it has to show both current size and also xpected size.I want to write a script.so that it has to start download all App's at a time.so finally here is the sample O/P Appname Downloadedsize Expectedsize result XXXX 2554958 2554958 Pass XXXX 832158 754112 Fail Here the size is in KB's.Now plz tell me how to write the script in python. Thanx in Advance to all :) -- Cheers, M.Srikanth Kumar, Phone no: +91-9866774007 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071003/5c9133dd/attachment.htm From poolmasterji at yahoo.com Wed Oct 3 06:35:15 2007 From: poolmasterji at yahoo.com (Kamal) Date: Tue, 2 Oct 2007 21:35:15 -0700 Subject: [Tutor] for a given file, how to find file size? Message-ID: <333eea650710022135g5ebf9477le088b973c6e16bb1@mail.gmail.com> would appreciate any pointers. -- Thanks, Kamal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/f30912f5/attachment.htm From kpsingh at gmail.com Wed Oct 3 06:42:35 2007 From: kpsingh at gmail.com (Kamal) Date: Tue, 2 Oct 2007 21:42:35 -0700 Subject: [Tutor] for a given file, how to find file size? In-Reply-To: <333eea650710022135g5ebf9477le088b973c6e16bb1@mail.gmail.com> References: <333eea650710022135g5ebf9477le088b973c6e16bb1@mail.gmail.com> Message-ID: <333eea650710022142u5ea15c62sce10ebc05c6efccc@mail.gmail.com> never mind found my answer here http://docs.python.org/lib/os-file-dir.html On 10/2/07, Kamal wrote: > > would appreciate any pointers. > > -- > Thanks, > Kamal -- Thanks, Kamal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071002/aeef2b99/attachment.htm From alan.gauld at btinternet.com Wed Oct 3 08:12:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 3 Oct 2007 07:12:11 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au><4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au><47024BB9.1000800@bigfoot.com> <4702E25F.9090906@bigfoot.com> Message-ID: "Ricardo Ar?oz" wrote >sorry, forgot a piece of the code : > >s = list(s) >while s[0].isspace() : > while s[-1].isspace() : > del s[-1] > del s[0] > s = ''.join(s) It still won't work. Strings are immutable, you can't use del to delete a character. Try it. >>> del('foo'[-1]) Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item deletion >>> Alan G. From alan.gauld at btinternet.com Wed Oct 3 08:22:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 3 Oct 2007 07:22:08 +0100 Subject: [Tutor] xml parsing References: Message-ID: "chinni" wrote > I am working on MAC and my App was based on Xml file.If any updates > r any > changes in the xml file my app will load that changes. > as i am new to python.i want to automate that one. > .... details snipped > Here the size is in KB's.Now plz tell me how to write the script in > python. > Thanx in Advance to all :) First learn to program in Python. There are many tutorials to choose from. Second design a solution to your problem Third code it in Python. Now to start you on the first step, I suggest you go to the Python web site and download a copy of Python and install it on your computer. Then go to the begginners page and work through one of the tutprials. If you can program in any other language the official tutor is best. If you have anything you don't understand ask questions here. The more specific the question the better and it helps if you can show us what you have tried and what erros you are getting. Or at the very least explain what you were thinking of trying. Once you can write basic Python programs we can think about stage 2. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From witham.ian at gmail.com Wed Oct 3 10:56:16 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 3 Oct 2007 21:56:16 +1300 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au> <4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au> <47024BB9.1000800@bigfoot.com> <4702E25F.9090906@bigfoot.com> Message-ID: On 10/3/07, Alan Gauld wrote: > > > "Ricardo Ar?oz" wrote > > >sorry, forgot a piece of the code : > > > >s = list(s) > >while s[0].isspace() : > > while s[-1].isspace() : > > del s[-1] > > del s[0] > > s = ''.join(s) > > It still won't work. Strings are immutable, you can't use del > to delete a character. Try it. > Alan, he does convert to a list first and then rejoin to a string afterwards, so using del is not the problem. However, the script is still flawed. The loop to delete trailing whitespace is nested within the loop to delete the leading whitespace. The trailing whitespace loop only needs to be run once, but it is currently being processed once for each leading space and not at all if there are no leading spaces! For instance, " Myriad Harbor " strips OK, but "Myriad Harbor " does not. The solution of course is to keep the two loops separate: s = list(s) while s[0].isspace() : del s[0] while s[-1].isspace() : del s[-1] s = ''.join(s) Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071003/a4d6f28c/attachment-0001.htm From cuongvt at fpt.vn Wed Oct 3 05:07:12 2007 From: cuongvt at fpt.vn (cuongvt) Date: Tue, 2 Oct 2007 20:07:12 -0700 (PDT) Subject: [Tutor] newbie: Django suited for database driven web application? In-Reply-To: <47030120.5040905@tds.net> References: <13010754.post@talk.nabble.com> <47030120.5040905@tds.net> Message-ID: <13012222.post@talk.nabble.com> Tnx for quick answer, I go for python and Django Kent Johnson wrote: > > cuongvt wrote: >> Hello >> I'm new to both Django and Python. I'm mainly developing on PHP. >> I tend to move to Django. But I want to confirm as below: >> I heard that Django is mainly used for something like content management, >> CMS or something >> like that and Rails is mainly for web applications. >> So my question: is it true or not? > > No. >> For rapid web application development, can I use Django to create >> intranet >> database web driven >> application in my company for example: empoyees time management, goods >> import/export management, >> salary management etc? > > I don't know why not! > > Look here for many examples of Django sites: > http://www.djangosites.org/latest/ > > Here is the one I work on: > http://blogcosm.com > > Here is a small catalog site: > http://www.americanpersonalizedproducts.com/ > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/newbie%3A-Django-suited-for-database-driven-web-application--tf4559119.html#a13012222 Sent from the Python - tutor mailing list archive at Nabble.com. From ricaraoz at gmail.com Wed Oct 3 12:49:07 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 03 Oct 2007 07:49:07 -0300 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au><4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au><47024BB9.1000800@bigfoot.com> <4702E25F.9090906@bigfoot.com> Message-ID: <470373A3.1000408@bigfoot.com> Alan Gauld wrote: > "Ricardo Ar?oz" wrote > >> sorry, forgot a piece of the code : >> >> s = list(s) >> while s[0].isspace() : >> while s[-1].isspace() : >> del s[-1] >> del s[0] >> s = ''.join(s) > > It still won't work. Strings are immutable, you can't use del > to delete a character. Try it. It comes straight from Idle (still warm ;-) ). Notice s = list(s) and s = ''.join(s), so I'm not using del with strings but with a list and that is ok. Try it, it does work. > >>>> del('foo'[-1]) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: object doesn't support item deletion > Not what I'm doing. Cheers Ricardo From ricaraoz at gmail.com Wed Oct 3 12:56:22 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 03 Oct 2007 07:56:22 -0300 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au> <4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au> <47024BB9.1000800@bigfoot.com> <4702E25F.9090906@bigfoot.com> Message-ID: <47037556.2050208@bigfoot.com> Ian Witham wrote: > > On 10/3/07, *Alan Gauld* > wrote: > > > "Ricardo Ar?oz" > wrote > > >sorry, forgot a piece of the code : > > > >s = list(s) > >while s[0].isspace() : > > while s[-1].isspace() : > > del s[-1] > > del s[0] > > s = ''.join(s) > > It still won't work. Strings are immutable, you can't use del > to delete a character. Try it. > > > Alan, he does convert to a list first and then rejoin to a string > afterwards, so using del is not the problem. > > However, the script is still flawed. > The loop to delete trailing whitespace is nested within the loop to > delete the leading whitespace. The trailing whitespace loop only needs > to be run once, but it is currently being processed once for each > leading space and not at all if there are no leading spaces! > For instance, " Myriad Harbor " strips OK, but "Myriad Harbor " does not. > > The solution of course is to keep the two loops separate: > > s = list(s) > while s[0].isspace() : > del s[0] > while s[-1].isspace() : > del s[-1] > s = ''.join(s) > You are right Ian. It's an extra "s[-1].isspace()" (and a jump) for each leading whitespace, so though it works yours is still better. Don't know why didn't see it :(, perhaps because I took code from the previous post and did a quick fix. :( (and blushing in shame) From dos.fool at gmail.com Wed Oct 3 14:53:32 2007 From: dos.fool at gmail.com (max baseman) Date: Wed, 3 Oct 2007 06:53:32 -0600 Subject: [Tutor] Tkinter text Message-ID: <7F520B73-CE99-45BA-B523-121CF1988636@gmail.com> hello im working on my first simple gui using Tkinter i've got two questions, 1st how would you go about creating a hidden text file that trys on a apple and if that does not work tries to do it on a windows computer? the program I'm making is a vary simple text editor for one file all it needs to be able to do is add text and save. as far as i can see i'll mostly need to use the text widget but i cant find a tutorial for that widget mostly just for the text entry widget which is only for one line of text. if anyone knows a good tut that would be great thank you From sacharook at hotmail.co.uk Wed Oct 3 15:10:33 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Wed, 3 Oct 2007 14:10:33 +0100 Subject: [Tutor] data from excel spreadsheet to csv and manipulate In-Reply-To: <004d01c8042c$db761440$0b0aa8c0@rbsassociates.local> References: <004d01c8042c$db761440$0b0aa8c0@rbsassociates.local> Message-ID: Hi can anyone help with the best way to tackle this? I have a spreadsheet ms excel, that has a name column that I want to extract to csv and manipulate as follows. The name column has data in this format Name Surname Firstname after extracting and manipulating I want it to be as follows in three comma separated fields; Firstname, Surname, Firstname Surname So Smith John becomes John, Smith, John Smith I hope I have explained myself. I want to use python to do all this if sensible, so what is the best approach? Many thanks S _________________________________________________________________ Feel like a local wherever you go. http://www.backofmyhand.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071003/5fd9e162/attachment.htm From kent37 at tds.net Wed Oct 3 16:10:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 Oct 2007 10:10:13 -0400 Subject: [Tutor] data from excel spreadsheet to csv and manipulate In-Reply-To: References: <004d01c8042c$db761440$0b0aa8c0@rbsassociates.local> Message-ID: <4703A2C5.5000600@tds.net> sacha rook wrote: > Hi > > can anyone help with the best way to tackle this? > > I have a spreadsheet ms excel, that has a name column that I want to > extract to csv and manipulate as follows. If you can save the spreadsheet as csv then you can use the csv module for reading and writing. To read the excel file directly you can use one of these: http://www.lexicon.net/sjmachin/xlrd.htm http://sourceforge.net/projects/pyexcelerator If you are running on Windows then you can also script Excel directly with COM: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440661 Kent From jason.massey at gmail.com Wed Oct 3 17:20:07 2007 From: jason.massey at gmail.com (Jason Massey) Date: Wed, 3 Oct 2007 10:20:07 -0500 Subject: [Tutor] for a given file, how to find file size? In-Reply-To: <333eea650710022142u5ea15c62sce10ebc05c6efccc@mail.gmail.com> References: <333eea650710022135g5ebf9477le088b973c6e16bb1@mail.gmail.com> <333eea650710022142u5ea15c62sce10ebc05c6efccc@mail.gmail.com> Message-ID: <7e3eab2c0710030820q345d54bbp71ea8d5d1b7e42a@mail.gmail.com> Are you sure? From the link you provided it looks as if: *stat*( path) Perform a stat() system call on the given path. The return value is an object whose attributes correspond to the members of the statstructure, namely: st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink(number of hard links), st_uid (user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows): >>> import os >>> statinfo = os.stat('somefile.txt') >>> statinfo (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732) >>> statinfo.st_size 926L >>> does exactly what you want. On 10/2/07, Kamal wrote: > > never mind found my answer here > > http://docs.python.org/lib/os-file-dir.html > > > On 10/2/07, Kamal wrote: > > > > would appreciate any pointers. > > > > -- > > Thanks, > > Kamal > > > > > -- > Thanks, > Kamal > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071003/4852d626/attachment.htm From kent37 at tds.net Wed Oct 3 17:40:29 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 Oct 2007 11:40:29 -0400 Subject: [Tutor] for a given file, how to find file size? In-Reply-To: <333eea650710022142u5ea15c62sce10ebc05c6efccc@mail.gmail.com> References: <333eea650710022135g5ebf9477le088b973c6e16bb1@mail.gmail.com> <333eea650710022142u5ea15c62sce10ebc05c6efccc@mail.gmail.com> Message-ID: <4703B7ED.9090706@tds.net> Kamal wrote: > never mind found my answer here > > http://docs.python.org/lib/os-file-dir.html os.path.getsize() also works. Kent From kpsingh at gmail.com Wed Oct 3 19:54:10 2007 From: kpsingh at gmail.com (Kamal) Date: Wed, 3 Oct 2007 10:54:10 -0700 Subject: [Tutor] for a given file, how to find file size? In-Reply-To: <4703B7ED.9090706@tds.net> References: <333eea650710022135g5ebf9477le088b973c6e16bb1@mail.gmail.com> <333eea650710022142u5ea15c62sce10ebc05c6efccc@mail.gmail.com> <4703B7ED.9090706@tds.net> Message-ID: <333eea650710031054y3103e918qc6fb057632827329@mail.gmail.com> Thanks Jason and Kent for the responses. On 10/3/07, Kent Johnson wrote: > Kamal wrote: > > never mind found my answer here > > > > http://docs.python.org/lib/os-file-dir.html > > os.path.getsize() also works. > > Kent > -- Thanks, Kamal From pkraus at pelsupply.com Wed Oct 3 22:40:08 2007 From: pkraus at pelsupply.com (Paul D. Kraus) Date: Wed, 3 Oct 2007 16:40:08 -0400 Subject: [Tutor] Sending Email Message-ID: <4e2aea430710031340s15508172q8473ad0a20415bad@mail.gmail.com> I have a turbogears app that needs to be able to send out email notifications to users. Just plain text, no attachments. Can anyone suggest some lightweight module? Maybe something Akin to Perl's MIME::Lite. Paul From steve at alchemy.com Wed Oct 3 22:45:03 2007 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 3 Oct 2007 13:45:03 -0700 Subject: [Tutor] Sending Email In-Reply-To: <4e2aea430710031340s15508172q8473ad0a20415bad@mail.gmail.com> References: <4e2aea430710031340s15508172q8473ad0a20415bad@mail.gmail.com> Message-ID: <20071003204503.GF88747@dragon.alchemy.com> On Wed, Oct 03, 2007 at 04:40:08PM -0400, Paul D. Kraus wrote: > I have a turbogears app that needs to be able to send out email > notifications to users. Just plain text, no attachments. Can anyone > suggest some lightweight module? > > Maybe something Akin to Perl's MIME::Lite. Python comes with an smtplib module which works very well. You say you want plain text, so just do this: import smtplib mail = smtplib.SMTP(mailhost_name) mail.sendmail(from_addr, to_addr, msg) mail.quit() You can use MIME modules too if you want attachments and stuff, but this is pretty simple for plain text. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From kent37 at tds.net Wed Oct 3 23:02:52 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 03 Oct 2007 17:02:52 -0400 Subject: [Tutor] Sending Email In-Reply-To: <20071003204503.GF88747@dragon.alchemy.com> References: <4e2aea430710031340s15508172q8473ad0a20415bad@mail.gmail.com> <20071003204503.GF88747@dragon.alchemy.com> Message-ID: <4704037C.1000904@tds.net> Steve Willoughby wrote: > Python comes with an smtplib module which works very well. You say > you want plain text, so just do this: > > import smtplib > > mail = smtplib.SMTP(mailhost_name) > mail.sendmail(from_addr, to_addr, msg) > mail.quit() One gotcha is that msg must also include From and Two headers. A slightly longer example is here: http://docs.python.org/lib/SMTP-example.html Kent From steve at alchemy.com Wed Oct 3 23:09:07 2007 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 3 Oct 2007 14:09:07 -0700 Subject: [Tutor] Sending Email In-Reply-To: <4704037C.1000904@tds.net> References: <4e2aea430710031340s15508172q8473ad0a20415bad@mail.gmail.com> <20071003204503.GF88747@dragon.alchemy.com> <4704037C.1000904@tds.net> Message-ID: <20071003210907.GG88747@dragon.alchemy.com> On Wed, Oct 03, 2007 at 05:02:52PM -0400, Kent Johnson wrote: > One gotcha is that msg must also include From and Two headers. A > slightly longer example is here: > http://docs.python.org/lib/SMTP-example.html Yes, that's important to remember. Actually, you want to put all the headers you care about in msg (probably Subject at least, along with To, From, and possibly Cc). You can also, by the way, exploit the separation of naming recipient(s) in the sendmail() method and listing them in the To: header in the message text in order to do blind-Cc (Bcc). Just name some people in the sendmail() parameter but not in the To: or Cc: headers, and they are blind-carbon-copied. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From steve at alchemy.com Wed Oct 3 23:25:14 2007 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 3 Oct 2007 14:25:14 -0700 Subject: [Tutor] Sending Email In-Reply-To: <20071003210907.GG88747@dragon.alchemy.com> References: <4e2aea430710031340s15508172q8473ad0a20415bad@mail.gmail.com> <20071003204503.GF88747@dragon.alchemy.com> <4704037C.1000904@tds.net> <20071003210907.GG88747@dragon.alchemy.com> Message-ID: <20071003212514.GH88747@dragon.alchemy.com> On Wed, Oct 03, 2007 at 02:09:07PM -0700, Steve Willoughby wrote: > On Wed, Oct 03, 2007 at 05:02:52PM -0400, Kent Johnson wrote: > > One gotcha is that msg must also include From and Two headers. A > > slightly longer example is here: > > http://docs.python.org/lib/SMTP-example.html > > Yes, that's important to remember. Actually, you want to > put all the headers you care about in msg (probably Subject > at least, along with To, From, and possibly Cc). You can also, > by the way, exploit the separation of naming recipient(s) in the > sendmail() method and listing them in the To: header in the message > text in order to do blind-Cc (Bcc). Just name some people in > the sendmail() parameter but not in the To: or Cc: headers, and > they are blind-carbon-copied. ...and don't forget the blank line between headers and message text. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From alan.gauld at btinternet.com Wed Oct 3 23:37:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 3 Oct 2007 22:37:41 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au><4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au><47024BB9.1000800@bigfoot.com> <4702E25F.9090906@bigfoot.com> <470373A3.1000408@bigfoot.com> Message-ID: "Ricardo Ar?oz" wrote > >It still won't work. Strings are immutable, you can't use del > > to delete a character. Try it. > > It comes straight from Idle (still warm ;-) ). > Notice s = list(s) Shame and embarrassment! I read that code through both times and never noticed the list conversion either time! I did wonder about the join() but just dismissed it as irrelevant. Grovelling apologies. Alan G. From alan.gauld at btinternet.com Wed Oct 3 23:58:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 3 Oct 2007 22:58:17 +0100 Subject: [Tutor] Tkinter text References: <7F520B73-CE99-45BA-B523-121CF1988636@gmail.com> Message-ID: "max baseman" wrote > i've got two questions, 1st how would you go about creating a hidden > text file that trys on a apple and if that does not work tries to do > it on a windows computer? I don;t undeetabnd this bit. What does the text file try on the Apple/Windows computer? > the program I'm making is a vary simple text editor for one file all > it needs to be able to do is add text and save. as far as i can see > i'll mostly need to use the text widget but i cant find a tutorial > for that widget mostly just for the text entry widget which is only > for one line of text. if anyone knows a good tut that would be great This should only be about 20 lines of code. The Text widget plus the standard fole open/save dialogs should dop all you need. For a very simple example of using the Text widget see the case study and the Event Driven programming topics of my tutor. For more detail see Fred Lundh's Tkinter reference. When you get stuck ask here. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dos.fool at gmail.com Thu Oct 4 00:30:37 2007 From: dos.fool at gmail.com (max baseman) Date: Wed, 3 Oct 2007 16:30:37 -0600 Subject: [Tutor] Tkinter text In-Reply-To: References: <7F520B73-CE99-45BA-B523-121CF1988636@gmail.com> Message-ID: <07CA79D0-9F78-4F5C-878A-8A8944CDD104@gmail.com> sorry, what i was trying to say was, how would i write something that at first tries to create a hidden file on a apple computer then if the computer was not a apple creates a hidden file on a windows OS i have slowly been reading your tutorial and it's really one of the best tuts i've ever read i really like and that was the first place i checked but in the GUI section the text entry bit is for a single line of text On Oct 3, 2007, at 3:58 PM, Alan Gauld wrote: > > "max baseman" wrote > >> i've got two questions, 1st how would you go about creating a hidden >> text file that trys on a apple and if that does not work tries to do >> it on a windows computer? > > I don;t undeetabnd this bit. What does the text file try on > the Apple/Windows computer? > >> the program I'm making is a vary simple text editor for one file all >> it needs to be able to do is add text and save. as far as i can see >> i'll mostly need to use the text widget but i cant find a tutorial >> for that widget mostly just for the text entry widget which is only >> for one line of text. if anyone knows a good tut that would be great > > This should only be about 20 lines of code. The Text widget plus > the standard fole open/save dialogs should dop all you need. > > For a very simple example of using the Text widget see the case > study and the Event Driven programming topics of my tutor. > > For more detail see Fred Lundh's Tkinter reference. > > When you get stuck ask here. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ricaraoz at gmail.com Thu Oct 4 01:48:02 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 03 Oct 2007 20:48:02 -0300 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> <45109da50709301605u362a2a25r82bb444cad5bc11d@mail.gmail.com> <47003DF4.2020903@exemail.com.au> <4701EB7E.5080801@exemail.com.au> <4701ECC5.9000009@exemail.com.au><4701ED96.4000307@exemail.com.au> <4701EE25.4050908@exemail.com.au><47024BB9.1000800@bigfoot.com> <4702E25F.9090906@bigfoot.com> <470373A3.1000408@bigfoot.com> Message-ID: <47042A32.6070201@bigfoot.com> Alan Gauld wrote: > "Ricardo Ar?oz" wrote > >>> It still won't work. Strings are immutable, you can't use del >>> to delete a character. Try it. >> It comes straight from Idle (still warm ;-) ). >> Notice s = list(s) > > Shame and embarrassment! I read that code through both times and > never noticed the list conversion either time! I did wonder about the > join() but just dismissed it as irrelevant. > > Grovelling apologies. > Don't worry, you can imagine MY 'shame and embarrasment' at being pointed that the while's should go separate as opposed to one within the other. 87( From cspears2002 at yahoo.com Thu Oct 4 02:08:53 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 3 Oct 2007 17:08:53 -0700 (PDT) Subject: [Tutor] creating the equivalent of string.strip() Message-ID: <816104.33507.qm@web51605.mail.re2.yahoo.com> I know people might be sick of this thread by now, but I decided to post a solution to this problem that uses regular expressions. #!/usr/bin/env python import string import re def my_strip(s): remove_leading = re.sub(r'^\s+','',s) remove_trailing = re.sub(r'\s+$','',remove_leading) new_s = remove_trailing return new_s test = raw_input("Enter a string with leading and trailing whitespace: ") #print test new_s = my_strip(test) print new_s From cspears2002 at yahoo.com Thu Oct 4 04:29:13 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 3 Oct 2007 19:29:13 -0700 (PDT) Subject: [Tutor] matching a street address with regular expressions Message-ID: <505641.42832.qm@web51601.mail.re2.yahoo.com> One of the exercises in Core Python Programming is to create a regular expression that will match a street address. Here is one of my attempts. >>> street = "1180 Bordeaux Drive" >>> patt = "\d+ \w+" >>> import re >>> m = re.match(patt, street) >>> if m is not None: m.group() ... '1180 Bordeaux' >>> Obviously, I can just create a pattern "\d+ \w+ \w+". However, the pattern would be useless if I had a street name like 3120 De la Cruz Boulevard. Any hints? From john at fouhy.net Thu Oct 4 04:42:09 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 4 Oct 2007 14:42:09 +1200 Subject: [Tutor] matching a street address with regular expressions In-Reply-To: <505641.42832.qm@web51601.mail.re2.yahoo.com> References: <505641.42832.qm@web51601.mail.re2.yahoo.com> Message-ID: <5e58f2e40710031942m3eb1e343t7e81b94eecc770ac@mail.gmail.com> On 04/10/2007, Christopher Spears wrote: > Obviously, I can just create a pattern "\d+ \w+ \w+". > However, the pattern would be useless if I had a > street name like 3120 De la Cruz Boulevard. Any > hints? Possibly you could create a list of street types ('Street', 'Road', 'Crescent', 'Lane', etc.), then construct a regular expression matching "a number, followed by one or more words, followed by a street type". Another thing you could do: put the street number, street name, and street type into separate named groups, so you could do things like "m['number']" to get the street number from the match object. Finally, street addresses can be very dirty -- you get people writing things like: "Flat A, 13 Main St" "13A Main St" "13-A Main St" "13/A Main St" "13-15 Main St" and other variations. Some people earn good money doing address cleaning :-) -- John. From poolmasterji at yahoo.com Thu Oct 4 07:35:47 2007 From: poolmasterji at yahoo.com (Kamal) Date: Wed, 3 Oct 2007 22:35:47 -0700 Subject: [Tutor] Timers in Python Message-ID: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> hello everyone, Is there a method in Python which does what setInterval('someFunction()',5000) does in Javascript. Basically, I want to call functionOne() every x minutes, and wondering whats the best way to do it. -- Thanks, Kamal From fast_primes at hotmail.com Thu Oct 4 07:38:08 2007 From: fast_primes at hotmail.com (Fast Primes) Date: Thu, 4 Oct 2007 01:38:08 -0400 Subject: [Tutor] Controlling MS Windows programs? Message-ID: I am looking for ways to control multiple Windows programs from Python, such that I can enter data via Python and have that data passed to an underlying third party program's GUI screen, operated on and the results possibly passed back to Python. Thence onto yet another program for further work. I've not seen any material covering this--even in Python Programming on Win32. Is it possible to come at this in a more straight forward way than having to concern oneself with COM and the related Windows internals? Thanks. FP _________________________________________________________________ Climb to the top of the charts!? Play Star Shuffle:? the word scramble challenge with star power. http://club.live.com/star_shuffle.aspx?icid=starshuffle_wlmailtextlink_oct -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071004/860fe5ce/attachment.htm From alan.gauld at btinternet.com Thu Oct 4 09:13:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Oct 2007 08:13:51 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <816104.33507.qm@web51605.mail.re2.yahoo.com> Message-ID: "Christopher Spears" wrote > I decided to post a solution to this problem that uses > regular expressions. > > def my_strip(s): > remove_leading = re.sub(r'^\s+','',s) > remove_trailing = > re.sub(r'\s+$','',remove_leading) > new_s = remove_trailing > return new_s You can replace the last two lines with return remove_trailing There is no need for new_s (In fact you could just return the last sub result and dispense with remove_training too!) Alan G. From alan.gauld at btinternet.com Thu Oct 4 09:27:20 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Oct 2007 08:27:20 +0100 Subject: [Tutor] Controlling MS Windows programs? References: Message-ID: "Fast Primes" wrote > I am looking for ways to control multiple Windows programs > from Python, such that I can enter data via Python and have > that data passed to an underlying third party program's GUI > screen, ... > Is it possible to come at this in a more straight forward way > than having to concern oneself with COM and the related > Windows internals? COM *is* the straightforward way, that is what COM is for. If you can't use COM you have to go through the far less reliable route of "screen scraping" the GUI. This involves passing windows messages to the target application to simulate user events. Look at the PostMessage function in the Win32 API (Check it on MSDN) as an example. Getting data back out can be even more tricky unless you can get the "handle" of the widgets concerned. That can usually be done with a combination of FindWindow() and GetChildWindows() calls You can access the API functions via ctypes. But COM is actually easier in most cases Windows was not designed for scripting! Thats why DDE/OLE/COM was developed. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Oct 4 09:34:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Oct 2007 08:34:25 +0100 Subject: [Tutor] matching a street address with regular expressions References: <505641.42832.qm@web51601.mail.re2.yahoo.com> Message-ID: "Christopher Spears" wrote > create a regular expression that will match a street > address. Here is one of my attempts. > > Obviously, I can just create a pattern "\d+ \w+ \w+". > However, the pattern would be useless if I had a > street name like 3120 De la Cruz Boulevard. Any > hints? Yes, don't go too far. Matching addresses is a fantastically difficult thing to do perfectly. There are several companies whose only product is software to match and check addresses and they sell it for hundreds of thousands of dollars a license! They spend years developing and improving it. Our suppllier is up to version 16 and they only release new versions every 2 years... Of course they are matching formats from countries around the world and providing GUI management consoles and MIS reports etc etc. But the core function of correctly identifying valid addresses remains a hugely complex task. Its a good idea to try just enough of it to realise how hard it is. Then stop. :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rob.andrews at gmail.com Thu Oct 4 10:41:21 2007 From: rob.andrews at gmail.com (Rob Andrews) Date: Thu, 4 Oct 2007 03:41:21 -0500 Subject: [Tutor] Timers in Python In-Reply-To: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> References: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> Message-ID: <8d757d2e0710040141w75351982wcd14fafddf7f5db1@mail.gmail.com> On 10/4/07, Kamal wrote: > Is there a method in Python which does what > setInterval('someFunction()',5000) does in Javascript. > > Basically, I want to call functionOne() every x minutes, and wondering > whats the best way to do it. Yes, the time module in the standard library has sleep(x), where x is in seconds. The Python Library Reference, section 14.2, goes into a bit more detail. -Rob A. From alan.gauld at btinternet.com Thu Oct 4 10:56:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Oct 2007 09:56:25 +0100 Subject: [Tutor] Timers in Python References: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> <8d757d2e0710040141w75351982wcd14fafddf7f5db1@mail.gmail.com> Message-ID: "Rob Andrews" wrote >> Is there a method in Python which does what >> setInterval('someFunction()',5000) does in Javascript. >> >> Basically, I want to call functionOne() every x minutes, and >> wondering >> whats the best way to do it. > > Yes, the time module in the standard library has sleep(x), where x > is > in seconds. Unfortunately sleep blocks the program so you may need to wrap it in a thread to launch the required function at the required time without blocking the main program. There probably is a third party module that will do this but I don't know of any. If its within a GUI context then I think both Tkinter and wxPython have timer facilities although I've never used them. Alan G. From kent37 at tds.net Thu Oct 4 12:41:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Oct 2007 06:41:33 -0400 Subject: [Tutor] Timers in Python In-Reply-To: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> References: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> Message-ID: <4704C35D.7090501@tds.net> Kamal wrote: > hello everyone, > > Is there a method in Python which does what > setInterval('someFunction()',5000) does in Javascript. > > Basically, I want to call functionOne() every x minutes, and wondering > whats the best way to do it. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65222 Kent From kent37 at tds.net Thu Oct 4 12:46:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Oct 2007 06:46:14 -0400 Subject: [Tutor] Timers in Python In-Reply-To: References: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> <8d757d2e0710040141w75351982wcd14fafddf7f5db1@mail.gmail.com> Message-ID: <4704C476.5010508@tds.net> Alan Gauld wrote: > If its within a GUI context then I think both Tkinter and wxPython > have timer facilities although I've never used them. Tkinter: http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm From rikard.bosnjakovic at gmail.com Thu Oct 4 13:18:20 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Thu, 4 Oct 2007 13:18:20 +0200 Subject: [Tutor] Timers in Python In-Reply-To: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> References: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> Message-ID: On 04/10/2007, Kamal wrote: > Basically, I want to call functionOne() every x minutes, and wondering > whats the best way to do it. If you need to run the functions concurrently, use threads. Else you can setup a simple signal-handler for SIGALRM and set the time accordingly: import signal def setup_signal(): # Wait 5 seconds before alarming signal.alarm(5) signal.signal(signal.SIGALRM, signal_handler) def signal_handler(signum, frame): print "I got an alarm!" # need to resetup the signal setup_signal() setup_signal() # A pointless loop for x in xrange(500000000): if (x % 100000) == 0: print x -- - Rikard - http://bos.hack.org/cv/ From tinoloc at gmail.com Thu Oct 4 17:36:45 2007 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 4 Oct 2007 11:36:45 -0400 Subject: [Tutor] getting a result from an if condition Message-ID: Hi Everybody, I'm having some problems with get an if block to work. import re regex=re.compile('(some expression)') # What I'm trying to get to work if (m=regex.search('some long string')): print m.groups() - The thing that isn't working is the m=regex .... in the if line. Is this possible in python? Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071004/eb60fe8d/attachment.htm From kent37 at tds.net Thu Oct 4 18:01:03 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Oct 2007 12:01:03 -0400 Subject: [Tutor] getting a result from an if condition In-Reply-To: References: Message-ID: <47050E3F.8030705@tds.net> Tino Dai wrote: > Hi Everybody, > > I'm having some problems with get an if block to work. > > import re > > regex=re.compile('(some expression)') > > # What I'm trying to get to work > if (m=regex.search('some long string')): > print m.groups() > > - The thing that isn't working is the m=regex .... in the if line. Is this > possible in python? No. Assignment in Python is a statement, not an expression. It does not have a value and it can't be used in a conditional. Use m=regex.search('some long string') if (m): print m.groups() Kents From noufal at airtelbroadband.in Thu Oct 4 19:23:18 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Thu, 04 Oct 2007 22:53:18 +0530 Subject: [Tutor] Timers in Python In-Reply-To: <4704C35D.7090501@tds.net> References: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> <4704C35D.7090501@tds.net> Message-ID: <47052186.5030400@airtelbroadband.in> Kent Johnson wrote: > Kamal wrote: >> hello everyone, >> >> Is there a method in Python which does what >> setInterval('someFunction()',5000) does in Javascript. >> >> Basically, I want to call functionOne() every x minutes, and wondering >> whats the best way to do it. You can also look at the sched module that comes with the standard distribution. -- ~noufal http://nibrahim.net.in/ From walksloud at gmail.com Thu Oct 4 21:15:41 2007 From: walksloud at gmail.com (Andre Walker-Loud) Date: Thu, 4 Oct 2007 15:15:41 -0400 Subject: [Tutor] using python to execute from Dir A in Dir B Message-ID: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> Hi All, lets say I am in Dir A (out of my control because I have submitted a job to a queuing system) and I have a python script which is running in this directory - the one I submitted to the queue what I need to do is have my python script run another executable, but it must do it from a directory different from the one I am in, it needs to run in the /scratch/ directory (again not my choice) Is this possible, and is it easy? the way I have been using python to run other executables is os.system('path/my.executable input') but this dumps the output in the directory I am currently in, and not the directory the my.executable lives in - I am hoping there is a simple way to tell python to run the executable in its directory, and have its output live there as well. If I were using CSH, I could do all this very simply by having these lines in my script ### .csh file cd /scratch my_exe.csh I am hoping this idea makes sense and is simple with python... Thanks, Andre From kent37 at tds.net Thu Oct 4 21:57:03 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Oct 2007 15:57:03 -0400 Subject: [Tutor] using python to execute from Dir A in Dir B In-Reply-To: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> References: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> Message-ID: <4705458F.5050605@tds.net> Andre Walker-Loud wrote: > Hi All, > > lets say I am in Dir A (out of my control because I have submitted a > job to a queuing system) > > and I have a python script which is running in this directory - the > one I submitted to the queue > > what I need to do is have my python script run another executable, > but it must do it from a directory different from the one I am in, it > needs to run in the /scratch/ directory (again not my choice) > > Is this possible, and is it easy? Use subprocess.Popen() with the cwd argument. Kent From tiagosaboga at terra.com.br Thu Oct 4 22:10:08 2007 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 4 Oct 2007 17:10:08 -0300 Subject: [Tutor] using python to execute from Dir A in Dir B In-Reply-To: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> References: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> Message-ID: <20071004201008.GC7084@localdomain> On Thu, Oct 04, 2007 at 03:15:41PM -0400, Andre Walker-Loud wrote: > what I need to do is have my python script run another executable, > but it must do it from a directory different from the one I am in, it > needs to run in the /scratch/ directory (again not my choice) > > Is this possible, and is it easy? > > the way I have been using python to run other executables is > > os.system('path/my.executable input') Have a look at the subprocess module. You should be able to do something like: subprocess.Popen(['path/my.executable'], cwd='path') I am not sure of the actual keyword to be used, so please look at the docs... Tiago. From lu.fangwen at yahoo.com Thu Oct 4 22:19:35 2007 From: lu.fangwen at yahoo.com (Fangwen Lu) Date: Thu, 4 Oct 2007 13:19:35 -0700 (PDT) Subject: [Tutor] How to do histogram Message-ID: <620987.4618.qm@web44913.mail.sp1.yahoo.com> Dear all- I want to get a histogram. And I did the following. from pylab import * x=(1,1,2,2,2,2,3,4) hist(x) Then I get (array([2, 0, 0, 4, 0, 0, 1, 0, 0, 1]), array([ 1. , 1.3, 1.6, 1.9, 2.2, 2.5, 2.8, 3.1, 3.4, 3.7]), ) But actually I want to get a picture. What's the problem? What should I do? Thanks. Fangwen --------------------------------- Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071004/918b9177/attachment.htm From rikard.bosnjakovic at gmail.com Thu Oct 4 23:08:06 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Thu, 4 Oct 2007 23:08:06 +0200 Subject: [Tutor] How to do histogram In-Reply-To: <620987.4618.qm@web44913.mail.sp1.yahoo.com> References: <620987.4618.qm@web44913.mail.sp1.yahoo.com> Message-ID: On 04/10/2007, Fangwen Lu wrote: > What's the problem? We have no idea. Perhaps you could give us some info of what errors the Python-process returns. Things will be easier to help out that way. -- - Rikard - http://bos.hack.org/cv/ From kent37 at tds.net Thu Oct 4 23:30:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 04 Oct 2007 17:30:58 -0400 Subject: [Tutor] How to do histogram In-Reply-To: <620987.4618.qm@web44913.mail.sp1.yahoo.com> References: <620987.4618.qm@web44913.mail.sp1.yahoo.com> Message-ID: <47055B92.3080608@tds.net> Fangwen Lu wrote: > Dear all- > > I want to get a histogram. And I did the following. > from pylab import * > x=(1,1,2,2,2,2,3,4) > hist(x) > > Then I get > (array([2, 0, 0, 4, 0, 0, 1, 0, 0, 1]), array([ 1. , 1.3, 1.6, 1.9, > 2.2, 2.5, 2.8, 3.1, 3.4, 3.7]), ) > > But actually I want to get a picture. > What's the problem? What should I do? Did you call show() ? There is a histogram example here: http://matplotlib.sourceforge.net/screenshots.html Kent From alan.gauld at btinternet.com Thu Oct 4 23:13:00 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Oct 2007 22:13:00 +0100 Subject: [Tutor] using python to execute from Dir A in Dir B References: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> Message-ID: "Andre Walker-Loud" wrote > If I were using CSH, I could do all this very simply by having these > lines in my script > > ### .csh file > > cd /scratch > my_exe.csh The best answer is to use subprocess as Kent suggested but you can also use os.chdir(path) before using os.system() But system() is deprecated in favour of the subprocess module. Of course you could also modify your script to take a path as a command line argument and use that to direct the output explicitly... Alan G. From dos.fool at gmail.com Fri Oct 5 01:37:00 2007 From: dos.fool at gmail.com (max baseman) Date: Thu, 4 Oct 2007 17:37:00 -0600 Subject: [Tutor] another quickie Message-ID: hello all, im sorry but i might be asking a lot of Tkinter questions for a bit. im still working on my first GUI, it is very simple all i want it to do is open a text file, write to it, than save it. so far i have a GUI with the ability to right text (nothing amazing), but i don't know how to have it display the text from a text file any help would be great from Tkinter import * top=Tk() F=Frame(top) F.pack() F.txtBox=Text(top) F.txtBox.pack() F.pack() this is all i have so far ^_^" From ricaraoz at gmail.com Thu Oct 4 14:31:00 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 04 Oct 2007 09:31:00 -0300 Subject: [Tutor] matching a street address with regular expressions In-Reply-To: <505641.42832.qm@web51601.mail.re2.yahoo.com> References: <505641.42832.qm@web51601.mail.re2.yahoo.com> Message-ID: <4704DD04.4020304@bigfoot.com> Christopher Spears wrote: > One of the exercises in Core Python Programming is to > create a regular expression that will match a street > address. Here is one of my attempts. > >>>> street = "1180 Bordeaux Drive" >>>> patt = "\d+ \w+" >>>> import re >>>> m = re.match(patt, street) >>>> if m is not None: m.group() > ... > '1180 Bordeaux' > > Obviously, I can just create a pattern "\d+ \w+ \w+". > However, the pattern would be useless if I had a > street name like 3120 De la Cruz Boulevard. Any > hints? > Maybe : r'^(\d+)\s+(.*?)(?:\s+)?(\d+.*)?$' street = "1180 Bordeaux Drive 5th floor apt 'A'" then : \1 : '1180' \2 : 'Bordeaux Drive' \3 : "5th floor apt 'A'" or : street = "1180 Bordeaux Drive" then : \1 : '1180' \2 : 'Bordeaux Drive' \3 : "" From jim at ubuntu-rocks.org Fri Oct 5 01:07:35 2007 From: jim at ubuntu-rocks.org (Jim Hutchinson) Date: Thu, 4 Oct 2007 17:07:35 -0600 Subject: [Tutor] random number generator Message-ID: <11e0aa300710041607m651c44a2r1874b4a885ccff50@mail.gmail.com> Hello, I am writing a little program to test a theory and as part of teaching myself Python. I've only been at this about a week now. I have a program that "should" work but doesn't. It generates a random number between 1 and 2 out to 10 decimal places. I think there is something wrong with how my random number is generated or defined or how my guesses are defined. I added a line to tell me what the random number is and then if I enter it as a guess it doesn't match and exit the loop. Any idea what I'm doing wrong? Here is a sample output: --- I'm thinking out to 10 decimal places. Good luck. 1.14981949962 Make a guess: 1.14981949962 Higher... Make another guess: 1.14981949963 Lower... 1.14981949963 Make another guess: --- Here is my code: --- # Number guessing game # # The computer will choose a number between 1 and 2 (to ten decimal places) # and the player will try to guess the number. The program will tell the # player the number is either higher or lower than the number they guessed. import random import os os.system("clear") print "\nWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 2." print "\nYes, that's right. Between 1 and 2." print "\nYou have heard of decimals right? Well, I'm" print "\nthinking out to 10 decimal places. Good luck.\n" # set random value random.seed() number = random.random() + 1 print number guess = float(raw_input("Make a guess: ")) tries = 1 # the guess loop while (guess != number): if (guess > number): print "Lower..." else: print "Higher..." guess = float(raw_input("Make another guess: ")) tries += 1 print "Congratulations! You guessed my number! The number was", number print "It took you only", tries, "tries!\n" # end --- Thanks, Jim -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From bhaaluu at gmail.com Fri Oct 5 03:12:23 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 4 Oct 2007 21:12:23 -0400 Subject: [Tutor] another quickie In-Reply-To: References: Message-ID: On 10/4/07, max baseman wrote: > hello all, im sorry but i might be asking a lot of Tkinter questions > for a bit. > im still working on my first GUI, it is very simple all i want it to > do is open a text file, write to it, than save it. so far i have a > GUI with the ability to right text (nothing amazing), but i don't > know how to have it display the text from a text file any help would > be great The book, Python Programming 3E by Mark Lutz has over 300 pages of Tkinter tutorial in it, covering just about anything you'd want to do with Tkinter. I've seen it "used" on the Internet for a little over $10. It retails for $60 (Over 1500 pages of pure Python programming). It is an O'Reilly book, and they have the code examples for the book on their site at: http://examples.oreilly.com/python3/ Lutz starts off simple, and gets as complicated as you can stand. Bite off small pieces, and chew well. > > from Tkinter import * > top=Tk() > F=Frame(top) > F.pack() > F.txtBox=Text(top) > F.txtBox.pack() > F.pack() > > this is all i have so far ^_^" Lutz develops a full-blown text-editor, using Tkinter, in PP3E. Happy Programming! -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From walksloud at gmail.com Fri Oct 5 04:45:49 2007 From: walksloud at gmail.com (Andre Walker-Loud) Date: Thu, 4 Oct 2007 22:45:49 -0400 Subject: [Tutor] using python to execute from Dir A in Dir B In-Reply-To: References: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> Message-ID: Thank you everyone for the help. I have two solutions, but I would love one that uses the subprocess.Popen() - I have no experience with this module.class - if someone with more experience would feel inclined to provide an example, I would be very much appreciative. SOLUTION 1 (my brute force method) create a csh file which does what I want, ##### filename: hack.csh #!/bin/csh set RUN_DIR = $1 set EXEC_DIR = $2 cd ${RUN_DIR} ${EXEC_DIR}/my.exe ##### then I call this in my python code from some arbitrary directory ##### python script... os.system('./hack.csh /scratch exec_dir') ##### SOLUTION 2 (courtesy of my computer-superhero friend - again simple) in my python script... ##### import os curdir = os.path.abspath('.') # in case I need to get back to where I am - in my case no os.chdir('RUN_DIR') # in my case RUN_DIR = /scratch if I wanted to get back to my old directory - then add os.chdir(curdir) ##### so both of these methods are sort of brute force - being completely unfamiliar with the subprocess module, again is someone would like to provide an example, or at least more hints than 'you should use subprocess.Popen()' I thank you in advance. Cheers, Andre On Oct 4, 2007, at 5:13 PM, Alan Gauld wrote: > "Andre Walker-Loud" wrote > >> If I were using CSH, I could do all this very simply by having these >> lines in my script >> >> ### .csh file >> >> cd /scratch >> my_exe.csh > > The best answer is to use subprocess as Kent suggested > but you can also use os.chdir(path) before using os.system() > But system() is deprecated in favour of the subprocess module. > > Of course you could also modify your script to take a > path as a command line argument and use that to direct > the output explicitly... > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From jerry.vb at gmail.com Fri Oct 5 06:12:16 2007 From: jerry.vb at gmail.com (Jerry VanBrimmer) Date: Thu, 4 Oct 2007 21:12:16 -0700 Subject: [Tutor] random number generator In-Reply-To: <11e0aa300710041607m651c44a2r1874b4a885ccff50@mail.gmail.com> References: <11e0aa300710041607m651c44a2r1874b4a885ccff50@mail.gmail.com> Message-ID: <901b226d0710042112h70fc8cew705ff10a5002e3c8@mail.gmail.com> I'm no Python wizard, I'm still learning myself. But I think you need another "if" statement to check if "guess" is equal to "number". if guess == number: print "Congratulations!" Something like that. On 10/4/07, Jim Hutchinson wrote: > Hello, > > I am writing a little program to test a theory and as part of teaching > myself Python. I've only been at this about a week now. I have a > program that "should" work but doesn't. It generates a random number > between 1 and 2 out to 10 decimal places. I think there is something > wrong with how my random number is generated or defined or how my > guesses are defined. I added a line to tell me what the random number > is and then if I enter it as a guess it doesn't match and exit the > loop. Any idea what I'm doing wrong? Here is a sample output: > > --- > I'm thinking out to 10 decimal places. Good luck. > > 1.14981949962 > Make a guess: 1.14981949962 > Higher... > Make another guess: 1.14981949963 > Lower... > 1.14981949963 > Make another guess: > --- > > Here is my code: > > --- > # Number guessing game > # > # The computer will choose a number between 1 and 2 (to ten decimal places) > # and the player will try to guess the number. The program will tell the > # player the number is either higher or lower than the number they guessed. > import random > import os > os.system("clear") > print "\nWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 2." > print "\nYes, that's right. Between 1 and 2." > print "\nYou have heard of decimals right? Well, I'm" > print "\nthinking out to 10 decimal places. Good luck.\n" > # set random value > random.seed() > number = random.random() + 1 > print number > guess = float(raw_input("Make a guess: ")) > tries = 1 > # the guess loop > while (guess != number): > if (guess > number): > print "Lower..." > else: > print "Higher..." > guess = float(raw_input("Make another guess: ")) > tries += 1 > print "Congratulations! You guessed my number! The number was", number > print "It took you only", tries, "tries!\n" > # end > --- > > Thanks, > Jim > > -- > Please avoid sending me Word or PowerPoint attachments. > See http://www.gnu.org/philosophy/no-word-attachments.html > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Jesus is coming!................................................Rev. 1:7 The Bottom Line................................................John 3:3-7 From carroll at tjc.com Fri Oct 5 07:38:58 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 4 Oct 2007 22:38:58 -0700 (PDT) Subject: [Tutor] random number generator In-Reply-To: <11e0aa300710041607m651c44a2r1874b4a885ccff50@mail.gmail.com> Message-ID: On Thu, 4 Oct 2007, Jim Hutchinson wrote: > Any idea what I'm doing wrong? > while (guess != number): This is your problem. Like all^h^h^h most numbers in computing, floating point numbers are stored in binary. They only approximate the decimal values they print out as. Two numbers can print as the same value but actually have different values. If you want to see if the numbers are identical to 10 decimal places, use this instead: while (abs(guess-number) > 0.0000000001): From carroll at tjc.com Fri Oct 5 07:41:32 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 4 Oct 2007 22:41:32 -0700 (PDT) Subject: [Tutor] random number generator In-Reply-To: <901b226d0710042112h70fc8cew705ff10a5002e3c8@mail.gmail.com> Message-ID: On Thu, 4 Oct 2007, Jerry VanBrimmer wrote: > I'm no Python wizard, I'm still learning myself. But I think you need > another "if" statement to check if "guess" is equal to "number". > > if guess == number: > print "Congratulations!" No, he's got the equivalent function in his while statement: while (guess != number): The idea is to stay in the loop as long as they're UNequal, and then drop out to the "Congratulations" part. But comparing floats as equal or not equal is never a very robust idea. http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate From aijames at exemail.com.au Fri Oct 5 07:47:13 2007 From: aijames at exemail.com.au (Andrew James) Date: Fri, 05 Oct 2007 15:47:13 +1000 Subject: [Tutor] random number generator In-Reply-To: <4705CB4F.3070600@exemail.com.au> References: <11e0aa300710041607m651c44a2r1874b4a885ccff50@mail.gmail.com> <901b226d0710042112h70fc8cew705ff10a5002e3c8@mail.gmail.com> <4705CB4F.3070600@exemail.com.au> Message-ID: <4705CFE1.8060903@exemail.com.au> I need to start using the reply all button... Andrew James wrote: > while guess != number: > guess = float(raw_input("Make another guess: ")) > if guess > number: > print "Lower..." > elif guess < number: > print "Higher..." > tries += 1 > > You're asking people to change their choice before the while loop > ends. Now this looks a little ugly as it will be asking people to make > two guesses right off the bat, or it'll use the term "another" for > their first guess. Shouldn't be too hard to change. Or do this. > > while guess != number: > if guess > number: > print "Lower..." > elif guess < number: > print "Higher..." > tries += 1 > if guess != number: > guess = float(raw_input("Make another guess: ")) > > > > > Jerry VanBrimmer wrote: >> I'm no Python wizard, I'm still learning myself. But I think you need >> another "if" statement to check if "guess" is equal to "number". >> >> if guess == number: >> print "Congratulations!" >> >> >> Something like that. >> >> >> >> On 10/4/07, Jim Hutchinson wrote: >> >>> Hello, >>> >>> I am writing a little program to test a theory and as part of teaching >>> myself Python. I've only been at this about a week now. I have a >>> program that "should" work but doesn't. It generates a random number >>> between 1 and 2 out to 10 decimal places. I think there is something >>> wrong with how my random number is generated or defined or how my >>> guesses are defined. I added a line to tell me what the random number >>> is and then if I enter it as a guess it doesn't match and exit the >>> loop. Any idea what I'm doing wrong? Here is a sample output: >>> >>> --- >>> I'm thinking out to 10 decimal places. Good luck. >>> >>> 1.14981949962 >>> Make a guess: 1.14981949962 >>> Higher... >>> Make another guess: 1.14981949963 >>> Lower... >>> 1.14981949963 >>> Make another guess: >>> --- >>> >>> Here is my code: >>> >>> --- >>> # Number guessing game >>> # >>> # The computer will choose a number between 1 and 2 (to ten decimal >>> places) >>> # and the player will try to guess the number. The program will tell >>> the >>> # player the number is either higher or lower than the number they >>> guessed. >>> import random >>> import os >>> os.system("clear") >>> print "\nWelcome to 'Guess My Number'!" >>> print "\nI'm thinking of a number between 1 and 2." >>> print "\nYes, that's right. Between 1 and 2." >>> print "\nYou have heard of decimals right? Well, I'm" >>> print "\nthinking out to 10 decimal places. Good luck.\n" >>> # set random value >>> random.seed() >>> number = random.random() + 1 >>> print number >>> guess = float(raw_input("Make a guess: ")) >>> tries = 1 >>> # the guess loop >>> while (guess != number): >>> if (guess > number): >>> print "Lower..." >>> else: >>> print "Higher..." >>> guess = float(raw_input("Make another guess: ")) >>> tries += 1 >>> print "Congratulations! You guessed my number! The number was", number >>> print "It took you only", tries, "tries!\n" >>> # end >>> --- >>> >>> Thanks, >>> Jim >>> >>> -- >>> Please avoid sending me Word or PowerPoint attachments. >>> See http://www.gnu.org/philosophy/no-word-attachments.html >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> >> > From alan.gauld at btinternet.com Fri Oct 5 09:17:37 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Oct 2007 08:17:37 +0100 Subject: [Tutor] using python to execute from Dir A in Dir B References: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> Message-ID: "Andre Walker-Loud" wrote > this module.class - if someone with more experience would feel > inclined to provide an example, I would be very much appreciative. The subprocess module documentation has several examples of using both the Popen class and the call function. The given example for os.system is: sts = os.system("mycmd" + " myarg") ==> p = Popen("mycmd" + " myarg", shell=True) sts = os.waitpid(p.pid, 0)To which you would need to add cwd=path making it:p = Popen("mycmd" + " myarg", shell=True, cwd=path) sts = os.waitpid(p.pid, 0)The other difference using Popen is that it raises an OSError exception if the program fails to run so you should wrap the calls in a try/except if you want to catch that.HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071005/249f2f2a/attachment.htm From alan.gauld at btinternet.com Fri Oct 5 09:33:06 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Oct 2007 08:33:06 +0100 Subject: [Tutor] random number generator References: <11e0aa300710041607m651c44a2r1874b4a885ccff50@mail.gmail.com> Message-ID: "Jim Hutchinson" wrote > program that "should" work but doesn't. It generates a random number > between 1 and 2 out to 10 decimal places. Ok, Here's the problem. You are trying to compare two floating point numbers. But python stores data in binary and displays it in decimal. A lot of decimal numbers cannot be exactly represented in binary so what you see displayed is an approximation of the actual number stored in memory. > while (guess != number): So when you try to compare the number you entered with the number stored in memory they are not quite the same. The normal way of dealing with this in programs is to define a very small number (often called epsilon or e) and check if your guess is plus or minus e from the target. So your code would become e = 0.0000000001 while not( guess - e < number < guess + e ): # ...your code here I briefly mention this in the Raw Materials topic of my tutor when discussing Real numbers HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Oct 5 09:46:52 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Oct 2007 08:46:52 +0100 Subject: [Tutor] another quickie References: Message-ID: "max baseman" wrote > do is open a text file, write to it, than save it. so far i have a > GUI with the ability to right text (nothing amazing), but i don't > know how to have it display the text from a text file any help would > be great > > from Tkinter import * > top=Tk() > F=Frame(top) > F.pack() > F.txtBox=Text(top) > F.txtBox.pack() > F.pack() Ok This gets you the basic text box. Now you need to open the file, read it into a variable and insert that into the text box. I assume you already know how to open the file and read it into a variable. (If not see File handling in my tutorial) To insert it into the text box use the insert method as shown in my case study: self.txtBox.insert(END, resultStr) If you want to insert it at a specific location(like the start) you can replace END with 1.0 as also shown in the case study for deleting the content: self.txtBox.delete(1.0, END) Did you check the Tkinter reference link: http://www.pythonware.com/library/tkinter/introduction/x8309-patterns.htm It shows how to manipulate the contents of the Text widget in various ways. Including inserting text. PS. If you don't want to hard code the file name you can use a Tkinter FileOpen standard dialog to get the filename(and path) from the user prior to opening it. http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm To save your changes use the filesaveas dialog to get the target filename(optional) and then Text.select to get the text out of the widget and then the usual Python file methods to write the text out to file. All the information you need should be in the links in this message. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Oct 5 10:36:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Oct 2007 09:36:46 +0100 Subject: [Tutor] using python to execute from Dir A in Dir B References: <316C4B5E-3122-4BD7-8D0B-C8299D61AB03@gmail.com> Message-ID: Not sure what happened to the formatting here... It should be: --------------------- "Alan Gauld" wrote The given example for os.system is: sts = os.system("mycmd" + " myarg") ==> p = Popen("mycmd" + " myarg", shell=True) sts = os.waitpid(p.pid, 0) To which you would need to add cwd=path making it: p = Popen("mycmd" + " myarg", shell=True, cwd=path) sts = os.waitpid(p.pid, 0) The other difference using Popen is that it raises an OSError exception if the program fails to run so you should wrap the calls in a try/except if you want to catch that. ------------------------ HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jecarnell at saintfrancis.com Fri Oct 5 17:43:08 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Fri, 5 Oct 2007 10:43:08 -0500 Subject: [Tutor] Controlling the number of decimal places "Representation Error" In-Reply-To: Message-ID: Question: Is it a bad practice to avoid 0.1 representation errors (0.100000000000001) by just doing the following? #NOTE: all the myVariableName stuff is because Outlook keeps changing everything I type. #I need 2 decimal places (my input number shouldn't be over 255) myNum = 1 myDiv = 3 #10000/3 = 3333 and I remember that the last 3 digits are decimals the very last can have int() problems myResult = (myNum * 1000)/myDiv myArray = [] For I in range( wookie loads ): myArray.append(myResult) #this thing can get big, but I don't need that much precision #but I do need to keep it small since it might be running on #an embedded system Sincerely, James Carnell From jeff at san-dc.com Fri Oct 5 18:29:22 2007 From: jeff at san-dc.com (Jeff Johnson) Date: Fri, 05 Oct 2007 09:29:22 -0700 Subject: [Tutor] Python Magazine Message-ID: <47066662.7050902@san-dc.com> I've just been told by the editors at Python Magazine that the first issue is out. It's all-electronic so anyone can download and read it. Let them know what you think: http://www.pythonmagazine.com/c/issue/2007/10 You can also subscribe for print + online. -- Jeff Jeff Johnson jeff at san-dc.com SanDC, Inc. 623-582-0323 Fax 623-869-0675 From kent37 at tds.net Fri Oct 5 18:49:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 05 Oct 2007 12:49:44 -0400 Subject: [Tutor] Controlling the number of decimal places "Representation Error" In-Reply-To: References: Message-ID: <47066B28.5080508@tds.net> Carnell, James E wrote: > Question: > Is it a bad practice to avoid 0.1 representation errors > (0.100000000000001) by just doing the following? I'm afraid I don't understand either the problem you are trying to solve or your proposed solution. Can you say more about it? Kent > > #NOTE: all the myVariableName stuff is because Outlook keeps changing > everything I type. > > #I need 2 decimal places (my input number shouldn't be over 255) > > myNum = 1 > myDiv = 3 > > #10000/3 = 3333 and I remember that the last 3 digits are decimals the > very last can have int() problems > > myResult = (myNum * 1000)/myDiv > > myArray = [] > > For I in range( wookie loads ): > myArray.append(myResult) #this thing can get big, but I don't > need that much precision > #but I do need to keep it small since > it might be running on > #an embedded system > > > Sincerely, > > James Carnell > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lavendula6654 at yahoo.com Fri Oct 5 22:00:55 2007 From: lavendula6654 at yahoo.com (Elaine) Date: Fri, 5 Oct 2007 13:00:55 -0700 (PDT) Subject: [Tutor] finding square roots Message-ID: <973514.6769.qm@web31713.mail.mud.yahoo.com> Does anyone know which is the more efficient way of finding a square root in Python: sqrt(x) or x ** 0.5 ??? Thanks, Elaine ____________________________________________________________________________________ Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting From brunson at brunson.com Fri Oct 5 22:13:32 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 05 Oct 2007 14:13:32 -0600 Subject: [Tutor] finding square roots In-Reply-To: <973514.6769.qm@web31713.mail.mud.yahoo.com> References: <973514.6769.qm@web31713.mail.mud.yahoo.com> Message-ID: <47069AEC.6000805@brunson.com> Elaine wrote: > Does anyone know which is the more efficient way of > finding a square root in Python: > > sqrt(x) or x ** 0.5 > I dunno, let's check: >>> import timeit >>> t = timeit.Timer( "12 ** .5" ) >>> print t.timeit(10000000) 2.29147315025 >>> t = timeit.Timer( "sqrt(12)", "from math import sqrt" ) >>> print t.timeit(10000000) 7.17679214478 Looks like ** is about three times faster than sqrt(), but that could be the function overhead. > ??? > > Thanks, > Elaine > > > > ____________________________________________________________________________________ > Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. > http://smallbusiness.yahoo.com/webhosting > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lu.fangwen at yahoo.com Fri Oct 5 23:58:38 2007 From: lu.fangwen at yahoo.com (Fangwen Lu) Date: Fri, 5 Oct 2007 14:58:38 -0700 (PDT) Subject: [Tutor] questions about previous emails Message-ID: <768844.90867.qm@web44910.mail.sp1.yahoo.com> Dear all- I am a new-comer to tutor at python.org. I guess a lot of my future questions may have been asked by others already. As I am a new-comer, I don't have the previous emails. I wonder whether there is a way for searching for previous questions and answers so that I don't need to ask simple questions to overload the message flows. Thanks. Fangwen --------------------------------- Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071005/f0d0b73d/attachment.htm From brunson at brunson.com Sat Oct 6 00:02:12 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 05 Oct 2007 16:02:12 -0600 Subject: [Tutor] questions about previous emails In-Reply-To: <768844.90867.qm@web44910.mail.sp1.yahoo.com> References: <768844.90867.qm@web44910.mail.sp1.yahoo.com> Message-ID: <4706B464.30909@brunson.com> Fangwen Lu wrote: > Dear all- > > I am a new-comer to tutor at python.org. I guess a lot of my future > questions may have been asked by others already. > > As I am a new-comer, I don't have the previous emails. > > I wonder whether there is a way for searching for previous questions > and answers so that I don't need to ask simple questions to overload > the message flows. Click on the link at the bottom of every message and there is a link in the middle of the page directing you to the archives. Hope the helps, e. > > Thanks. > > Fangwen > > ------------------------------------------------------------------------ > Be a better Heartthrob. Get better relationship answers > from > someone who knows. > Yahoo! Answers - Check it out. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Oct 6 00:01:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Oct 2007 23:01:56 +0100 Subject: [Tutor] finding square roots References: <973514.6769.qm@web31713.mail.mud.yahoo.com> <47069AEC.6000805@brunson.com> Message-ID: "Eric Brunson" wrote > >>> import timeit > >>> t = timeit.Timer( "12 ** .5" ) > >>> print t.timeit(10000000) > 2.29147315025 > >>> t = timeit.Timer( "sqrt(12)", "from math import sqrt" ) > >>> print t.timeit(10000000) > 7.17679214478 > > Looks like ** is about three times faster than sqrt(), but that > could be > the function overhead. >>> timeit.Timer("import math; math.sqrt(64)").timeit(1000) 0.002298138362618829 >>> timeit.Timer("import math; 64 ** 0.5").timeit(1000) 0.018225722100503106 I get the opposite result by includsing the importt in both timing sesions. Looks like it was the import that was slow. But that shouldn't affect real world usage sinmce you only do it once... Alan G. From brunson at brunson.com Sat Oct 6 00:09:27 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 05 Oct 2007 16:09:27 -0600 Subject: [Tutor] finding square roots In-Reply-To: References: <973514.6769.qm@web31713.mail.mud.yahoo.com> <47069AEC.6000805@brunson.com> Message-ID: <4706B617.8020900@brunson.com> Alan Gauld wrote: > "Eric Brunson" wrote > > >>>>> import timeit >>>>> t = timeit.Timer( "12 ** .5" ) >>>>> print t.timeit(10000000) >>>>> >> 2.29147315025 >> >>>>> t = timeit.Timer( "sqrt(12)", "from math import sqrt" ) >>>>> print t.timeit(10000000) >>>>> >> 7.17679214478 >> >> Looks like ** is about three times faster than sqrt(), but that >> could be >> the function overhead. >> > > >>>> timeit.Timer("import math; math.sqrt(64)").timeit(1000) >>>> > 0.002298138362618829 > >>>> timeit.Timer("import math; 64 ** 0.5").timeit(1000) >>>> > 0.018225722100503106 > > I get the opposite result by includsing the importt in both > timing sesions. Looks like it was the import that was slow. > But that shouldn't affect real world usage sinmce you only > do it once... > Maybe I'm mis-remembering the documentation of timeit. I thought the second argument to the Timer constructor was "setup code", i.e. code to be executed once before executing the first argument in the timing loop. > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Oct 6 00:52:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Oct 2007 23:52:10 +0100 Subject: [Tutor] questions about previous emails References: <768844.90867.qm@web44910.mail.sp1.yahoo.com> Message-ID: "Fangwen Lu" wrote > I wonder whether there is a way for searching for previous questions > and answers so that I don't need to ask simple questions to > overload the message flows. There are at leasty 3 archives, two of which are searchable. The official archive on the Pyhon.org web site (not searchable) The Activestate archive (searchable) The Gmane.org news feed archive (searchable) The latter allows you to receive group email as if it were a newsgroup rather than email which some (including me!) find more convenient. (There is also a web interface if you need it) Alan G. From alan.gauld at btinternet.com Sat Oct 6 00:55:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Oct 2007 23:55:48 +0100 Subject: [Tutor] finding square roots References: <973514.6769.qm@web31713.mail.mud.yahoo.com> <47069AEC.6000805@brunson.com> <4706B617.8020900@brunson.com> Message-ID: "Eric Brunson" wrote >>>>>> t = timeit.Timer( "sqrt(12)", "from math import sqrt" ) >>>>>> print t.timeit(10000000) >>> 7.17679214478 >>>>> timeit.Timer("import math; math.sqrt(64)").timeit(1000) >> 0.002298138362618829 >>>>> timeit.Timer("import math; 64 ** 0.5").timeit(1000) >> 0.018225722100503106 >> >> I get the opposite result by includsing the importt in both >> timing sessions. Looks like it was the import that was slow. > > Maybe I'm mis-remembering the documentation of timeit. I thought > the > second argument to the Timer constructor was "setup code", i.e. code > to > be executed once before executing the first argument in the timing > loop. It seems to suggest that, so I don't understand the reason, but in any case its a fairer comparison to include the import in both tests. Doing it your way gives me: >>> timeit.Timer("64 ** 0.5", "import math").timeit(1000) 0.00039243745641215355 >>> timeit.Timer("math.sqrt(64)", "import math").timeit(1000) 0.00062668800364917843 >>> Which favours ** but by a smaller margin. Interesting, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Sat Oct 6 01:24:11 2007 From: wescpy at gmail.com (wesley chun) Date: Fri, 5 Oct 2007 16:24:11 -0700 Subject: [Tutor] finding square roots In-Reply-To: References: <973514.6769.qm@web31713.mail.mud.yahoo.com> <47069AEC.6000805@brunson.com> <4706B617.8020900@brunson.com> Message-ID: <78b3a9580710051624y225f1d1p786436e389a73d4a@mail.gmail.com> oddly enough, i get different results doing it the "old-fashioned" way: $ sqrt.py using ** 0.000447034835815 using sqrt() 0.000399112701416 $ sqrt.py using ** 0.00043797492981 using sqrt() 0.000399827957153 $ sqrt.py using ** 0.00043797492981 using sqrt() 0.000402927398682 here's the code snippet... *seems* right to me, but let me know u see any flaws: from math import sqrt from time import time print "using **" i = 0 now = time() while i < 1000: 64 ** 0.5 i += 1 print time()-now print "using sqrt()" i = 0 now = time() while i < 1000: sqrt(64) i += 1 print time()-now -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wolf1boy85 at yahoo.com Sat Oct 6 04:22:26 2007 From: wolf1boy85 at yahoo.com (Robert Jackson) Date: Fri, 5 Oct 2007 19:22:26 -0700 (PDT) Subject: [Tutor] "alias" instance of logger Message-ID: <983478.60409.qm@web45601.mail.sp1.yahoo.com> I'm working with an instance of a Python logger. Some code: log = logging.basicConfig(level=logging.DEBUG,filename="/home/richard/templog",filemode='w') Later in my program I do: log.info("finished step 4.") Python spits out this error: Traceback (most recent call last): File "", line 1, in AttributeError: 'NoneType' object has no attribute 'info' I CAN, however, do: logging.info("finished step 4.") And it works. What confuses me about this is that I can do something like this: # call another function and pass it the logger instance: foo(logging) And, if I define foo() like this: def foo(log): # this works fine! log.info("finished step 4.") The log.info works fine inside of foo(). Why is it that I can pass logging as an instance into a function, and use whatever instance name I wants inside of foo(), but I can't assign an "alias" for the logging instance inside of main() (by doing instancealias = logging.basic())? /r ____________________________________________________________________________________ Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow From wolf1boy85 at yahoo.com Sat Oct 6 04:23:28 2007 From: wolf1boy85 at yahoo.com (Robert Jackson) Date: Fri, 5 Oct 2007 19:23:28 -0700 (PDT) Subject: [Tutor] "alias" instance of logger Message-ID: <314367.81099.qm@web45613.mail.sp1.yahoo.com> By the way, I could have SWORN that I've done this successfully in the past in another program. I am relatively certain I have used log.LEVEL() in some of my programs in the past, but I can't figure out how I did it. /r ----- Original Message ---- From: Robert Jackson To: tutor at python.org Sent: Friday, October 5, 2007 10:22:26 PM Subject: "alias" instance of logger I'm working with an instance of a Python logger. Some code: log = logging.basicConfig(level=logging.DEBUG,filename="/home/richard/templog",filemode='w') Later in my program I do: log.info("finished step 4.") Python spits out this error: Traceback (most recent call last): File "", line 1, in AttributeError: 'NoneType' object has no attribute 'info' I CAN, however, do: logging.info("finished step 4.") And it works. What confuses me about this is that I can do something like this: # call another function and pass it the logger instance: foo(logging) And, if I define foo() like this: def foo(log): # this works fine! log.info("finished step 4.") The log.info works fine inside of foo(). Why is it that I can pass logging as an instance into a function, and use whatever instance name I wants inside of foo(), but I can't assign an "alias" for the logging instance inside of main() (by doing instancealias = logging.basic())? /r ____________________________________________________________________________________ Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow ____________________________________________________________________________________ Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From kent37 at tds.net Sat Oct 6 06:24:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 Oct 2007 00:24:36 -0400 Subject: [Tutor] "alias" instance of logger In-Reply-To: <983478.60409.qm@web45601.mail.sp1.yahoo.com> References: <983478.60409.qm@web45601.mail.sp1.yahoo.com> Message-ID: <47070E04.9090408@tds.net> Robert Jackson wrote: > log = logging.basicConfig(level=logging.DEBUG,filename="/home/richard/templog",filemode='w') logging.basicConfig() does not return a logger, it returns None. > Later in my program I do: > > log.info("finished step 4.") > > Python spits out this error: > Traceback (most recent call last): > > File "", line 1, in > > AttributeError: 'NoneType' object has no attribute 'info' Because log is None and None does not have an 'info' attribute. > > I CAN, however, do: > logging.info("finished step 4.") Sure, logging is the logging module and it has an info function. This is normal usage. > What confuses me about this is that I can do something like this: > > # call another function and pass it the logger instance: > > foo(logging) You are not passing a logger, you are passing the logging module itself. > And, if I define foo() like this: > > def foo(log): > > # this works fine! > > log.info("finished step 4.") > > The log.info works fine inside of foo(). Sure, because inside of foo, the name 'log' is bound to the actual parameter passed in which is the logging module. > Why is it that I can pass logging as an instance into a function, and > use whatever instance name I wants inside of foo(), That is true of every function parameter, you can give them whatever name you want. > but I can't assign > an "alias" for the logging instance inside of main() (by doing instancealias = logging.basic())? Because you are not aliasing logging here. Just assign log = logging though I don't see the point, just use logging.info() etc. Kent From norman at khine.net Sat Oct 6 09:04:00 2007 From: norman at khine.net (Norman Khine) Date: Sat, 06 Oct 2007 09:04:00 +0200 Subject: [Tutor] Random module help Message-ID: <47073360.9050306@khine.net> Hello, I have an 'Exam' module which selects new random set of questions and displays it, well this is the idea n;). Here is what I have so far: >>> import random >>> n_question = 5 >>> q = {1:'1q', 2:'2q', 3:'3q', 4:'4q', 5:'5q', 6:'6q', 7:'7q', 8:'8q', 9:'9q', 0:'0q'} >>> if len(q) > n_question: ... q_keys = random.sample(q.keys(), n_question) ... else: ... q_keys = q.keys() ... >>> q_keys.sort() >>> a = [q[x] for x in q_keys] >>> a ['1q', '4q', '5q', '7q', '8q'] >>> a ['1q', '4q', '5q', '7q', '8q'] This only returns the same questions, what am I doing wrong? How do I return a different set? I would like to have a group of similar questions and then select a random set out of this to make up my final namespace (a), thus avoiding similar questions being selected from the pool of questions. Is there a more elegant solution which will pull a random selection of questions? Cheers -- Norman -- Norman Khine 7 rue Ponscarme, Paris, 75013, France tel +33 870 628 934 fax +33 142 724 4437 %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From alan.gauld at btinternet.com Sat Oct 6 09:24:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Oct 2007 08:24:56 +0100 Subject: [Tutor] Random module help References: <47073360.9050306@khine.net> Message-ID: "Norman Khine" wrote > >>> a = [q[x] for x in q_keys] > >>> a > ['1q', '4q', '5q', '7q', '8q'] > >>> a > ['1q', '4q', '5q', '7q', '8q'] > > > This only returns the same questions, what am I doing wrong? How do > I > return a different set? I don't understand your problem. You are printing 'a' twice but not doing anything between times. So of course it prints the same thing. I'd be worried if it didn't! Can you demonstrate what you think is wrong? Alan G. From norman at khine.net Sat Oct 6 10:27:50 2007 From: norman at khine.net (Norman Khine) Date: Sat, 06 Oct 2007 10:27:50 +0200 Subject: [Tutor] Random module help In-Reply-To: References: <47073360.9050306@khine.net> Message-ID: <47074706.5080405@khine.net> Alan Gauld wrote: > "Norman Khine" wrote > >>>>> a = [q[x] for x in q_keys] >>>>> a >> ['1q', '4q', '5q', '7q', '8q'] >>>>> a >> ['1q', '4q', '5q', '7q', '8q'] >> >> >> This only returns the same questions, what am I doing wrong? How do >> I >> return a different set? > > I don't understand your problem. > You are printing 'a' twice but not doing anything between times. > So of course it prints the same thing. I'd be worried if it didn't! > > Can you demonstrate what you think is wrong? > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Sorry, I think I have it ;) exam.py import random n_questions = 5 q = {1:'1q', 2:'2q', 3:'3q', 4:'4q', 5:'5q', 6:'6q', 7:'7q', 8:'8q', 9:'9q', 0:'0q'} if len(q) > n_questions: q_keys = random.sample(q.keys(), n_questions) else: q_keys = q.keys() q_keys.sort() a = [q[x] for x in q_keys] print a So now when I execute python exam.py, I get: python exam.py ['1q', '2q', '4q', '5q', '6q'] ['1q', '4q', '5q', '7q', '8q'] ['0q', '2q', '6q', '8q', '9q'] ['0q', '1q', '2q', '4q', '9q'] But what I was wondering if possible in achieving is that my questions set (q) contains questions that are similar, i.e. they are written in different ways, so I wanted to get the random set of unique questions rather then have variations of the same question returned in my set. All the questions are stored in one dictionary, perhaps I need to change this structure? Does it make sense? ;) Cheers -- Norman From linpeiheng at 163.com Sat Oct 6 13:42:03 2007 From: linpeiheng at 163.com (=?gb2312?B?wdbF4Lrj?=) Date: Sat, 6 Oct 2007 19:42:03 +0800 Subject: [Tutor] How can I get ASCII of 'a' and '1'? Message-ID: <4707748E.08E15E.11422@m5-82.163.com> How can I get ASCII for alphabet and number, such as 'a' and '1'. I can get ASCII for character naturally in C but I don't how to in Python. From alan.gauld at btinternet.com Sat Oct 6 13:45:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Oct 2007 12:45:49 +0100 Subject: [Tutor] Random module help References: <47073360.9050306@khine.net> <47074706.5080405@khine.net> Message-ID: "Norman Khine" wrote > But what I was wondering if possible in achieving is that my > questions > set (q) contains questions that are similar, i.e. they are written > in > different ways, so I wanted to get the random set of unique > questions > rather then have variations of the same question returned in my set. It sounds like maybe you need a list of questions against the keys. That way you can select one of the list of similar questons at random whenever that key is chosen. {'q1': ['What is you name?', 'who are you?', 'what are you called?'], 'q2': ["What's your address?", 'Where do you live?'], q3: [ etc....] } HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From norman at khine.net Sat Oct 6 14:30:20 2007 From: norman at khine.net (Norman Khine) Date: Sat, 06 Oct 2007 14:30:20 +0200 Subject: [Tutor] Random module help In-Reply-To: References: <47073360.9050306@khine.net> <47074706.5080405@khine.net> Message-ID: <47077FDC.8020905@khine.net> Hi Alan, Thanks for the suggestion, but I am not sure it is what I am after. From your dictionary, for example, I wanted to have a list as: "what is your name?" "where do you live?" then the next time I run the program I will get: "who are you? "what is your address? etc... rather then, what I have now is: "what is your name?" "who are you?" ... I have updated the code as you suggested to: import random n_questions = 5 q = {'1': ['1a', '1b', '1c'], '2': ['2a', '2b', '2c'], '3': ['3a', '3b', '3c'], '4': ['4a', '4b', '4c'], '5': ['5a', '5b', '5c'], '6': ['6a', '6b', '6c'], '7': ['7a', '7b', '7c'], '8': ['8a', '8b', '8c'] } if len(q) > n_questions: q_keys = random.sample(q.keys(), n_questions) else: q_keys = q.keys() q_keys.sort() a = [q[x] for x in q_keys] print a which returns: [['2a', '2b', '2c'], ['4a', '4b', '4c'], ['5a', '5b', '5c'], ['7a', '7b', '7c'], ['8a', '8b', '8c']] etc... So from this how do I choose a random element and produce a new dictionary like for example: [2a, 4b, 5c, 7b, 8c] Thanks Alan Gauld wrote: > "Norman Khine" wrote > >> But what I was wondering if possible in achieving is that my >> questions >> set (q) contains questions that are similar, i.e. they are written >> in >> different ways, so I wanted to get the random set of unique >> questions >> rather then have variations of the same question returned in my set. > > It sounds like maybe you need a list of questions against the keys. > That way you can select one of the list of similar questons at > random whenever that key is chosen. > > {'q1': ['What is you name?', 'who are you?', 'what are you called?'], > 'q2': ["What's your address?", 'Where do you live?'], > q3: [ etc....] > } > > HTH, > > -- Norman From kent37 at tds.net Sat Oct 6 15:00:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 Oct 2007 09:00:04 -0400 Subject: [Tutor] How can I get ASCII of 'a' and '1'? In-Reply-To: <4707748E.08E15E.11422@m5-82.163.com> References: <4707748E.08E15E.11422@m5-82.163.com> Message-ID: <470786D4.9060400@tds.net> ??? wrote: > How can I get ASCII for alphabet and number, such as 'a' and '1'. I can get ASCII for character naturally in C but I don't how to in Python. You can get the character codes using ord(): In [1]: ord('a') Out[1]: 97 In [2]: ord('1') Out[2]: 49 The inverse function is chr(): In [3]: chr(97) Out[3]: 'a' Kent From alan.gauld at btinternet.com Sat Oct 6 16:03:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Oct 2007 15:03:36 +0100 Subject: [Tutor] Random module help References: <47073360.9050306@khine.net> <47074706.5080405@khine.net> <47077FDC.8020905@khine.net> Message-ID: "Norman Khine" wrote > q_keys.sort() > a = [q[x] for x in q_keys] a = [random.choice(q[x]) for x in q_keys] > > So from this how do I choose a random element and produce a new > dictionary like for example: See above. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jim at ubuntu-rocks.org Sat Oct 6 19:19:07 2007 From: jim at ubuntu-rocks.org (Jim Hutchinson) Date: Sat, 6 Oct 2007 11:19:07 -0600 Subject: [Tutor] random number generator Message-ID: <11e0aa300710061019u6a285832mc273515fa8f5aa93@mail.gmail.com> Greetings all, It seems I forgot to subscribe to the list so I didn't receive any of the replies. However, I did check the archive and found all of the very helpful suggestions. Thanks for your time. Based on the replies I was able to get this to more or less work. However, one problem still exists. If you guess a number that is slightly larger than the random number it evaluates to correct For example: ---- The number is 1.78889511441 Make a guess: 1.788895114455 Congratulations! You guessed my number! The number was 1.78889511441 It took you only 1 tries! --- Or even: --- 1.36344601965 Make a guess: 1.3634460196 Congratulations! You guessed my number! The number was 1.36344601965 It took you only 1 tries! --- I'm also unclear as to how it is choosing a random number out to 10 decimal places. Is that the default and it's just coincidence that I chose 10? What if I want a random number to 20 decimal places or five? Here is the code: # Number guessing game # # The computer will choose a number between 1 and 2 (to ten decimal places) # and the player will try to guess the number. The program will tell the # player the number is either higher or lower than the number they guessed. import random import os os.system("clear") print "\nWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 2." print "\nYes, that's right. Between 1 and 2." print "\nYou have heard of decimals right? Well, I'm" print "\nthinking out to 10 decimal places. Good luck.\n" # set random value random.seed() number = random.random() + 1 print number guess = float(raw_input("Make a guess: ")) tries = 1 # the guess loop while (abs(number-guess) > 0.0000000001): if guess > number: print "Lower..." elif guess < number: print "Higher..." tries += 1 if guess != number: guess = float(raw_input("Make another guess: ")) print "\nCongratulations! You guessed my number! The number was", number print "\nIt took you only", tries, "tries!\n" # end Thanks again, Jim -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From bhaaluu at gmail.com Sat Oct 6 19:36:35 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 6 Oct 2007 13:36:35 -0400 Subject: [Tutor] How can I get ASCII of 'a' and '1'? In-Reply-To: <470786D4.9060400@tds.net> References: <4707748E.08E15E.11422@m5-82.163.com> <470786D4.9060400@tds.net> Message-ID: Here's a handy reference file for ASCII. (See attached file) -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html On 10/6/07, Kent Johnson wrote: > $BNSG]91(B wrote: > > How can I get ASCII for alphabet and number, such as 'a' and '1'. I can get ASCII for character naturally in C but I don't how to in Python. > > You can get the character codes using ord(): > In [1]: ord('a') > Out[1]: 97 > In [2]: ord('1') > Out[2]: 49 > > The inverse function is chr(): > In [3]: chr(97) > Out[3]: 'a' > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ascii.txt Url: http://mail.python.org/pipermail/tutor/attachments/20071006/6ef32be8/attachment.txt From brunson at brunson.com Sat Oct 6 19:40:48 2007 From: brunson at brunson.com (Eric Brunson) Date: Sat, 06 Oct 2007 11:40:48 -0600 Subject: [Tutor] How can I get ASCII of 'a' and '1'? In-Reply-To: References: <4707748E.08E15E.11422@m5-82.163.com> <470786D4.9060400@tds.net> Message-ID: <4707C8A0.9050102@brunson.com> Or, if you're on a real operating system (i.e. linix) you can type "man ascii". ;-) bhaaluu wrote: > Here's a handy reference file for ASCII. > (See attached file) > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From brunson at brunson.com Sat Oct 6 21:35:03 2007 From: brunson at brunson.com (Eric Brunson) Date: Sat, 06 Oct 2007 13:35:03 -0600 Subject: [Tutor] =?iso-8859-1?q?=CD=F8=D2=D7=D3=CA=CF=E4=D7=D4=B6=AF=BB=D8?= =?iso-8859-1?q?=B8=B4=3A_Re=3A__How_can_I_get_ASCII_of_=27a=27_and_=271?= =?iso-8859-1?q?=27=3F?= In-Reply-To: <4707C8B4.38FD7E.20486> References: <4707748E.08E15E.11422@m5-82.163.com> <470786D4.9060400@tds.net> <4707C8A0.9050102@brunson.com> <4707C8B4.38FD7E.20486> Message-ID: <4707E367.5030707@brunson.com> What is that, Perl? ;-) linpeiheng at 163.com wrote: > ???????????????????????? > > > > -------------------------------------------- > ????163????--??????????????????2000??????????????????????????????????24?????????????? > ????????????????????????????????http://mail.163.com From kent37 at tds.net Sat Oct 6 23:14:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 06 Oct 2007 17:14:34 -0400 Subject: [Tutor] =?gb2312?b?zfjS19PKz+TX1Lavu9i4tDogUmU6ICBIb3cgY2FuIEkg?= =?gb2312?b?Z2V0IEFTQ0lJIG9mICdhJyBhbmQgJzEnPw==?= In-Reply-To: <4707E367.5030707@brunson.com> References: <4707748E.08E15E.11422@m5-82.163.com> <470786D4.9060400@tds.net> <4707C8A0.9050102@brunson.com> <4707C8B4.38FD7E.20486> <4707E367.5030707@brunson.com> Message-ID: <4707FABA.1010405@tds.net> Eric Brunson wrote: > What is that, Perl? ;-) It is Chinese if you look at it right. Kent > linpeiheng at 163.com wrote: >> ???????????? >> >> >> >> -------------------------------------------- >> ??163??--?????????2000?????????????????24??????? >> ????????????????http://mail.163.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pierre.cutellic at gmail.com Sat Oct 6 23:17:17 2007 From: pierre.cutellic at gmail.com (pierre cutellic) Date: Sat, 6 Oct 2007 23:17:17 +0200 Subject: [Tutor] ZeroDivisionError: float division Message-ID: <3c8b20230710061417g5e09531kd2896b6bf5edce0f@mail.gmail.com> Hi, i'm actually stuck with a stupid syntax problem. here is a a piece of code i can't debug: kx = (neighbor[1]+agent[1])/(dx-(neighbor[1]+agent[1])) in this line, 'neighbor[1]' and 'agent[1]' are both integers and 'dx' is a float so it gives me the following error: 'ZeroDivisionError: float division'. And it is the same if i convert them into floats by float() function. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071006/94ff5d20/attachment.htm From alan.gauld at btinternet.com Sun Oct 7 00:28:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Oct 2007 23:28:24 +0100 Subject: [Tutor] ZeroDivisionError: float division References: <3c8b20230710061417g5e09531kd2896b6bf5edce0f@mail.gmail.com> Message-ID: "pierre cutellic" wrote > here is a a piece of code i can't debug: > > kx = (neighbor[1]+agent[1])/(dx-(neighbor[1]+agent[1])) > > in this line, 'neighbor[1]' and 'agent[1]' are both integers and > 'dx' is a > float so it gives me the following error: 'ZeroDivisionError: float > division'. So have you checked that the divisor is not zero? ie that (dx-(neighbor[1]+agent[1]) is not zero. That's normally the cause of a ZeroDivisionError. Without a bit more code or some debug output we can't really say much more. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From aijames at exemail.com.au Sun Oct 7 03:52:51 2007 From: aijames at exemail.com.au (Andrew James) Date: Sun, 07 Oct 2007 11:52:51 +1000 Subject: [Tutor] random number generator In-Reply-To: <11e0aa300710061019u6a285832mc273515fa8f5aa93@mail.gmail.com> References: <11e0aa300710061019u6a285832mc273515fa8f5aa93@mail.gmail.com> Message-ID: <47083BF3.5090804@exemail.com.au> I'm tempted to suggest using a hack to avoid floating point errors. Anyway, it isn't choosing a number to ten decimal places. It's actually out to 11 in both examples you gave. And it evaluates to correct because your guesses were to at least 10 places, which is as far as you account for in the line 'while (abs(number-guess) > 0.0000000001): ' Jim Hutchinson wrote: > Greetings all, > > It seems I forgot to subscribe to the list so I didn't receive any of > the replies. However, I did check the archive and found all of the > very helpful suggestions. Thanks for your time. > > Based on the replies I was able to get this to more or less work. > However, one problem still exists. If you guess a number that is > slightly larger than the random number it evaluates to correct > > For example: > > ---- > The number is 1.78889511441 > Make a guess: 1.788895114455 > > Congratulations! You guessed my number! The number was 1.78889511441 > > It took you only 1 tries! > --- > > Or even: > > --- > 1.36344601965 > Make a guess: 1.3634460196 > > Congratulations! You guessed my number! The number was 1.36344601965 > > It took you only 1 tries! > --- > > I'm also unclear as to how it is choosing a random number out to 10 > decimal places. Is that the default and it's just coincidence that I > chose 10? What if I want a random number to 20 decimal places or five? > > Here is the code: > > # Number guessing game > # > # The computer will choose a number between 1 and 2 (to ten decimal places) > # and the player will try to guess the number. The program will tell the > # player the number is either higher or lower than the number they guessed. > import random > import os > os.system("clear") > print "\nWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 2." > print "\nYes, that's right. Between 1 and 2." > print "\nYou have heard of decimals right? Well, I'm" > print "\nthinking out to 10 decimal places. Good luck.\n" > # set random value > random.seed() > number = random.random() + 1 > print number > guess = float(raw_input("Make a guess: ")) > tries = 1 > # the guess loop > while (abs(number-guess) > 0.0000000001): > if guess > number: > print "Lower..." > elif guess < number: > print "Higher..." > tries += 1 > if guess != number: > guess = float(raw_input("Make another guess: ")) > print "\nCongratulations! You guessed my number! The number was", number > print "\nIt took you only", tries, "tries!\n" > # end > > Thanks again, > Jim > From ihappydeer at gmail.com Sun Oct 7 07:42:04 2007 From: ihappydeer at gmail.com (Happy Deer) Date: Sat, 6 Oct 2007 22:42:04 -0700 Subject: [Tutor] a code question, but don't know question's name Message-ID: Dear all- I am writing a function as follows. def getdata(varlist): .... eventually I have a variable called "data", which have exactly the same number of columns as the name of variables in varlist. Say varlist=['var1','var2','var3']. I want to assign var1=data[:,0], var2=data[:,1], var3=data[:2] and return var1, var2, var3. But when I write the function, I only know I want to assign data[:,0] to a variable which has a name as varlist[0]. How to write this? Thank you! Deer -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071006/059b4da2/attachment.htm From rdm at rcblue.com Sun Oct 7 08:05:03 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 06 Oct 2007 23:05:03 -0700 Subject: [Tutor] Top Programming Languages of 2013 Message-ID: <20071007060510.5DC811E4006@bag.python.org> Dick Moores From norman at khine.net Sun Oct 7 09:25:11 2007 From: norman at khine.net (Norman Khine) Date: Sun, 07 Oct 2007 09:25:11 +0200 Subject: [Tutor] Random module help In-Reply-To: References: <47073360.9050306@khine.net> <47074706.5080405@khine.net> <47077FDC.8020905@khine.net> Message-ID: <470889D7.1050107@khine.net> Thank you, this is great. Alan Gauld wrote: > "Norman Khine" wrote > > >> q_keys.sort() >> a = [q[x] for x in q_keys] > > a = [random.choice(q[x]) for x in q_keys] > >> So from this how do I choose a random element and produce a new >> dictionary like for example: > > See above. > > -- Norman From alan.gauld at btinternet.com Sun Oct 7 09:34:50 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Oct 2007 08:34:50 +0100 Subject: [Tutor] a code question, but don't know question's name References: Message-ID: "Happy Deer" wrote > def getdata(varlist): > > .... > eventually I have a variable called "data", which have exactly the > same > number of columns as the name of variables in varlist. > Say varlist=['var1','var2','var3']. I want to assign > var1=data[:,0], > var2=data[:,1], var3=data[:2] and return var1, var2, var3. It doesn't matter what you call the variables inside the function, that won't affect what they are called after you return the values. The notation data[;,0] doesn't make sense and is an error in Python. I#m not sure what you think it does. I assume you simply mean data[0]? Now, to your functions purpose. If the varlist contains 7 names, do you still only want to return var1, var2, var3? Or do you want to return all 7 values? If so then just return data... If not do you need to find the index of var1,var2,var3 in varlist and return the corresponding values from data? Its not clear to me exactly what the function is supposed to do. And without any code it's hard to guess. > But when I write the function, I only know I want to assign > data[:,0] to a > variable which has a name as varlist[0]. How to write this? I repeat that any variable names you define inside the function will not be visible outside the function. If you want to pass the name back to the outside world you should return a name/value tuple or a dictionary eg. {'var1' : 42, 'var2': 66, 'var3' 99} HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Oct 7 09:39:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Oct 2007 08:39:58 +0100 Subject: [Tutor] Top Programming Languages of 2013 References: <20071007060510.5DC811E4006@bag.python.org> Message-ID: "Dick Moores" wrote > > Interesting, but I'm not sure what the criteria for "top" is. Is it a measure of power, popularity, usage? Scary that HTML/CSS should be so high though given its not a programming language at all! Alan G. From ricaraoz at gmail.com Sun Oct 7 13:53:37 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 07 Oct 2007 08:53:37 -0300 Subject: [Tutor] Top Programming Languages of 2013 In-Reply-To: References: <20071007060510.5DC811E4006@bag.python.org> Message-ID: <4708C8C1.1020704@bigfoot.com> Alan Gauld wrote: > "Dick Moores" wrote > >> >> > > Interesting, but I'm not sure what the criteria for "top" is. > Is it a measure of power, popularity, usage? > > Scary that HTML/CSS should be so high though > given its not a programming language at all! > > Alan G. > Besides all that, we are programmers not fashion models. Who cares which is the "top" language, leave that for the "top models" and such. Our trade is code, not fashion. From adam.jtm30 at gmail.com Sun Oct 7 14:15:27 2007 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sun, 7 Oct 2007 13:15:27 +0100 Subject: [Tutor] Top Programming Languages of 2013 In-Reply-To: References: <20071007060510.5DC811E4006@bag.python.org> <4708C8C1.1020704@bigfoot.com> Message-ID: On 07/10/2007, Ricardo Ar?oz wrote: > > Alan Gauld wrote: > > "Dick Moores" wrote > > > >> > >> > > > > Interesting, but I'm not sure what the criteria for "top" is. > > Is it a measure of power, popularity, usage? > > > > Scary that HTML/CSS should be so high though > > given its not a programming language at all! > > > > Alan G. > > > > Besides all that, we are programmers not fashion models. Who cares which > is the "top" language, leave that for the "top models" and such. Our > trade is code, not fashion. It appears from the original survey page that it is the most popular by employer demand so it probably does matter if you want a job in that sort of area http://www.redcanary.ca/view/top-10-programming -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071007/ef21c89d/attachment.htm From nytrokiss at gmail.com Sun Oct 7 09:59:50 2007 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 7 Oct 2007 00:59:50 -0700 Subject: [Tutor] Top Programming Languages of 2013 In-Reply-To: References: <20071007060510.5DC811E4006@bag.python.org> Message-ID: <8a6b8e350710070059w1da168e8jbfb5c4e6cfca744c@mail.gmail.com> What are these stats based on? On 10/7/07, Alan Gauld wrote: > > > "Dick Moores" wrote > > > > > > > Interesting, but I'm not sure what the criteria for "top" is. > Is it a measure of power, popularity, usage? > > Scary that HTML/CSS should be so high though > given its not a programming language at all! > > Alan G. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/mens/cufflinks.html http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071007/4de3e82c/attachment.htm From kent37 at tds.net Sun Oct 7 14:44:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 08:44:13 -0400 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: References: Message-ID: <4708D49D.10807@tds.net> Alan Gauld wrote: > The notation data[;,0] doesn't make sense and is an error in Python. > I#m not sure what you think it does. I assume you simply mean > data[0]? [:,0] is an extended slice, not an error: http://docs.python.org/ref/slicings.html It is used in Numeric/numpy to select from multidimensional arrays. Kent From kent37 at tds.net Sun Oct 7 14:48:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 08:48:13 -0400 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: References: Message-ID: <4708D58D.1000805@tds.net> Happy Deer wrote: > Dear all- > > I am writing a function as follows. > > def getdata(varlist): > > .... > eventually I have a variable called "data", which have exactly the same > number of columns as the name of variables in varlist. > Say varlist=['var1','var2','var3']. I want to assign var1=data[:,0], > var2=data[:,1], var3=data[:2] and return var1, var2, var3. > > But when I write the function, I only know I want to assign data[:,0] to > a variable which has a name as varlist[0]. How to write this? Generally in Python when you want to assign a value to a name determined by another variable, you should use a dictionary instead. The keys of the dict are the names and the values are the values. Kent From kent37 at tds.net Sun Oct 7 15:03:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 09:03:25 -0400 Subject: [Tutor] largest and smallest numbers In-Reply-To: <730562.77936.qm@web51603.mail.re2.yahoo.com> References: <730562.77936.qm@web51603.mail.re2.yahoo.com> Message-ID: <4708D91D.6060107@tds.net> Christopher Spears wrote: > One of the exercises from Core Python Programmng (2nd > Edition) asks me to determine the largest and smallest > integers, float, and complex numbers my system can > handle. Using python.org and Google, I have > discovered my system's largest and smallest ingtegers: > >>>> import sys >>>> sys.maxint > 2147483647 >>>> -sys.maxint - 1 > -2147483648 > > How can I find the largest float and complex numbers? There is an extensive discussion starting here: http://homepages.cwi.nl/%7Esteven/enquire.html It also points to float.h. On my computer that is at /usr/includes/float.h and includes among other things #define __FLT_MIN__ 1.17549435e-38F #define __FLT_MAX__ 3.40282347e+38F Kent From alan.gauld at btinternet.com Sun Oct 7 17:29:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Oct 2007 16:29:17 +0100 Subject: [Tutor] a code question, but don't know question's name References: <4708D49D.10807@tds.net> Message-ID: "Kent Johnson" wrote >> The notation data[;,0] doesn't make sense and is an error in >> Python. > > [:,0] is an extended slice, not an error: > http://docs.python.org/ref/slicings.html > Really? I got an error from the interpreter. >>> d[:,0] Traceback (most recent call last): File "", line 1, in ? TypeError: list indices must be integers >>> I thought extended slices were double colon?... but I see that's actually a "long slice" Following the link I get the somewhat obscure explanation: """ The semantics for an extended slicing are as follows. The primary must evaluate to a mapping object, """ This bit I understand :-) """ and it is indexed with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; """ This seems to be the case here, but where is the tuple? Is it the whole list and the zeroth item? If i try testing anything I just get an error. When were these introduced? I am on v2.4.3 """ otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object. The conversion of a proper slice is a slice object (see section 3.2) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions. """ And most of that I don't understand. Can someone who does give some examples of this and what you would use it for? > It is used in Numeric/numpy to select from multidimensional arrays. I don't use either, but since its part of the languyage I assiume it can be used in normal Python lists too? please? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Oct 7 19:01:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 13:01:45 -0400 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: References: <4708D49D.10807@tds.net> Message-ID: <470910F9.7060403@tds.net> Alan Gauld wrote: > "Kent Johnson" wrote > >>> The notation data[;,0] doesn't make sense and is an error in >>> Python. >> [:,0] is an extended slice, not an error: >> http://docs.python.org/ref/slicings.html >> > > Really? I got an error from the interpreter. > >>>> d[:,0] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: list indices must be integers Ok. What I meant is, it is not a *syntax* error. > Following the link I get the somewhat obscure explanation: > > """ > The semantics for an extended slicing are as follows. > The primary must evaluate to a mapping object, > """ > This bit I understand :-) > > """ > and it is indexed with a key that is constructed from the slice list, > as follows. If the slice list contains at least one comma, the key > is a tuple containing the conversion of the slice items; > """ > > This seems to be the case here, but where is the tuple? The tuple is the parameter passed to __getitem__(): In [1]: class sliced(object): ...: def __getitem__(self, item): ...: print repr(item) ...: ...: In [2]: s=sliced() In [3]: s[3] 3 In [4]: s[1:2:3] slice(1, 2, 3) In [5]: s[:,0] (slice(None, None, None), 0) > If i try testing anything I just get an error. There's the rub. Extended slicing is not supported by any built-in containers. That's why you get a TypeError when you try it with a list. > When were these introduced? I am on v2.4.3 At least since 2.0 :-) http://www.python.org/doc/2.0/ref/slicings.html > > """ > otherwise, the conversion of the lone slice item is the key. The > conversion of a slice item that is an expression is that expression. > The conversion of an ellipsis slice item is the built-in Ellipsis > object. The conversion of a proper slice is a slice object (see > section 3.2) whose start, stop and step attributes are the values of > the expressions given as lower bound, upper bound and stride, > respectively, substituting None for missing expressions. > """ > > And most of that I don't understand. It is saying what the values passed to __getitem__() are: either a plain object (probably an integer); an Ellipsis object, if the parameter is ...: In [6]: s[...] Ellipsis or a slice object, or a tuple of such things. > Can someone who does give some examples of this > and what you would use it for? > >> It is used in Numeric/numpy to select from multidimensional arrays. See the numpy docs for examples. > I don't use either, but since its part of the languyage I assiume it > can be used in normal Python lists too? No. It can be used for user-defined classes but it is not supported by any built-ins. IIUC this feature was added specifically for Numeric. Kent From kent37 at tds.net Sun Oct 7 20:25:51 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 14:25:51 -0400 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: <470910F9.7060403@tds.net> References: <4708D49D.10807@tds.net> <470910F9.7060403@tds.net> Message-ID: <470924AF.5070802@tds.net> Kent Johnson wrote: > Alan Gauld wrote: >> "Kent Johnson" wrote >> >>>> The notation data[;,0] doesn't make sense and is an error in >>>> Python. >>> [:,0] is an extended slice, not an error: >>> http://docs.python.org/ref/slicings.html We discussed this quite a bit last July: http://mail.python.org/pipermail/tutor/2007-July/055814.html Kent From davmillar at gmail.com Sun Oct 7 20:53:04 2007 From: davmillar at gmail.com (David Millar) Date: Sun, 7 Oct 2007 14:53:04 -0400 Subject: [Tutor] File Writing Permission? Message-ID: Hi everyone, I'm working on making a Debian package for a game I'm working on, and it works fine, but I've run into a problem with my script now. The script is placed in /usr/bin so all users on the system have access, but even though it will run fine, I can't save files to that directory, so the saving feature doesn't work and the rest of my game is crippled now. Any ideas on how I could progress? I tried appending "~/" to the filename for that copy of the script, but it just makes the terminal window close without warning. Any help would be appreciated. def savegame(fname): # This part isn't necessary, I just wanted to see if it would save to the user's home folder if os.name == "posix": fname = "~/" + fname infile = open(fname,"w") # Save the maps mapchanges.append([6,1,rrmap]) mapchanges.append([6,2,treemap]) picklelist = [choins, inventory, book, mapchanges, event, cdata] pickle.dump(picklelist,infile) # Delete the saved maps because they will just get in the way later del mapchanges[len(mapchanges)-1] del mapchanges[len(mapchanges)-1] infile.close() David Millar http://www.thegriddle.net/python/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071007/f31fea00/attachment.htm From wormwood_3 at yahoo.com Sun Oct 7 20:54:14 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 7 Oct 2007 11:54:14 -0700 (PDT) Subject: [Tutor] Logging with proper format Message-ID: <310572.59936.qm@web32403.mail.mud.yahoo.com> Hello tutors, I am adding logging to a program I am writing. I have some messages I want to log that are rather long. The problem I am running into is that when the line is more than the 80 character line recommendation and I split it across 2 lines with "\", the output is affected. Example code: logger.info("Checked %s records in %s seconds, yielding an average of \ %s seconds per record." % (len(self.data), duration, avgquery) ) The current output: 2007-10-07 14:49:42,902 - ipinfo - INFO - Checked 4 records in 0.0698790550232 seconds, yielding an average of 0.0174697637558 seconds per record. Desired output would be: 2007-10-07 14:49:42,902 - ipinfo - INFO - Checked 4 records in 0.0698790550232 seconds, yielding an average of 0.0174697637558 seconds per record. So what is the best way to break long code lines and still preserve desired output? Thanks, Sam From ihappydeer at gmail.com Sun Oct 7 21:29:54 2007 From: ihappydeer at gmail.com (Happy Deer) Date: Sun, 7 Oct 2007 12:29:54 -0700 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: <470924AF.5070802@tds.net> References: <4708D49D.10807@tds.net> <470910F9.7060403@tds.net> <470924AF.5070802@tds.net> Message-ID: Thank all for the discussion. Maybe I can separate my question into two. First, I have experience in Matlab, where I can use "eval". I wonder whether someone knows about it. Second, if I just want to return data[:,1], ...data[:,-1] separately without knowing ahead how many columns data has. What should I do? On 10/7/07, Kent Johnson wrote: > > Kent Johnson wrote: > > Alan Gauld wrote: > >> "Kent Johnson" wrote > >> > >>>> The notation data[;,0] doesn't make sense and is an error in > >>>> Python. > >>> [:,0] is an extended slice, not an error: > >>> http://docs.python.org/ref/slicings.html > > We discussed this quite a bit last July: > http://mail.python.org/pipermail/tutor/2007-July/055814.html > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071007/78bc7caf/attachment.htm From wormwood_3 at yahoo.com Sun Oct 7 21:47:04 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 7 Oct 2007 12:47:04 -0700 (PDT) Subject: [Tutor] Logging with proper format Message-ID: <506938.42158.qm@web32414.mail.mud.yahoo.com> Sent this almost an hour ago, did not get it from the list yet. No idea why, but sending again... -------------------------- Hello tutors, I am adding logging to a program I am writing. I have some messages I want to log that are rather long. The problem I am running into is that when the line is more than the 80 character line recommendation and I split it across 2 lines with "\", the output is affected. Example code: logger.info("Checked %s records in %s seconds, yielding an average of \ %s seconds per record." % (len(self.data), duration, avgquery) ) The current output: 2007-10-07 14:49:42,902 - ipinfo - INFO - Checked 4 records in 0.0698790550232 seconds, yielding an average of 0.0174697637558 seconds per record. Desired output would be: 2007-10-07 14:49:42,902 - ipinfo - INFO - Checked 4 records in 0.0698790550232 seconds, yielding an average of 0.0174697637558 seconds per record. So what is the best way to break long code lines and still preserve desired output? Thanks, Sam From brunson at brunson.com Sun Oct 7 22:05:56 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 07 Oct 2007 14:05:56 -0600 Subject: [Tutor] File Writing Permission? In-Reply-To: References: Message-ID: <47093C24.4040904@brunson.com> David Millar wrote: > Hi everyone, > > I'm working on making a Debian package for a game I'm working on, and > it works fine, but I've run into a problem with my script now. The > script is placed in /usr/bin so all users on the system have access, > but even though it will run fine, I can't save files to that > directory, so the saving feature doesn't work and the rest of my game > is crippled now. Any ideas on how I could progress? I tried appending > "~/" to the filename for that copy of the script, but it just makes > the terminal window close without warning. Any help would be appreciated. > > def savegame(fname): > # This part isn't necessary, I just wanted to see if it would save > to the user's home folder > if os.name == "posix": > fname = "~/" + fname Hi Dave, Python doesn't immediately do tilde expansion on filenames, you have to ask for it explicitly. Normally this is done by your shell, but since most modern shells do it, it's easy to assume it's an inherent property of filenames and not an added feature. Simply change: fname = "~/" + fname to: fname = os.path.expanduser( os.path.join( "~", fname ) ) Hope that helps, e. > infile = open(fname,"w") > # Save the maps > mapchanges.append([6,1,rrmap]) > mapchanges.append([6,2,treemap]) > picklelist = [choins, inventory, book, mapchanges, event, cdata] > pickle.dump(picklelist,infile) > # Delete the saved maps because they will just get in the way later > del mapchanges[len(mapchanges)-1] > del mapchanges[len(mapchanges)-1] > infile.close() > > David Millar > http://www.thegriddle.net/python/ > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ihappydeer at gmail.com Sun Oct 7 22:07:00 2007 From: ihappydeer at gmail.com (Happy Deer) Date: Sun, 7 Oct 2007 13:07:00 -0700 Subject: [Tutor] corresponding command in Python to "eval" in Matlab Message-ID: Dear all- I wonder whether there is a way in Python which can do what "eval" in Matlab does. Say, varlist is a 1 by k tuple/list, which contains strings for variable names. For example, varlist=['var1','var2',...'vark'] data is a n by k matrix. I want to assign each column in data to each variable in varlist and get var1=data[:,1]... vark=data[:,k] Anyone knows how to do this? Fangwen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071007/2b505d3d/attachment.htm From brunson at brunson.com Sun Oct 7 22:08:05 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 07 Oct 2007 14:08:05 -0600 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: References: <4708D49D.10807@tds.net> <470910F9.7060403@tds.net> <470924AF.5070802@tds.net> Message-ID: <47093CA5.60008@brunson.com> Happy Deer wrote: > Thank all for the discussion. > Maybe I can separate my question into two. > > First, I have experience in Matlab, where I can use "eval". I wonder > whether someone knows about it. > > Second, if I just want to return data[:,1], ...data[:,-1] separately > without knowing ahead how many columns data has. What should I do? I'm still unsure if you even need extended slicing. Given: data = [ 1, 2, 3, 4, 5, 6 ] What do you expect data[:,1] and data[:,-1] to return? > > > > On 10/7/07, *Kent Johnson* > > wrote: > > Kent Johnson wrote: > > Alan Gauld wrote: > >> "Kent Johnson" > wrote > >> > >>>> The notation data[;,0] doesn't make sense and is an error in > >>>> Python. > >>> [:,0] is an extended slice, not an error: > >>> http://docs.python.org/ref/slicings.html > > We discussed this quite a bit last July: > http://mail.python.org/pipermail/tutor/2007-July/055814.html > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From clazzt at arnet.com.ar Sun Oct 7 22:07:31 2007 From: clazzt at arnet.com.ar (claxo) Date: Sun, 07 Oct 2007 17:07:31 -0300 Subject: [Tutor] File Writing Permission? In-Reply-To: References: Message-ID: > if os.name == "posix": > fname = "~/" + fname > infile = open(fname,"w") you must expand '~' before open: fname = os.path.join('~',fname) fname = os.path.expanduser( fname ) infile = open(fname,'w') From ihappydeer at gmail.com Sun Oct 7 22:14:38 2007 From: ihappydeer at gmail.com (Happy Deer) Date: Sun, 7 Oct 2007 13:14:38 -0700 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: <47093CA5.60008@brunson.com> References: <4708D49D.10807@tds.net> <470910F9.7060403@tds.net> <470924AF.5070802@tds.net> <47093CA5.60008@brunson.com> Message-ID: I am writing a function getdata for other people, and I want others can use the function as follows. var1,var2, var3=getdata(..., ['var1','var2','var3'],...) If I can not return data column by column, I can not get the above, right? On 10/7/07, Eric Brunson wrote: > > Happy Deer wrote: > > Thank all for the discussion. > > Maybe I can separate my question into two. > > > > First, I have experience in Matlab, where I can use "eval". I wonder > > whether someone knows about it. > > > > Second, if I just want to return data[:,1], ...data[:,-1] separately > > without knowing ahead how many columns data has. What should I do? > > I'm still unsure if you even need extended slicing. > > Given: > > data = [ 1, 2, 3, 4, 5, 6 ] > > What do you expect data[:,1] and data[:,-1] to return? > > > > > > > > > > On 10/7/07, *Kent Johnson* > > > wrote: > > > > Kent Johnson wrote: > > > Alan Gauld wrote: > > >> "Kent Johnson" > wrote > > >> > > >>>> The notation data[;,0] doesn't make sense and is an error in > > >>>> Python. > > >>> [:,0] is an extended slice, not an error: > > >>> http://docs.python.org/ref/slicings.html > > > > We discussed this quite a bit last July: > > http://mail.python.org/pipermail/tutor/2007-July/055814.html > > > > Kent > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071007/a7f51077/attachment-0001.htm From clazzt at arnet.com.ar Sun Oct 7 22:12:18 2007 From: clazzt at arnet.com.ar (claxo) Date: Sun, 07 Oct 2007 17:12:18 -0300 Subject: [Tutor] Logging with proper format In-Reply-To: <310572.59936.qm@web32403.mail.mud.yahoo.com> References: <310572.59936.qm@web32403.mail.mud.yahoo.com> Message-ID: dont indent the line after '\', that means 0 indent s = 'hello\ boy' From kent37 at tds.net Sun Oct 7 22:17:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 16:17:35 -0400 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: References: <4708D49D.10807@tds.net> <470910F9.7060403@tds.net> <470924AF.5070802@tds.net> Message-ID: <47093EDF.10906@tds.net> Happy Deer wrote: > First, I have experience in Matlab, where I can use "eval". I wonder > whether someone knows about it. Python has an eval() function but it's use is discouraged, there is usually a better way. It would help if you would give us more context for your problem. > Second, if I just want to return data[:,1], ...data[:,-1] separately > without knowing ahead how many columns data has. What should I do? I'm assuming data is a numpy or Numeric array though it would help if you would confirm that. In [10]: from numpy import array In [11]: a = array([[1,2,3],[4,5,6]]) a.shape gives the dimensions; a.shape[1] is the second dimension In [15]: a.shape Out[15]: (2, 3) In [18]: a.shape[1] Out[18]: 3 You can use a list comprehension to make a list of the columns. In [19]: [ a[:,i] for i in range(1, a.shape[1])] Out[19]: [array([2, 5]), array([3, 6])] Note you asked for data[:,1], ...data[:,-1] which does not include the first column. Kent From brunson at brunson.com Sun Oct 7 22:18:08 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 07 Oct 2007 14:18:08 -0600 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: References: <4708D49D.10807@tds.net> <470910F9.7060403@tds.net> <470924AF.5070802@tds.net> <47093CA5.60008@brunson.com> Message-ID: <47093F00.2020701@brunson.com> Happy Deer wrote: > I am writing a function getdata for other people, and I want others > can use the function as follows. > > var1,var2, var3=getdata(..., ['var1','var2','var3'],...) > > If I can not return data column by column, I can not get the above, > right? Given: data = [ 1, 2, 3, 4, 5, 6 ] What do you expect data[:,1] and data[:,-1] to return? > > On 10/7/07, *Eric Brunson* > wrote: > > Happy Deer wrote: > > Thank all for the discussion. > > Maybe I can separate my question into two. > > > > First, I have experience in Matlab, where I can use "eval". I wonder > > whether someone knows about it. > > > > Second, if I just want to return data[:,1], ...data[:,-1] separately > > without knowing ahead how many columns data has. What should I do? > > I'm still unsure if you even need extended slicing. > > Given: > > data = [ 1, 2, 3, 4, 5, 6 ] > > What do you expect data[:,1] and data[:,-1] to return? > > > > > > > > > > On 10/7/07, *Kent Johnson* >> > > wrote: > > > > Kent Johnson wrote: > > > Alan Gauld wrote: > > >> "Kent Johnson" < kent37 at tds.net > >> wrote > > >> > > >>>> The notation data[;,0] doesn't make sense and is an > error in > > >>>> Python. > > >>> [:,0] is an extended slice, not an error: > > >>> http://docs.python.org/ref/slicings.html > > > > We discussed this quite a bit last July: > > http://mail.python.org/pipermail/tutor/2007-July/055814.html > > > > Kent > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > From brunson at brunson.com Sun Oct 7 22:15:56 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 07 Oct 2007 14:15:56 -0600 Subject: [Tutor] corresponding command in Python to "eval" in Matlab In-Reply-To: References: Message-ID: <47093E7C.9000207@brunson.com> A good python coder would probably not choose to pollute his name space like that. My choice would be to assign the elements of "data" to a dictionary indexed by the strings in varlist like this: vardict = dict( zip( varlist, data ) ) and reference "var1" as: vardict['var1'] Happy Deer wrote: > Dear all- > > I wonder whether there is a way in Python which can do what "eval" in > Matlab does. > Say, varlist is a 1 by k tuple/list, which contains strings for > variable names. > For example, varlist=['var1','var2',...'vark'] > data is a n by k matrix. > I want to assign each column in data to each variable in varlist and > get var1=data[:,1]... vark=data[:,k] > > Anyone knows how to do this? > > Fangwen > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Sun Oct 7 22:19:15 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 07 Oct 2007 14:19:15 -0600 Subject: [Tutor] Logging with proper format In-Reply-To: References: <310572.59936.qm@web32403.mail.mud.yahoo.com> Message-ID: <47093F43.4040503@brunson.com> claxo wrote: > dont indent the line after '\', that means 0 indent > > s = 'hello\ > boy' > Or, arguably better: s = '''hello boy''' > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Oct 7 22:20:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 16:20:26 -0400 Subject: [Tutor] Logging with proper format In-Reply-To: <310572.59936.qm@web32403.mail.mud.yahoo.com> References: <310572.59936.qm@web32403.mail.mud.yahoo.com> Message-ID: <47093F8A.60200@tds.net> wormwood_3 wrote: > Hello tutors, > > I am adding logging to a program I am writing. I have some messages I want to log that are rather long. The problem I am running into is that when the line is more than the 80 character line recommendation and I split it across 2 lines with "\", the output is affected. > > Example code: > > logger.info("Checked %s records in %s seconds, yielding an average of \ > %s seconds per record." % (len(self.data), duration, avgquery) ) ^^^^^^^^^^^^ <- this is white space in your string! Try this: logger.info("Checked %s records in %s seconds, yielding an \ average of \ %s seconds per record." % (len(self.data), duration, avgquery) ) Kent From kent37 at tds.net Sun Oct 7 22:25:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 16:25:47 -0400 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: References: <4708D49D.10807@tds.net> <470910F9.7060403@tds.net> <470924AF.5070802@tds.net> <47093CA5.60008@brunson.com> Message-ID: <470940CB.6010401@tds.net> Happy Deer wrote: > I am writing a function getdata for other people, and I want others can > use the function as follows. > > var1,var2, var3=getdata(..., ['var1','var2','var3'],...) There is no need to pass the variable names to getdata. Have you read any Python tutorials? There are several good ones listed here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > If I can not return data column by column, I can not get the above, right? You can just return the columns: def getdata(data): return data[:,0], data[:,1], data[:,2] Kent > > On 10/7/07, *Eric Brunson* > wrote: > > Happy Deer wrote: > > Thank all for the discussion. > > Maybe I can separate my question into two. > > > > First, I have experience in Matlab, where I can use "eval". I wonder > > whether someone knows about it. > > > > Second, if I just want to return data[:,1], ...data[:,-1] separately > > without knowing ahead how many columns data has. What should I do? > > I'm still unsure if you even need extended slicing. > > Given: > > data = [ 1, 2, 3, 4, 5, 6 ] > > What do you expect data[:,1] and data[:,-1] to return? > > > > > > > > > > On 10/7/07, *Kent Johnson* >> > > wrote: > > > > Kent Johnson wrote: > > > Alan Gauld wrote: > > >> "Kent Johnson" < kent37 at tds.net > >> wrote > > >> > > >>>> The notation data[;,0] doesn't make sense and is an error in > > >>>> Python. > > >>> [:,0] is an extended slice, not an error: > > >>> http://docs.python.org/ref/slicings.html > > > > We discussed this quite a bit last July: > > http://mail.python.org/pipermail/tutor/2007-July/055814.html > > > > Kent > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > From brunson at brunson.com Sun Oct 7 22:26:53 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 07 Oct 2007 14:26:53 -0600 Subject: [Tutor] corresponding command in Python to "eval" in Matlab In-Reply-To: <47093E7C.9000207@brunson.com> References: <47093E7C.9000207@brunson.com> Message-ID: <4709410D.1040204@brunson.com> However, I didn't actually answer your question. As Kent has already mentioned, eval is quite dangerous in python and to be avoided when possible. I think it would be safer to do something like this: l = locals() for x, y in zip( varlist, data ): l[x] = y or, more tersely: [ locals()[x] = y for x, y in zip( varlist, data ) ] This will accomplish what you're trying to do, but a dict really gives you greater functionality than assigning to local variables. Python is *not* Matlab. Functions that have the same name are not necessarily equivalent. Plus, you should start to "think in Python" rather than "thinking in Matlab" and transliterating. Eric Brunson wrote: > A good python coder would probably not choose to pollute his name space > like that. My choice would be to assign the elements of "data" to a > dictionary indexed by the strings in varlist like this: > > vardict = dict( zip( varlist, data ) ) > > and reference "var1" as: > > vardict['var1'] > > Happy Deer wrote: > >> Dear all- >> >> I wonder whether there is a way in Python which can do what "eval" in >> Matlab does. >> Say, varlist is a 1 by k tuple/list, which contains strings for >> variable names. >> For example, varlist=['var1','var2',...'vark'] >> data is a n by k matrix. >> I want to assign each column in data to each variable in varlist and >> get var1=data[:,1]... vark=data[:,k] >> >> Anyone knows how to do this? >> >> Fangwen >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Oct 7 22:30:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 16:30:30 -0400 Subject: [Tutor] corresponding command in Python to "eval" in Matlab In-Reply-To: References: Message-ID: <470941E6.5040502@tds.net> Happy Deer wrote: > Dear all- > > I wonder whether there is a way in Python which can do what "eval" in > Matlab does. > Say, varlist is a 1 by k tuple/list, which contains strings for variable > names. > For example, varlist=['var1','var2',...'vark'] > data is a n by k matrix. > I want to assign each column in data to each variable in varlist and get > var1=data[:,1]... vark=data[:,k] A better way to do this is to make a dictionary that holds the values: values = dict(var1=data[:,1]... vark=data[:,k]) or perhaps just a list with the columns as I have already shown you in a separate email. Python is not Matlab, it will serve you well in the long run to learn the Python way of Python instead of trying to write Matlab programs in Python. Python's support for lists and dictionaries is very strong and useful. Kent From kent37 at tds.net Sun Oct 7 22:32:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 16:32:33 -0400 Subject: [Tutor] Logging with proper format In-Reply-To: <47093F43.4040503@brunson.com> References: <310572.59936.qm@web32403.mail.mud.yahoo.com> <47093F43.4040503@brunson.com> Message-ID: <47094261.1050306@tds.net> Eric Brunson wrote: > claxo wrote: >> dont indent the line after '\', that means 0 indent >> >> s = 'hello\ >> boy' >> > > Or, arguably better: > > s = '''hello > boy''' That is a different string, it contains a newline, the original does not: In [20]: s = 'hello\ ....: boy' In [21]: s2 = '''hello ....: boy''' In [22]: s==s2 Out[22]: False In [23]: print s helloboy In [24]: print s2 hello boy Kent From kent37 at tds.net Sun Oct 7 22:36:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 16:36:26 -0400 Subject: [Tutor] corresponding command in Python to "eval" in Matlab In-Reply-To: <4709410D.1040204@brunson.com> References: <47093E7C.9000207@brunson.com> <4709410D.1040204@brunson.com> Message-ID: <4709434A.8080404@tds.net> Eric Brunson wrote: > However, I didn't actually answer your question. > > As Kent has already mentioned, eval is quite dangerous in python and to > be avoided when possible. I think it would be safer to do something > like this: > > l = locals() > for x, y in zip( varlist, data ): > l[x] = y > > or, more tersely: > > [ locals()[x] = y for x, y in zip( varlist, data ) ] > > > This will accomplish what you're trying to do, but a dict really gives > you greater functionality than assigning to local variables. This will only work at global scope where locals() is globals() and writable. In function scope assigning to locals()[...] does not change the local namespace: In [27]: def foo(): ....: locals()['x'] = 1 ....: print x ....: ....: In [28]: foo() ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in File "", line 3, in foo : global name 'x' is not defined Kent From amonroe at columbus.rr.com Sun Oct 7 21:55:27 2007 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 7 Oct 2007 15:55:27 -0400 Subject: [Tutor] Logging with proper format In-Reply-To: <506938.42158.qm@web32414.mail.mud.yahoo.com> References: <506938.42158.qm@web32414.mail.mud.yahoo.com> Message-ID: <135-33393948.20071007155527@columbus.rr.com> > logger.info("Checked %s records in %s seconds, yielding an average of \ > %s seconds per record." % (len(self.data), duration, avgquery) ) ^^^^^^^^^^^^^ Remove these spaces. It makes the source code look weird, but the output will be correct. Alan From eike.welk at gmx.net Sun Oct 7 23:20:52 2007 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 07 Oct 2007 23:20:52 +0200 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: References: <470924AF.5070802@tds.net> Message-ID: <200710072320.53346.eike.welk@gmx.net> On Sunday 07 October 2007 21:29, Happy Deer wrote: > Thank all for the discussion. > Maybe I can separate my question into two. > > First, I have experience in Matlab, where I can use "eval". I > wonder whether someone knows about it. I suspect you are using Numpy, you should subscribe to the Numpy mailing-list. There are people that can compare Numpy to Matlab. Probably you should also subscribe to the Scipy mailing list(s). http://www.scipy.org/Mailing_Lists > > Second, if I just want to return data[:,1], ...data[:,-1] > separately without knowing ahead how many columns data has. What > should I do? eike at bookxie:~> ipython --pylab In [1]:a = array([[1,2,3], [4,5,6]]) In [2]:a Out[2]: array([[1, 2, 3], [4, 5, 6]]) In [3]:a[:,0] Out[3]:array([1, 4]) In [4]:a.shape Out[4]:(2, 3) In [6]:for i in range(a.shape[1]): .6.: print a[:,i] .6.: [1 4] [2 5] [3 6] If you want a[:,i] be/stay a column vector use the matrix class. The mat constructor function even has Matlab like syntax. In [8]:import numpy as np In [9]:a = np.mat("1,2,3; 4,5,6") In [11]:a Out[11]: matrix([[1, 2, 3], [4, 5, 6]]) In [12]:a[:,0] Out[12]: matrix([[1], [4]]) I shortened the Ipython session a little, you don't want to see my syntax errors I guess. HTH, Eike. From eike.welk at gmx.net Sun Oct 7 23:47:19 2007 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 07 Oct 2007 23:47:19 +0200 Subject: [Tutor] Logging with proper format In-Reply-To: <47094261.1050306@tds.net> References: <310572.59936.qm@web32403.mail.mud.yahoo.com> <47093F43.4040503@brunson.com> <47094261.1050306@tds.net> Message-ID: <200710072347.19893.eike.welk@gmx.net> On Sunday 07 October 2007 22:32, Kent Johnson wrote: > Eric Brunson wrote: > > claxo wrote: > >> dont indent the line after '\', that means 0 indent > >> > >> s = 'hello\ > >> boy' > > > > Or, arguably better: > > > > s = '''hello > > boy''' > And there is even a third way:-) >>> s = "hello " \ ... "world." >>> s 'hello world.' Two strings that are adjacent to each other, are concatenated into one string; like in C++. Regards, Eike. From eike.welk at gmx.net Sun Oct 7 23:57:21 2007 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 07 Oct 2007 23:57:21 +0200 Subject: [Tutor] a code question, but don't know question's name In-Reply-To: <47093EDF.10906@tds.net> References: <47093EDF.10906@tds.net> Message-ID: <200710072357.21638.eike.welk@gmx.net> I have written the exact same reply. Sorry for that! I should have read the other replies first. Eike. From sanelson at gmail.com Mon Oct 8 00:50:20 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Sun, 7 Oct 2007 23:50:20 +0100 Subject: [Tutor] Permission Report Message-ID: Hello all, I have a tree of code on a machine which has been tweaked and fiddled with over several months, and which passes tests. I have the same codebase in a new virtual machine. A shell hack[0] shows me that the permissions are very different between the two. I could use rsync or something to synchronise them, but I would like to produce a report of the sort: Change file: foo from 755 to 775 So I can try to work out why this is necessary. I'm not sure how best to proceed - I guess walk through the filesystem gathering info using stat, then do the same on the new system, and compare. Or are there some clever modules I could use? S. From alan.gauld at btinternet.com Mon Oct 8 01:21:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Oct 2007 00:21:59 +0100 Subject: [Tutor] Permission Report References: Message-ID: "Stephen Nelson-Smith" wrote > I could use rsync or something to synchronise them, but I would like > to produce a report of the sort: > > Change file: foo from 755 to 775 > > I'm not sure how best to proceed - I guess walk through the > filesystem > gathering info using stat, then do the same on the new system, and > compare. Yes, os.walk and os.stat should do what you want. There is a dircmp module that may do what you want but I've not used it. Alan G From wormwood_3 at yahoo.com Mon Oct 8 03:07:45 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 7 Oct 2007 18:07:45 -0700 (PDT) Subject: [Tutor] Updating MySQL Database Message-ID: <481695.95012.qm@web32405.mail.mud.yahoo.com> Hello all, I have a script which takes data from a file or MySQL DB, looks up some stuff, then can print results to console or file. I would also like it to be able to update a MySQL database with the results. Does anyone have any ideas on how to do this? I can update records just fine, but what is the best way to do LOTS of updates aside from running an update statement per record? Using that method, for example, assuming I have a list of results, each line of the form "ip,fqdn": for line in inputlist: updatequery = "update resultstable set fqdn = line.split(",")[1] where ip = line.split(",")[0];" connection = MySQLdb.connect(db=self.todatabase, host=self.host, user=self.user, passwd=self.passwd, port=int(self.port)) cursor = connection.cursor() cursor.execute(updatequery) queryresults = cursor.fetchall() cursor.close() connection.close() But this means making a connection and query for every line of results, which is a lot. Any ideas on optimization? Thanks, Sam From ricaraoz at gmail.com Mon Oct 8 03:42:07 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 07 Oct 2007 22:42:07 -0300 Subject: [Tutor] Updating MySQL Database In-Reply-To: <481695.95012.qm@web32405.mail.mud.yahoo.com> References: <481695.95012.qm@web32405.mail.mud.yahoo.com> Message-ID: <47098AEF.50502@bigfoot.com> wormwood_3 wrote: > Hello all, > > I have a script which takes data from a file or MySQL DB, looks up some stuff, then can print results to console or file. I would also like it to be able to update a MySQL database with the results. Does anyone have any ideas on how to do this? I can update records just fine, but what is the best way to do LOTS of updates aside from running an update statement per record? Using that method, for example, assuming I have a list of results, each line of the form "ip,fqdn": > > for line in inputlist: > updatequery = "update resultstable set fqdn = line.split(",")[1] where ip = line.split(",")[0];" > connection = MySQLdb.connect(db=self.todatabase, host=self.host, > user=self.user, passwd=self.passwd, port=int(self.port)) > cursor = connection.cursor() > cursor.execute(updatequery) > queryresults = cursor.fetchall() > cursor.close() > connection.close() > > But this means making a connection and query for every line of results, which is a lot. Any ideas on optimization? > > Thanks, > Sam Haven't worked with DBs in Python yet but I guess it can't be too different. What if you put the connect/disconnect outside your loop? connection = MySQLdb.connect(db=self.todatabase, host=self.host, user=self.user, passwd=self.passwd, port=int(self.port)) cursor = connection.cursor() for line in inputlist: updatequery = "update resultstable set fqdn = line.split(",")[1] where ip = line.split(",")[0];" cursor.execute(updatequery) queryresults = cursor.fetchall() cursor.close() connection.close() Do you need to do the "cursor.fetchall()"? AFAIK an update will return no data. You might want to use transactions too (outside the loop). BTW, I think your updatequery not properly configured, MySQL supports (?) variable substitution (and even if it didn't your updatequery is wrong, the variables should be outside the string with a %). HTH From kent37 at tds.net Mon Oct 8 03:41:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 21:41:49 -0400 Subject: [Tutor] Permission Report In-Reply-To: References: Message-ID: <47098ADD.6080805@tds.net> Alan Gauld wrote: > There is a dircmp module that may do what you want but I've not > used it. It was deprecated in Python 2.0 and removed in 2.5. From a quick look it might provide a useful framework but it doesn't compare permissions. Kent From kent37 at tds.net Mon Oct 8 03:48:41 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 07 Oct 2007 21:48:41 -0400 Subject: [Tutor] Updating MySQL Database In-Reply-To: <481695.95012.qm@web32405.mail.mud.yahoo.com> References: <481695.95012.qm@web32405.mail.mud.yahoo.com> Message-ID: <47098C79.2010103@tds.net> wormwood_3 wrote: > Hello all, > > I have a script which takes data from a file or MySQL DB, looks up some stuff, then can print results to console or file. I would also like it to be able to update a MySQL database with the results. Does anyone have any ideas on how to do this? I can update records just fine, but what is the best way to do LOTS of updates aside from running an update statement per record? Using that method, for example, assuming I have a list of results, each line of the form "ip,fqdn": > > for line in inputlist: > updatequery = "update resultstable set fqdn = line.split(",")[1] where ip = line.split(",")[0];" This doesn't look like real code, is it missing some quotes and +? It also looks like you are embedding the data in the SQL command, this is very bad practice, it opens you to SQL injection attacks and doesn't correctly handle data with special characters. You should pass the parameters in a separate list. > connection = MySQLdb.connect(db=self.todatabase, host=self.host, > user=self.user, passwd=self.passwd, port=int(self.port)) > cursor = connection.cursor() > cursor.execute(updatequery) > queryresults = cursor.fetchall() > cursor.close() > connection.close() > > But this means making a connection and query for every line of results, which is a lot. Any ideas on optimization? There is no need to make a new connection and cursor for each query, you can reuse the same cursor, just put the code to aquire and close them outside the loop. Also take a look at cursor.executemany(). I'm not familiar with MySQL but there is probably a way to run commands from a file, that may be faster than doing it from Python. You could build a file with all the required commands. Kent From rick at niof.net Mon Oct 8 04:14:04 2007 From: rick at niof.net (Rick Pasotto) Date: Sun, 7 Oct 2007 22:14:04 -0400 Subject: [Tutor] Updating MySQL Database In-Reply-To: <481695.95012.qm@web32405.mail.mud.yahoo.com> References: <481695.95012.qm@web32405.mail.mud.yahoo.com> Message-ID: <20071008021404.GI23783@niof.net> On Sun, Oct 07, 2007 at 06:07:45PM -0700, wormwood_3 wrote: > Hello all, > > I have a script which takes data from a file or MySQL DB, looks up > some stuff, then can print results to console or file. I would also > like it to be able to update a MySQL database with the results. Does > anyone have any ideas on how to do this? I can update records just > fine, but what is the best way to do LOTS of updates aside from > running an update statement per record? Using that method, for > example, assuming I have a list of results, each line of the form > "ip,fqdn": > > for line in inputlist: > updatequery = "update resultstable set fqdn = line.split(",")[1] where ip = line.split(",")[0];" > connection = MySQLdb.connect(db=self.todatabase, host=self.host, > user=self.user, passwd=self.passwd, port=int(self.port)) > cursor = connection.cursor() > cursor.execute(updatequery) > queryresults = cursor.fetchall() > cursor.close() > connection.close() > > But this means making a connection and query for every line of > results, which is a lot. Any ideas on optimization? Good grief! Open the connection and create the cursor ONCE, use it as many times as you need, and then close it (them). Closing the connection automatically closes the cursor. CAUTION: the following is not fully tested but I believe it to be correct. connection = MySQLdb.connect(db=self.todatabase,host-self.host, user=self.user, passwd=self.passwd, port=int(self.port)) cursor = connection.cursor() for line in inputlist: (ip,fqdn) = line.split(',') updatequery = "update resultstable set %s where ip = %s" % (fqdn,ip) cursor.execute(updatequery) connection.close() Alternatively you could do: connection = MySQLdb.connect(db=self.todatabase,host-self.host, user=self.user, passwd=self.passwd, port=int(self.port)) cursor = connection.cursor() updatequery = "update resultstable set %s where ip = %s" for line in inputlist: vals = list(line.split(',')) vals.reverse() cursor.execute(updatequery,vals) connection.close() I think the second version is more efficient. or you could do: connection = MySQLdb.connect(db=self.todatabase,host-self.host, user=self.user, passwd=self.passwd, port=int(self.port)) cursor = connection.cursor() updatequery = "update resultstable set %s where ip = %s" for line in inputlist: (ip,fqdn) = line.split(',') cursor.execute(updatequery,(fqdn,ip)) connection.close() Note that for these last two there is a comma between the arguments to cursor.execute() rather than a percent. -- "I am only one. But I am one. I cannot do everything but I can do something. And I will not let what I cannot do interfere with what I can do." -- Edward E. Hule Rick Pasotto rick at niof.net http://www.niof.net From eric at ericwalstad.com Mon Oct 8 05:07:12 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Sun, 07 Oct 2007 20:07:12 -0700 Subject: [Tutor] Updating MySQL Database In-Reply-To: <481695.95012.qm@web32405.mail.mud.yahoo.com> References: <481695.95012.qm@web32405.mail.mud.yahoo.com> Message-ID: <47099EE0.9050406@ericwalstad.com> Hey Sam, wormwood_3 wrote: > Hello all, > > I have a script which takes data from a file or MySQL DB, looks up some stuff, then can print results to console or file. I would also like it to be able to update a MySQL database with the results. Does anyone have any ideas on how to do this? I can update records just fine, but what is the best way to do LOTS of updates aside from running an update statement per record? I recommend not worrying about speed on your first iteration of your script. I'd first define 'too slow', then write the script the way that feels intuitive to you. If your script passes your threshold of 'too slow', then look at optimizing it. If optimization is really necessary, I'd look into .executemany(). If that is still too slow for you then I'd consider writing the update SQL to a file and then calling mysql, passing it the sql file your script created. I found this last approach the fastest for a data import script I once wrote for importing millions of records to a PostgreSQL database. -E From davmillar at gmail.com Mon Oct 8 05:59:17 2007 From: davmillar at gmail.com (David Millar) Date: Sun, 7 Oct 2007 23:59:17 -0400 Subject: [Tutor] File Writing Permission? In-Reply-To: References: Message-ID: Thanks - it still took a bit more tweaking because of how I wrote a few things, but the saving works fine now. I've been having trouble with finding a version of the curses library for Windows that I can get working, so I just used os.path.expanduser no matter the system. :/ Dave On 10/7/07, claxo wrote: > > > > if os.name == "posix": > > fname = "~/" + fname > > infile = open(fname,"w") > > > you must expand '~' before open: > > fname = os.path.join('~',fname) > fname = os.path.expanduser( fname ) > infile = open(fname,'w') > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071007/08d6329f/attachment.htm From steve at alchemy.com Mon Oct 8 06:08:15 2007 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 07 Oct 2007 21:08:15 -0700 Subject: [Tutor] Updating MySQL Database In-Reply-To: <20071008021404.GI23783@niof.net> References: <481695.95012.qm@web32405.mail.mud.yahoo.com> <20071008021404.GI23783@niof.net> Message-ID: <4709AD2F.2090209@alchemy.com> Rick Pasotto wrote: > (ip,fqdn) = line.split(',') > updatequery = "update resultstable set %s where ip = %s" % (fqdn,ip) > cursor.execute(updatequery) > connection.close() > > Alternatively you could do: > > connection = MySQLdb.connect(db=self.todatabase,host-self.host, > user=self.user, passwd=self.passwd, port=int(self.port)) > cursor = connection.cursor() > updatequery = "update resultstable set %s where ip = %s" > for line in inputlist: > vals = list(line.split(',')) > vals.reverse() > cursor.execute(updatequery,vals) > connection.close() > > I think the second version is more efficient. Not only is it more efficient, I'd say it's the ONLY way you should be doing this. using % to splice the data values into the SQL query string itself is fraught with problems, SQL injection vulnerability and getting proper data syntax being the most obvious ones. Letting the MySQL module do it for you, by using %s (and ONLY %s regardless of data type!) where you want data to go, and supplying a list of values to cursor.execute(), lets the library code properly escape and quote the data as appropriate. It understands things like datetime, float, string, None, etc. natively which is a big win. From mogmios at mlug.missouri.edu Mon Oct 8 12:03:37 2007 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 8 Oct 2007 04:03:37 -0600 Subject: [Tutor] Top Programming Languages of 2013 In-Reply-To: <20071007060510.5DC811E4006@bag.python.org> References: <20071007060510.5DC811E4006@bag.python.org> Message-ID: <58d0a7010710080303y4e247282jaef5bef3c7253181@mail.gmail.com> I'd guess that by 2013 we'll be using a slightly more graceful, but still horribly wrong (and unsupported by IE 7.666), redo of HTML, CSS, Javascript, Flash, and Java with a poorly conceived back-end marriage of PHP + MySQL or some horrible Microsoft technology for most apps. I'll also venture that as great as Python is it won't have settled on a really good web development framework by then because half it's fans want to copy bloat like Ruby on Rails or .NET and the other half want to be able to develop every line of code themselves and none of them can agree on a single stable easy-to-use Pythonic platform. We still won't have a Python-based Javascript replacement either because nobody can get motivated to replace the crappy client-side scripting language web developers have come to know and hate. 2013 isn't that far away. A few buzzwords will become boring by then and we'll mostly be doing what we're doing now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071008/9fd54a59/attachment.htm From hrhan at att.net Mon Oct 8 16:50:02 2007 From: hrhan at att.net (Howard Hansen) Date: Mon, 08 Oct 2007 09:50:02 -0500 Subject: [Tutor] newbie: Django suited for database driven web application? In-Reply-To: <47030120.5040905@tds.net> References: <13010754.post@talk.nabble.com> <47030120.5040905@tds.net> Message-ID: <470A439A.9030301@att.net> Kent Johnson wrote: > cuongvt wrote: > >> Hello >> I'm new to both Django and Python. I'm mainly developing on PHP. >> I tend to move to Django. But I want to confirm as below: >> I heard that Django is mainly used for something like content management, >> CMS or something >> like that and Rails is mainly for web applications. >> So my question: is it true or not? >> > > No. > >> For rapid web application development, can I use Django to create intranet >> database web driven >> application in my company for example: empoyees time management, goods >> import/export management, >> salary management etc? >> > > I don't know why not! > > Look here for many examples of Django sites: > http://www.djangosites.org/latest/ > > Here is the one I work on: > http://blogcosm.com > > Here is a small catalog site: > http://www.americanpersonalizedproducts.com/ > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Additional information on Django may be found in the book "Python Frameworks, Web 2.0 Programming with Django and Turbogears" by D. Moore, R. Budd and W. Wright Howard From brunson at brunson.com Mon Oct 8 16:58:21 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 08 Oct 2007 08:58:21 -0600 Subject: [Tutor] Logging with proper format In-Reply-To: <47094261.1050306@tds.net> References: <310572.59936.qm@web32403.mail.mud.yahoo.com> <47093F43.4040503@brunson.com> <47094261.1050306@tds.net> Message-ID: <470A458D.6020604@brunson.com> Kent Johnson wrote: > Eric Brunson wrote: > >> claxo wrote: >> >>> dont indent the line after '\', that means 0 indent >>> >>> s = 'hello\ >>> boy' >>> >>> >> Or, arguably better: >> >> s = '''hello >> boy''' >> > > That is a different string, it contains a newline, the original does not: > > In [20]: s = 'hello\ > ....: boy' > In [21]: s2 = '''hello > ....: boy''' > In [22]: s==s2 > Out[22]: False > In [23]: print s > helloboy > In [24]: print s2 > hello > boy > You're right. I though he was looking to embed the newline, but I read it wrong. > > Kent > From sanelson at gmail.com Mon Oct 8 19:55:35 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Mon, 8 Oct 2007 18:55:35 +0100 Subject: [Tutor] Fwd: Permission Report In-Reply-To: References: Message-ID: Sorry... ---------- Forwarded message ---------- From: Stephen Nelson-Smith Date: Oct 8, 2007 6:54 PM Subject: Re: [Tutor] Permission Report To: Alan Gauld On 10/8/07, Alan Gauld wrote: > Yes, os.walk and os.stat should do what you want. Ok - I have: import os, stat permissions = {} for dir, base, files in os.walk('/home/peter/third/accounts/'): for f in files: file = os.path.join(dir, f) perm = os.stat(file)[stat.ST_MODE] permissions[file] = oct(stat.S_IMODE(perm)) This is fine - it stores the info I need. But if I want to run the same procedure on a remote host, and store the results in a dictionary so they can be compared, what would I do? S. From wormwood_3 at yahoo.com Mon Oct 8 20:24:04 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 8 Oct 2007 11:24:04 -0700 (PDT) Subject: [Tutor] Updating MySQL Database Message-ID: <877314.42477.qm@web32406.mail.mud.yahoo.com> Thanks to everyone who responded for the information and tips. * That line I had: > for line in inputlist: > updatequery = "update resultstable set fqdn = line.split(",")[1] where ip = line.split(",")[0];" was totally bogus. I was typing and thinking, and not at the same rate:-) The real thing would be something more like: for line in inputlist: fqdn = line.split(",")[1] ip = line.split(",")[0] updatequery = "update resultstable set fqdn = '%s' where ip = '%s';" % (fqdn, ip) * I will try a first version with a single connection and close, looping through executes in the middle. Should have thought of that first... Thanks again, Sam _____________________________________ ----- Original Message ---- From: Eric Walstad To: wormwood_3 Cc: Python Tutorlist Sent: Sunday, October 7, 2007 11:07:12 PM Subject: Re: [Tutor] Updating MySQL Database Hey Sam, wormwood_3 wrote: > Hello all, > > I have a script which takes data from a file or MySQL DB, looks up some stuff, then can print results to console or file. I would also like it to be able to update a MySQL database with the results. Does anyone have any ideas on how to do this? I can update records just fine, but what is the best way to do LOTS of updates aside from running an update statement per record? I recommend not worrying about speed on your first iteration of your script. I'd first define 'too slow', then write the script the way that feels intuitive to you. If your script passes your threshold of 'too slow', then look at optimizing it. If optimization is really necessary, I'd look into .executemany(). If that is still too slow for you then I'd consider writing the update SQL to a file and then calling mysql, passing it the sql file your script created. I found this last approach the fastest for a data import script I once wrote for importing millions of records to a PostgreSQL database. -E From brunson at brunson.com Mon Oct 8 21:01:28 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 08 Oct 2007 13:01:28 -0600 Subject: [Tutor] Updating MySQL Database In-Reply-To: <877314.42477.qm@web32406.mail.mud.yahoo.com> References: <877314.42477.qm@web32406.mail.mud.yahoo.com> Message-ID: <470A7E88.8080504@brunson.com> wormwood_3 wrote: > Thanks to everyone who responded for the information and tips. > > * That line I had: > >> for line in inputlist: >> updatequery = "update resultstable set fqdn = line.split(",")[1] where ip = line.split(",")[0];" >> > > was totally bogus. I was typing and thinking, and not at the same rate:-) The real thing would be something more like: > > for line in inputlist: > fqdn = line.split(",")[1] > ip = line.split(",")[0] > updatequery = "update resultstable set fqdn = '%s' where ip = '%s';" % (fqdn, ip) > > * I will try a first version with a single connection and close, looping through executes in the middle. Should have thought of that first... > Let me add another point to the "don't put your bind variables in the statement yourself" camp, like you're doing. If the database supports prepared statements, the db module will offer the statement without specific values to the database which will then preprocess and cache the prepared statement. Then, when you call the statement repeatedly with different bind variables, the database will be able to pull the preprocessed statement from cache and bind the variable values to it, saving the overhead of "compiling" the statement repeatedly. I don't believe mysql supports this, I know Oracle does, but no matter, don't do: updatequery = "update resultstable set fqdn = '%s' where ip = '%s'" % (fqdn, ip) curs.execute( updatequery ) do updatequery = "update resultstable set fqdn = %s where ip = %s" curs.execute( updatequery, ( fqdn, ip ) ) Hope that helps, e. P.S. you don't need the semicolon. > Thanks again, > Sam > > _____________________________________ > ----- Original Message ---- > From: Eric Walstad > To: wormwood_3 > Cc: Python Tutorlist > Sent: Sunday, October 7, 2007 11:07:12 PM > Subject: Re: [Tutor] Updating MySQL Database > > Hey Sam, > wormwood_3 wrote: > >> Hello all, >> >> I have a script which takes data from a file or MySQL DB, looks up some stuff, then can print results to console or file. I would also like it to be able to update a MySQL database with the results. Does anyone have any ideas on how to do this? I can update records just fine, but what is the best way to do LOTS of updates aside from running an update statement per record? >> > > I recommend not worrying about speed on your first iteration of your > script. I'd first define 'too slow', then write the script the way that > feels intuitive to you. If your script passes your threshold of 'too > slow', then look at optimizing it. > > If optimization is really necessary, I'd look into .executemany(). If > that is still too slow for you then I'd consider writing the update SQL > to a file and then calling mysql, passing it the sql file your script > created. I found this last approach the fastest for a data import > script I once wrote for importing millions of records to a PostgreSQL > database. > > -E > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cappy2112 at gmail.com Mon Oct 8 22:57:00 2007 From: cappy2112 at gmail.com (Tony Cappellini) Date: Mon, 8 Oct 2007 13:57:00 -0700 Subject: [Tutor] os.rename anomaly in Python 2.3 on Windows XP Message-ID: <8249c4ac0710081357u2ccdffe0j34f0470cc46ef62e@mail.gmail.com> Using Windows XP, SP2 and Python 2.3 I've written a script which walks through a bunch of directories and replaces characters which are typically illegals as filenames, with an '_' character. The directories are part of a package of software which is released by a group of people from Japan, and as such, they use their own character set (probably Kanji). However, most of the time, there are only 1 or 2 directories with unknown or illegal characters, as determined by my system (which does not use the Kanji characters). When my script encounters a directory with the unwanted characters, it's easy to detect them and filter them out. The next step is to rename the file to get rid of the problem characters. However, recently when I called os.rename(oldname, newname) an OS exception was thrown with "Illegal filename". I was able to narrow it down to oldname being the cause of the problem. Some of the characters showed up as ? in the Python strings. Oddly enough, os.rename() cannot perform the renaming of the directories, but I can do this manually in File Explorer or even in a CMD console using "rename" So what is os.renaming() actually calling on a Windows system, that won't allow me to rename dirs with illegal characters? From rdm at rcblue.com Tue Oct 9 03:01:14 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 08 Oct 2007 18:01:14 -0700 Subject: [Tutor] print question Message-ID: <20071009010118.B3A8C1E4008@bag.python.org> def secsToHMS(seconds): """ Convert seconds to hours:minutes:seconds, with seconds rounded to nearest hundredths of a second, and print """ hours, minutes = 0, 0 if seconds >= 60 and seconds < 3600: minutes, seconds = divmod(seconds, 60) elif seconds >= 3600: hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) seconds = str(round(seconds,2)) print "%d:%d:%s" % (int(hours), int(minutes), seconds) secsToHMS(18456.876012) This prints 5:7:36.88 What's the best way to get hours in 2 or more digits, and minutes in 2 digits, so that the above would be 05:07:36.88? (I'm writing a stopwatch.) Thanks, Dick Moores From john at fouhy.net Tue Oct 9 03:24:40 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 9 Oct 2007 14:24:40 +1300 Subject: [Tutor] print question In-Reply-To: <20071009010118.B3A8C1E4008@bag.python.org> References: <20071009010118.B3A8C1E4008@bag.python.org> Message-ID: <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> On 09/10/2007, Dick Moores wrote: > What's the best way to get hours in 2 or more digits, and minutes in > 2 digits, so that the above would be 05:07:36.88? (I'm writing a stopwatch.) String formatting! >>> template = '%02d:%02d:%02d.%02d' >>> template % (1, 22, 3, 44) '01:22:03.44' -- John. From witham.ian at gmail.com Tue Oct 9 03:27:33 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 9 Oct 2007 14:27:33 +1300 Subject: [Tutor] print question In-Reply-To: <20071009010118.B3A8C1E4008@bag.python.org> References: <20071009010118.B3A8C1E4008@bag.python.org> Message-ID: On 10/9/07, Dick Moores wrote: > > def secsToHMS(seconds): > """ > Convert seconds to hours:minutes:seconds, with seconds rounded > to nearest hundredths of a second, and print > """ > hours, minutes = 0, 0 > if seconds >= 60 and seconds < 3600: > minutes, seconds = divmod(seconds, 60) > elif seconds >= 3600: > hours, seconds = divmod(seconds, 3600) > minutes, seconds = divmod(seconds, 60) > seconds = str(round(seconds,2)) > print "%d:%d:%s" % (int(hours), int(minutes), seconds) > > secsToHMS(18456.876012) > > This prints 5:7:36.88 > > What's the best way to get hours in 2 or more digits, and minutes in > 2 digits, so that the above would be 05:07:36.88? (I'm writing a > stopwatch.) The string formatting operators you have used ("%d:%d:%s") can be altered with certain flags to give you the desired output. The relevant documentation is here The example near the top of the page shows how to pad the output with leading zeros. Good luck. Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071009/d76f98ae/attachment-0001.htm From chukgoodin at gmail.com Tue Oct 9 03:50:33 2007 From: chukgoodin at gmail.com (Chuk Goodin) Date: Mon, 8 Oct 2007 18:50:33 -0700 Subject: [Tutor] Nested list access? Message-ID: <5bfe5dce0710081850p70b49da6ifafcf0d1c532f4ce@mail.gmail.com> I've got a bit of code here that's giving me some trouble. I am trying to make a 2 dimensional array with nested lists, but when I try to change one element, it changes all the elements in that "column". --begin code-- width = 7 depth = 6 board = [['.']*width]*depth def printBoard(board): 'Prints out the 6 x 7 board' for i in board: #print board for j in i: print j, print return printBoard(board) print board[0][4]='X' #I think this is the line I'm having trouble with print board printBoard(board) --end code-- Here's some of the output in question: . . . . X . . . . . . X . . . . . . X . . . . . . X . . . . . . X . . . . . . X . . I'm trying to get it to make only one 'X'. Any hints? it feels kind of like a syntax error on my part... -- chuk From john at fouhy.net Tue Oct 9 04:00:41 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 9 Oct 2007 15:00:41 +1300 Subject: [Tutor] Nested list access? In-Reply-To: <5bfe5dce0710081850p70b49da6ifafcf0d1c532f4ce@mail.gmail.com> References: <5bfe5dce0710081850p70b49da6ifafcf0d1c532f4ce@mail.gmail.com> Message-ID: <5e58f2e40710081900u3b15c6b4hbc3cebda18db4aa1@mail.gmail.com> On 09/10/2007, Chuk Goodin wrote: > I've got a bit of code here that's giving me some trouble. I am trying > to make a 2 dimensional array with nested lists, but when I try to > change one element, it changes all the elements in that "column". > > I'm trying to get it to make only one 'X'. Any hints? it feels kind of > like a syntax error on my part... Nah, it's more subtle than that. This is your problem here: > board = [['.']*width]*depth Let's break this up a bit: row = ['.']*width board = [row]*depth This gives you a list that looks like this: [row, row, row, row, row, row, row] You see that? Every interior list is the _same list_. So when you change one, you change them all (because there is only one there to change). You need to make a new list for each row. You could do that in a loop: board = [] for i in range(depth): board.append(['.']*width) or, more compactly, in a list comprehension: board = [['.']*width for i in range(depth)] BTW, when you write ['.']*width, that gives you a list with `width` copies of the same string. But it doesn't matter because strings are immutable. HTH! -- John. From rabidpoobear at gmail.com Tue Oct 9 04:09:56 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 08 Oct 2007 21:09:56 -0500 Subject: [Tutor] os.rename anomaly in Python 2.3 on Windows XP In-Reply-To: <8249c4ac0710081357u2ccdffe0j34f0470cc46ef62e@mail.gmail.com> References: <8249c4ac0710081357u2ccdffe0j34f0470cc46ef62e@mail.gmail.com> Message-ID: <470AE2F4.9000208@gmail.com> Tony Cappellini wrote: > Using Windows XP, SP2 and Python 2.3 > > I've written a script which walks through a bunch of directories and > replaces characters which are typically illegals as filenames, with an > '_' character. > > The directories are part of a package of software which is released by > a group of people from Japan, and as such, they use their own > character set (probably Kanji). However, most of the time, there are > only 1 or 2 directories with unknown or illegal characters, as > determined by > my system (which does not use the Kanji characters). > > When my script encounters a directory with the unwanted characters, > it's easy to detect them and filter them out. The next step is to > rename the file to get rid of the problem characters. > > However, recently when I called os.rename(oldname, newname) an OS > exception was thrown with "Illegal filename". I was able to narrow it > down to oldname being the cause of the problem. > Some of the characters showed up as ? in the Python strings. > > Oddly enough, os.rename() cannot perform the renaming of the > directories, but I can do this manually in File Explorer or even in a > CMD console using "rename" > > So what is os.renaming() actually calling on a Windows system, that > won't allow me to rename dirs with illegal characters? > Sounds like it has something to do with Unicode. Your filenames aren't being interpreted correctly. Perhaps os.listdir is giving you the UTF-8 versions rather than the Unicode versions of the filenames? -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rdm at rcblue.com Tue Oct 9 04:15:44 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 08 Oct 2007 19:15:44 -0700 Subject: [Tutor] print question In-Reply-To: <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.co m> References: <20071009010118.B3A8C1E4008@bag.python.org> <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> Message-ID: <20071009021557.9DC381E4008@bag.python.org> At 06:24 PM 10/8/2007, John Fouhy wrote: >On 09/10/2007, Dick Moores wrote: > > What's the best way to get hours in 2 or more digits, and minutes in > > 2 digits, so that the above would be 05:07:36.88? (I'm writing a > stopwatch.) > >String formatting! > > >>> template = '%02d:%02d:%02d.%02d' > >>> template % (1, 22, 3, 44) >'01:22:03.44' Thanks! So now I have def secsToHMS(seconds): """ Convert seconds to hours:minutes:seconds, with seconds rounded to hundredths of a second, and print """ hours, minutes = 0, 0 if seconds >= 60 and seconds < 3600: minutes, seconds = divmod(seconds, 60) elif seconds >= 3600: hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) seconds = str(round(seconds,2)).split('.') print seconds print seconds[0] hundredths = seconds[1] print hundredths print "%02d:%02d:%02d.%02d" % (int(hours), int(minutes), int(seconds[0]), int(seconds[1])) secsToHMS(4789.3459876) Which prints 01:19:49.35 Any improvements in the function to suggest? Dick From kent37 at tds.net Tue Oct 9 04:30:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 08 Oct 2007 22:30:20 -0400 Subject: [Tutor] print question In-Reply-To: <20071009021557.9DC381E4008@bag.python.org> References: <20071009010118.B3A8C1E4008@bag.python.org> <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> <20071009021557.9DC381E4008@bag.python.org> Message-ID: <470AE7BC.7020700@tds.net> Dick Moores wrote: > At 06:24 PM 10/8/2007, John Fouhy wrote: >> On 09/10/2007, Dick Moores wrote: >>> What's the best way to get hours in 2 or more digits, and minutes in >>> 2 digits, so that the above would be 05:07:36.88? (I'm writing a >> stopwatch.) >> >> String formatting! >> >>>>> template = '%02d:%02d:%02d.%02d' >>>>> template % (1, 22, 3, 44) >> '01:22:03.44' > > Thanks! > > So now I have > > def secsToHMS(seconds): > """ > Convert seconds to hours:minutes:seconds, with seconds rounded > to hundredths of a second, and print > """ > hours, minutes = 0, 0 > if seconds >= 60 and seconds < 3600: > minutes, seconds = divmod(seconds, 60) > elif seconds >= 3600: You don't need this conditional, just use the next two lines unconditionally. If seconds<3600 it will still do the right thing. > hours, seconds = divmod(seconds, 3600) > minutes, seconds = divmod(seconds, 60) > seconds = str(round(seconds,2)).split('.') You don't have to split the seconds, look at the %f formatting operator. Kent > print seconds > print seconds[0] > hundredths = seconds[1] > print hundredths > > print "%02d:%02d:%02d.%02d" % (int(hours), int(minutes), > int(seconds[0]), int(seconds[1])) > > secsToHMS(4789.3459876) > > Which prints 01:19:49.35 > > Any improvements in the function to suggest? > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From witham.ian at gmail.com Tue Oct 9 04:45:26 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 9 Oct 2007 15:45:26 +1300 Subject: [Tutor] print question In-Reply-To: <20071009021557.9DC381E4008@bag.python.org> References: <20071009010118.B3A8C1E4008@bag.python.org> <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> <20071009021557.9DC381E4008@bag.python.org> Message-ID: > > > Thanks! > > So now I have > > def secsToHMS(seconds): > """ > Convert seconds to hours:minutes:seconds, with seconds rounded > to hundredths of a second, and print > """ > hours, minutes = 0, 0 > if seconds >= 60 and seconds < 3600: > minutes, seconds = divmod(seconds, 60) > elif seconds >= 3600: > hours, seconds = divmod(seconds, 3600) > minutes, seconds = divmod(seconds, 60) > seconds = str(round(seconds,2)).split('.') > print seconds > print seconds[0] > hundredths = seconds[1] > print hundredths > > print "%02d:%02d:%02d.%02d" % (int(hours), int(minutes), > int(seconds[0]), int(seconds[1])) > > secsToHMS(4789.3459876) > > Which prints 01:19:49.35 > > Any improvements in the function to suggest? Don't need that conditional. Try this: minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) and you don't need the 'hundredths"... hours and minutes are already integers (you don't need to convert them to int in your string formatting) and seconds is a float. (if you supplied a float to the function) Try %f for formatting a float. With these changes you could get your function down to 3 or 4 lines of code. Also, it is generally better form to return a value than to have the function do the printing, then you could print the result like this: print secsToHMS(4789.3459876) Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071009/62855c51/attachment.htm From rdm at rcblue.com Tue Oct 9 07:33:03 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 08 Oct 2007 22:33:03 -0700 Subject: [Tutor] print question In-Reply-To: <470AE7BC.7020700@tds.net> References: <20071009010118.B3A8C1E4008@bag.python.org> <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> <20071009021557.9DC381E4008@bag.python.org> <470AE7BC.7020700@tds.net> Message-ID: <20071009053306.726441E4008@bag.python.org> Thanks, Kent and Ian. See below. At 07:30 PM 10/8/2007, Kent Johnson wrote: >> if seconds >= 60 and seconds < 3600: >> minutes, seconds = divmod(seconds, 60) >> elif seconds >= 3600: > >You don't need this conditional, just use the next two lines >unconditionally. If seconds<3600 it will still do the right thing. > >> hours, seconds = divmod(seconds, 3600) >> minutes, seconds = divmod(seconds, 60) >> seconds = str(round(seconds,2)).split('.') > >You don't have to split the seconds, look at the %f formatting operator. def secsToHMS(seconds): """ Convert seconds to hours:minutes:seconds, with seconds rounded to hundredths of a second """ minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return "%02d:%02d:%2.2f" % (hours, minutes, seconds) print secsToHMS(87154.04987) --> 24:12:34.05 (what I wanted) print secsToHMS(154.04987) --> 00:02:34.05 (what I wanted) but print secsToHMS(4.04987) --> 00:00:4.05 (I wanted 00:00:04.05) I don't see how to get 00:00:04.05 using %f . is as clear as mud. Dick >Kent > >> print seconds >> print seconds[0] >> hundredths = seconds[1] >> print hundredths >> print "%02d:%02d:%02d.%02d" % (int(hours), int(minutes), >> int(seconds[0]), int(seconds[1])) >>secsToHMS(4789.3459876) >>Which prints 01:19:49.35 >>Any improvements in the function to suggest? >>Dick >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Oct 9 09:58:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Oct 2007 08:58:56 +0100 Subject: [Tutor] print question References: <20071009010118.B3A8C1E4008@bag.python.org><5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com><20071009021557.9DC381E4008@bag.python.org><470AE7BC.7020700@tds.net> <20071009053306.726441E4008@bag.python.org> Message-ID: "Dick Moores" wrote > return "%02d:%02d:%2.2f" % (hours, minutes, seconds) > print secsToHMS(4.04987) --> 00:00:4.05 (I wanted 00:00:04.05) > > I don't see how to get 00:00:04.05 using %f . > is as > clear as mud. > %f is like this: .f If you provide a - sign it left justifies, without a minus right justifies The minimum width includes the decimal point. So in your case you want 2 + 1 + 2 = 5 decimal places is number of digits after the point So you need: %5.2f HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Tue Oct 9 10:15:39 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 09 Oct 2007 01:15:39 -0700 Subject: [Tutor] print question In-Reply-To: References: <20071009010118.B3A8C1E4008@bag.python.org> <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> <20071009021557.9DC381E4008@bag.python.org> <470AE7BC.7020700@tds.net> <20071009053306.726441E4008@bag.python.org> Message-ID: <20071009081547.94FF91E4009@bag.python.org> At 12:58 AM 10/9/2007, Alan Gauld wrote: >"Dick Moores" wrote > > > return "%02d:%02d:%2.2f" % (hours, minutes, seconds) > > > print secsToHMS(4.04987) --> 00:00:4.05 (I wanted 00:00:04.05) > > > > I don't see how to get 00:00:04.05 using %f . > > is as > > clear as mud. > > > >%f is like this: > >.f > >If you provide a - sign it left justifies, without a minus right >justifies > >The minimum width includes the decimal point. So in your case >you want 2 + 1 + 2 = 5 > >decimal places is number of digits after the point > >So you need: > >%5.2f Well, I'm getting closer, but still no cigar: def secsToHMS(seconds): """ Convert seconds to hours:minutes:seconds, with seconds rounded to hundredths of a second """ #hours, minutes = 0, 0 minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return "%02d:%02d:%5.2f" % (hours, minutes, seconds) print secsToHMS(4.04987) This prints 00:00: 4.05 not 00:00:04.05 Dick From mail at timgolden.me.uk Tue Oct 9 11:33:38 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 09 Oct 2007 10:33:38 +0100 Subject: [Tutor] os.rename anomaly in Python 2.3 on Windows XP In-Reply-To: <8249c4ac0710081357u2ccdffe0j34f0470cc46ef62e@mail.gmail.com> References: <8249c4ac0710081357u2ccdffe0j34f0470cc46ef62e@mail.gmail.com> Message-ID: <470B4AF2.6050709@timgolden.me.uk> Tony Cappellini wrote: > Using Windows XP, SP2 and Python 2.3 > > I've written a script which walks through a bunch of directories and > replaces characters which are typically illegals as filenames, with an > '_' character. [...] > When my script encounters a directory with the unwanted characters, > it's easy to detect them and filter them out. The next step is to > rename the file to get rid of the problem characters. [...] > However, recently when I called os.rename(oldname, newname) an OS > exception was thrown with "Illegal filename". I was able to narrow it > down to oldname being the cause of the problem. > Some of the characters showed up as ? in the Python strings. > > Oddly enough, os.rename() cannot perform the renaming of the > directories, but I can do this manually in File Explorer or even in a > CMD console using "rename" > > So what is os.renaming() actually calling on a Windows system, that > won't allow me to rename dirs with illegal characters? Well, the simple answer to that is (cut-and-pasted and snipped a bit) from the posixmodule.c source: if (unicode_file_names()) { ... result = MoveFileW(PyUnicode_AsUnicode(o1), PyUnicode_AsUnicode(o2)); ... result = MoveFileA(p1, p2); so it's using the MoveFileW with two unicode filenames, or the MoveFileA with two non-unicode filenames. So... are you calling os.rename with unicode or non-unicode filenames? If you're using, say, os.walk or os.listdir to walk your tree, pass it a unicode path to start with, and the filenames coming back will also be unicode. Try this, for example: import os, sys # # filename with random non-ascii char # filename = u"abc\u0123.txt" open (filename, "w").close () for i in os.listdir (u"."): print i.encode (sys.stdout.encoding, "replace") new_filename = unicode (filename.encode ("ascii", "replace").replace ("?", "_")) os.rename (filename, new_filename) for i in os.listdir (u"."): print i The filename with the random unicode char is shown (with the fill-in question-mark) in the initial list. It's then renamed with the non-ascii char replaced by "_" and appears without an encoding in the final list. I think this is what you're after. TJG From python at kapitalisten.no Tue Oct 9 11:30:09 2007 From: python at kapitalisten.no (=?iso-8859-15?Q?=D8yvind?=) Date: Tue, 9 Oct 2007 11:30:09 +0200 (CEST) Subject: [Tutor] Increase speed Message-ID: <39934.57.66.51.2.1191922209.squirrel@mail.sporck.net> Hello. I have written a simple application that does a number of simple calculations. In psudo-code it looks something like below. The program works fine. However, it seems like I need a supercomputer to finish the resultwithin a reasonable timeframe, as the var.txt contains a lot of variables that has to be computed. And, since my budget doesn't include a supercomputer, I need to optimize the script. I have been able to half the running-time by flushing the file more seldom, and a little more by try and fail. However, half is still a looong time. I would like to increase the speed even more. Does anyone have any suggestions of what I should do? Is Stackless Python an option? Is there some other steps I could take? Some basic steps? Thanks in advance, ?yvind class start: filles = open("var.txt","r") into memory def oppned(self): return randint(0,1) def verdier(self): increase variable x and y def verdi(self): for i in filles: generate random from oppned simple calculation if result 1: write result if result 2: generate new random, calculate more write result if result 3: write result, use new variable if __name__ == '__main__': n = start() for x in range(0,10000): n.verdier() for y in range(0,100): n.verdi() n.fil.write(result) if variable x > 0.32: break -- This email has been scanned for viruses & spam by Domenebutikken - www.domenebutikken.no Denne e-posten er sjekket for virus & spam av Domenebutikken - www.domenebutikken.no From kent37 at tds.net Tue Oct 9 12:37:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Oct 2007 06:37:44 -0400 Subject: [Tutor] print question In-Reply-To: <20071009081547.94FF91E4009@bag.python.org> References: <20071009010118.B3A8C1E4008@bag.python.org> <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> <20071009021557.9DC381E4008@bag.python.org> <470AE7BC.7020700@tds.net> <20071009053306.726441E4008@bag.python.org> <20071009081547.94FF91E4009@bag.python.org> Message-ID: <470B59F8.8010506@tds.net> Dick Moores wrote: > return "%02d:%02d:%5.2f" % (hours, minutes, seconds) Try %05.2f The leading 0 is a 'conversion flag' that specifies zero-padding. Kent From samirgimlilegolas at hotmail.com Tue Oct 9 10:24:35 2007 From: samirgimlilegolas at hotmail.com (samir amassine) Date: Tue, 9 Oct 2007 10:24:35 +0200 Subject: [Tutor] Sqrt on a variable In-Reply-To: <244437.59832.qm@web61219.mail.yahoo.com> References: <244437.59832.qm@web61219.mail.yahoo.com> Message-ID: hello, i can't seem to use the sqrt function on a variable, do you know how i can???i want to make the ABC formulaSamir _________________________________________________________________ Probeer Live.nl Probeer Live.nl: zoekmachine van de makers van MSN! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071009/efd693dc/attachment.htm From kent37 at tds.net Tue Oct 9 12:49:15 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Oct 2007 06:49:15 -0400 Subject: [Tutor] Increase speed In-Reply-To: <39934.57.66.51.2.1191922209.squirrel@mail.sporck.net> References: <39934.57.66.51.2.1191922209.squirrel@mail.sporck.net> Message-ID: <470B5CAB.2010408@tds.net> ?yvind wrote: > Hello. > > I have written a simple application that does a number of simple > calculations. In psudo-code it looks something like below. I think this is the first time I have ever been asked to optimize code without looking at the code! It's hard to optimize pseudo-code. Can you show the real code? I will make some general suggestions. > Does anyone have any suggestions of what I should do? Is Stackless Python > an option? Is there some other steps I could take? Some basic steps? AFAIK Stackless is not faster for single-threaded calculations. Unfortunately heavy-duty number crunching is not a strong point of Python (because every operation requires a virtual method call). Try psyco. Use numpy if you can. Move the calculations into C code (maybe with pyrex). Move loop control into C code by using list comprehension or map. Reduce the number of name lookups. Make names local. Kent > > Thanks in advance, > ?yvind > > class start: > > filles = open("var.txt","r") into memory > > def oppned(self): > return randint(0,1) > > def verdier(self): > increase variable x and y > > def verdi(self): > for i in filles: > generate random from oppned > simple calculation > > if result 1: > write result > > if result 2: > generate new random, calculate more > write result > > if result 3: > write result, use new variable > > if __name__ == '__main__': > n = start() > for x in range(0,10000): > n.verdier() > for y in range(0,100): > n.verdi() > > n.fil.write(result) > if variable x > 0.32: > break > > > From rdm at rcblue.com Tue Oct 9 12:50:09 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 09 Oct 2007 03:50:09 -0700 Subject: [Tutor] print question In-Reply-To: <470B59F8.8010506@tds.net> References: <20071009010118.B3A8C1E4008@bag.python.org> <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> <20071009021557.9DC381E4008@bag.python.org> <470AE7BC.7020700@tds.net> <20071009053306.726441E4008@bag.python.org> <20071009081547.94FF91E4009@bag.python.org> <470B59F8.8010506@tds.net> Message-ID: <20071009105016.BBAB41E4008@bag.python.org> At 03:37 AM 10/9/2007, Kent Johnson wrote: >Dick Moores wrote: >> return "%02d:%02d:%5.2f" % (hours, minutes, seconds) > >Try %05.2f > >The leading 0 is a 'conversion flag' that specifies zero-padding. Huh. Thought I'd tried that. Guess not. Thanks, Kent! From rabidpoobear at gmail.com Tue Oct 9 13:19:13 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 09 Oct 2007 06:19:13 -0500 Subject: [Tutor] Sqrt on a variable In-Reply-To: References: <244437.59832.qm@web61219.mail.yahoo.com> Message-ID: <470B63B1.8070308@gmail.com> samir amassine wrote: > hello, > i can't seem to use the sqrt function on a variable, do you know how i > can??? > i want to make the ABC formula > > Samir Samir - Next time you ask the list a question, please include some information about what you've already tried and why you think it didn't work, and if it did work, why it didn't meet your expectations. We can just give you the answer, but so could google or various other sources. If you show us what you've tried, we can glean from that what problem you're having, and find a way to explain how to fix it in a way we think you'll understand. To answer your question, try typing the following two lines into the interactive interpreter (Python shell) >>> import math >>> help(math.sqrt) The help() function reads the documentation strings from functions so you can get an explanation of how to use them. HTH, -Luke From ksterling at mindspring.com Tue Oct 9 15:11:06 2007 From: ksterling at mindspring.com (Ken Oliver) Date: Tue, 9 Oct 2007 09:11:06 -0400 (EDT) Subject: [Tutor] Sqrt on a variable Message-ID: <7539895.1191935466761.JavaMail.root@mswamui-chipeau.atl.sa.earthlink.net> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071009/46dcee2e/attachment.htm From brunson at brunson.com Tue Oct 9 16:03:19 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 09 Oct 2007 08:03:19 -0600 Subject: [Tutor] Increase speed In-Reply-To: <39934.57.66.51.2.1191922209.squirrel@mail.sporck.net> References: <39934.57.66.51.2.1191922209.squirrel@mail.sporck.net> Message-ID: <470B8A27.5010503@brunson.com> ?yvind wrote: > Hello. > > I have written a simple application that does a number of simple > calculations. In psudo-code it looks something like below. > > The program works fine. However, it seems like I need a supercomputer to > finish the resultwithin a reasonable timeframe, as the var.txt contains a > lot of variables that has to be computed. And, since my budget doesn't > include a supercomputer, I need to optimize the script. I have been able > to half the running-time by flushing the file more seldom, and a little > more by try and fail. However, half is still a looong time. I would like > to increase the speed even more. > > Does anyone have any suggestions of what I should do? Is Stackless Python > an option? Is there some other steps I could take? Some basic steps? > I've had quite a bit of success using psyco (google it). It only works on x86 platforms and I was unsuccessful getting it compiled on Solaris 10 for x86, but I didn't try that hard, if you're on Linux you shouldn't have many problems. I saw speedups anywhere from 2 to 10 times, depending on the code. Hope that helps,e e. > Thanks in advance, > ?yvind > > class start: > > filles = open("var.txt","r") into memory > > def oppned(self): > return randint(0,1) > > def verdier(self): > increase variable x and y > > def verdi(self): > for i in filles: > generate random from oppned > simple calculation > > if result 1: > write result > > if result 2: > generate new random, calculate more > write result > > if result 3: > write result, use new variable > > if __name__ == '__main__': > n = start() > for x in range(0,10000): > n.verdier() > for y in range(0,100): > n.verdi() > > n.fil.write(result) > if variable x > 0.32: > break > > > > From alan.gauld at btinternet.com Tue Oct 9 16:17:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Oct 2007 15:17:32 +0100 Subject: [Tutor] print question References: <20071009010118.B3A8C1E4008@bag.python.org> <5e58f2e40710081824v4624e39bg111fcab9be53c340@mail.gmail.com> <20071009021557.9DC381E4008@bag.python.org> <470AE7BC.7020700@tds.net> <20071009053306.726441E4008@bag.python.org> <20071009081547.94FF91E4009@bag.python.org> <470B59F8.8010506@tds.net> Message-ID: "Kent Johnson" wrote in message news:470B59F8.8010506 at tds.net... > Dick Moores wrote: >> return "%02d:%02d:%5.2f" % (hours, minutes, seconds) > > Try %05.2f > > The leading 0 is a 'conversion flag' that specifies zero-padding. Sorry I should have included that in my post but I assumed it was "obvious" since thats what you did with the %d fields... Never assume: it makes an ass out of u and me... :-) Alan G From alan.gauld at btinternet.com Tue Oct 9 16:36:06 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Oct 2007 15:36:06 +0100 Subject: [Tutor] Increase speed References: <39934.57.66.51.2.1191922209.squirrel@mail.sporck.net> Message-ID: "?yvind" wrote > Does anyone have any suggestions of what I should do? Your pseudo code is a bit too pseudo to be useful for performance tuning. > class start: You don;t really need a class here, somple functions will suffice but won't make much difference to speed. > filles = open("var.txt","r") into memory Not sure what you mean by "into memory" here. Are you storing the open file handle or the contents of the file? > def oppned(self): > return randint(0,1) Since you only return randint you can do away with the function and its call overhead and just call randint directly. > def verdier(self): > increase variable x and y You don't specify how these are increased nor where they come from. If you mean the loop indices below then directly modifying loop items inside the loop can be a risky move leading to difficult to predict results. > def verdi(self): > for i in filles: This will either be a sequence of characers if you read the contents or a series of lines if you just stored the file object. Not sure which. Also, not knowing the format or content of the file makes it hard to guess what is going on! > generate random from oppned just use randint() > simple calculation > if result 1: > write result Where are you writing it to? stdout or to a file? If to a file are you open/closing it each write or do you open it once and only close at the end? Hopefu;lly its not the same file you are reading from, or things could get confused! > if result 2: > generate new random, calculate more > write result > > if result 3: > write result, use new variable As above. > if __name__ == '__main__': > n = start() Not needed if you do away with the class. > for x in range(0,10000): > n.verdier() This was supposed to change y. However y gets reset immediately by the loop. so it appears the y processing is wasted. for y in range(0,100): n.verdi() n.fil.write(result) n.fil was opened for reading not writing. if variable x > 0.32: break It might be easier if you just posted the code. Alan G. From wormwood_3 at yahoo.com Tue Oct 9 19:57:20 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 9 Oct 2007 10:57:20 -0700 (PDT) Subject: [Tutor] Missing LOTS of list messages Message-ID: <892607.54315.qm@web32401.mail.mud.yahoo.com> Hello tutors, I just discovered again that I am missing lots of messages from the list. Compared to this: http://www.nabble.com/Updating-MySQL-Database-t4585380.html where 8 messages are listed, my email client shows 5. They are not in spam, I just never got them. Since this is the third time I assume it is happening all the time. Has anyone else experienced this? I am using Yahoo! Mail, not sure if anyone experiences the same with other services... If anyone has ideas, I would welcome them. I hate the idea of missing great messages from the list (much less sending responses that have already been covered...) -Sam From kent37 at tds.net Tue Oct 9 20:11:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Oct 2007 14:11:19 -0400 Subject: [Tutor] Missing LOTS of list messages In-Reply-To: <892607.54315.qm@web32401.mail.mud.yahoo.com> References: <892607.54315.qm@web32401.mail.mud.yahoo.com> Message-ID: <470BC447.7040704@tds.net> wormwood_3 wrote: > Hello tutors, > > I just discovered again that I am missing lots of messages from the list. > > Has anyone else experienced this? I am using Yahoo! Mail, not sure if > anyone experiences the same with other services... I dunno about regular Yahoo! Mail, but the mail forwarding I get from their domain hosting is lousy, my mail regularly gets bounced. I have stopped giving out that email address. Maybe you should try Gmail? Ken From bhaaluu at gmail.com Tue Oct 9 21:02:30 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 9 Oct 2007 15:02:30 -0400 Subject: [Tutor] Missing LOTS of list messages In-Reply-To: <470BC447.7040704@tds.net> References: <892607.54315.qm@web32401.mail.mud.yahoo.com> <470BC447.7040704@tds.net> Message-ID: On 10/9/07, Kent Johnson wrote: > > Maybe you should try Gmail? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I think Gmail is a very good idea for mailing lists. 1. You get over 2.8GB of storage space. 2. Good Spam filter. 3. Seems to get all the Tutor list mail. 4. You can set up filters for incoming list mail. 5. Easy to organize (labels, filters, stars...) 6. Fantastic email search engine (based on Google, of course). 7. You no longer need an invitation for an email account. Back when I applied, I waited for about 6 months to get an invitation from Google. I'm sure there are other good reasons to get a Gmail account in addition to the ones I've mentioned above. Happy ['Python'] Programming! -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From mlangford.cs03 at gtalumni.org Tue Oct 9 21:49:59 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 9 Oct 2007 15:49:59 -0400 Subject: [Tutor] Increase speed In-Reply-To: <39934.57.66.51.2.1191922209.squirrel@mail.sporck.net> References: <39934.57.66.51.2.1191922209.squirrel@mail.sporck.net> Message-ID: <82b4f5810710091249h3e19d92dl79ec5e57d183b1bb@mail.gmail.com> You don't know what's slow. This is the perfect tool for a profiler. http://docs.python.org/lib/profile.html --Michael On 10/9/07, ?yvind wrote: > > Hello. > > I have written a simple application that does a number of simple > calculations. In psudo-code it looks something like below. > > The program works fine. However, it seems like I need a supercomputer to > finish the resultwithin a reasonable timeframe, as the var.txt contains a > lot of variables that has to be computed. And, since my budget doesn't > include a supercomputer, I need to optimize the script. I have been able > to half the running-time by flushing the file more seldom, and a little > more by try and fail. However, half is still a looong time. I would like > to increase the speed even more. > > Does anyone have any suggestions of what I should do? Is Stackless Python > an option? Is there some other steps I could take? Some basic steps? > > Thanks in advance, > ?yvind > > class start: > > filles = open("var.txt","r") into memory > > def oppned(self): > return randint(0,1) > > def verdier(self): > increase variable x and y > > def verdi(self): > for i in filles: > generate random from oppned > simple calculation > > if result 1: > write result > > if result 2: > generate new random, calculate more > write result > > if result 3: > write result, use new variable > > if __name__ == '__main__': > n = start() > for x in range(0,10000): > n.verdier() > for y in range(0,100): > n.verdi() > > n.fil.write(result) > if variable x > 0.32: > break > > > > -- > This email has been scanned for viruses & spam by Domenebutikken - > www.domenebutikken.no > Denne e-posten er sjekket for virus & spam av Domenebutikken - > www.domenebutikken.no > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071009/5c4b0a7d/attachment.htm From cappy2112 at gmail.com Wed Oct 10 02:08:37 2007 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 9 Oct 2007 17:08:37 -0700 Subject: [Tutor] os.rename anomaly in Python 2.3 on Windows XP In-Reply-To: <470AE2F4.9000208@gmail.com> References: <8249c4ac0710081357u2ccdffe0j34f0470cc46ef62e@mail.gmail.com> <470AE2F4.9000208@gmail.com> Message-ID: <8249c4ac0710091708g5845858eg9baa4722e1be2056@mail.gmail.com> Thanks. Unfortunately,os.listdir() returns the same string as glob.glob, for the problem file I mentioned. When I pass that string to os.rename() OSError: [Errno 22] Invalid argument > Sounds like it has something to do with Unicode. > Your filenames aren't being interpreted correctly. Perhaps os.listdir > is giving you the UTF-8 versions > rather than the Unicode versions of the filenames? > -Luke From witham.ian at gmail.com Wed Oct 10 02:30:59 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 10 Oct 2007 13:30:59 +1300 Subject: [Tutor] Sqrt on a variable In-Reply-To: References: <244437.59832.qm@web61219.mail.yahoo.com> Message-ID: On 10/9/07, samir amassine wrote: > > hello, > i can't seem to use the sqrt function on a variable, do you know how i > can??? > i want to make the ABC formula > > Samir > Hi Samir, You could import sqrt from the math module OR, you can do it without importing anything by raising to the power of a half. So, instead of using sqrt(x) you could use: x ** .5 Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071010/dabff093/attachment.htm From alan.gauld at btinternet.com Wed Oct 10 02:34:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Oct 2007 01:34:41 +0100 Subject: [Tutor] Missing LOTS of list messages References: <892607.54315.qm@web32401.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > I just discovered again that I am missing lots of messages from the > list. > Has anyone else experienced this? > I am using Yahoo! Mail, I use the gmane news interface rather than email but when people reply to me I get the replies via email at my Yahoo address (aka btinternet) and I've noticed several messages coming in several days after the thread has finished. For example I just got Erics post about extended slicing a few minutes ago but it was posted 9:00pm on Sunday night! So maybe you arenm't missing them its just taking a long time.... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ericlake at ubuntu.com Wed Oct 10 03:54:56 2007 From: ericlake at ubuntu.com (Eric Lake) Date: Tue, 9 Oct 2007 21:54:56 -0400 Subject: [Tutor] Finding a project Message-ID: <20071010015456.GA5889@localdomain> What is a good way to find a project to work on? I really want to work on something but I can not think of anything useful to write. I am interested in sysadmin stuff (backups, monitoring, etc). That being said I don't really have experience writing apps like that. But I really want to learn. -- Thanks Eric Lake -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 481 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20071009/1875787e/attachment.pgp From kent37 at tds.net Wed Oct 10 04:09:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 09 Oct 2007 22:09:47 -0400 Subject: [Tutor] Fwd: Permission Report In-Reply-To: References: Message-ID: <470C346B.2090304@tds.net> Stephen Nelson-Smith wrote: > But if I want to run the same procedure on a remote host, and store > the results in a dictionary so they can be compared, what would I do? What kind of access do you have to the remote host? If you have filesystem access you can use the same program running locally. By the way you dismissed rsync but it has both --verbose and --dry-run options which might give you what you want. I don't know if it will report differences in permissions. Kent From wormwood_3 at yahoo.com Wed Oct 10 04:36:09 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 9 Oct 2007 19:36:09 -0700 (PDT) Subject: [Tutor] Finding a project Message-ID: <499034.41848.qm@web32412.mail.mud.yahoo.com> When I started out (not long ago), I started working on projects I had the need for. I have done a lot of small sysadmin projects, and they have all been things I found I needed or would help me doing sysadmin work. Try to think of tasks you have to often do that are at all subject to automation. Even ones that seem like they might be hard to automate, might be a good target for a starting project. The good thing about working on sysadmin projects is that it is a well-travelled path. Someone has likely written something similar to what you need, so finding inspiration and help is not as hard as with other sorts of projects. If you really need inspiration, check out the Python Cookbook: http://aspn.activestate.com/ASPN/Python/Cookbook/ It has lots of great examples of relatively small things average people have completed in Python. Maybe you can start by finding several that do things you need, and write something to weave them together. Happy coding! -Sam ___________________________ ----- Original Message ---- From: Eric Lake To: Python Tutor mailing list Sent: Tuesday, October 9, 2007 9:54:56 PM Subject: [Tutor] Finding a project What is a good way to find a project to work on? I really want to work on something but I can not think of anything useful to write. I am interested in sysadmin stuff (backups, monitoring, etc). That being said I don't really have experience writing apps like that. But I really want to learn. -- Thanks Eric Lake From allen.fowler at yahoo.com Wed Oct 10 06:15:25 2007 From: allen.fowler at yahoo.com (Allen Fowler) Date: Tue, 9 Oct 2007 21:15:25 -0700 (PDT) Subject: [Tutor] Exceptions: Logging TB and local variables? Message-ID: <466702.38703.qm@web45610.mail.sp1.yahoo.com> Hi, My code looks like this: for item in bigset: self.__sub1(item) self.__sub2(item) self.__sub3(item) # the subX functions, in turn, use various 3rd party modules. Now, I would like to do this: for item in bigset: try: self.__sub1(item) self.__sub2(item) self.__sub3(item) except StandardError: # Log error and continue to next item in set. log_error_to_file() In the error log, I would like to record a stacktrace and various local variables that existed in subX at the time the Exception was thrown... (even though the actual exception may have been thrown from deep inside some 3rd party module that subX called) How should I do this? Am I barking up the right tree? Thank you, Allen --------------------------------- Need a vacation? Get great deals to amazing places on Yahoo! Travel. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071009/a8030b0e/attachment.htm From ebrosh at nana10.co.il Wed Oct 10 06:23:59 2007 From: ebrosh at nana10.co.il (Eli Brosh) Date: Wed, 10 Oct 2007 06:23:59 +0200 Subject: [Tutor] Extract lines from a multinile string Message-ID: <957526FB6E347743AAB42B212AB54FDA95BA36@NANAMAILBACK1.nanamail.co.il> Hello I have a multiline string such as: s='''This is the first line This is the second line This is the third longer line''' Note that s has no control character such as \n. The lines are defined as in "natural" writing. How can I extract from s, several strings, each of which is a line from the original string ? s1='This is the first line' s2='This is the second line' s3='This is the third longer line' Suppose this can be done using some kind of loop, How can I know that I extracted the last line in the string ? Thanks Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071010/9122d513/attachment.htm From john at fouhy.net Wed Oct 10 06:37:27 2007 From: john at fouhy.net (John Fouhy) Date: Wed, 10 Oct 2007 17:37:27 +1300 Subject: [Tutor] Extract lines from a multinile string In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95BA36@NANAMAILBACK1.nanamail.co.il> References: <957526FB6E347743AAB42B212AB54FDA95BA36@NANAMAILBACK1.nanamail.co.il> Message-ID: <5e58f2e40710092137qed8a4a5yd8e3c4f5b811717f@mail.gmail.com> On 10/10/2007, Eli Brosh wrote: > > > Hello > I have a multiline string such as: > s='''This is the first line > This is the second line > This is the third longer line''' > > Note that s has no control character such as \n. Did you check that? >>> s = '''This is the first line. ... This is the second line. ... This is the third longer line.''' >>> print s This is the first line. This is the second line. This is the third londer line. >>> print repr(s) 'This is the first line.\nThis is the second line.\nThis is the third longer line.' A multiline string has newline characters by definition. You can split the string around them by using s.split(): >>> s.split('\n') ['This is the first line.', 'This is the second line.', 'This is the third longer line.'] HTH! -- John. From alan.gauld at btinternet.com Wed Oct 10 09:27:39 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Oct 2007 08:27:39 +0100 Subject: [Tutor] Exceptions: Logging TB and local variables? References: <466702.38703.qm@web45610.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote > Now, I would like to do this: > > for item in bigset: > try: > self.__sub1(item) > self.__sub2(item) > self.__sub3(item) > except StandardError: > # Log error and continue to next item in set. > log_error_to_file() > > In the error log, I would like to record a stacktrace and various > local variables that existed in subX at the time the Exception > was thrown... Look at the traceback module. It was discussed in a recent thread - A Simple question - starting on October 2nd... > (even though the actual exception may have been thrown from > deep inside some 3rd party module that subX called) Examining data at the time of an exception is easy enough but only if the data is in scope. If it is local data within the raising function then bit will be gone by the time you catch the exception. The only way would be to pass it as part of the exception at the point of raise. But if its global or variables at the catching level then you can just use them as normal from inside the except clause. HTH, Alan G From kalle.svensson at gmail.com Wed Oct 10 09:52:55 2007 From: kalle.svensson at gmail.com (Kalle Svensson) Date: Wed, 10 Oct 2007 09:52:55 +0200 Subject: [Tutor] Exceptions: Logging TB and local variables? In-Reply-To: References: <466702.38703.qm@web45610.mail.sp1.yahoo.com> Message-ID: <9584033b0710100052p52e299d9h6b61bf4949126cb6@mail.gmail.com> On 10/10/07, Alan Gauld wrote: > > "Allen Fowler" wrote > > > Now, I would like to do this: > > > > for item in bigset: > > try: > > self.__sub1(item) > > self.__sub2(item) > > self.__sub3(item) > > except StandardError: > > # Log error and continue to next item in set. > > log_error_to_file() > > > > In the error log, I would like to record a stacktrace and various > > local variables that existed in subX at the time the Exception > > was thrown... > > Look at the traceback module. > It was discussed in a recent thread - A Simple question - starting > on October 2nd... > > > (even though the actual exception may have been thrown from > > deep inside some 3rd party module that subX called) > > Examining data at the time of an exception is easy enough > but only if the data is in scope. If it is local data within the > raising function then bit will be gone by the time you catch > the exception. Well, not entirely. If you look at the sys.exc_info() function there is a way to get the backtrace of the currently handled exception. Using this, you can get to the locals: >>> def a(x): ... l = 0 ... print x/l ... >>> def b(y): ... c = 75 ... a(y) ... >>> try: ... b(3) ... except: ... t,v,bt = sys.exc_info() ... >>> bt >>> dir(bt) ['tb_frame', 'tb_lasti', 'tb_lineno', 'tb_next'] >>> bt.tb_next.tb_frame.f_locals {'y': 3, 'c': 75} >>> bt.tb_next.tb_next.tb_frame.f_locals {'x': 3, 'l': 0} >>> del bt Read more about backtrace and frame objects on: http://www.python.org/doc/ref/types.html http://www.python.org/doc/lib/module-sys.html Also note the warnings in the sys.exc_info documentation. Regards, Kalle From alan.gauld at btinternet.com Wed Oct 10 10:40:20 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Oct 2007 09:40:20 +0100 Subject: [Tutor] Exceptions: Logging TB and local variables? References: <466702.38703.qm@web45610.mail.sp1.yahoo.com> <9584033b0710100052p52e299d9h6b61bf4949126cb6@mail.gmail.com> Message-ID: "Kalle Svensson" wrote >> but only if the data is in scope. If it is local data within the >> raising function then bit will be gone by the time you catch >> the exception. > > Well, not entirely. If you look at the sys.exc_info() function there > is a way to get the backtrace of the currently handled exception. I knew you could get the backtrace but... >>>> def a(x): > ... l = 0 > ... print x/l > ... >>>> def b(y): > ... c = 75 > ... a(y) > ... >>>> try: > ... b(3) > ... except: > ... t,v,bt = sys.exc_info() > ... >>>> bt.tb_next.tb_frame.f_locals > {'y': 3, 'c': 75} ...I didn't realize it included local variables(eg c) , I thought it only had the functions and the arguments passed. Interesting, and very useful. Thanks for that, Alan G From sanelson at gmail.com Wed Oct 10 11:18:41 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Wed, 10 Oct 2007 10:18:41 +0100 Subject: [Tutor] Fwd: Permission Report In-Reply-To: <470C346B.2090304@tds.net> References: <470C346B.2090304@tds.net> Message-ID: On 10/10/07, Kent Johnson wrote: > Stephen Nelson-Smith wrote: > > But if I want to run the same procedure on a remote host, and store > > the results in a dictionary so they can be compared, what would I do? > > What kind of access do you have to the remote host? If you have > filesystem access you can use the same program running locally. In the end I used sshfs, which worked fine. S. From kent37 at tds.net Wed Oct 10 14:22:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Oct 2007 08:22:47 -0400 Subject: [Tutor] Exceptions: Logging TB and local variables? In-Reply-To: <466702.38703.qm@web45610.mail.sp1.yahoo.com> References: <466702.38703.qm@web45610.mail.sp1.yahoo.com> Message-ID: <470CC417.70801@tds.net> Allen Fowler wrote: > In the error log, I would like to record a stacktrace and various local > variables that existed in subX at the time the Exception was thrown... The stack trace is easy - add the parameter exc_info=True to the logging call, e.g. logging.error('Oops!', exc_info=True) When you to this the traceback is included in the log message. For the local variables, you have to do some work yourself. You might look at IPython, it has an option to show local variables in the post-mortem stack traces, maybe you could take some code from there. See the ultraTB module. Kent From norman at khine.net Wed Oct 10 17:13:23 2007 From: norman at khine.net (Norman Khine) Date: Wed, 10 Oct 2007 17:13:23 +0200 Subject: [Tutor] Finding a project In-Reply-To: <20071010015456.GA5889@localdomain> References: <20071010015456.GA5889@localdomain> Message-ID: <470CEC13.8050207@khine.net> maybe you can contribute and help out on some open source projects. i know that the guys at http://ikaaro.org need help with testing. http://download.ikaaro.org/itools/itools-0.16.8.tar.gz or if you want the latest, you can check it out from: % git-clone http://lleu.org/itools.git Eric Lake wrote: > What is a good way to find a project to work on? I really want to work > on something but I can not think of anything useful to write. I am > interested in sysadmin stuff (backups, monitoring, etc). That being said > I don't really have experience writing apps like that. But I really want > to learn. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Norman From deliberatus at verizon.net Wed Oct 10 19:30:10 2007 From: deliberatus at verizon.net (Kirk Bailey) Date: Wed, 10 Oct 2007 13:30:10 -0400 Subject: [Tutor] remmote access in a python program Message-ID: <470D0C22.4000805@verizon.net> OK, python program in box 1 needs to build a list of files available to be examined in box 2 on the firms LAN- .xls spreadsheet files. Sounds like a glob.glob task, but in a remote fashion. I never tried this before, what's the smart answer? -- Salute! -Kirk Bailey Think +-----+ | BOX | +-----+ knihT Fnord. From kent37 at tds.net Wed Oct 10 19:52:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Oct 2007 13:52:04 -0400 Subject: [Tutor] remmote access in a python program In-Reply-To: <470D0C22.4000805@verizon.net> References: <470D0C22.4000805@verizon.net> Message-ID: <470D1144.2000509@tds.net> Kirk Bailey wrote: > OK, python program in box 1 needs to build a list of files available to be > examined in box 2 on the firms LAN- .xls spreadsheet files. Sounds like a > glob.glob task, but in a remote fashion. I never tried this before, what's > the smart answer? What kind of access does box 1 have to box 2? filesystem? ssh? Kent From kent37 at tds.net Wed Oct 10 20:37:43 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Oct 2007 14:37:43 -0400 Subject: [Tutor] remmote access in a python program In-Reply-To: <470D1354.9060003@verizon.net> References: <470D0C22.4000805@verizon.net> <470D1144.2000509@tds.net> <470D1354.9060003@verizon.net> Message-ID: <470D1BF7.2020609@tds.net> Kirk Bailey wrote: > they are on the same LAN, and the files may be accessed via http. As in, directory listings rendered to HTML? Sounds like a job for urllib2 (in the standard lib) and BeautifulSoup. http://www.crummy.com/software/BeautifulSoup/ Kent PS Please use Reply All to reply on-list. From kent37 at tds.net Wed Oct 10 14:52:12 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Oct 2007 08:52:12 -0400 Subject: [Tutor] Updating MySQL Database In-Reply-To: <47098C79.2010103@tds.net> References: <481695.95012.qm@web32405.mail.mud.yahoo.com> <47098C79.2010103@tds.net> Message-ID: <470CCAFC.1040101@tds.net> Kent Johnson wrote: > It > also looks like you are embedding the data in the SQL command, this is > very bad practice, it opens you to SQL injection attacks For a humorous explanation of why you don't want to directly embed data into SQL commands, see today's xkcd: http://xkcd.com/327/ Kent From christopher.henk at allisontransmission.com Wed Oct 10 20:59:02 2007 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Wed, 10 Oct 2007 14:59:02 -0400 Subject: [Tutor] Updating MySQL Database In-Reply-To: <470CCAFC.1040101@tds.net> Message-ID: That Slashdot comment makes so much more sense now. Chris Henk Allison Transmission phone: 317.242.2569 cell: 765.337.8769 fax: 317.242.3469 e-mail: christopher.henk at allisontransmission.com Kent Johnson Sent by: tutor-bounces at python.org 10/10/2007 08:52 AM To Python Tutorlist cc Subject Re: [Tutor] Updating MySQL Database Kent Johnson wrote: > It > also looks like you are embedding the data in the SQL command, this is > very bad practice, it opens you to SQL injection attacks For a humorous explanation of why you don't want to directly embed data into SQL commands, see today's xkcd: http://xkcd.com/327/ Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071010/aeaf20e3/attachment.htm From wormwood_3 at yahoo.com Wed Oct 10 21:48:43 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 10 Oct 2007 12:48:43 -0700 (PDT) Subject: [Tutor] Updating MySQL Database Message-ID: <638407.47860.qm@web32404.mail.mud.yahoo.com> I loved that strip so much. I printed it today, and it is on the door of our IT office:-) ----- Original Message ---- From: Kent Johnson To: Python Tutorlist Sent: Wednesday, October 10, 2007 8:52:12 AM Subject: Re: [Tutor] Updating MySQL Database Kent Johnson wrote: > It > also looks like you are embedding the data in the SQL command, this is > very bad practice, it opens you to SQL injection attacks For a humorous explanation of why you don't want to directly embed data into SQL commands, see today's xkcd: http://xkcd.com/327/ Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Wed Oct 10 22:49:20 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 10 Oct 2007 13:49:20 -0700 Subject: [Tutor] An idea for a script Message-ID: <20071010204930.68AD41E400E@bag.python.org> I think I could learn a lot about the use of Python with the web by writing a script that would look at and find all the links to more that just the default shown by this one: . I think there should be about 20 URLs in the list. But I need a start. So give me one? Thanks, Dick Moores From witham.ian at gmail.com Wed Oct 10 23:06:26 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 11 Oct 2007 10:06:26 +1300 Subject: [Tutor] An idea for a script In-Reply-To: <20071010204930.68AD41E400E@bag.python.org> References: <20071010204930.68AD41E400E@bag.python.org> Message-ID: On 10/11/07, Dick Moores wrote: > > I think I could learn a lot about the use of Python with the web by > writing a script that would look at > and find all the links > to more that just the default shown by this one: > . I think there should be > about 20 URLs in the list. But I need a start. So give me one? A start? Start with urllib2 in the standard library. Load the page source at and have your script create a list of all the URLs you wish to visit. Loop through that list, opening each URL. If the page source is different from the standard "WAITING..." source then you can add that URL to a new list of "good" URLS. HTH, Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071011/2e3721cb/attachment.htm From eric at ericwalstad.com Wed Oct 10 23:23:23 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 10 Oct 2007 14:23:23 -0700 Subject: [Tutor] An idea for a script In-Reply-To: <20071010204930.68AD41E400E@bag.python.org> References: <20071010204930.68AD41E400E@bag.python.org> Message-ID: <470D42CB.4090707@ericwalstad.com> Dick Moores wrote: > I think I could learn a lot about the use of Python with the web by > writing a script that would look at > and find all the links > to more that just the default shown by this one: > . I think there should be > about 20 URLs in the list. But I need a start. So give me one? BeautifulSoup? # untested... import urllib from BeautifulSoup import BeautifulSoup starship_crew_list_url = 'http://starship.python.net/crew/index.html' starship_crew_list_html = urllib.urlopen(starship_crew_list_url).read() soup = BeautifulSoup(starship_crew_list_html) for anchor in soup.fetch('a'): print anchor # / untested -Eric should be one of the results you see :) From john at fouhy.net Wed Oct 10 23:31:53 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 11 Oct 2007 10:31:53 +1300 Subject: [Tutor] Extract lines from a multinile string-Thanks In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95BA38@NANAMAILBACK1.nanamail.co.il> References: <957526FB6E347743AAB42B212AB54FDA95BA36@NANAMAILBACK1.nanamail.co.il> <5e58f2e40710092137qed8a4a5yd8e3c4f5b811717f@mail.gmail.com> <957526FB6E347743AAB42B212AB54FDA95BA38@NANAMAILBACK1.nanamail.co.il> Message-ID: <5e58f2e40710101431v20ac7a5ck18fe92a9db0d2edb@mail.gmail.com> Hi Eli, Please use "reply to all" so that other list users can follow the conversation if they wish. On 11/10/2007, Eli Brosh wrote: > Thank you very much for the reply. > No, I did not check that there is no control character in the multiline. > I just assumed that it is not there if I did not put it there. > Now, I understand it better. > > I am now trying to use python instead of MATLAB. > I found it somewhat annoying that in order to define a two-dimensional array > in python I need some may [[[]]] and ,,: > A = array([[0, 1, 2, 3], # initialize 2-d array > [4, 5, 6, 7], > [8, 9, 10, 11], > [12, 13, 14, 15]]) > > I thought it could be good to have a function str2array into which you put > a string and it is turned into an array: > > A = str2array(''' 1 2 3 > 4 5 6 7 > 8 9 10 11 > 12 13 14 15''') > > Is there already such a function ? I'm not aware of any such function. But you could write it simply as: def str2array(arrayStr): return [[int(i) for i in s.split()] for s in arrayStr.split('\n')] (or replace int() by float() if you expect floating point numbers) But if you want to use python to replace matlab, you should look in to numpy. numpy is a popular python module that supports scientific computation. It includes support for two-dimensional arrays. If you use numpy, you may get some support on this list, but there are also numpy-specific lists. -- John. From ed at goulart.ws Wed Oct 10 23:34:17 2007 From: ed at goulart.ws (Ed Goulart) Date: Wed, 10 Oct 2007 18:34:17 -0300 Subject: [Tutor] Re-Naming an existent file Message-ID: <9fd23a140710101434x36403b4fm7fc79c07125d7c2d@mail.gmail.com> Hello! Though I've tried very hard, I couldn't find in the WEB the needed help; so, if you can help me, please...!!! *The problem is* that I need to rename a file (*qso.txt*) after a value input "*call*" I get in the first line (<*call value*>*.txt*)* *... I get the file qso.txt but I get no success in getting the file re-named to .txt. ** *call* = raw_input ( "-> CALL: " ) qso = call + " " + raw_input( "-> QRA: " ) + " " + raw_input( "-> RST: " ) + " " + raw_input( "-> QTH: " ) + " " + raw_input( "-> OBS.: " ) f = file('qso.txt','w') # open for 'w'riting f.write(qso) # write text to file f.close() # close the file Thanks beforehand, Ed Goulart, ed at goulart.ws -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071010/6aca0488/attachment.htm From kent37 at tds.net Wed Oct 10 23:45:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Oct 2007 17:45:00 -0400 Subject: [Tutor] Extract lines from a multinile string-Thanks In-Reply-To: <5e58f2e40710101431v20ac7a5ck18fe92a9db0d2edb@mail.gmail.com> References: <957526FB6E347743AAB42B212AB54FDA95BA36@NANAMAILBACK1.nanamail.co.il> <5e58f2e40710092137qed8a4a5yd8e3c4f5b811717f@mail.gmail.com> <957526FB6E347743AAB42B212AB54FDA95BA38@NANAMAILBACK1.nanamail.co.il> <5e58f2e40710101431v20ac7a5ck18fe92a9db0d2edb@mail.gmail.com> Message-ID: <470D47DC.5010505@tds.net> John Fouhy wrote: >> I found it somewhat annoying that in order to define a two-dimensional array >> in python I need some may [[[]]] and ,,: >> A = array([[0, 1, 2, 3], # initialize 2-d array >> [4, 5, 6, 7], >> [8, 9, 10, 11], >> [12, 13, 14, 15]]) In [7]: import numpy In [9]: a=numpy.arange(16).reshape(4,4) In [10]: a Out[10]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) > But if you want to use python to replace matlab, you should look in to > numpy. From his use of array() I would guess he already has done that. Kent From bill at celestial.net Wed Oct 10 23:49:36 2007 From: bill at celestial.net (Bill Campbell) Date: Wed, 10 Oct 2007 14:49:36 -0700 Subject: [Tutor] Re-Naming an existent file In-Reply-To: <9fd23a140710101434x36403b4fm7fc79c07125d7c2d@mail.gmail.com> References: <9fd23a140710101434x36403b4fm7fc79c07125d7c2d@mail.gmail.com> Message-ID: <20071010214936.GA17829@ayn.mi.celestial.com> On Wed, Oct 10, 2007, Ed Goulart wrote: > > Hello! > > Though I've tried very hard, I couldn't find in the WEB the needed > help; so, if you can help me, please...!!! import os os.rename(old, new) Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 Do not meddle in the affairs of cats, for they are subtle and will piss on your computer. --Bruce Graham From kvander11 at gmail.com Wed Oct 10 23:49:52 2007 From: kvander11 at gmail.com (Kirk Vander Meulen) Date: Wed, 10 Oct 2007 16:49:52 -0500 Subject: [Tutor] internet access Message-ID: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> Hi, I'd like to write a script that limits internet access to certain hours of the day. This seems like it should be simple but I'm not very experienced with any programming that involves networking. Can someone point me in the right direction on this- I'm sure I can figure out how to use a calendar object or whatever to trigger daily events, but what's the best way to block/unblock networking? I'm running xp (probably vista soon) on the computer I want to do this with. Thanks in advance, Kirk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071010/6e1dd17f/attachment.htm From rdm at rcblue.com Thu Oct 11 01:20:41 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 10 Oct 2007 16:20:41 -0700 Subject: [Tutor] An idea for a script In-Reply-To: References: <20071010204930.68AD41E400E@bag.python.org> Message-ID: <20071010232102.911A41E4002@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071010/041a22f8/attachment.htm From witham.ian at gmail.com Thu Oct 11 01:40:00 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 11 Oct 2007 12:40:00 +1300 Subject: [Tutor] An idea for a script In-Reply-To: <20071010232102.911A41E4002@bag.python.org> References: <20071010204930.68AD41E400E@bag.python.org> <20071010232102.911A41E4002@bag.python.org> Message-ID: On 10/11/07, Dick Moores wrote: > > At 02:06 PM 10/10/2007, Ian Witham wrote: > > > On 10/11/07, *Dick Moores* wrote: > I think I could learn a lot about the use of Python with the web by > writing a script that would look at > < http://starship.python.net/crew/index.html> and find all the links > to more that just the default shown by this one: > < http://starship.python.net/crew/beazley/>. I think there should be > about 20 URLs in the list. But I need a start. So give me one? > > > > A start? Start with urllib2 in the standard library. > > Load the page source at < http://starship.python.net/crew/index.html> and > have your script create a list of all the URLs you wish to visit. > > Loop through that list, opening each URL. If the page source is different > from the standard "WAITING..." source then you can add that URL to a new > list of "good" URLS. > > > How about a hint of how to get those ">jcooley<" things from the source? > (I'm able to have the script get the source, using urllib2.) > I've done a similar thing 'the hard way' I extracted the information I needed using split. In your case you really need the content between each ( References: <20071010204930.68AD41E400E@bag.python.org> <20071010232102.911A41E4002@bag.python.org> Message-ID: <20071010234830.8E4371E4002@bag.python.org> At 04:20 PM 10/10/2007, Dick Moores wrote: >How about a hint of how to get those ">jcooley<" things from the >source? (I'm able to have the script get the source, using urllib2.) > >BTW I thought I wouldn't try to use BeautifulSoup right now, but >take the hard way. > >Dick I asked for a hint too soon. A light went on, and I think I'm on the way with from urllib2 import * u = 'http://starship.python.net/crew/index.html' f = urlopen(u) a = f.read() b = a.split('"') print b for x in b: if '<' not in x: print x This gets all, but not only, those ">jcooley<" things, I believe. Now I'll check my email for the hint I asked for.. Dick From kent37 at tds.net Thu Oct 11 02:16:56 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Oct 2007 20:16:56 -0400 Subject: [Tutor] An idea for a script In-Reply-To: <20071010232102.911A41E4002@bag.python.org> References: <20071010204930.68AD41E400E@bag.python.org> <20071010232102.911A41E4002@bag.python.org> Message-ID: <470D6B78.3040405@tds.net> Dick Moores wrote: > How about a hint of how to get those ">jcooley<" things from the source? > (I'm able to have the script get the source, using urllib2.) > > BTW I thought I wouldn't try to use BeautifulSoup right now, but take > the hard way. Well, you could probably do it with regular expressions, the source is pretty regular. You could use sgmllib directly, Dive Into Python has a chapter about this: http://www.diveintopython.org/html_processing/index.html or you could learn to use a handy tool and do it with BeautifulSoup... Kent From witham.ian at gmail.com Thu Oct 11 02:17:50 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 11 Oct 2007 13:17:50 +1300 Subject: [Tutor] An idea for a script In-Reply-To: <20071010234830.8E4371E4002@bag.python.org> References: <20071010204930.68AD41E400E@bag.python.org> <20071010232102.911A41E4002@bag.python.org> <20071010234830.8E4371E4002@bag.python.org> Message-ID: On 10/11/07, Dick Moores wrote: > > At 04:20 PM 10/10/2007, Dick Moores wrote: > >How about a hint of how to get those ">jcooley<" things from the > >source? (I'm able to have the script get the source, using urllib2.) > > > >BTW I thought I wouldn't try to use BeautifulSoup right now, but > >take the hard way. > > > >Dick > > I asked for a hint too soon. A light went on, and I think I'm on the way > with > > from urllib2 import * > u = 'http://starship.python.net/crew/index.html' > f = urlopen(u) > a = f.read() > b = a.split('"') > print b > for x in b: > if '<' not in x: > print x > > This gets all, but not only, those ">jcooley<" things, I believe. That looks like it will work... Try starting with a couple of 'splits' so that you are only working with the data between "The Crew" and "Looking for the official" a = f.read() a = a.split("The Crew")[1].split("Looking for")[0] Now you are only examining the relevant block of HTML. You can now filter the list with a list comprehension: b = a.split('"') b = [u for u in b if '<' not in u] Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071011/706b6abf/attachment.htm From carroll at tjc.com Thu Oct 11 02:50:41 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 10 Oct 2007 17:50:41 -0700 (PDT) Subject: [Tutor] os.rename anomaly in Python 2.3 on Windows XP In-Reply-To: <8249c4ac0710091708g5845858eg9baa4722e1be2056@mail.gmail.com> Message-ID: On Tue, 9 Oct 2007, Tony Cappellini wrote: > Unfortunately,os.listdir() returns the same string as glob.glob, for > the problem file I mentioned. Tony -- Try specifying the argument to os.listdir as a unicode string. I've found that cures many ailments like this. e.g., instead of something like: filelist = os.listdir('.') use: filelist = os.listdir(u'.') I don't think glob supports this. From rdm at rcblue.com Thu Oct 11 07:36:35 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 10 Oct 2007 22:36:35 -0700 Subject: [Tutor] An idea for a script In-Reply-To: <20071010204930.68AD41E400E@bag.python.org> References: <20071010204930.68AD41E400E@bag.python.org> Message-ID: <20071011053643.A2E171E400E@bag.python.org> I think I've done it, and with only the initial help from Ian. (The output is pasted at the bottom of the script.) Now I have to consider carefully all the ideas and suggestions offered, and also the undoubtedly forthcoming criticism. Thank you all very much. Dick Moores From mail at timgolden.me.uk Thu Oct 11 10:56:57 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 11 Oct 2007 09:56:57 +0100 Subject: [Tutor] internet access In-Reply-To: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> Message-ID: <470DE559.80206@timgolden.me.uk> Kirk Vander Meulen wrote: > I'd like to write a script that limits internet access to certain hours of > the day. This seems like it should be simple. That's a very optimistic point of view! > Can someone point me in the right direction on this- I'm sure I can > figure out how to use a calendar object or whatever to trigger daily > events, but what's the best way to block/unblock networking? > I'm running xp (probably vista soon) on the > computer I want to do this with. Well it's quite a wide-ranging question really, in spite of the apparent simplicity of the request To start with, just how secure does the solution need to be? Enough to prevent casual trespassing? Or robust enough to stop the most determined of (maybe teenage) script-kiddie? You could, for example, have a script scheduled to disable the primary NIC's network access at a certain time. But that would only be effective as long as users couldn't undo the effect. And would also prevent access to, say, any networked printers etc. Alternatively, you might reset its gateway so that local networking would succeed but internet access would not. (This stuff you could do quite simply with WMI, including the scheduling, although I'm sure there are alternatives). But this is all moderately flimsy stuff. In short, anything you do casually under Windows -- that I can think of at any rate -- could be undone by someone who gets admin access. If you're using some kind of ADSL router to access the internet, I believe some of them come with various firewall-y functions, of which timed access might be one. Alternatively, there is a small world of products out there for content filtering, timed access etc. Don't know what your need is, but they tend to be labelled as family-oriented so searching for terms like family web filter will probably get a few hits. Feel free to come back with more info / questions. TJG From alan.gauld at btinternet.com Thu Oct 11 12:19:06 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Oct 2007 11:19:06 +0100 Subject: [Tutor] internet access References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> Message-ID: "Kirk Vander Meulen" wrote > I'd like to write a script that limits internet access to certain > hours of > the day. This seems like it should be simple but I'm not very > experienced Its actually not that simple because its fundamentally going against the design of the computer. Modern computers and operating systems are designed to allow multiple users to perform multiple tasks 'simultaneously' without getting in each others way. Thus it's relatively easy for an application to change its own access but much more difficult for an application to change a user's access and even more difficult for one user's application to change access for every user or for the machine as a whole. It's designed to be that way. Now there is one loophole, which is the administrators account (which is root on Linux/MacOS or nearly every user on XP! I dunno if Vista has closed this gaping Windows security hole or not?). The administrator's account should not be used for day to day usaage (XP defaults not withstanding) but for administewring all other users and the machine itself. Thus to do what you need the application would need to run as administrator and would need to tweak the operating system networking setup. Neither of these are particularly trivial in a well set up machine (and for good reason). So the question is, do you want to lock down a single application? Or a single user? Or the whole computer? And which OS are you using? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From nephish at gmail.com Thu Oct 11 13:44:53 2007 From: nephish at gmail.com (shawn bright) Date: Thu, 11 Oct 2007 06:44:53 -0500 Subject: [Tutor] internet access In-Reply-To: References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> Message-ID: <384c93600710110444g1410385v8aaca2e75a62931c@mail.gmail.com> i did something very similar to this. My daughter would stay on her instant messenger (gaim) all night if i didn't. i have a cron script that checks the hour of day, if later than x pm. does os.system("/etc/init.d/network stop") os.system("chmod a-x /etc/init.d/network") ( so that a reboot doesn't override it ) then in the morning, makes it executable, and starts it up again. Then again, this is linux and my daughter, though somewhat geeky would not know how to beat this. Maybe something similar could be done in windows ? I don't know much about that OS. sk On 10/11/07, Alan Gauld wrote: > > "Kirk Vander Meulen" wrote > > > I'd like to write a script that limits internet access to certain > > hours of > > the day. This seems like it should be simple but I'm not very > > experienced > > Its actually not that simple because its fundamentally going against > the design of the computer. Modern computers and operating systems > are designed to allow multiple users to perform multiple tasks > 'simultaneously' without getting in each others way. Thus it's > relatively > easy for an application to change its own access but much more > difficult for an application to change a user's access and even more > difficult for one user's application to change access for every user > or for the machine as a whole. It's designed to be that way. > > Now there is one loophole, which is the administrators account > (which is root on Linux/MacOS or nearly every user on XP! > I dunno if Vista has closed this gaping Windows security hole or > not?). > > The administrator's account should not be used for day to day > usaage (XP defaults not withstanding) but for administewring all > other users and the machine itself. Thus to do what you need the > application would need to run as administrator and would need to > tweak the operating system networking setup. Neither of these are > particularly trivial in a well set up machine (and for good reason). > > So the question is, do you want to lock down a single application? > Or a single user? Or the whole computer? And which OS are you > using? > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071011/0d07b8d5/attachment.htm From kent37 at tds.net Thu Oct 11 13:48:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Oct 2007 07:48:02 -0400 Subject: [Tutor] An idea for a script In-Reply-To: <20071011053643.A2E171E400E@bag.python.org> References: <20071010204930.68AD41E400E@bag.python.org> <20071011053643.A2E171E400E@bag.python.org> Message-ID: <470E0D72.7030308@tds.net> Dick Moores wrote: > I think I've done it, and with only the initial help from Ian. > > (The output is > pasted at the bottom of the script.) > print "starting at", time.asctime()[11:19] You can ask for the format you want directly: print "starting at", time.strftime('%H:%M:%S') > b = a.split('href="') > lstB = [] > for x in b: > lstB.append(x) This just makes a copy of b, which you probably don't need, I don't see any other use of b. So just write lstB = a.split('href="') Kent From mail at timgolden.me.uk Thu Oct 11 14:02:54 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 11 Oct 2007 13:02:54 +0100 Subject: [Tutor] internet access In-Reply-To: <384c93600710110444g1410385v8aaca2e75a62931c@mail.gmail.com> References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> <384c93600710110444g1410385v8aaca2e75a62931c@mail.gmail.com> Message-ID: <470E10EE.9020700@timgolden.me.uk> shawn bright wrote: > i did something very similar to this. My daughter would stay on her instant > messenger (gaim) all night if i didn't. i have a cron script that checks the > hour of day, if later than x pm. does > os.system("/etc/init.d/network stop") > os.system("chmod a-x /etc/init.d/network") ( so that a reboot doesn't > override it ) > > then in the morning, makes it executable, and starts it up again. > Then again, this is linux and my daughter, though somewhat geeky would not > know how to beat this. > Maybe something similar could be done in windows ? I don't know much about > that OS. Broadly, that's what my earlier suggestion amounted to. Windows works very differently but disabling the network card from a scheduled job is about as close as you're going to get. (I think). TJG From sanelson at gmail.com Thu Oct 11 15:25:08 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Thu, 11 Oct 2007 14:25:08 +0100 Subject: [Tutor] VIX API Message-ID: Hello, Does anyone know if there are python bindings for the VMware VIX API? I googled for a bit, but didn't find them... How tricky would it be to wrap the C API? S. From mlangford.cs03 at gtalumni.org Thu Oct 11 16:43:38 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 11 Oct 2007 10:43:38 -0400 Subject: [Tutor] internet access In-Reply-To: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> Message-ID: <82b4f5810710110743m56f83014p5bcc8572068f99e1@mail.gmail.com> While I don't know how to do it in a platform independent way, WSH appears to have all the net functions you'd need (I've only looked at Vista....but I assume Xp is the same). http://en.wikipedia.org/wiki/Windows_Script_Host If you find python bindings for WSH, let us know (or if you make some with SWIG: www.swig.org) --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ On 10/10/07, Kirk Vander Meulen wrote: > > Hi, > I'd like to write a script that limits internet access to certain hours of > the day. This seems like it should be simple but I'm not very experienced > with any programming that involves networking. Can someone point me in the > right direction on this- I'm sure I can figure out how to use a calendar > object or whatever to trigger daily events, but what's the best way to > block/unblock networking? I'm running xp (probably vista soon) on the > computer I want to do this with. Thanks in advance, > > Kirk > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071011/af89f83f/attachment.htm From mlangford.cs03 at gtalumni.org Thu Oct 11 16:44:26 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 11 Oct 2007 10:44:26 -0400 Subject: [Tutor] VIX API In-Reply-To: <82b4f5810710110719xf370c3al5a52c715e17d8b02@mail.gmail.com> References: <82b4f5810710110719xf370c3al5a52c715e17d8b02@mail.gmail.com> Message-ID: <82b4f5810710110744j1ddd19c3p8e11060c13cc5b5e@mail.gmail.com> There is a wrapper. It's called pyvix (http://sourceforge.net/projects/pyvix). If you actually use it, let me know how it goes. I use vmware every day at work and would love to control it via some python tools if the API functions well. I've not had the time to play with it. Creating your own wrapper using swig(http://www.swig.org/) is not a bad exercise if you've not done it. Callbacks are the only part that I'd call really *hard* about wrapping a C Api using python, but debugging is definitely different across language boundaries if you've not done it before. Now if you're really feeling like you want to cause yourself some pain, you can try to hand code a python extension...but I suggest you try the automated tool first.... --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ On 10/11/07, Stephen Nelson-Smith wrote: > > Hello, > > Does anyone know if there are python bindings for the VMware VIX API? > > I googled for a bit, but didn't find them... > > How tricky would it be to wrap the C API? > > S. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071011/628d862e/attachment-0001.htm From kent37 at tds.net Thu Oct 11 16:58:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Oct 2007 10:58:13 -0400 Subject: [Tutor] VIX API In-Reply-To: <82b4f5810710110744j1ddd19c3p8e11060c13cc5b5e@mail.gmail.com> References: <82b4f5810710110719xf370c3al5a52c715e17d8b02@mail.gmail.com> <82b4f5810710110744j1ddd19c3p8e11060c13cc5b5e@mail.gmail.com> Message-ID: <470E3A05.3010607@tds.net> Michael Langford wrote: > Creating your own wrapper using swig(http://www.swig.org/) is not a bad > exercise if you've not done it. Callbacks are the only part that I'd > call really *hard* about wrapping a C Api using python, but debugging is > definitely different across language boundaries if you've not done it > before. > > Now if you're really feeling like you want to cause yourself some pain, > you can try to hand code a python extension...but I suggest you try the > automated tool first.... IIUC the ctypes module is another option though I don't have any experience with it... Kent From mail at timgolden.me.uk Thu Oct 11 17:05:44 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 11 Oct 2007 16:05:44 +0100 Subject: [Tutor] internet access In-Reply-To: <82b4f5810710110743m56f83014p5bcc8572068f99e1@mail.gmail.com> References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> <82b4f5810710110743m56f83014p5bcc8572068f99e1@mail.gmail.com> Message-ID: <470E3BC8.4000306@timgolden.me.uk> Michael Langford wrote: > While I don't know how to do it in a platform independent way, WSH > appears to have all the net functions you'd need (I've only looked at > Vista....but I assume Xp is the same). > > http://en.wikipedia.org/wiki/Windows_Script_Host > > If you find python bindings for WSH, let us know (or if you make some > with SWIG: www.swig.org ) You can usually automate WSH via pywin32, but can you post or point to an example somewhere which does what the OP's after? I'm happy to help translate into Python if it fits the bill. TJG From roychenlei at gmail.com Thu Oct 11 17:27:05 2007 From: roychenlei at gmail.com (Roy Chen) Date: Thu, 11 Oct 2007 23:27:05 +0800 Subject: [Tutor] Question about default values for arguments Message-ID: <6D2F6231-094E-4BC1-A04B-B81E0D1B5610@gmail.com> Hi everyone, been looking at the following functions, but can't figure out how they work. def f(a, L=[]): L.append(a) return L def g(a, L=None): if L == None: L = [] L.append(a) return L print f(1) print f(2) print f(3) print g(1) print g(2) print g(3) The output is: [1] [1, 2] [1, 2, 3] [1] [2] [3] I understand that default arguments are evaluated once only, at the point of function definition, but I can't wrap my head around how the function g() doesn't do the same thing as the function f(). Any help would be most appreciated, thanks. From kent37 at tds.net Thu Oct 11 17:30:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Oct 2007 11:30:20 -0400 Subject: [Tutor] Question about default values for arguments In-Reply-To: <6D2F6231-094E-4BC1-A04B-B81E0D1B5610@gmail.com> References: <6D2F6231-094E-4BC1-A04B-B81E0D1B5610@gmail.com> Message-ID: <470E418C.3050500@tds.net> Roy Chen wrote: > Hi everyone, been looking at the following functions, but can't > figure out how they work. > > def f(a, L=[]): > L.append(a) > return L > > def g(a, L=None): > if L == None: > L = [] > L.append(a) > return L http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Kent From steve at alchemy.com Thu Oct 11 17:19:49 2007 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 11 Oct 2007 08:19:49 -0700 Subject: [Tutor] internet access In-Reply-To: <82b4f5810710110743m56f83014p5bcc8572068f99e1@mail.gmail.com> References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> <82b4f5810710110743m56f83014p5bcc8572068f99e1@mail.gmail.com> Message-ID: <470E3F15.6040603@alchemy.com> This is where it's an advantage to setting up an old PC as a firewall for your network. Stick Linux on it, set up your filtering rules, and let it sit between your home network and the outside world. You can then have it block that PC's access to the Internet via cron scripts, possibly even selectively, between certain times, and there's nothing that anything done on that PC (short of a modem with dialup access) can do to override that. From brunson at brunson.com Thu Oct 11 18:08:39 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 11 Oct 2007 10:08:39 -0600 Subject: [Tutor] internet access In-Reply-To: <470E3F15.6040603@alchemy.com> References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> <82b4f5810710110743m56f83014p5bcc8572068f99e1@mail.gmail.com> <470E3F15.6040603@alchemy.com> Message-ID: <470E4A87.1000405@brunson.com> I used to run an old linux laptop with two NICs as my firewall, but I played a bit with DD-WRT and now I'm an evangelist. DD-WRT is based on an embedded Linux kernel and provides a great set of features, including time based filters, web GUI, ssh access and a real unix command line as well as VPN, traffic shaping and a host of other great services. I generally advocate the Motorola WR850G's, as they allow you to load the DD-WRT firmware from the factory web interface, whereas many other devices require a "hack". Supported hardware is listed here:http://www.dd-wrt.com/wiki/index.php/Supported_Devices, if you have a SOHO wireless G router, there's a good chance DD-WRT will run on it. That reminds me, there's a new release I should go try out. :-) Steve Willoughby wrote: > This is where it's an advantage to setting up an old PC as a firewall > for your network. Stick Linux on it, set up your filtering rules, and > let it sit between your home network and the outside world. You can > then have it block that PC's access to the Internet via cron scripts, > possibly even selectively, between certain times, and there's nothing > that anything done on that PC (short of a modem with dialup access) can > do to override that. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Thu Oct 11 18:08:14 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Oct 2007 17:08:14 +0100 Subject: [Tutor] Question about default values for arguments References: <6D2F6231-094E-4BC1-A04B-B81E0D1B5610@gmail.com> Message-ID: "Roy Chen" wrote > def f(a, L=[]): > L.append(a) > return L This creates a single list object L used for all calls to f() that don;t provide an explicit L. Thus each call appends to the same object. > > def g(a, L=None): > if L == None: > L = [] > L.append(a) > return L This creates a new L on each invocation of g() where L is None or not supplied. > print f(1) > print f(2) > print f(3) > print g(1) > print g(2) > print g(3) > > The output is: > [1] > [1, 2] > [1, 2, 3] The same default object returned each time > [1] > [2] > [3] 3 new objects returned. > I understand that default arguments are evaluated once only, at the > point of function definition, but I can't wrap my head around how > the > function g() doesn't do the same thing as the function f(). Because it creates a new object at execution not at definition. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Oct 11 18:02:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Oct 2007 17:02:30 +0100 Subject: [Tutor] internet access References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> <82b4f5810710110743m56f83014p5bcc8572068f99e1@mail.gmail.com> Message-ID: "Michael Langford" > > If you find python bindings for WSH, let us know (or if you make > some with > SWIG: www.swig.org) Python alreeady has bindings and they come as part of the winall package from Mark Hammond. It involves running a registration script to register python with WSH as a scripting language. (This also allows you to use python inside HTML for client side scripting on IE) AIR Details are in his Win32 book. However, I confess that I find WSH easier from VB Script than from Python unless the logic is very complex. Alan G. From alan.gauld at btinternet.com Thu Oct 11 17:58:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Oct 2007 16:58:53 +0100 Subject: [Tutor] internet access References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> <384c93600710110444g1410385v8aaca2e75a62931c@mail.gmail.com> Message-ID: "shawn bright" wrote > messenger (gaim) all night if i didn't. i have a cron script that > checks the > hour of day, if later than x pm. does > os.system("/etc/init.d/network stop") > os.system("chmod a-x /etc/init.d/network") ( so that a reboot > doesn't > override it ) Whilst this is a Python list it might not always be the best solution. In the case above a shell script is probably better since all you are doing is calling shell commands. I assume your cron is run as root? Alan G From brunson at brunson.com Thu Oct 11 18:59:46 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 11 Oct 2007 10:59:46 -0600 Subject: [Tutor] internet access In-Reply-To: References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> <384c93600710110444g1410385v8aaca2e75a62931c@mail.gmail.com> Message-ID: <470E5682.9000108@brunson.com> Alan Gauld wrote: > "shawn bright" wrote > > >> messenger (gaim) all night if i didn't. i have a cron script that >> checks the >> hour of day, if later than x pm. does >> os.system("/etc/init.d/network stop") >> os.system("chmod a-x /etc/init.d/network") ( so that a reboot >> doesn't >> override it ) >> > > Whilst this is a Python list it might not always be the best solution. > In the case above a shell script is probably better since all you are > doing is calling shell commands. > As my dear old dad would say, "There's a right tool for every job, and it's almost never vise grips." :-) (What do you call vise grips in the UK? Vise-grips is a trademarked name in the US, but has become a general term for locking pliers. See: http://www.irwin.com/irwin/consumer/jhtml/detail.jhtml?prodId=IrwinProd100300) > I assume your cron is run as root? > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Thu Oct 11 23:21:23 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Oct 2007 22:21:23 +0100 Subject: [Tutor] internet access References: <2d0c08ca0710101449x56903d1bud8ebd205754aeb6f@mail.gmail.com> <384c93600710110444g1410385v8aaca2e75a62931c@mail.gmail.com> <470E5682.9000108@brunson.com> Message-ID: "Eric Brunson" wrote > (What do you call vise grips in the UK? Vice grips - with a c. But there are various types and they all have specific names too. I'm not sure which variety you mean. A google search reveals that there are a few types in the US too... all called vise grips... :-) The most commonly shown are known here as mole-grips (don't ask me why!) And my electronics cataloge has them listed as the rather prosaic "locking pliers" Alan G. From rdm at rcblue.com Fri Oct 12 07:53:12 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 11 Oct 2007 22:53:12 -0700 Subject: [Tutor] 2 problems in a small script Message-ID: <20071012055549.CE0BB1E4027@bag.python.org> Please see the code and it's output here: I'm attempting to eliminate the elements (strings) of lstA that are not well-formed in that they contain at least one character that is not in the string astr. Problems: 1) If lstA[n] is removed, lstA[n+1] is skipped--isn't examined at all, and remains in the final form of lstA whether well-formed or not. Using print statements is as far as my debugging skills go, so you can see of bunch of them in the code. I did try to use winpdb for the first time, but haven't figured it out yet. Ulipad now has it built in, so I'd like to learn to use it it.. 2) I'm not able to get the "for char in wordWithCommas:" loop to stop examining a wordWithCommas after it's word has been removed. I've tried "continue" and "break" in various places to no avail. I'd appreciate some help. Thanks, Dick Moores Win XP, Python 2.5.1 From aditya.n.lal at gmail.com Fri Oct 12 08:25:40 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Fri, 12 Oct 2007 11:55:40 +0530 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012055549.CE0BB1E4027@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> Message-ID: <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> Hi Dick, You are deleting from the SAME list that you are traversing. This results in problems. You should just create a new list for the elements that are well-formed. astr = ... lstA = ... def wellFormed(word) : for ch in word : if ch not in astr : return False return True final = [] for word in lstA : if wellFormed(word) : final.append(word) You can also look at documentation for filter function (which is now handled via list comprehension). finalList = filter( wellFormed, lstA ) or finalList = [ word for word in lstA if wellformed(word) ] HTH Aditya On 10/12/07, Dick Moores wrote: > > Please see the code and it's output here: > > > > I'm attempting to eliminate the elements (strings) of lstA that are > not well-formed in that they contain at least one character that is > not in the string astr. > > Problems: > 1) If lstA[n] is removed, lstA[n+1] is skipped--isn't examined at > all, and remains in the final form of lstA whether well-formed or not. > > Using print statements is as far as my debugging skills go, so you > can see of bunch of them in the code. I did try to use winpdb for the > first time, but haven't figured it out yet. Ulipad now has it built > in, so I'd like to learn to use it it.. > > 2) I'm not able to get the "for char in wordWithCommas:" loop to stop > examining a wordWithCommas after it's word has been removed. I've > tried "continue" and "break" in various places to no avail. > > I'd appreciate some help. > > Thanks, > > Dick Moores > Win XP, Python 2.5.1 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071012/f6db3998/attachment.htm From rdm at rcblue.com Fri Oct 12 09:02:29 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 00:02:29 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.co m> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> Message-ID: <20071012070242.A3FDC1E401C@bag.python.org> At 11:25 PM 10/11/2007, Aditya Lal wrote: >Hi Dick, > >You are deleting from the SAME list that you are traversing. This >results in problems. Aditya, Well, if deleting from the same list I'm traversing is the problem, why doesn't inserting the line lstB = lstA and deleting from lstB clear it up? The output is exactly the same. I'm really puzzled. See I thank you for showing me another way to get the result I want, but first I want to know why my code didn't work. Dick From aditya.n.lal at gmail.com Fri Oct 12 09:18:47 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Fri, 12 Oct 2007 12:48:47 +0530 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012070242.A3FDC1E401C@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <20071012070242.A3FDC1E401C@bag.python.org> Message-ID: <5df213700710120018s7e119eeex276f2a5a5ede6d1@mail.gmail.com> lstB = lstA The above just points lstB to lstA and *does not* create a copy. If you do not understand "pointers", think of lstB an alias of lstA. If you want to create a copy you need to explicitly do it. lstB = [] for word in lstA : lstB.append(word) or shortcut lstB = lstA[:] So, even though you created a new variable lstB it was actually modifying lstA. HTH Aditya On 10/12/07, Dick Moores wrote: > > At 11:25 PM 10/11/2007, Aditya Lal wrote: > >Hi Dick, > > > >You are deleting from the SAME list that you are traversing. This > >results in problems. > > Aditya, > > Well, if deleting from the same list I'm traversing is the problem, > why doesn't inserting the line > lstB = lstA > > and deleting from lstB clear it up? The output is exactly the same. > I'm really puzzled. See > > I thank you for showing me another way to get the result I want, but > first I want to know why my code didn't work. > > Dick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071012/9f48f1cc/attachment.htm From alan.gauld at btinternet.com Fri Oct 12 09:34:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Oct 2007 08:34:48 +0100 Subject: [Tutor] 2 problems in a small script References: <20071012055549.CE0BB1E4027@bag.python.org><5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.co m> <20071012070242.A3FDC1E401C@bag.python.org> Message-ID: "Dick Moores" wrote > Well, if deleting from the same list I'm traversing is the problem, > why doesn't inserting the line > lstB = lstA > > and deleting from lstB clear it up? The output is exactly the same. You are not copying the list you are just making a second name refer to the same list. You need to make a new copy, as in: lstB = lstA[:] # a full slice creates a copy But thats not an efficient approach if you have a big list, the best route is to build a new list, preferably using a list comprehension. > I thank you for showing me another way to get the result I want, but > first I want to know why my code didn't work. The reason is as stated. Your solution didn't do what you thought it did :-) The other way you can do it is to use a while loop: n = 0 while n < len(myList): #computed each time if some_test(myList[n]): del(myList[n]) else: n += 1 Note we do not increment n when we delete an element. I cover this in the branching topic of my tutorial in the section Modifying collections from inside loops HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Fri Oct 12 09:37:34 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 00:37:34 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: <5df213700710120018s7e119eeex276f2a5a5ede6d1@mail.gmail.com > References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <20071012070242.A3FDC1E401C@bag.python.org> <5df213700710120018s7e119eeex276f2a5a5ede6d1@mail.gmail.com> Message-ID: <20071012074735.8545C1E4037@bag.python.org> At 12:18 AM 10/12/2007, Aditya Lal wrote: >lstB = lstA[:] Thanks! I'd completely forgotten how to copy a list. Dick From rdm at rcblue.com Fri Oct 12 10:16:57 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 01:16:57 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012055549.CE0BB1E4027@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> Message-ID: <20071012081757.A6AFB1E401C@bag.python.org> At 10:53 PM 10/11/2007, Dick Moores wrote: >Please see the code and it's output here: > > > >I'm attempting to eliminate the elements (strings) of lstA that are >not well-formed in that they contain at least one character that is >not in the string astr. > >Problems: >1) If lstA[n] is removed, lstA[n+1] is skipped--isn't examined at >all, and remains in the final form of lstA whether well-formed or not. > >Using print statements is as far as my debugging skills go, so you >can see of bunch of them in the code. I did try to use winpdb for the >first time, but haven't figured it out yet. Ulipad now has it built >in, so I'd like to learn to use it it.. > >2) I'm not able to get the "for char in wordWithCommas:" loop to stop >examining a wordWithCommas after it's word has been removed. I've >tried "continue" and "break" in various places to no avail. > >I'd appreciate some help. Now that Aditya and Alan have come to my rescue, problem #1 has been solved. But #2 remains.. Dick From aditya.n.lal at gmail.com Fri Oct 12 12:09:39 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Fri, 12 Oct 2007 15:39:39 +0530 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012081757.A6AFB1E401C@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> <20071012081757.A6AFB1E401C@bag.python.org> Message-ID: <5df213700710120309x5dfdfe1bl8a68710035813c5c@mail.gmail.com> w.r.t. prob 2, there is no break/continue in the code that you have given. I added the "break" statement after you remove the word from lstB and code does seems to work for me. if word in lstB: lstB.remove(word) print print "Removed", word break Can you specify where did you try putting break/continue ? On 10/12/07, Dick Moores wrote: > > At 10:53 PM 10/11/2007, Dick Moores wrote: > >Please see the code and it's output here: > > > > > > > >I'm attempting to eliminate the elements (strings) of lstA that are > >not well-formed in that they contain at least one character that is > >not in the string astr. > > > >Problems: > >1) If lstA[n] is removed, lstA[n+1] is skipped--isn't examined at > >all, and remains in the final form of lstA whether well-formed or not. > > > >Using print statements is as far as my debugging skills go, so you > >can see of bunch of them in the code. I did try to use winpdb for the > >first time, but haven't figured it out yet. Ulipad now has it built > >in, so I'd like to learn to use it it.. > > > >2) I'm not able to get the "for char in wordWithCommas:" loop to stop > >examining a wordWithCommas after it's word has been removed. I've > >tried "continue" and "break" in various places to no avail. > > > >I'd appreciate some help. > > Now that Aditya and Alan have come to my rescue, problem #1 has been > solved. But #2 remains.. > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071012/bfe5e7d8/attachment.htm From kent37 at tds.net Fri Oct 12 12:41:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Oct 2007 06:41:53 -0400 Subject: [Tutor] 2 problems in a small script In-Reply-To: <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> Message-ID: <470F4F71.9030905@tds.net> Aditya Lal wrote: > finalList = [ word for word in lstA if wellformed(word) ] or do everything in one statement: finalList = [ word for word in lstA if all(c in astr for c in word) ] Note to Dick: You don't have to convert word to a list before iterating it: wordWithCommas = list(word) print "wordWithCommas is", wordWithCommas for char in wordWithCommas: could be just for char in word: Kent From rdm at rcblue.com Fri Oct 12 13:39:56 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 04:39:56 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: <470F4F71.9030905@tds.net> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <470F4F71.9030905@tds.net> Message-ID: <20071012114003.80DB21E401D@bag.python.org> At 03:41 AM 10/12/2007, Kent Johnson wrote: >Aditya Lal wrote: >>finalList = [ word for word in lstA if wellformed(word) ] > >or do everything in one statement: > finalList = [ word for word in lstA if all(c in astr for c in word) ] I'm just not comfortable with list comprehensions yet, but I see that although yours is very succinct, it's clear enough. And I'd forgotten about the all() and any() (both new with 2.5 .) >Note to Dick: >You don't have to convert word to a list before iterating it: > wordWithCommas = list(word) > print "wordWithCommas is", wordWithCommas > for char in wordWithCommas: > >could be just > for char in word: Sure, strings are iterable. Dumb of me. Thanks, Dick From kent37 at tds.net Fri Oct 12 14:35:55 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Oct 2007 08:35:55 -0400 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012114003.80DB21E401D@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <470F4F71.9030905@tds.net> <20071012114003.80DB21E401D@bag.python.org> Message-ID: <470F6A2B.3060806@tds.net> Dick Moores wrote: > At 03:41 AM 10/12/2007, Kent Johnson wrote: >> finalList = [ word for word in lstA if all(c in astr for c in word) ] > > I'm just not comfortable with list comprehensions yet, Hmm, too bad. I use list comps and generator expressions constantly. > but I see that > although yours is very succinct, it's clear enough. Or maybe *because* it is succinct. Most list comps and genexps are either applying a function to every element of a list (map): [ f(x) for x in seq ] or filtering a list: [ x for x in seq if f(x) ] and occasionally both: [ f(x) for x in seq if g(x) ] where f and g could be actual functions or simple expressions. I think the reason I like them so much is because they are succinct, high-level, and flow in the same order as my thoughts. For example, the requirement "Give me a list of the square of every element of seq" translates directly to [ # Give me a list x*x # of the square for x in seq ] # of every element of seq and "I need a list of every element in seq that is > 2" becomes [ # I need a list x for x in seq # of every element in seq if x>2 ] # that is > 2 I have a writeup here: http://personalpages.tds.net/~kent37/kk/00003.html Kent From rdm at rcblue.com Fri Oct 12 16:22:36 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 07:22:36 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.co m> <20071012070242.A3FDC1E401C@bag.python.org> Message-ID: <20071012142254.BA2EA1E4021@bag.python.org> At 12:34 AM 10/12/2007, Alan Gauld wrote: >lstB = lstA[:] # a full slice creates a copy > >But thats not an efficient approach if you have a big list, the >best route is to build a new list, preferably using a list >comprehension. Alan, here's a test I made up. It doesn't show your contention is correct, but I imagine you or someone else will show me I don't know what I'm doing. :-) Maybe lstA isn't big enough, or complex enough? =============== # timing3WaysCopyList.py import time print "starting at", time.strftime('%H:%M:%S') n = 1 lstA = [1000*'qwerty123456']*10000000 print "First Way: lstB = lstA[:]" print "starting at", time.strftime('%H:%M:%S') timeStart = time.time() lstB = lstA[:] timeEnd = time.time() print "Time was %.4g seconds" % (timeEnd - timeStart) print print "Second Way: for x in lstA" print "starting at", time.strftime('%H:%M:%S') timeStart = time.time() lstC = [] for x in lstA: lstC.append(x) timeEnd = time.time() print "Time was %.4g seconds" % (timeEnd - timeStart) print print "Third Way: List Comprehension" print "starting at", time.strftime('%H:%M:%S') timeStart = time.time() lstD = [x for x in lstA] timeEnd = time.time() print "Time was %.4g seconds" % (timeEnd - timeStart) print ====================== Output: First Way: lstB = lstA[:] Time was 0.281 seconds Second Way: for x in lstA; lstC.append(x) Time was 7.359 seconds Third Way: List Comprehension [x for x in lstA] Time was 4.203 seconds ======================= Dick From rdm at rcblue.com Fri Oct 12 16:36:02 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 07:36:02 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: <470F6A2B.3060806@tds.net> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <470F4F71.9030905@tds.net> <20071012114003.80DB21E401D@bag.python.org> <470F6A2B.3060806@tds.net> Message-ID: <20071012143612.97E4A1E4030@bag.python.org> At 05:35 AM 10/12/2007, Kent Johnson wrote: >Dick Moores wrote: >>At 03:41 AM 10/12/2007, Kent Johnson wrote: >>> finalList = [ word for word in lstA if all(c in astr for c in word) ] >>I'm just not comfortable with list comprehensions yet, > >Hmm, too bad. I use list comps and generator expressions constantly. > >>but I see that although yours is very succinct, it's clear enough. > >Or maybe *because* it is succinct. Most list comps and genexps are >either applying a function to every element of a list (map): >[ f(x) for x in seq ] > >or filtering a list: >[ x for x in seq if f(x) ] > >and occasionally both: >[ f(x) for x in seq if g(x) ] > >where f and g could be actual functions or simple expressions. > >I think the reason I like them so much is because they are succinct, >high-level, and flow in the same order as my thoughts. For example, >the requirement "Give me a list of the square of every element of >seq" translates directly to >[ # Give me a list >x*x # of the square >for x in seq ] # of every element of seq > >and "I need a list of every element in seq that is > 2" becomes >[ # I need a list >x for x in seq # of every element in seq >if x>2 ] # that is > 2 > >I have a writeup here: >http://personalpages.tds.net/~kent37/kk/00003.html > >Kent Terrific, Kent. I promise I'll use 'em whenever I can. And I'll also try again to understand generators: . But I'll begin with the section just before that, on iterators: . Looks like tough going.. Dick From kent37 at tds.net Fri Oct 12 16:53:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Oct 2007 10:53:36 -0400 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012143612.97E4A1E4030@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <470F4F71.9030905@tds.net> <20071012114003.80DB21E401D@bag.python.org> <470F6A2B.3060806@tds.net> <20071012143612.97E4A1E4030@bag.python.org> Message-ID: <470F8A70.7040906@tds.net> Dick Moores wrote: > Terrific, Kent. I promise I'll use 'em whenever I can. And I'll also > try again to understand generators: > . > But I'll begin with the section just before that, on iterators: > . > Looks like tough going.. Maybe you like my writeup better: http://personalpages.tds.net/~kent37/kk/00004.html There's not much reason to write iterators from scratch anymore; in most cases it is simpler to write a generator function. It's good to understand the concept of an iterator but the details of the plumbing are not so important. Kent From kent37 at tds.net Fri Oct 12 16:55:01 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Oct 2007 10:55:01 -0400 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012143612.97E4A1E4030@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <470F4F71.9030905@tds.net> <20071012114003.80DB21E401D@bag.python.org> <470F6A2B.3060806@tds.net> <20071012143612.97E4A1E4030@bag.python.org> Message-ID: <470F8AC5.5060206@tds.net> Dick Moores wrote: > Terrific, Kent. I promise I'll use 'em whenever I can. And I'll also > try again to understand generators: > . > But I'll begin with the section just before that, on iterators: > . > Looks like tough going.. Maybe you like my writeup better: http://personalpages.tds.net/~kent37/kk/00004.html There's not much reason to write iterators from scratch anymore; in most cases it is simpler to write a generator function. It's good to understand the concept of an iterator but the details of the plumbing are not so important. Kent From gregg at lind-beil.net Fri Oct 12 16:14:32 2007 From: gregg at lind-beil.net (gregg at lind-beil.net) Date: Fri, 12 Oct 2007 09:14:32 -0500 (CDT) Subject: [Tutor] slice lists and slicing syntax questions Message-ID: <3329.209.98.145.171.1192198472.squirrel@www.lind-beil.net> Hello Python Tutor! I have been using Python for years now, in all kinds of environments, but I don't really understand the restrictions on slicing. As described in http://jtauber.com/blog/2005/08/16/python_slice_questions/ and http://mail.python.org/pipermail/python-list/2006-February/368291.html, in matrix oriented languages like R, Octave / Matlab, and NumPy, vectors, lists, and matrices support slice lists of arbitrary indices. example: x is vector of length 5, with value "a","b","c","d","e" , then: x[3,1,1,1,3,2] # gives [d, b, b, b, d, c] What is the python equivalent? a. Am I understanding the situation correctly? b. Why was this particular way of doing slices chosen? c. What is the best solution for "masking" vectors? Is it to use filter? Using NumPy? To use a list comprehension, a la: [a[j] for j in good_indices] (I ask this because I think this is a misfeature, and I hope that I can be corrected in my perception, not because I dislike Python. Quite the contrary!) Thanks, Gregg Lind From rdm at rcblue.com Fri Oct 12 19:32:00 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 10:32:00 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: <470F8A70.7040906@tds.net> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <470F4F71.9030905@tds.net> <20071012114003.80DB21E401D@bag.python.org> <470F6A2B.3060806@tds.net> <20071012143612.97E4A1E4030@bag.python.org> <470F8A70.7040906@tds.net> Message-ID: <20071012173307.A3B881E4022@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071012/6cf7845d/attachment.htm From kent37 at tds.net Fri Oct 12 19:55:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Oct 2007 13:55:23 -0400 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012173307.A3B881E4022@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <470F4F71.9030905@tds.net> <20071012114003.80DB21E401D@bag.python.org> <470F6A2B.3060806@tds.net> <20071012143612.97E4A1E4030@bag.python.org> <470F8A70.7040906@tds.net> <20071012173307.A3B881E4022@bag.python.org> Message-ID: <470FB50B.7070403@tds.net> Dick Moores wrote: > BTW is Kent's Korner still going at your SIG? Can we expect some more of > these gems to appear soon on < http://personalpages.tds.net/~kent37/kk/>? Yes, it's a regular monthly feature of the meeting. I missed last month but there should be another one in a few weeks. The meeting is the fourth Thursday so new issues appear about that time. And of course anyone near Manchester, NH on the fourth Thursday of the month is welcome to drop by and get the presentation in person! Kent From rdm at rcblue.com Fri Oct 12 20:11:26 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 11:11:26 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: <470FB50B.7070403@tds.net> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <470F4F71.9030905@tds.net> <20071012114003.80DB21E401D@bag.python.org> <470F6A2B.3060806@tds.net> <20071012143612.97E4A1E4030@bag.python.org> <470F8A70.7040906@tds.net> <20071012173307.A3B881E4022@bag.python.org> <470FB50B.7070403@tds.net> Message-ID: <20071012181134.D5B711E4022@bag.python.org> At 10:55 AM 10/12/2007, Kent Johnson wrote: >Dick Moores wrote: >>BTW is Kent's Korner still going at your SIG? Can we expect some >>more of these gems to appear soon on < >>http://personalpages.tds.net/~kent37/kk/>? > >Yes, it's a regular monthly feature of the meeting. I missed last >month but there should be another one in a few weeks. The meeting is >the fourth Thursday so new issues appear about that time. Great! I've just set to get a notification of a change on Kent's Korner page. >And of course anyone near Manchester, NH on the fourth Thursday of >the month is welcome to drop by and get the presentation in person! I won't be get there for a while at least--I live near Seattle. :( Dick From alan.gauld at btinternet.com Fri Oct 12 20:29:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Oct 2007 19:29:30 +0100 Subject: [Tutor] 2 problems in a small script References: <20071012055549.CE0BB1E4027@bag.python.org><5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com><5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.co m><20071012070242.A3FDC1E401C@bag.python.org> <20071012142254.BA2EA1E4021@bag.python.org> Message-ID: "Dick Moores" wrote >>But thats not an efficient approach if you have a big list, the >>best route is to build a new list, preferably using a list >>comprehension. > > Alan, here's a test I made up. It doesn't show your contention is > correct, but I imagine you or someone else will show me I don't know > what I'm doing. :-) Efficiency isn't always measured in terms of speed! Think about the memory resources. Imagine you have a list of a few million entries. Now with your approach you make a copy (doubling the memory usage) then delete the ones you don't need - possibly most of them. But with a LC you start with the original list and build a new list with only those elements you need. Thus the maximum memory use is the final product. The reason thats significant is that on most OS proceses don't release memory back to the OS untul,after they die. So your approach will leave your program consuming twice the size of the list forever more (until it dies) whereas the other approach only uses List1 + List2... Of course for 1) a short lived process on a PC 2) with lots of RAM and 3) a single user or for small size lists then that won't make much difference. But if any of those conditions is not true it could be significant HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Fri Oct 12 20:44:53 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 12 Oct 2007 11:44:53 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.co m> <20071012070242.A3FDC1E401C@bag.python.org> <20071012142254.BA2EA1E4021@bag.python.org> Message-ID: <20071012184503.AD8BD1E4022@bag.python.org> At 11:29 AM 10/12/2007, Alan Gauld wrote: >"Dick Moores" wrote > > >>But thats not an efficient approach if you have a big list, the > >>best route is to build a new list, preferably using a list > >>comprehension. > > > > Alan, here's a test I made up. It doesn't show your contention is > > correct, but I imagine you or someone else will show me I don't know > > what I'm doing. :-) > >Efficiency isn't always measured in terms of speed! > >Think about the memory resources. Imagine you have a list >of a few million entries. Now with your approach you make >a copy (doubling the memory usage) then delete the ones >you don't need - possibly most of them. But with a LC you >start with the original list and build a new list with only those >elements you need. Thus the maximum memory use is >the final product. > >The reason thats significant is that on most OS proceses >don't release memory back to the OS untul,after they die. >So your approach will leave your program consuming >twice the size of the list forever more (until it dies) whereas >the other approach only uses List1 + List2... > >Of course for >1) a short lived process on a PC >2) with lots of RAM and >3) a single user > >or for small size lists > >then that won't make much difference. >But if any of those conditions is not true it could be significant Aha! See, I figured you'd tell me I was all wet. Thanks, Alan. Dick From kent37 at tds.net Fri Oct 12 20:48:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Oct 2007 14:48:16 -0400 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012142254.BA2EA1E4021@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.co m> <20071012070242.A3FDC1E401C@bag.python.org> <20071012142254.BA2EA1E4021@bag.python.org> Message-ID: <470FC170.2020409@tds.net> Dick Moores wrote: > At 12:34 AM 10/12/2007, Alan Gauld wrote: >> lstB = lstA[:] # a full slice creates a copy >> >> But thats not an efficient approach if you have a big list, the >> best route is to build a new list, preferably using a list >> comprehension. > > Alan, here's a test I made up. It doesn't show your contention is > correct, but I imagine you or someone else will show me I don't know > what I'm doing. :-) > > Maybe lstA isn't big enough, or complex enough? If all you want to do is copy the list, then lstB = lstA[:] is fine, or you can use lstB = list(lstA) But the original question was about *filtering* the list. With the copy you are back to your original problem - how do I delete items from a list while iterating over it? The list comp is probably faster for this than anything you can come up with that starts with a copy and then deletes items. Kent > > =============== > # timing3WaysCopyList.py > import time > print "starting at", time.strftime('%H:%M:%S') > > n = 1 > lstA = [1000*'qwerty123456']*10000000 > > print "First Way: lstB = lstA[:]" > print "starting at", time.strftime('%H:%M:%S') > timeStart = time.time() > lstB = lstA[:] > timeEnd = time.time() > print "Time was %.4g seconds" % (timeEnd - timeStart) > print > > print "Second Way: for x in lstA" > print "starting at", time.strftime('%H:%M:%S') > timeStart = time.time() > lstC = [] > for x in lstA: > lstC.append(x) > timeEnd = time.time() > print "Time was %.4g seconds" % (timeEnd - timeStart) > print > > print "Third Way: List Comprehension" > print "starting at", time.strftime('%H:%M:%S') > timeStart = time.time() > lstD = [x for x in lstA] > timeEnd = time.time() > print "Time was %.4g seconds" % (timeEnd - timeStart) > print > ====================== > > Output: > > First Way: lstB = lstA[:] > Time was 0.281 seconds > > Second Way: for x in lstA; lstC.append(x) > Time was 7.359 seconds > > Third Way: List Comprehension [x for x in lstA] > Time was 4.203 seconds > ======================= > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jim at well.com Fri Oct 12 21:00:08 2007 From: jim at well.com (jim stockford) Date: Fri, 12 Oct 2007 12:00:08 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: <470FC170.2020409@tds.net> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.co m> <20071012070242.A3FDC1E401C@bag.python.org> <20071012142254.BA2EA1E4021@bag.python.org> <470FC170.2020409@tds.net> Message-ID: <0648c37efb572869b839af6cc35592c1@well.com> On Oct 12, 2007, at 11:48 AM, Kent Johnson wrote: > If all you want to do is copy the list, then > lstB = lstA[:] > is fine, or you can use > lstB = list(lstA) why choose one over the other? is there a performance or other difference? From kent37 at tds.net Fri Oct 12 21:18:57 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 12 Oct 2007 15:18:57 -0400 Subject: [Tutor] 2 problems in a small script In-Reply-To: <0648c37efb572869b839af6cc35592c1@well.com> References: <20071012055549.CE0BB1E4027@bag.python.org> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.com> <5df213700710112325g64417e8fjf75278ced4889364@mail.gmail.co m> <20071012070242.A3FDC1E401C@bag.python.org> <20071012142254.BA2EA1E4021@bag.python.org> <470FC170.2020409@tds.net> <0648c37efb572869b839af6cc35592c1@well.com> Message-ID: <470FC8A1.9020305@tds.net> jim stockford wrote: > > On Oct 12, 2007, at 11:48 AM, Kent Johnson wrote: > >> If all you want to do is copy the list, then >> lstB = lstA[:] >> is fine, or you can use >> lstB = list(lstA) > > why choose one over the other? is there a performance > or other difference? The timeit module helps figure out if there is a performance difference. Slicing seems to have a slight edge over a wide range if list sizes: src $ python -m timeit -s 'l1=range(1000)' 'l2=list(l1)' 100000 loops, best of 3: 5.12 usec per loop src $ python -m timeit -s 'l1=range(1000)' 'l2=l1[:]' 100000 loops, best of 3: 4.27 usec per loop src $ python -m timeit -s 'l1=range(10)' 'l2=list(l1)' 1000000 loops, best of 3: 0.487 usec per loop src $ python -m timeit -s 'l1=range(10)' 'l2=l1[:]' 1000000 loops, best of 3: 0.258 usec per loop src $ python -m timeit -s 'l1=range(10000)' 'l2=list(l1)' 10000 loops, best of 3: 126 usec per loop src $ python -m timeit -s 'l1=range(10000)' 'l2=l1[:]' 10000 loops, best of 3: 108 usec per loop Other than that I think it is personal preference, whichever you prefer. Kent From andrewwu at gmail.com Fri Oct 12 21:48:56 2007 From: andrewwu at gmail.com (Andrew Wu) Date: Fri, 12 Oct 2007 12:48:56 -0700 Subject: [Tutor] Help with packages and namespaces please Message-ID: <99acdf3c0710121248g2632355buaddedc36060d712b@mail.gmail.com> Hi all, I'm new to the list and relatively new to python, and very new to the use and creation of packages. Let's say I have these files in one directory: PrintBase.py PrintHello.py PrintBye.py PrintBase defines a very simple base class PrintBase, whose __init__ method initializes a member to an optionally provided string (otherwise the string is empty) and whose PrintMe method prints the string given (or empty string otherwise). PrintHello defines a class that inherits from PrintBase and whose PrintMe method prepends a 'Hello, ' to the provided string. PrintBye defines a class that inherits from PrintBase and whose PrintMe method prepends a 'Good-bye' to the provided string. Since all the files are in the same directory, I can use import statements like from PrintHello import PrintHello ... I'd like to reorganize the files so they're like the Sound example in the Python tutorial: PrintMe/ PrintMe/PrintBase/PrintBase.py PrintMe/PrintHello/PrintHello.py PrintMe/PrintBye/PrintBye.py I've created empty __init__.py files in each of the subdirectories. Here I run into a number of problems and get confused - my goal is to keep the import statements as they are (the actual files I'd be editing are many and I'd rather avoid having to edit them all) - is there something I can put in the __init__.py files so that the modules are brought into namespace w/o having to use absolute module notation? As simple tests, I've tried running different import commands in the python interpreter: I've tried adding the absolute directory paths to __path__ in each __init__.py per subdirectory, and adding the paths to sys.path. When I do that and run the python intepreter and try 'from PrintMe.PrintHello import PrintHello' I get an error saying 'Error when calling the metaclass bases, module.__init__() takes at most 2 arguments (3 given)'. The same code functioned fine when all the files were in the same directory, so I'm confused about why the interpreter thinks I'm passing 3 arguments along. W/o those directories in sys.path I get an import error (there is no module named 'PrintBase'). Also, if I'm in one of the subdirectories I get a similar error when attempting to import the toplevel (PrintMe) package. (Essentially I would like to structure the directories (er package?) so that files in one subdirectory can subclass base classes from a sibling (not parent) directory, ideally in a way that doesn't require each file to state something like 'from 'PrintMe.PrintHello ... import ...' but instead 'from PrintHello import ...'. Is this possible, and if so how can I go about doing it?) Many Thanks! Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071012/bd026268/attachment-0001.htm From carroll at tjc.com Fri Oct 12 22:58:03 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 12 Oct 2007 13:58:03 -0700 (PDT) Subject: [Tutor] 2 problems in a small script In-Reply-To: <470F6A2B.3060806@tds.net> Message-ID: On Fri, 12 Oct 2007, Kent Johnson wrote: > Dick Moores wrote: > > > I'm just not comfortable with list comprehensions yet, > > Hmm, too bad. I use list comps and generator expressions constantly. It took me a while to get list comprehensions. It's one of those things that suddenly snaps into place and you're suddenly comfortable with. What took me the longest time is to realize that it's really a way of generating one list from another list. Once I got that, I started naturally turning to list comprehensions whenever I found myself generating one list from another. From alan.gauld at btinternet.com Sat Oct 13 01:19:52 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Oct 2007 00:19:52 +0100 Subject: [Tutor] 2 problems in a small script References: <470F6A2B.3060806@tds.net> Message-ID: "Terry Carroll" wrote > It took me a while to get list comprehensions. It's one of those > things > that suddenly snaps into place and you're suddenly comfortable with. Me too and I still don't like the syntax. its the [x for x in... bit at the start that reads badly for me, I'd have preferred if there was a seperator of some sort: [x | for x in ... or something. The problem is most punctuation is already used for something that is valid in an expression. The only thing that I think is OK is an exclamation mark but that, although somewhat similar to a | looks like a factorial operarion. But once you get used to it they are concise if not quite as descriptive as their functional.equivalents map/filter. Alan G. From alan.gauld at btinternet.com Sat Oct 13 01:37:23 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Oct 2007 00:37:23 +0100 Subject: [Tutor] slice lists and slicing syntax questions References: <3329.209.98.145.171.1192198472.squirrel@www.lind-beil.net> Message-ID: wrote > in matrix oriented languages like R, Octave / Matlab, and NumPy, > vectors, > lists, and matrices support slice lists of arbitrary indices. Python is a general purpose language and not matrix oriented. In fact it doesn't have native support for a matrix as such only through add on modules such as numpy. So not surprisingly normal python slicing doesn't do fancy tricks As a recent thread on extended slicing shows numpy (and potentially, other third party modules) can do fancy tricks with slicing of multi dimensional structures, but they aren't 'standard' python. In fact, Python was the first language I had seen that treated slicing as an operation and I thought it was really neat! Up till then(~1997) I had always had to write functions to do that (or use library functions if they existed). > example: x is vector of length 5, with value "a","b","c","d","e" , > then: > > x[3,1,1,1,3,2] # gives [d, b, b, b, d, c] > > What is the python equivalent? > > [a[j] for j in good_indices] I think that's probably as close as you can get. I can't think of anything more concise. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From witham.ian at gmail.com Sat Oct 13 03:48:19 2007 From: witham.ian at gmail.com (Ian Witham) Date: Sat, 13 Oct 2007 14:48:19 +1300 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071012055549.CE0BB1E4027@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> Message-ID: On 10/12/07, Dick Moores wrote: > > Please see the code and it's output here: > > > > I'm attempting to eliminate the elements (strings) of lstA that are > not well-formed in that they contain at least one character that is > not in the string astr. Hi Dick, If your interested, this could be done succinctly with set types. (no iterating required!) def well_formed(word): return not set('#.<@') & set(word) >>> well_formed('porkpie') True >>> well_formed('p#rkpie') False And then it seems you are coming to terms with list comprehensions... my_list = [word for word in my_list if well_formed(my_word)] OR... my_list = filter(well_formed, my_list) Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071013/36fc063b/attachment.htm From ebrosh at nana10.co.il Sat Oct 13 11:04:05 2007 From: ebrosh at nana10.co.il (Eli Brosh) Date: Sat, 13 Oct 2007 11:04:05 +0200 Subject: [Tutor] Variables in workspace Message-ID: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> Hello I am working with python interactively using IDLE. Since starting, I defined some variables: s='string' a=1 b=[1,2] c=1.02 and so on. Now, I want to know which variables are in my workspace. That is, is there a command similar to "who" in MATLAB ? I want to call "who" and get the output: s a b c (a listing of all the variables I defined in the session) Now, is there a way to clear some or all the variables in that list ? Thanks Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071013/285f8e22/attachment.htm From kent37 at tds.net Sat Oct 13 14:54:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Oct 2007 08:54:27 -0400 Subject: [Tutor] Variables in workspace In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> References: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> Message-ID: <4710C003.2010409@tds.net> Eli Brosh wrote: > I am working with python interactively using IDLE. > > Since starting, I defined some variables: > > Now, I want to know which variables are in my workspace. ==== RESTART ================================ >>> dir() ['__builtins__', '__doc__', '__name__'] >>> s='string' >>> a=1 >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 's'] > Now, is there a way to clear some or all the variables in that list ? >>> del a >>> del s >>> dir() ['__builtins__', '__doc__', '__name__'] To clear all you can Restart Shell from the menu. Kent From kent37 at tds.net Sat Oct 13 15:19:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Oct 2007 09:19:27 -0400 Subject: [Tutor] Help with packages and namespaces please In-Reply-To: <99acdf3c0710121248g2632355buaddedc36060d712b@mail.gmail.com> References: <99acdf3c0710121248g2632355buaddedc36060d712b@mail.gmail.com> Message-ID: <4710C5DF.2080201@tds.net> Andrew Wu wrote: > Let's say I have these files in one directory: > > PrintBase.py > PrintHello.py > PrintBye.py > I'd like to reorganize the files so they're like the Sound example in > the Python tutorial: > > PrintMe/ > PrintMe/PrintBase/PrintBase.py > PrintMe/PrintHello/PrintHello.py > PrintMe/PrintBye/PrintBye.py Will there be more modules in each subdirectory? I'm not sure if this is just for learning or if it is a simplification of a real problem, but from your description of the classes it sounds like they belong in the same package. > I've created empty __init__.py files in each of the subdirectories. > Here I run into a number of problems and get confused - my goal is to > keep the import statements as they are (the actual files I'd be editing > are many and I'd rather avoid having to edit them all) - is there > something I can put in the __init__.py files so that the modules are > brought into namespace w/o having to use absolute module notation? You can bring names into the package namespace, but the actual code will still run in the module where it is defined. For example, in PrintMe/PrintBase/__init__.py you can say from PrintBase import Printbase Hmm. I'm not sure if this will work the way you want because of the name collisions. Using the sound example where the names are unique, suppose wavread.py includes a function read_wav(). Then in Formats/__init__.py you can say from wavread import read_wav This imports the name read_wav into the Formats package namespace so other code will be able to say from Sound.Formats import read_wav In your example, *without* the import in PrintBase/__init__.py it is already valid to say from PrintMe.PrintBase import PrintBase which will access the *module* PrintBase. When you add the line from PrintBase import Printbase to __init__.py then there are two possible meanings for PrintMe.PrintBase.PrintBase and I don't know which one will have priority. My guess is that the module import will win but I don't know. At best this seems like a recipe for endless confusion - you have three entities named PrintBase - a package, a module and a class. If the import in __init__ promotes the class as you want, it still won't help with the imports in PrintHello.py - it will still have to say at least from PrintMe.PrintBase import PrintBase Why do you want to do this? It looks like a confusing mess to me. > > As simple tests, I've tried running different import commands in the > python interpreter: > > I've tried adding the absolute directory paths to __path__ in each > __init__.py per subdirectory, and adding the paths to sys.path. Yuck. What is the point of the directories and packages if you are going to put every thing on sys.path anyway? But I think it should work if you put each of the subdirectories of PrintMe on sys.path. > When I > do that and run the python intepreter and try 'from PrintMe.PrintHello > import PrintHello' I get an error saying 'Error when calling the > metaclass bases, module.__init__() takes at most 2 arguments (3 > given)'. The same code functioned fine when all the files were in the > same directory, so I'm confused about why the interpreter thinks I'm > passing 3 arguments along. You get an error on the import? Please show the traceback. Kent From bgailer at alum.rpi.edu Sat Oct 13 16:29:33 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 13 Oct 2007 10:29:33 -0400 Subject: [Tutor] Variables in workspace In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> References: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> Message-ID: <4710D64D.10901@alum.rpi.edu> Eli Brosh wrote: > > Hello > I am working with python interactively using IDLE. > > Since starting, I defined some variables: > s='string' > a=1 > b=[1,2] > c=1.02 > > and so on. > > Now, I want to know which variables are in my workspace. > That is, is there a command similar to "who" in MATLAB ? > I want to call "who" > and get the output: > s a b c > (a listing of all the variables I defined in the session) > Start IDLE, then enter dir(). That will give you the names already in the workspace. Then assign your variables and enter dir() again. > > > Now, is there a way to clear some or all the variables in that list ? > Clear? Do you mean set to None or delete them? The del statement is the way to delete variables. Since dir() gives you their names one needs use eval. for varName in dir(): eval 'del ' + varName Of course that is overkill as it will delete __builtins__ etc, so you want to screen out all the names that you see in the initial dir() call. From mlangford.cs03 at gtalumni.org Sat Oct 13 16:32:39 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sat, 13 Oct 2007 10:32:39 -0400 Subject: [Tutor] slice lists and slicing syntax questions In-Reply-To: <3329.209.98.145.171.1192198472.squirrel@www.lind-beil.net> References: <3329.209.98.145.171.1192198472.squirrel@www.lind-beil.net> Message-ID: <82b4f5810710130732t66b10ec8k7197cbc47a881def@mail.gmail.com> On 10/12/07, gregg at lind-beil.net < gregg at lind-beil.net> wrote: > > I have been using Python for years now, in all kinds of environments, but > example: x is vector of length 5, with value "a","b","c","d","e" , then: > > x[3,1,1,1,3,2] # gives [d, b, b, b, d, c] > > What is the python equivalent? a. Am I understanding the situation correctly? When you call [] on an object, it calls __getitem__The definition for getitem is __getitem__(self,key), where key can be an integer or a slice object. Slice objects are either a range or a range+step. You've got the right picture b. Why was this particular way of doing slices chosen? Dunno. I'll leave this to the language historians. I will say a differently implemented slice object interface would lend itself to novel types of slicing, like you're talking about. If, for instance, the slice object would return an iterator of indicies, you could add this case to the indexable objects. However, the way it currently is, I don't see that being possible. Also, the way it currently is, I don't see it working well with all the code that implements __getitem__ as it's currently written even if slice was implemented. c. What is the best solution for "masking" vectors? > I'm with a decorator, you can get to at least x(4,3,3,3,2,1) returning the type of list you want. At the same time, I'm not sure you're going to be able to override the __getitem__ prototype without some serious pain.I've never tried to change the function/method signature with a decorator, but I'm pretty sure its possible at least for the non-builtin attributes. You may want to try to write a PEP for python 3000. So much is being changed with that, you may get it in. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071013/49b37ad2/attachment.htm From kent37 at tds.net Sat Oct 13 16:47:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Oct 2007 10:47:45 -0400 Subject: [Tutor] slice lists and slicing syntax questions In-Reply-To: <82b4f5810710130732t66b10ec8k7197cbc47a881def@mail.gmail.com> References: <3329.209.98.145.171.1192198472.squirrel@www.lind-beil.net> <82b4f5810710130732t66b10ec8k7197cbc47a881def@mail.gmail.com> Message-ID: <4710DA91.8030902@tds.net> Michael Langford wrote: > When you call [] on an object, it calls __getitem__The definition for > getitem is __getitem__(self,key), where key can be an integer or a slice > object. Or a tuple of integers/slices. > You may want to try to write a PEP for python 3000. So much is being > changed with that, you may get it in. The deadline for PEPs for Python 3 has long passed - it was in April IIRC. Kent From kent37 at tds.net Sat Oct 13 16:49:12 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Oct 2007 10:49:12 -0400 Subject: [Tutor] Variables in workspace In-Reply-To: <4710D64D.10901@alum.rpi.edu> References: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> <4710D64D.10901@alum.rpi.edu> Message-ID: <4710DAE8.2010702@tds.net> bob gailer wrote: > The del statement is the way to delete variables. Since dir() gives you > their names one needs use eval. > > for varName in dir(): > eval 'del ' + varName I think del globals()[varName] would work. Kent From bgailer at alum.rpi.edu Sat Oct 13 17:35:55 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 13 Oct 2007 11:35:55 -0400 Subject: [Tutor] Variables in workspace In-Reply-To: <4710DAE8.2010702@tds.net> References: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> <4710D64D.10901@alum.rpi.edu> <4710DAE8.2010702@tds.net> Message-ID: <4710E5DB.9040001@alum.rpi.edu> Kent Johnson wrote: > bob gailer wrote: >> The del statement is the way to delete variables. Since dir() gives >> you their names one needs use eval. >> >> for varName in dir(): >> eval 'del ' + varName > > I think del globals()[varName] would work. Yep. That was nagging a corner of my brain, but not surfacing. From alan.gauld at btinternet.com Sat Oct 13 18:30:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Oct 2007 17:30:05 +0100 Subject: [Tutor] Variables in workspace References: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> Message-ID: "Eli Brosh" wrote > Now, I want to know which variables are in my workspace. Try dir() That should give you the names in the current namespace. You will see some names you didn't define too. dir()is a really helpful command when you want to see whats possible. >>> dir('') Will list all the methods of a string for example. >>> import math >>> dir(math) will list all the math functions and constants. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From chiselchip at earthlink.net Sat Oct 13 20:58:20 2007 From: chiselchip at earthlink.net (LandSurveyor) Date: Sat, 13 Oct 2007 14:58:20 -0400 (GMT-04:00) Subject: [Tutor] upgrading Python Message-ID: <22923524.1192301901117.JavaMail.root@elwamui-sweet.atl.sa.earthlink.net> I wish to upgrade Python from the [Vers.] 2.3.4 that came packaged with my Mandrake 10.1 Linux OS to the current 2.5.1. The 'hash/bang' line of my python scripts is "#!/usr/bin/python". There are two files, both executables, in my /usr/bin directory; they are 1)python, and 2)python2.3. I just simply don't know what to do next!? The advise I can google to is typically overly generous, full of contradictions (sometime within the same post..."Well you can do this, but if you wanna do that instead..."). Well, I don't know why "I want to do this", or "do that instead". I just want to know where to put my new version of python, and when I unzip/configure/and so on..., will I end up with: 1)an application that will pick up seamlessly and run my apps? 2)will pythontutor still be available? 3)will I have an upgraded & accessible package of modules? 4)will I need to modify the "hash/bang" line? 5)when I type 'python' on a command line, how will I access the new 2.5.1 rather than the older version? i.e., where do I go to modify the results of that request? Oh, and could I-as I understand (to a limited degree) Linux- install the entire package within my home directory, following the principle that I am a user without admin privileges, and then change the "hash/bang" line to redirect to my 'embedded' version, and thus be running 2.5.1 within my own little world? And if I did so, the same questions persist. If I asked for a module, would I get the one from my 2.5.1, or the module that exists in the older 2.3.4? And when I entered 'python' from a command line (to access the interpreter) how would I get my 2.5.1 version, rather than the older 2.3.4. It's just amazing, the array of niggling little questions that no one thinks about, but that create unmountable stumbling blocks once they pop up in the middle of your path, isn't it!? But, they are enough to completely stop me in my tracks, and they are the nitty-gritty questions that no one seems to think important enough to address and clarify. Thanks, folks. From davmillar at gmail.com Sat Oct 13 21:19:41 2007 From: davmillar at gmail.com (David Millar) Date: Sat, 13 Oct 2007 15:19:41 -0400 Subject: [Tutor] upgrading Python In-Reply-To: <22923524.1192301901117.JavaMail.root@elwamui-sweet.atl.sa.earthlink.net> References: <22923524.1192301901117.JavaMail.root@elwamui-sweet.atl.sa.earthlink.net> Message-ID: Hi there, I'm not familiar with Mandrake, but I use Ubuntu Linux and my package manager does updates for me. It looks like Madrake has a package manager called urpmi according to Wikipedia - have you tried using that to install a new RPM package for Python 2.5.1 or simply trying to have it automatically update for you? If you have some other package manager there may be a different way to do it though - if you had apt-get or Synaptic I could walk you through it that way. Anyway, once you do have it installed, I believe that /usr/bin/python just has the basic stuff and references everything else in the other executable script, so you shouldn't have to change the "#!" line ever ever. I hope something I said helps with Q4&5! Dave On 10/13/07, LandSurveyor wrote: > > I wish to upgrade Python from the [Vers.] 2.3.4 that came packaged with my > Mandrake 10.1 Linux OS to the current 2.5.1. The 'hash/bang' line of my > python scripts is "#!/usr/bin/python". There are two files, both > executables, in my /usr/bin directory; they are 1)python, and 2)python2.3. > > I just simply don't know what to do next!? The advise I can google to is > typically overly generous, full of contradictions (sometime within the same > post..."Well you can do this, but if you wanna do that instead..."). Well, > I don't know why "I want to do this", or "do that instead". I just want to > know where to put my new version of python, and when I unzip/configure/and > so on..., will I end up with: > > 1)an application that will pick up seamlessly and run my apps? > 2)will pythontutor still be available? > 3)will I have an upgraded & accessible package of modules? > 4)will I need to modify the "hash/bang" line? > 5)when I type 'python' on a command line, how will I access the new 2.5.1rather than the older version? > i.e., where do I go to modify the results of that request? > > Oh, and could I-as I understand (to a limited degree) Linux- install the > entire package within my home directory, following the principle that I am a > user without admin privileges, and then change the "hash/bang" line to > redirect to my 'embedded' version, and thus be running 2.5.1 within my own > little world? And if I did so, the same questions persist. If I asked for > a module, would I get the one from my 2.5.1, or the module that exists in > the older 2.3.4? And when I entered 'python' from a command line (to > access the interpreter) how would I get my 2.5.1 version, rather than the > older 2.3.4. > > It's just amazing, the array of niggling little questions that no one > thinks about, but that create unmountable stumbling blocks once they pop up > in the middle of your path, isn't it!? But, they are enough to completely > stop me in my tracks, and they are the nitty-gritty questions that no one > seems to think important enough to address and clarify. > > Thanks, folks. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071013/43a7c7b6/attachment.htm From dkuhlman at rexx.com Sat Oct 13 22:55:59 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 13 Oct 2007 13:55:59 -0700 Subject: [Tutor] slice lists and slicing syntax questions In-Reply-To: <82b4f5810710130732t66b10ec8k7197cbc47a881def@mail.gmail.com> References: <3329.209.98.145.171.1192198472.squirrel@www.lind-beil.net> <82b4f5810710130732t66b10ec8k7197cbc47a881def@mail.gmail.com> Message-ID: <20071013205559.GA81493@cutter.rexx.com> On Sat, Oct 13, 2007 at 10:32:39AM -0400, Michael Langford wrote: > On 10/12/07, gregg at lind-beil.net < gregg at lind-beil.net> wrote: > > > > I have been using Python for years now, in all kinds of environments, but > > example: x is vector of length 5, with value "a","b","c","d","e" , then: > > > > x[3,1,1,1,3,2] # gives [d, b, b, b, d, c] > > > > What is the python equivalent? > > a. Am I understanding the situation correctly? > > When you call [] on an object, it calls __getitem__The definition for > getitem is __getitem__(self,key), where key can be an integer or a slice > object. Slice objects are either a range or a range+step. You've got the > right picture __getitem__() suggests a Pythonic solution: subclass list and override __getitem__(): class subscriptlist(list): def __getitem__(self, subscripts): #print 'type(subscripts):', type(subscripts) if (isinstance(subscripts, tuple) or isinstance(subscripts, list)): vals = [] for subscript in subscripts: vals.append(list.__getitem__(self, subscript)) return vals else: val = list.__getitem__(self, subscripts) return val def test(): a = range(10) b = [x * 5 for x in a] c = subscriptlist(b) d = c[2,5,6,8] print 'd:', d e = c[2] print 'e:', e test() Which prints out: d: [10, 25, 30, 40] e: 10 Was that what you wanted? Notice that "c[2,5,6,8]" results in passing a tuple to __getitem__, because it is the comma that marks a literal representation of a tuple. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dkuhlman at rexx.com Sat Oct 13 23:32:12 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 13 Oct 2007 14:32:12 -0700 Subject: [Tutor] Variables in workspace In-Reply-To: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> References: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> Message-ID: <20071013213212.GB81493@cutter.rexx.com> On Sat, Oct 13, 2007 at 11:04:05AM +0200, Eli Brosh wrote: > > Hello > I am working with python interactively using IDLE. > > Since starting, I defined some variables: > s='string' > a=1 > b=[1,2] > c=1.02 > > and so on. > > Now, I want to know which variables are in my workspace. > That is, is there a command similar to "who" in MATLAB ? > I want to call "who" > and get the output: > s a b c > (a listing of all the variables I defined in the session) > > Now, is there a way to clear some or all the variables in that list ? What is your purpose? What is your use case? Usually, when this question or its spawn come up on this list, the answer (and the right one, I think) is: Do not use separate variables, use keys in a dictionary. And, you might think: But that's not what I asked for. However, as your mother might say: That's what's good for you. Also, remember, in Python, global variables are just entries in the dictionary returned by globals(), anyway. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From bhaaluu at gmail.com Sat Oct 13 23:47:53 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 13 Oct 2007 17:47:53 -0400 Subject: [Tutor] upgrading Python In-Reply-To: <22923524.1192301901117.JavaMail.root@elwamui-sweet.atl.sa.earthlink.net> References: <22923524.1192301901117.JavaMail.root@elwamui-sweet.atl.sa.earthlink.net> Message-ID: Greetings, On my system I can have several python versions installed because they install as python2.3, python2.4, etc. $ which python /usr/bin/python $ ls -l /usr/bin/python ... /usr/bin/python -> python2.4 Here, we can see that "python" is just a link to /usr/bin/python2.4 So, I can install python 2.5, and simply change the link so when I enter "python" at the prompt, it will start python2.5. $ man ln ln [OPTION]... [-T] TARGET LINK_NAME (1st form) So, after installing python 2.5, change to /usr/bin, remove /usr/bin/python $ cd /usr/bin $ rm python And now make a new link to python2.5 (you may have to be root!): # ln -s /usr/bin/python2.5 python If I'm not mistaken, the library files, and so forth are stored in different directories, so installing a new version, won't corrupt an older version. ..../lib/python2.4/site-packages See how python 2.4 is in the python2.4 directory? If, for some reason, you want the other version, just start it with the absolute pathname: $ /usr/bin/python2.3 I hope this is helpful? I don't use Mandrake, so I'm unfamiliar with its package manager, or how to do upgrades for it. The above are generic *nix commands that should work with any distro. apt-get and Synaptic rock! =) -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html On 10/13/07, LandSurveyor wrote: > I wish to upgrade Python from the [Vers.] 2.3.4 that came packaged with my Mandrake 10.1 Linux OS to the current 2.5.1. The 'hash/bang' line of my python scripts is "#!/usr/bin/python". There are two files, both executables, in my /usr/bin directory; they are 1)python, and 2)python2.3. > > I just simply don't know what to do next!? The advise I can google to is typically overly generous, full of contradictions (sometime within the same post..."Well you can do this, but if you wanna do that instead..."). Well, I don't know why "I want to do this", or "do that instead". I just want to know where to put my new version of python, and when I unzip/configure/and so on..., will I end up with: > > 1)an application that will pick up seamlessly and run my apps? > 2)will pythontutor still be available? > 3)will I have an upgraded & accessible package of modules? > 4)will I need to modify the "hash/bang" line? > 5)when I type 'python' on a command line, how will I access the new 2.5.1 rather than the older version? i.e., where do I go to modify the results of that request? > > Oh, and could I-as I understand (to a limited degree) Linux- install the entire package within my home directory, following the principle that I am a user without admin privileges, and then change the "hash/bang" line to redirect to my 'embedded' version, and thus be running 2.5.1 within my own little world? And if I did so, the same questions persist. If I asked for a module, would I get the one from my 2.5.1, or the module that exists in the older 2.3.4? And when I entered 'python' from a command line (to access the interpreter) how would I get my 2.5.1 version, rather than the older 2.3.4. > > It's just amazing, the array of niggling little questions that no one thinks about, but that create unmountable stumbling blocks once they pop up in the middle of your path, isn't it!? But, they are enough to completely stop me in my tracks, and they are the nitty-gritty questions that no one seems to think important enough to address and clarify. > > Thanks, folks. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From paulino1 at sapo.pt Sun Oct 14 02:42:18 2007 From: paulino1 at sapo.pt (Paulino) Date: Sun, 14 Oct 2007 01:42:18 +0100 Subject: [Tutor] File upload from python shell Message-ID: <471165EA.2050502@sapo.pt> Hello! How can I upload a file from python? If it is a form to fill with values it's simple: urlopen("http://site.com/action?key1=value1;key2=value2") and I get the form filled. What about uploading a file programmaticaly? Thank you Paulino From varsha.purohit at gmail.com Sun Oct 14 03:40:14 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sat, 13 Oct 2007 18:40:14 -0700 Subject: [Tutor] [tutor] Formbuffer question in PIL Message-ID: Hello all, I need some help in using formbuffer function in PIL. Does anybody have sample program related to this ? thanks, -- Varsha -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071013/abf46569/attachment.htm From varsha.purohit at gmail.com Sun Oct 14 03:42:14 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sat, 13 Oct 2007 18:42:14 -0700 Subject: [Tutor] [tutor] Formbuffer question in PIL In-Reply-To: References: Message-ID: oops.. i wanted to ask about frombuffer which is in image library of PIL. I read the documentation but wanted a small sample program to understand its function... On 10/13/07, Varsha Purohit wrote: > > Hello all, > I need some help in using formbuffer function in PIL. Does anybody > have sample program related to this ? > thanks, > -- > Varsha > > -- Varsha Purohit, Graduate Student, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071013/c0325d6e/attachment-0001.htm From alan.gauld at btinternet.com Sun Oct 14 10:04:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Oct 2007 09:04:46 +0100 Subject: [Tutor] File upload from python shell References: <471165EA.2050502@sapo.pt> Message-ID: "Paulino" wrote > How can I upload a file from python? Just to be clear. You want to send a file from your computer to another computer? The simplest way to do that is using ftp. There is an ftp module. However for that to work the receiving computer needs to be running an ftp server. > If it is a form to fill with values it's simple: > > urlopen("http://site.com/action?key1=value1;key2=value2") > and I get the form filled. That may not always work if the form relies on an HTTP/POST request rather than a GET request. I'm not sure how you get urllib to use POST. Hmm, checking the docs it says: ------------------- urlopen( url[, data]) Open the URL url, which can be either a string or a Request object. data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format. -------------------------- > What about uploading a file programmaticaly? If you mean you want to submit a web form that requires a file then the form will use a POST request, so you will need to create a data string for the urlopen call using urlencode. However, how a file would be encoded into a string I don't know! I''ve never used POST requests in urllib. From a scan of the module it looks like you may need to use a FileOpener object but its not clear to me how that works. Hopefully someone else has done this already and can help. Alan G From rdm at rcblue.com Sun Oct 14 11:28:39 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 14 Oct 2007 02:28:39 -0700 Subject: [Tutor] 2 problems in a small script In-Reply-To: References: <20071012055549.CE0BB1E4027@bag.python.org> Message-ID: <20071014092847.8710B1E4026@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071014/50970e5b/attachment.htm From david at zettazebra.com Sun Oct 14 15:08:02 2007 From: david at zettazebra.com (David Clymer) Date: Sun, 14 Oct 2007 09:08:02 -0400 Subject: [Tutor] File upload from python shell In-Reply-To: <471165EA.2050502@sapo.pt> References: <471165EA.2050502@sapo.pt> Message-ID: <1192367282.22554.20.camel@zepto.home.zettazebra.com> On Sun, 2007-10-14 at 01:42 +0100, Paulino wrote: > Hello! > > > How can I upload a file from python? > > If it is a form to fill with values it's simple: > > > urlopen("http://site.com/action?key1=value1;key2=value2") and I get the > form filled. > > > What about uploading a file programmaticaly? Google tells me that urllib2 does not support file uploads properly, however it also tells me that one can use httplib directly to do it: http://wiki.forum.nokia.com/index.php/How_to_upload_a_file_to_server_with_application/x-www-form-urlencoded -davidc -- gpg-key: http://www.zettazebra.com/files/key.gpg -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20071014/a2c34121/attachment.pgp From ebrosh at nana10.co.il Sun Oct 14 18:05:07 2007 From: ebrosh at nana10.co.il (Eli Brosh) Date: Sun, 14 Oct 2007 18:05:07 +0200 Subject: [Tutor] Variables in workspace References: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il> <4710D64D.10901@alum.rpi.edu> <4710DAE8.2010702@tds.net> <4710E5DB.9040001@alum.rpi.edu> Message-ID: <957526FB6E347743AAB42B212AB54FDA95BA43@NANAMAILBACK1.nanamail.co.il> Many thanks to Bob and Kent and all the good people in the tutor forum. The dir() and del work really well ! Eli ________________________________ ???: bob gailer [mailto:bgailer at alum.rpi.edu] ????: ? 10/13/2007 17:35 ??: Kent Johnson ???? ??????: Eli Brosh; tutor at python.org ????: Re: [Tutor] Variables in workspace Kent Johnson wrote: > bob gailer wrote: >> The del statement is the way to delete variables. Since dir() gives >> you their names one needs use eval. >> >> for varName in dir(): >> eval 'del ' + varName > > I think del globals()[varName] would work. Yep. That was nagging a corner of my brain, but not surfacing. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071014/56946c68/attachment-0001.htm From chiselchip at earthlink.net Sun Oct 14 18:34:37 2007 From: chiselchip at earthlink.net (LandSurveyor) Date: Sun, 14 Oct 2007 12:34:37 -0400 (GMT-04:00) Subject: [Tutor] upgrading Python Message-ID: <7508625.1192379677560.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> Thanks for the 'meaty' response. Therein was the nitty-gritty I could actually use. Learned a bunch too...had never used a link before. Didn't know why I would want to. BTW, I met with HUGE success! Anyway...my approach was to take the road of a user (with my own '/home' account, and no SU privileges. That only went so far. I installed the new Python (2.5.1) in a directory within my home that I called, incisively, '/usrlowell'. Therein I opened up the .tgz file, and got as far as 'make', when it required me to have SU privileges (so much for the theory that I could do all I wished within my own 'world'). That speed bump has undermined a number of concepts I thought I'd figured out-regarding autonomy for a user-so I don't know now what I don't know.). Long and the short of it, the 'make' and 'make install' continued in the /usr/bin environ (i.e., departed from my '/home' directories). I did not at first 'rm' the /usr/bin/python file-was too nervous to try it! What I did, though was go into my new dedicated /home/usrlowell/'newPythonPlace' directory, and found another file named 'python*'. On command line I entered ./python, and sure enough I got python 2.5.1. Wow! Then I went back to /usr/bin, erased the 'python' file, created a link to my dedicated (/home/etc...etc) file, and sure enough, "which python" continues to yield /usr/bin/python, but "python" brings up the new 2.5.1. The experience has shaken some of my established ideas of how Linux works, but it's been a great leap forward for me (as someone once said, "Do that which you are afraid to do"). Thanks for all the help. BTW, I think-with this post-I've figured out how to correctly reply within this tutor envronment. I THINK!? -----Original Message----- >From: bhaaluu >Sent: Oct 13, 2007 5:47 PM >To: LandSurveyor >Cc: tutor at python.org >Subject: Re: [Tutor] upgrading Python > >Greetings, >On my system I can have several python versions installed because >they install as python2.3, python2.4, etc. > >$ which python >/usr/bin/python >$ ls -l /usr/bin/python >... /usr/bin/python -> python2.4 > >Here, we can see that "python" is just a link to /usr/bin/python2.4 >So, I can install python 2.5, and simply change the link so when I >enter "python" at the prompt, it will start python2.5. > >$ man ln >ln [OPTION]... [-T] TARGET LINK_NAME (1st form) > >So, after installing python 2.5, change to /usr/bin, remove /usr/bin/python >$ cd /usr/bin >$ rm python > >And now make a new link to python2.5 (you may have to be root!): ># ln -s /usr/bin/python2.5 python > >If I'm not mistaken, the library files, and so forth are stored in different >directories, so installing a new version, won't corrupt an older version. >..../lib/python2.4/site-packages > >See how python 2.4 is in the python2.4 directory? > >If, for some reason, you want the other version, just start it with the >absolute pathname: >$ /usr/bin/python2.3 > >I hope this is helpful? I don't use Mandrake, so I'm unfamiliar with >its package manager, or how to do upgrades for it. The above are >generic *nix commands that should work with any distro. > >apt-get and Synaptic rock! =) >-- >b h a a l u u at g m a i l dot c o m >http://www.geocities.com/ek.bhaaluu/index.html > >On 10/13/07, LandSurveyor wrote: >> I wish to upgrade Python from the [Vers.] 2.3.4 that came packaged with my Mandrake 10.1 Linux OS to the current 2.5.1. The 'hash/bang' line of my python scripts is "#!/usr/bin/python". There are two files, both executables, in my /usr/bin directory; they are 1)python, and 2)python2.3. >> >> I just simply don't know what to do next!? The advise I can google to is typically overly generous, full of contradictions (sometime within the same post..."Well you can do this, but if you wanna do that instead..."). Well, I don't know why "I want to do this", or "do that instead". I just want to know where to put my new version of python, and when I unzip/configure/and so on..., will I end up with: >> >> 1)an application that will pick up seamlessly and run my apps? >> 2)will pythontutor still be available? >> 3)will I have an upgraded & accessible package of modules? >> 4)will I need to modify the "hash/bang" line? >> 5)when I type 'python' on a command line, how will I access the new 2.5.1 rather than the older version? i.e., where do I go to modify the results of that request? >> >> Oh, and could I-as I understand (to a limited degree) Linux- install the entire package within my home directory, following the principle that I am a user without admin privileges, and then change the "hash/bang" line to redirect to my 'embedded' version, and thus be running 2.5.1 within my own little world? And if I did so, the same questions persist. If I asked for a module, would I get the one from my 2.5.1, or the module that exists in the older 2.3.4? And when I entered 'python' from a command line (to access the interpreter) how would I get my 2.5.1 version, rather than the older 2.3.4. >> >> It's just amazing, the array of niggling little questions that no one thinks about, but that create unmountable stumbling blocks once they pop up in the middle of your path, isn't it!? But, they are enough to completely stop me in my tracks, and they are the nitty-gritty questions that no one seems to think important enough to address and clarify. >> >> Thanks, folks. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> From rabidpoobear at gmail.com Sun Oct 14 19:17:07 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 14 Oct 2007 12:17:07 -0500 Subject: [Tutor] File upload from python shell In-Reply-To: <471165EA.2050502@sapo.pt> References: <471165EA.2050502@sapo.pt> Message-ID: <47124F13.1090607@gmail.com> Paulino wrote: > Hello! > > > How can I upload a file from python? > > If it is a form to fill with values it's simple: > > > urlopen("http://site.com/action?key1=value1;key2=value2") and I get the > form filled. > Only if the form uses the GET method. If your file upload form used GET, you could upload your file like this as well (after base-64 encoding it.) I recommend reading the Wikipedia articles on GET and POST so you can know the difference. > > What about uploading a file programmaticaly? > file uploads usually use the POST method, not GET. they're generally the same thing as text or radiobutton form entries, except their input type is set to file, so that it's base-64 encoded so that there's no errors in transmission. basically you'll have to look at a few things: 1. how the POST method is structured. 2. Which keys your file-uploading page wants. 3. how to base-64 encode your file. 4. how to measure the length of all your keys and data so that you can set content-length header correctly. 5. how to submit this new http request properly. What are you trying to upload to? if it's ImageShack by any coincidence, I have some code that does that already. If it's something else, the code would probably be similar. Let me know if you want to take a look at that. -Luke From rdm at rcblue.com Sun Oct 14 20:23:55 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 14 Oct 2007 11:23:55 -0700 Subject: [Tutor] 2 problems in a small script Message-ID: <20071014182407.AD5141E4011@bag.python.org> **Blush** These lines were in my last post in this thread: "Done. I had no idea set could be used that way! With a couple of modifications, I used your ideas in both and (see the thread I started, )." They should have read: "Done. I had no idea set could be used that way! With a couple of modifications, I used your ideas in both and (see the thread I started, )." But also, though I'm very glad Ian showed me how to use sets in that magic way, I had forgotten that a list comprehension can be much more succinct: lstB = [ word for word in lstA if all(char in astr for char in word) ] in "buggy" (line 11) lstD = [ word for word in lstC if all(char in astr for char in word) ] in "getCrew" (line 26) (Thanks to Kent, I believe.) These further revisions can be seen at and . Dick From chiselchip at earthlink.net Sun Oct 14 21:18:48 2007 From: chiselchip at earthlink.net (LandSurveyor) Date: Sun, 14 Oct 2007 15:18:48 -0400 (GMT-04:00) Subject: [Tutor] upgrading Python Message-ID: <22220592.1192389529090.JavaMail.root@elwamui-cypress.atl.sa.earthlink.net> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071014/1156808b/attachment.htm From bhaaluu at gmail.com Sun Oct 14 22:55:21 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 14 Oct 2007 16:55:21 -0400 Subject: [Tutor] upgrading Python In-Reply-To: <7508625.1192379677560.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> References: <7508625.1192379677560.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> Message-ID: On 10/14/07, LandSurveyor wrote: > Long and the short of it, the 'make' and 'make install' continued in the /usr/bin environ (i.e., departed from my '/home' directories). I did not at first 'rm' the /usr/bin/python file-was too nervous to try it! What I did, though was go into my new dedicated /home/usrlowell/'newPythonPlace' directory, and found another file named 'python*'. On command line I entered ./python, and sure enough I got python 2.5.1. Wow! Then I went back to /usr/bin, erased the 'python' file, created a link to my dedicated (/home/etc...etc) file, and sure enough, "which python" continues to yield /usr/bin/python, but "python" brings up the new 2.5.1. > > The experience has shaken some of my established ideas of how Linux works, but it's been a great leap forward for me (as someone once said, "Do that which you are afraid to do"). > > Thanks for all the help. BTW, I think-with this post-I've figured out how to correctly reply within this tutor envronment. I THINK!? Linus Torvalds designed Linux with one objective: FUN. The cool thing about GNU/Linux is: if something breaks, you get to keep BOTH halves. =) ALL the source code is available, from the first assembly language bits, all the way up to the meaty stuff, like X-Windows, and everything in between, and on top of, and behind. GNU/Linux is a programmer's heaven. It is infinitely extensible, and configurable. Why people even give MS any mind-share is beyond me.... (Well, other than they maintain an illegal monopoly... but we won't go there.) Python is free and completely open. Python and Linux were started about the same time (c.1991); so they are like, the same age, more or less. =) There are over 200 different Linux LiveCDs available, customized for all sorts of different things. They are bootable. When they boot, they create a RAM-disk, and run from that. So the hard drive is not touched. Apps are dynamically uncompressed and loaded from CD into the RAM-disk (a small performance hit here, when running from LiveCD), but otherwise, the Linux LiveCDs are an excellent way to test drive GNU/Linux, try it out, look at Free Software, and become familiar with it. After all, familiarity is what makes MS-Windows seem so easy. Once you become familiar with GNU/Linux, you find it is much easier than MS-Windows! (I always feel like I'm chained to a huge steel ball when I have to use a MS-Windows PC - that's how kludgey it its). FrozenTech has a pretty good list of Linux LiveCDs. Python is *usually* installed by default on a LiveCD. Some popular Linux LiveCDs: Knoppix SimplyMEPIS Kubuntu -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From paulino1 at sapo.pt Mon Oct 15 00:51:38 2007 From: paulino1 at sapo.pt (Paulino) Date: Sun, 14 Oct 2007 23:51:38 +0100 Subject: [Tutor] File upload from python shell In-Reply-To: <47124F13.1090607@gmail.com> References: <471165EA.2050502@sapo.pt> <47124F13.1090607@gmail.com> Message-ID: <47129D7A.1040502@sapo.pt> Luke Paireepinart escreveu: > Paulino wrote: >> Hello! >> >> >> How can I upload a file from python? >> >> If it is a form to fill with values it's simple: >> >> >> urlopen("http://site.com/action?key1=value1;key2=value2") and I get >> the form filled. >> > Only if the form uses the GET method. > If your file upload form used GET, you could upload your file like > this as well (after base-64 encoding it.) > I recommend reading the Wikipedia articles on GET and POST so you can > know the difference. >> >> What about uploading a file programmaticaly? >> > file uploads usually use the POST method, not GET. > they're generally the same thing as text or radiobutton form entries, > except their input type is set to file, > so that it's base-64 encoded so that there's no errors in transmission. > basically you'll have to look at a few things: > 1. how the POST method is structured. > 2. Which keys your file-uploading page wants. > 3. how to base-64 encode your file. > 4. how to measure the length of all your keys and data so that you can > set content-length header correctly. > 5. how to submit this new http request properly. > > What are you trying to upload to? > if it's ImageShack by any coincidence, I have some code that does that > already. > If it's something else, the code would probably be similar. > Let me know if you want to take a look at that. > -Luke > > I want to upload pdf files, to an intranet server, that I also control. Yes I think it would be very usefull to have a look at your code. The urlopen function can take an optional data parameter that is used to specify a POST request, but i couldn't find information about how to set the data parameter properly. Thank You Paulino From rabidpoobear at gmail.com Mon Oct 15 03:57:03 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 14 Oct 2007 20:57:03 -0500 Subject: [Tutor] File upload from python shell In-Reply-To: <47129D7A.1040502@sapo.pt> References: <471165EA.2050502@sapo.pt> <47124F13.1090607@gmail.com> <47129D7A.1040502@sapo.pt> Message-ID: <4712C8EF.4040305@gmail.com> Paulino wrote: > Luke Paireepinart escreveu: >> Paulino wrote: >>> Hello! >>> >>> >>> How can I upload a file from python? >>> >>> If it is a form to fill with values it's simple: >>> >>> >>> urlopen("http://site.com/action?key1=value1;key2=value2") and I get >>> the form filled. >>> >> Only if the form uses the GET method. >> If your file upload form used GET, you could upload your file like >> this as well (after base-64 encoding it.) >> I recommend reading the Wikipedia articles on GET and POST so you can >> know the difference. >>> >>> What about uploading a file programmaticaly? >>> >> file uploads usually use the POST method, not GET. >> they're generally the same thing as text or radiobutton form entries, >> except their input type is set to file, >> so that it's base-64 encoded so that there's no errors in transmission. >> basically you'll have to look at a few things: >> 1. how the POST method is structured. >> 2. Which keys your file-uploading page wants. >> 3. how to base-64 encode your file. >> 4. how to measure the length of all your keys and data so that you >> can set content-length header correctly. >> 5. how to submit this new http request properly. >> >> What are you trying to upload to? >> if it's ImageShack by any coincidence, I have some code that does >> that already. >> If it's something else, the code would probably be similar. >> Let me know if you want to take a look at that. >> -Luke >> >> > I want to upload pdf files, to an intranet server, that I also control. Well, give us more information on the server. If you have control over it, why bother using HTTP? Why not use FTP or SSH? They'd have more flexibility and probably robustness as well. Is the OS Windows or Linux or something else? -Luke From rdm at rcblue.com Mon Oct 15 08:15:30 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 14 Oct 2007 23:15:30 -0700 Subject: [Tutor] largest and smallest numbers In-Reply-To: References: <730562.77936.qm@web51603.mail.re2.yahoo.com> Message-ID: <20071015061540.948D91E4035@bag.python.org> At 06:01 PM 9/24/2007, Terry Carroll wrote: >On Mon, 24 Sep 2007, Christopher Spears wrote: > > > How can I find the largest float and complex numbers? > >That's an interesting question.. > >I just tried this: > >x = 2.0 >while True: > x = x*2 > print x > if repr(x) == "1.#INF": break > >to just keep doubling X until Python began representing it as infinity. >My output: > >4.0 >8.0 >16.0 >32.0 >64.0 >128.0 > . . . >137438953472.0 >274877906944.0 >549755813888.0 >1.09951162778e+012 >2.19902325555e+012 >4.3980465111e+012 > . . . >2.24711641858e+307 >4.49423283716e+307 >8.98846567431e+307 >1.#INF > >So I'd say, the answer is somewhere between 8.98846567431e+307 and double >that. I pinched it down some more (after dinner): >>> 1.79769313486e+308 * (1.000000000000001 ** 1160) 1.7976931348623151e+308 >>> 1.79769313486e+308 * (1.000000000000001 ** 1161) 1.#INF Dick Moores Win XP From alan.gauld at btinternet.com Mon Oct 15 10:09:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 09:09:53 +0100 Subject: [Tutor] Variables in workspace References: <957526FB6E347743AAB42B212AB54FDA95BA40@NANAMAILBACK1.nanamail.co.il><4710D64D.10901@alum.rpi.edu> <4710DAE8.2010702@tds.net><4710E5DB.9040001@alum.rpi.edu> <957526FB6E347743AAB42B212AB54FDA95BA43@NANAMAILBACK1.nanamail.co.il> Message-ID: "Eli Brosh" wrote > The dir() and del work really well ! I meant to add that if you look at the names a lot then you migt prefer PyCrust asa shell rather than IDLE. PyCrust has a small namespace window on permanent display wich shows all of the names dynamically in an explorer type view. That means as you import modules they appear as drill downs. PyCrust comes with the wxPython GUI toolkit. HTH, Alan g From alan.gauld at btinternet.com Mon Oct 15 10:20:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 09:20:41 +0100 Subject: [Tutor] upgrading Python References: <7508625.1192379677560.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> Message-ID: "LandSurveyor" wrote > had never used a link before. Didn't know why I would want to. Links are super cool, you can do lots with them, just beware of circular references or things like tar or cp -r will go into endless loops! > and got as far as 'make', when it required me to have SU privileges > (so much for the theory that I could do all I wished within my own > 'world'). You can, but you need to edit make to remove any hard coded paths or if it iuses references to environment variables make sure they point to where you want them to point. The standard makefile script assumes you are building Python in the 'standard' place and so uses the standard locations for things like libraries, man pages etc. > That speed bump has undermined a number of concepts > I thought I'd figured out-regarding autonomy for a user-so > I don't know now what I don't know.). Users have autonomy but still rely on accessing things (like man pages, libraries and executables) from general purpose locations. If you want to create new versions of those things you will need to do some work, including modifying your environment variables for PATH, MANPATH, and possibly the LIBS stuff too. That way the OS knows to look in your places as well as the standard places. BTW none of this is unique to Linux, most multi user OS work this way too including Windows XP/Vista. > Thanks for all the help. BTW, I think-with this post-I've figured > out how to correctly reply within this tutor envronment. I THINK!? Well it got to me ok! :-) Alan G From alan.gauld at btinternet.com Mon Oct 15 10:35:20 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 09:35:20 +0100 Subject: [Tutor] upgrading Python References: <22220592.1192389529090.JavaMail.root@elwamui-cypress.atl.sa.earthlink.net> Message-ID: "LandSurveyor" wrote > a.. the digraphs I have incorporated from the Vim environment > into my scripts no longer work. Can you show us an example? > b.. Within my code, I have two adjacent 'try/except' sequences. Again can you show us the actual code segment? Its hard to guess Alan G. From alan.gauld at btinternet.com Mon Oct 15 10:33:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 09:33:25 +0100 Subject: [Tutor] upgrading Python References: <7508625.1192379677560.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> Message-ID: "bhaaluu" wrote > Why people even give MS any mind-share is beyond me.... For the same reason most people don't buy kit cars. Linux is a great hobbyist environment and if you want your OS to be a hobby then use Linux you will learn a lot about your computers. But if you just want to unpack the box turn it on and start writing documents, editing photos etc use Windows (or MacOS). I've been working professionally with Unix and Unix-like OS for over 20 years now but when I bought a laptop for my own use I bought a Mac - Unix without the pain. > easy. Once you become familiar with GNU/Linux, you find it is much > easier than MS-Windows! Sorry, I can't agree. Linux has a lot of rough edges where you still need to open text files and eit them, stop and start services etc That is never going to be easier for the average user than clicking a few boxes in a dalog. Linux is a hobbyist OS, it allows you all the power and flexibility but at the expense of exposing great swathes of the under-belly of the PC. Most users simply don't want to know that stuff and don't have the time to learn. Fortunately for us Python runs on both so the readers of this forum have the luxury of choosing which to use. As a programmer there is a much stronger case for using Linux because it does allow far greater access and therefore makes many programming tasks easier. Plus nearly everything is controlled by text files - which are prorammatically easy to manipulate. But for ordinary users Linux remains complex. IMHO of course! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Oct 15 13:36:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Oct 2007 07:36:54 -0400 Subject: [Tutor] 2 problems in a small script In-Reply-To: <20071014092847.8710B1E4026@bag.python.org> References: <20071012055549.CE0BB1E4027@bag.python.org> <20071014092847.8710B1E4026@bag.python.org> Message-ID: <471350D6.3050603@tds.net> Dick Moores wrote: >> If your interested, this could be done succinctly with set types. (no >> iterating required!) > Done. I had no idea set could be used that way! With a couple of > modifications, I used your ideas in both and > (see the thread I started, < > http://www.nabble.com/An-idea-for-a-script-tf4603558.html#a13149808 >). You might as well create the set of disallowed letters just once: astr = set(ascii_letters + digits + '-_') > >> OR... >> >> my_list = filter(well_formed, my_list) > > I'll look into "filter". The list comp form is actually preferred and IIRC filter() has been eliminated from Python 3. > > A question: > > Here's my(yours) well_formed(): > > def well_formed(word, astr): > """ > Returns True if set() - set() is empty; False if > not. > """ > return not set(word) - set(astr) > > Is it OK to use like that in a docstring? Sure why not? Kent From kent37 at tds.net Mon Oct 15 13:44:43 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Oct 2007 07:44:43 -0400 Subject: [Tutor] File upload from python shell In-Reply-To: <471165EA.2050502@sapo.pt> References: <471165EA.2050502@sapo.pt> Message-ID: <471352AB.906@tds.net> Paulino wrote: > Hello! > > > How can I upload a file from python? > > If it is a form to fill with values it's simple: > > > urlopen("http://site.com/action?key1=value1;key2=value2") and I get the > form filled. > > > What about uploading a file programmaticaly? This might help: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 Kent From kent37 at tds.net Mon Oct 15 13:49:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Oct 2007 07:49:04 -0400 Subject: [Tutor] upgrading Python In-Reply-To: <22220592.1192389529090.JavaMail.root@elwamui-cypress.atl.sa.earthlink.net> References: <22220592.1192389529090.JavaMail.root@elwamui-cypress.atl.sa.earthlink.net> Message-ID: <471353B0.5090700@tds.net> LandSurveyor wrote: > Some interesting (!?) things happened when I upgraded from Python 2.3 > to Python 2.5.1. My editor of choice is Vim, the platform is > MandrakeLinux 10.1... > > * the digraphs I have incorporated from the Vim environment into my > scripts no longer work. The resultant error message referred me > to pep-0263 I guess this means that you have non-ascii characters in your source code but you have not included an encoding declaration. From "What's New in Python 2.5": ASCII is now the default encoding for modules. It's now a syntax error if a module contains string literals with 8-bit characters but doesn't have an encoding declaration. In Python 2.4 this triggered a warning, not a syntax error. See PEP 263 for how to declare a module's encoding; for example, you might add a line like this near the top of the source file: # -*- coding: latin1 -*- http://www.python.org/dev/peps/pep-0263/ Kent From kent37 at tds.net Mon Oct 15 13:53:32 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Oct 2007 07:53:32 -0400 Subject: [Tutor] largest and smallest numbers In-Reply-To: <20071015061540.948D91E4035@bag.python.org> References: <730562.77936.qm@web51603.mail.re2.yahoo.com> <20071015061540.948D91E4035@bag.python.org> Message-ID: <471354BC.7000008@tds.net> Dick Moores wrote: > I pinched it down some more (after dinner): > > >>> 1.79769313486e+308 * (1.000000000000001 ** 1160) > 1.7976931348623151e+308 > >>> 1.79769313486e+308 * (1.000000000000001 ** 1161) > 1.#INF This looks promising: In [8]: x=1.7976931348623157e+308 In [9]: y=0.0000000000000001e+308 In [10]: x+y Out[10]: inf Courtesy numpy: In [4]: from numpy import finfo, float64 In [7]: print finfo(float64) Machine parameters for --------------------------------------------------------------------- precision= 15 resolution= 1.0000000000000001e-15 machep= -52 eps= 2.2204460492503131e-16 negep = -53 epsneg= 1.1102230246251565e-16 minexp= -1022 tiny= 2.2250738585072014e-308 maxexp= 1024 max= 1.7976931348623157e+308 nexp = 11 min= -max --------------------------------------------------------------------- Kent From surendrak2 at yahoo.com Mon Oct 15 14:03:01 2007 From: surendrak2 at yahoo.com (surendra kumar) Date: Mon, 15 Oct 2007 05:03:01 -0700 (PDT) Subject: [Tutor] Python Message-ID: <531851.25476.qm@web60922.mail.yahoo.com> Please give me details of python tution, Thanks surendra kumar --------------------------------- Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/389aedd8/attachment.htm From bhaaluu at gmail.com Mon Oct 15 14:39:48 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 15 Oct 2007 08:39:48 -0400 Subject: [Tutor] upgrading Python In-Reply-To: References: <7508625.1192379677560.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> Message-ID: Greetings, On 10/15/07, Alan Gauld wrote: > > "bhaaluu" wrote > > > Why people even give MS any mind-share is beyond me.... > > For the same reason most people don't buy kit cars. > Linux is a great hobbyist environment and if you want your > OS to be a hobby then use Linux you will learn a lot > about your computers. But if you just want to unpack > the box turn it on and start writing documents, editing > photos etc use Windows (or MacOS). No, I think that GNU/Linux is now way beyond 'hobbyist environment'. IBM, Novell, and others are giving it very serious mind-share. Most of the GNU/Linux distros I've seen can be turned on and the user can immediately start writing documents, doing spreadsheets, editing photos, etc. IF you can point and click in MS-Windows, you can do the same in GNU/Linux. In fact, the GUIs I've seen on some GNU/Linux machines make MS-Windows look like an ill-designed toy. When was the last time you took a look at GNU/Linux? =) The main reason why NO other OS can get a foothold in the PC desktop market is because Microsoft has and maintains an illegal monopoly. This illegally maintained monopoly raises the barrier to entry to the PC desktop market SO high, that even being given away for Free, another OS (including the *BSDs) cannot enter the market. Only recently has DELL begun offering Desktop PCs with GNU/Linux pre-installed. > I've been working professionally with Unix and Unix-like > OS for over 20 years now but when I bought a laptop > for my own use I bought a Mac - Unix without the pain. So, you use PCs with MS-Windows, and Mac,... really, when was the last time you took a look at GNU/Linux? My suggestion: Look up a Linux User Group (LUG) in your local area, and attend their next meeting. I'm so sure someone will have a recent install of one of the GNU/Linux distros you can look at. I think you'll be surprised. > > easy. Once you become familiar with GNU/Linux, you find it is much > > easier than MS-Windows! > > Sorry, I can't agree. Linux has a lot of rough edges > where you still need to open text files and eit them, stop > and start services etc That is never going to be easier for > the average user than clicking a few boxes in a dalog. Here again, I wonder when you last looked at GNU/Linux? It has been a long time since I've had to hand-edit a text configuration file to get something to work. A looooong time! But when I DO need to edit a config file, I'm REALLY glad it is a text file that is *usually* human-readable. > Linux is a hobbyist OS, it allows you all the power and flexibility > but at the expense of exposing great swathes of the under-belly > of the PC. Most users simply don't want to know that stuff and > don't have the time to learn. Like I've said, most users are simply unfamiliar with GNU/Linux. Linux LiveCDs are a great way to become familiar with GNU/Linux without installing anything on the hard drive. I think they'll find that the "great swathes of the under-belly of the PC" are not exposed. One really cool thing about GNU/Linux: it isn't plagued with all the MS-Windows problems that never seem to get fixed properly. Another cool thing: when you connect a GNU/Linux machine to the Internet, the OS doesn't automatically send a package to Redmond, WA, telling them what's on your PC. If I'm not mistaken MS-Vista is the most intrusive of all the MS-Windows OSs. GNU/Linux is completely opena and free (free, as in freedom of speech -- all the source code to everything is available for review, modification, customization, sharing, etc.). > Fortunately for us Python runs on both so the readers of this > forum have the luxury of choosing which to use. As a > programmer there is a much stronger case for using Linux > because it does allow far greater access and therefore makes > many programming tasks easier. Plus nearly everything is > controlled by text files - which are prorammatically > easy to manipulate. But for ordinary users Linux remains > complex. Take another look at GNU/Linux! All your arguments are old. Your arguments lead me to believe that you looked at GNU/Linux several years ago, wrote it off as a 'hobbyist OS', and haven't looked at it since. Besides, this is a Programmer's list. So the argument of GNU/Linux being "too complex" for "most users" doesn't really apply here. Programmers are "One Percenters". Most users are NOT programmers. Not only that, they cringe when they hear the word 'programming.' GNU/Linux is a Programmer's Paradise. Especially for Python! Now for what seems to be a contradiction: GNU/Linux is a perfect OS for the hobbyist programmer! It has dozens of compilers/interpreters available for absolutely free (free as in speech, and free as in beer). I have 12 feet of shelf space lined up with old MS-DOS/Windows compilers/libraries that are obsolete. They represent hundreds of dollars. I started out on MS-DOS/Windows, but soon found out that being a hobbyist programmer on that platform was Exteremely Expensive. Being a hobbyist programmer on the GNU/Linux platform is not only fun, but also is way easier on my pocketbook. =) The last time I looked, a MS-Windows computer didn't have ANY compiler/interpreter installed by default? Correct me if I'm wrong. 8^D > IMHO of course! :-) > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld Of course! 8^D I'm having a great time learning Python on the GNU/Linux platform, and reading/doing this great Python Tutor mailing list! -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From kent37 at tds.net Mon Oct 15 14:39:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Oct 2007 08:39:20 -0400 Subject: [Tutor] Python In-Reply-To: <531851.25476.qm@web60922.mail.yahoo.com> References: <531851.25476.qm@web60922.mail.yahoo.com> Message-ID: <47135F78.2010706@tds.net> surendra kumar wrote: > Please give me details of python tution This is a mailing list for people who are learning python, and people who like to help others learn python. http://mail.python.org/mailman/listinfo/tutor Kent From bhaaluu at gmail.com Mon Oct 15 14:47:59 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 15 Oct 2007 08:47:59 -0400 Subject: [Tutor] Python In-Reply-To: <531851.25476.qm@web60922.mail.yahoo.com> References: <531851.25476.qm@web60922.mail.yahoo.com> Message-ID: Greetings, On 10/15/07, surendra kumar wrote: > Please give me details of python tution, Thanks > surendra kumar > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Send your questions to the Tutor maillist: Tutor at python.org. When replying to a post, select 'Reply to all' (or the equivalent on your mail-reader), as the default is set to reply only to the poster. You'll get a better response when the whole list can read your post. Please don't start a new thread (Subject) by replying to an existing thread. Please compose a new post with a new Subject. It is a good idea to send in a snippet of code with your question, along with any error messages. It is also a good idea to let the Tutors know which version of Python you are using. With that in mind, ask your Python questions on this list. That's a good start! 8^D -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From kent37 at tds.net Mon Oct 15 14:52:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Oct 2007 08:52:21 -0400 Subject: [Tutor] upgrading Python In-Reply-To: References: <7508625.1192379677560.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> Message-ID: <47136285.7030303@tds.net> bhaaluu wrote: > On 10/15/07, Alan Gauld wrote: >> "bhaaluu" wrote >> >>> Why people even give MS any mind-share is beyond me.... > > No, I think that GNU/Linux is now way beyond 'hobbyist environment'. OK, I think that is enough Linux/Windows/Mac advocacy (and trolling) for now. Let's keep this list for Python discussion. Thanks, Kent From ricaraoz at gmail.com Mon Oct 15 15:11:09 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 15 Oct 2007 10:11:09 -0300 Subject: [Tutor] upgrading Python In-Reply-To: References: <7508625.1192379677560.JavaMail.root@elwamui-milano.atl.sa.earthlink.net> Message-ID: <471366ED.2060409@bigfoot.com> bhaaluu wrote: > Greetings, > > On 10/15/07, Alan Gauld wrote: >> "bhaaluu" wrote >> > So, you use PCs with MS-Windows, and Mac,... really, when was the > last time you took a look at GNU/Linux? My suggestion: Look up > a Linux User Group (LUG) in your local area, and attend their next > meeting. I'm so sure someone will have a recent install of one of > the GNU/Linux distros you can look at. I think you'll be surprised. > I'd check Knoppix and/or KUbuntu (that's Ubuntu with KDE). Both are live CD's so you can check and use the system without compromising your box. I prefer Knoppix, but it's a personal choice. >>> easy. Once you become familiar with GNU/Linux, you find it is much >>> easier than MS-Windows! >> Sorry, I can't agree. Linux has a lot of rough edges >> where you still need to open text files and eit them, stop >> and start services etc That is never going to be easier for >> the average user than clicking a few boxes in a dalog. > Maybe if you are a 'power user' you might need to do that. Or if there is an extremely grave fuck up in your machine. Then, is Wds you would need to call an expert with his special soft tools. But if you are Joe Average then you don't need to touch that kind of stuff. Besides that, Joe Average is not interested in starting/stoping services, neither in Wds nor in Linux. And I guess it is easier doing it in Linux. Anyway you should make up your own mind checking the aforementioned distros, they can be downloaded in a few minutes, then you burn a cd and voil?, there you go. Cheers From ramkumar.kashyap at gmail.com Mon Oct 15 17:01:31 2007 From: ramkumar.kashyap at gmail.com (Ramkumar Kashyap) Date: Mon, 15 Oct 2007 11:01:31 -0400 Subject: [Tutor] newbie question Message-ID: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> Hi all, I have just started learning to program and am working through the Beginning Python from Wrox. I am working through one of the examples in the books on dictionaries. Here is the example. >>> menu_specials = {"breakfast" : "sausage and eggs", ... "lunch" : "split pea soup and garlic bread", ... "dinner": "2 hot dogs and onion rings"} >>> print "%s" % menu_specials["breakfast"] sausage and eggs >>> print "%s" % menu_specials["lunch"] split pea soup and garlic bread >>> print "%s" % menu_specials["dinner"] 2 hot dogs and onion rings I am trying to print out the entire dictionary but am getting an error. print "%s %s %s" % menu_specials["breakfast", "lunch", "dinner"] Traceback (most recent call last): File "", line 1, in KeyError: ('breakfast', 'lunch', 'dinner') I also tried print "%s %s %s" % menu_specials["breakfast"], menu_specials["lunch"], menu_specials["dinner"] Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string What is the correct syntax to output breakfast, lunch and dinner with one command? thanks, Ram -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/1740d632/attachment.htm From maseriyer at yahoo.com Mon Oct 15 17:17:34 2007 From: maseriyer at yahoo.com (Iyer) Date: Mon, 15 Oct 2007 08:17:34 -0700 (PDT) Subject: [Tutor] itertools.izip question? Message-ID: <110520.83644.qm@web50706.mail.re2.yahoo.com> I have a dictionary d = {0: array([0, 0], dtype=uint16), 1: array([1, 1], dtype=uint16), 2: array([2, 2], dtype=uint16), 3: array([3, 3], dtype=uint16)} or d = {0:d0,1:d1,2:d2,3:d3} d0, d1, d2 and d3 are numpy.ndarray type I wish to get the interleaved data by using outputdata = numpy.array([item for items in itertools.izip(d.values()) for item in items]) But I get outputdata = array([[0, 0], [1, 1], [2, 2], [3, 3]], dtype=uint16) which is different from the desired answer, which can be obtained by outputdata = numpy.array([item for items in itertools.izip(d0,d1,d2,d3) for item in items]) outputdata = array([0, 1, 2, 3, 0, 1, 2, 3], dtype=uint16) I notice that when outputdata = numpy.array([item for items in itertools.izip((d0,d1,d2,d3)) for item in items]) is used, outputdata = array([[0, 0], [1, 1], [2, 2], [3, 3]], dtype=uint16) Is there any way to izip over dictionary values d.values() and obtain outputdata = array([0, 1, 2, 3, 0, 1, 2, 3], dtype=uint16) I'm stumped a bit by this itertools izip behavior, suggestions appreciated. ~iyer --------------------------------- Need a vacation? Get great deals to amazing places on Yahoo! Travel. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/c7e3e27d/attachment.htm From trilokgk at gmail.com Mon Oct 15 17:35:22 2007 From: trilokgk at gmail.com (Trilok Khairnar) Date: Mon, 15 Oct 2007 21:05:22 +0530 Subject: [Tutor] newbie question In-Reply-To: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> Message-ID: <002401c80f41$030e5160$df2d580a@persistent.co.in> Either of the following should do it: print string.join([menu_specials[val] for val in menu_specials], ', ') or print string.join([menu_specials[val] for val in menu_specials.keys()], ', ') or print string.join([menu_specials[val] for val in ["breakfast", "lunch", "dinner"] ], ', ') Thanks, Trilok. ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Ramkumar Kashyap Sent: Monday, October 15, 2007 8:32 PM To: tutor at python.org Subject: [Tutor] newbie question Hi all, I have just started learning to program and am working through the Beginning Python from Wrox. I am working through one of the examples in the books on dictionaries. Here is the example. >>> menu_specials = {"breakfast" : "sausage and eggs", ... "lunch" : "split pea soup and garlic bread", ... "dinner": "2 hot dogs and onion rings"} >>> print "%s" % menu_specials["breakfast"] sausage and eggs >>> print "%s" % menu_specials["lunch"] split pea soup and garlic bread >>> print "%s" % menu_specials["dinner"] 2 hot dogs and onion rings I am trying to print out the entire dictionary but am getting an error. print "%s %s %s" % menu_specials["breakfast", "lunch", "dinner"] Traceback (most recent call last): File "", line 1, in KeyError: ('breakfast', 'lunch', 'dinner') I also tried print "%s %s %s" % menu_specials["breakfast"], menu_specials["lunch"], menu_specials["dinner"] Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string What is the correct syntax to output breakfast, lunch and dinner with one command? thanks, Ram From kent37 at tds.net Mon Oct 15 17:41:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Oct 2007 11:41:38 -0400 Subject: [Tutor] itertools.izip question? In-Reply-To: <110520.83644.qm@web50706.mail.re2.yahoo.com> References: <110520.83644.qm@web50706.mail.re2.yahoo.com> Message-ID: <47138A32.4070709@tds.net> Iyer wrote: > > > I have a dictionary > > d = {0: array([0, 0], dtype=uint16), 1: array([1, 1], dtype=uint16), 2: > array([2, 2], dtype=uint16), 3: array([3, 3], dtype=uint16)} > or > d = {0:d0,1:d1,2:d2,3:d3} > > > d0, d1, d2 and d3 are numpy.ndarray type > > I wish to get the interleaved data by using > > outputdata = numpy.array([item for items in itertools.izip(d.values()) > for item in items]) Try itertools.izip(*d.values()) What you are doing is passing a single list to izip(), just as if you said itertools.izip([d0,d1,d2,d3]). (Note the extra brackets compared to your sample below.) The *d.values() means, use this list as the parameter list (instead of as a single parameter). Kent > > But I get outputdata = array([[0, 0], [1, 1], [2, 2], > [3, 3]], dtype=uint16) > > which is different from the desired answer, which can be obtained by > > outputdata = numpy.array([item for items in itertools.izip(d0,d1,d2,d3) > for item in items]) > > outputdata = array([0, 1, 2, 3, 0, 1, 2, 3], dtype=uint16) From evert.rol at gmail.com Mon Oct 15 17:44:21 2007 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 15 Oct 2007 16:44:21 +0100 Subject: [Tutor] newbie question In-Reply-To: <002401c80f41$030e5160$df2d580a@persistent.co.in> References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> <002401c80f41$030e5160$df2d580a@persistent.co.in> Message-ID: Hi Ram, > Either of the following should do it: > > print string.join([menu_specials[val] for val in > menu_specials], ', ') > or > print string.join([menu_specials[val] for val in > menu_specials.keys()], > ', ') > or > print string.join([menu_specials[val] for val in ["breakfast", > "lunch", > "dinner"] ], ', ') In addition, you'll need a tuple as the print argument list below: >> print "%s %s %s" % (menu_specials["breakfast"], menu_specials ["lunch"], menu_specials["dinner"]) Your one-argument print statement can actually be written as a one- element tuple: >> print "%s" % (menu_specials["breakfast"], ) With this, and if you want to use your formatted print statements instead of the join, you could use something like print "Specials: %s %s %s" % tuple(menu_specials.values()) which turns the output of menu_specials.values() (a list) into a tuple. Disadvantage is that you'll need to know the number of values in advance, for the number of '%s' in your format string (alternatively, you could build up the format string in a loop first). Note that values() bypasses the above list comprehensions entirely. hth, Evert > Hi all, > > I have just started learning to program and am working through the > Beginning > Python from Wrox. > > I am working through one of the examples in the books on > dictionaries. Here > is the example. > >>>> menu_specials = {"breakfast" : "sausage and eggs", > ... "lunch" : "split pea soup and garlic bread", > ... "dinner": "2 hot dogs and onion rings"} >>>> print "%s" % menu_specials["breakfast"] > sausage and eggs >>>> print "%s" % menu_specials["lunch"] > split pea soup and garlic bread >>>> print "%s" % menu_specials["dinner"] > 2 hot dogs and onion rings > > I am trying to print out the entire dictionary but am getting an > error. > print "%s %s %s" % menu_specials["breakfast", "lunch", "dinner"] > Traceback (most recent call last): > File "", line 1, in > KeyError: ('breakfast', 'lunch', 'dinner') > > I also tried > print "%s %s %s" % menu_specials["breakfast"], menu_specials["lunch"], > menu_specials["dinner"] > Traceback (most recent call last): > File "", line 1, in > TypeError: not enough arguments for format string > > What is the correct syntax to output breakfast, lunch and dinner > with one > command? > > thanks, > > Ram > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From trilokgk at gmail.com Mon Oct 15 17:56:55 2007 From: trilokgk at gmail.com (Trilok Khairnar) Date: Mon, 15 Oct 2007 21:26:55 +0530 Subject: [Tutor] newbie question In-Reply-To: References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> <002401c80f41$030e5160$df2d580a@persistent.co.in> Message-ID: <002501c80f44$052f7c50$df2d580a@persistent.co.in> > With this, and if you want to use your formatted print statements instead of the join, you could use something like > print "Specials: %s %s %s" % tuple(menu_specials.values()) which turns the output of menu_specials.values() (a list) into a tuple. > Disadvantage is that you'll need to know the number of values in advance, for the number of '%s' in your format string (alternatively, > you could build up the format string in a loop first). Note that values() bypasses the above list comprehensions entirely. With the following, you can do fine without knowing the length in advance. tpl = tuple(menu_specials.values()) Print "Specials: " + ' '.join(["%s"*len(tpl)]) % tpl Thanks, Trilok. From trilokgk at gmail.com Mon Oct 15 17:59:29 2007 From: trilokgk at gmail.com (Trilok Khairnar) Date: Mon, 15 Oct 2007 21:29:29 +0530 Subject: [Tutor] newbie question References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> Message-ID: <002c01c80f44$61be3fb0$df2d580a@persistent.co.in> Thinking more about the solutions I posted, I have a couple of questions :-) 1] print string.join([menu_specials[val] for val in menu_specials], ', ') >> Will this use iterkeys() under the hood? 2] print string.join([menu_specials[val] for val in menu_specials.keys()], ', ') >> Given that a.keys() returns a "copy" of a's list of keys, will it be memory intensive for large lists and it's better to use an iterator? Thanks, Trilok. -----Original Message----- From: Trilok Khairnar [mailto:trilokgk at gmail.com] Sent: Monday, October 15, 2007 9:05 PM To: 'Ramkumar Kashyap' Cc: 'tutor at python.org' Subject: RE: [Tutor] newbie question Either of the following should do it: print string.join([menu_specials[val] for val in menu_specials], ', ') or print string.join([menu_specials[val] for val in menu_specials.keys()], ', ') or print string.join([menu_specials[val] for val in ["breakfast", "lunch", "dinner"] ], ', ') Thanks, Trilok. ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Ramkumar Kashyap Sent: Monday, October 15, 2007 8:32 PM To: tutor at python.org Subject: [Tutor] newbie question Hi all, I have just started learning to program and am working through the Beginning Python from Wrox. I am working through one of the examples in the books on dictionaries. Here is the example. >>> menu_specials = {"breakfast" : "sausage and eggs", ... "lunch" : "split pea soup and garlic bread", ... "dinner": "2 hot dogs and onion rings"} >>> print "%s" % menu_specials["breakfast"] sausage and eggs >>> print "%s" % menu_specials["lunch"] split pea soup and garlic bread >>> print "%s" % menu_specials["dinner"] 2 hot dogs and onion rings I am trying to print out the entire dictionary but am getting an error. print "%s %s %s" % menu_specials["breakfast", "lunch", "dinner"] Traceback (most recent call last): File "", line 1, in KeyError: ('breakfast', 'lunch', 'dinner') I also tried print "%s %s %s" % menu_specials["breakfast"], menu_specials["lunch"], menu_specials["dinner"] Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string What is the correct syntax to output breakfast, lunch and dinner with one command? thanks, Ram From rabidpoobear at gmail.com Mon Oct 15 18:33:07 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 15 Oct 2007 11:33:07 -0500 Subject: [Tutor] newbie question In-Reply-To: <002501c80f44$052f7c50$df2d580a@persistent.co.in> References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> <002401c80f41$030e5160$df2d580a@persistent.co.in> <002501c80f44$052f7c50$df2d580a@persistent.co.in> Message-ID: <47139643.1030508@gmail.com> Trilok Khairnar wrote: >> With this, and if you want to use your formatted print statements instead >> > of the join, you could use something like > >> print "Specials: %s %s %s" % tuple(menu_specials.values()) which turns the >> > output of menu_specials.values() (a list) into a tuple. > >> Disadvantage is that you'll need to know the number of values in advance, >> > for the number of '%s' in your format string (alternatively, > >> you could build up the format string in a loop first). Note that values() >> > bypasses the above list comprehensions entirely. > > With the following, you can do fine without knowing the length in advance. > > tpl = tuple(menu_specials.values()) > Print "Specials: " + ' '.join(["%s"*len(tpl)]) % tpl > I don't see the point of building a format string and then substituting for it. Why not just do: print "Specials: " + ' '.join(menu_specials.values()) -Luke From bgailer at alum.rpi.edu Mon Oct 15 18:33:27 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Mon, 15 Oct 2007 12:33:27 -0400 Subject: [Tutor] newbie question (teaching you to fish?) In-Reply-To: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> Message-ID: <47139657.6030305@alum.rpi.edu> Ramkumar Kashyap wrote: > Hi all, > > I have just started learning to program and am working through the > Beginning Python from Wrox. > > I am working through one of the examples in the books on dictionaries. > Here is the example. > > >>> menu_specials = {"breakfast" : "sausage and eggs", > ... "lunch" : "split pea soup and garlic bread", > ... "dinner": "2 hot dogs and onion rings"} > >>> print "%s" % menu_specials["breakfast"] > sausage and eggs > >>> print "%s" % menu_specials["lunch"] > split pea soup and garlic bread > >>> print "%s" % menu_specials["dinner"] > 2 hot dogs and onion rings > > I am trying to print out the entire dictionary but am getting an error. > print "%s %s %s" % menu_specials["breakfast", "lunch", "dinner"] > Traceback (most recent call last): > File "", line 1, in > KeyError: ('breakfast', 'lunch', 'dinner') Do you understand why you got that error? > > I also tried > print "%s %s %s" % menu_specials["breakfast"], menu_specials["lunch"], > menu_specials["dinner"] > Traceback (most recent call last): > File "", line 1, in > TypeError: not enough arguments for format string Do you understand why you got that error? The first step to getting things right is to understand the error and relate it to what Python expects. What are the acceptable right arguments to %? In what way did your 2nd attempt fail to meet these requirements? Once you answer that then the fix should be obvious. So give it a try, then come back for more help. From trilokgk at gmail.com Mon Oct 15 18:52:16 2007 From: trilokgk at gmail.com (Trilok Khairnar) Date: Mon, 15 Oct 2007 22:22:16 +0530 Subject: [Tutor] newbie question In-Reply-To: <47139643.1030508@gmail.com> References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> <002401c80f41$030e5160$df2d580a@persistent.co.in> <002501c80f44$052f7c50$df2d580a@persistent.co.in> <47139643.1030508@gmail.com> Message-ID: <000101c80f4b$c1b7a120$df2d580a@persistent.co.in> I agree, was just trying to take home the point that if at all a format string must be used (for whatever obscure reason), then it is not necesssary to know beforehand the number of values in the dictionary (or the length of list of its values) in order to to build the format string. Hope that was parseably short, though not quite exactly pithy. :-) Regards, Trilok -----Original Message----- From: Luke Paireepinart [mailto:rabidpoobear at gmail.com] Sent: Monday, October 15, 2007 10:03 PM To: Trilok Khairnar Cc: tutor at python.org Subject: Re: [Tutor] newbie question Trilok Khairnar wrote: >> With this, and if you want to use your formatted print statements >> instead >> > of the join, you could use something like > >> print "Specials: %s %s %s" % tuple(menu_specials.values()) which >> turns the >> > output of menu_specials.values() (a list) into a tuple. > >> Disadvantage is that you'll need to know the number of values in >> advance, >> > for the number of '%s' in your format string (alternatively, > >> you could build up the format string in a loop first). Note that >> values() >> > bypasses the above list comprehensions entirely. > > With the following, you can do fine without knowing the length in advance. > > tpl = tuple(menu_specials.values()) > Print "Specials: " + ' '.join(["%s"*len(tpl)]) % tpl > I don't see the point of building a format string and then substituting for it. Why not just do: print "Specials: " + ' '.join(menu_specials.values()) -Luke From alan.gauld at btinternet.com Mon Oct 15 18:56:09 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 17:56:09 +0100 Subject: [Tutor] newbie question References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> Message-ID: "Ramkumar Kashyap" wrote > print "%s %s %s" % menu_specials["breakfast"], > menu_specials["lunch"], > menu_specials["dinner"] Whoops, I also should have added parentheses around the values. Otherwise Python sees a tuple consisting of the string and first value followed by the two succeeding values. And the single value doesn't match the 3 %s tokens. So it should be: >>> print "%s %s %s" % (menu_specials["breakfast"], >>> menu_specials["lunch"], menu_specials["dinner"]) Because of the parens you don't need the \ character so you can ignore that bit. Note to self: Test before posting! Blush, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Oct 15 18:47:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 17:47:56 +0100 Subject: [Tutor] newbie question References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> Message-ID: "Ramkumar Kashyap" wrote >>>> menu_specials = {"breakfast" : "sausage and eggs", > ... "lunch" : "split pea soup and garlic bread", > ... "dinner": "2 hot dogs and onion rings"} >>>> print "%s" % menu_specials["breakfast"] You don't really need the %s bit it could just be >>> print menu_specials["breakfast"] > I am trying to print out the entire dictionary but am getting an > error. >>> print "%s %s %s" % menu_specials["breakfast", "lunch", "dinner"] The bit between [] is the key to the dictionary(notice key is singular!) You have passed a tuple of 3 strings (a tuple because they are separated by commas) as a key. But the dictionary keys are all single strings not tuples. In other words you need to access the dictionary 3 times like so: >>> print "%s %s %s" % menu_specials["breakfast"], >>> menu_specials["lunch"], menu_specials["dinner"] > print "%s %s %s" % menu_specials["breakfast"], > menu_specials["lunch"], > menu_specials["dinner"] That should have worked. are you sure you had it all on one line? If you need to break the line use a \ character. My previous example could be done like this: >>> print "%s %s %s" % menu_specials["breakfast"], \ menu_specials["lunch"], \ menu_specials["dinner"] Or missing the formatting string as: >>> print menu_specials["breakfast"], \ menu_specials["lunch"], \ menu_specials["dinner"] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pacbaby27 at yahoo.com Mon Oct 15 19:53:53 2007 From: pacbaby27 at yahoo.com (Latasha Marks) Date: Mon, 15 Oct 2007 10:53:53 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <138982.84959.qm@web56406.mail.re3.yahoo.com> Need help write a bowling progam for 10 frame have to print score and frames --------------------------------- Tonight's top picks. What will you watch tonight? Preview the hottest shows on Yahoo! TV. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/932083a3/attachment.htm From ddm2 at sfu.ca Mon Oct 15 19:17:02 2007 From: ddm2 at sfu.ca (ddm2 at sfu.ca) Date: Mon, 15 Oct 2007 10:17:02 -0700 Subject: [Tutor] Decimal Conversion Message-ID: <200710151717.l9FHH2Nd014578@rm-rstar.sfu.ca> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20071015/8f7fcdb2/attachment.txt From mlangford.cs03 at gtalumni.org Mon Oct 15 20:36:47 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 15 Oct 2007 14:36:47 -0400 Subject: [Tutor] Decimal Conversion In-Reply-To: <200710151717.l9FHH2Nd014578@rm-rstar.sfu.ca> References: <200710151717.l9FHH2Nd014578@rm-rstar.sfu.ca> Message-ID: <82b4f5810710151136y49979981mf811a2dc12c9075f@mail.gmail.com> Use b+=","+r instead. That will add the , to the string named by b, and will concatenate the string named by r to the end. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ On 10/15/07, ddm2 at sfu.ca wrote: > > Hi, > > I'm new to Python, and found some problems on the internet that would be a > good start to begin. The problem I have is that my conversion program > (which > currently only converts unsigned integers) also prints all these brackets > and commas. Here is my code and the result: > CODE: > print "" > print "--------------------" > print "Unsigned Binary" > print "--------------------" > print "" > n = int(raw_input("Please enter an integer: ")) > b = '' > while n > 0: > r = n%2 > n = n/2 > b = r,b > print b > > (ex: n = 15) > RESULT: > (1, (1, (1, (1, '')))) > > I think the problem is in the line of code 'b = r,b', but am not sure how > to > fix it. The tip given for the problem says I should 'append' r to b, but > since b is not a list, 'b = r,b' was the only thing that came to my mind. > > Thanks in advance. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/3ae42692/attachment.htm From mlangford.cs03 at gtalumni.org Mon Oct 15 21:17:13 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 15 Oct 2007 15:17:13 -0400 Subject: [Tutor] Decimal Conversion In-Reply-To: <82b4f5810710151136y49979981mf811a2dc12c9075f@mail.gmail.com> References: <200710151717.l9FHH2Nd014578@rm-rstar.sfu.ca> <82b4f5810710151136y49979981mf811a2dc12c9075f@mail.gmail.com> Message-ID: <82b4f5810710151217n5b58c198r3817f3ee62a5c516@mail.gmail.com> After sending the last email, I was more and more unsatisfied with it's level of detail I provided. Your original statement: b=b,r was doing nothing like you intended. The comma operator in this instance is making a tuple. The name b was being reassigned to the new tuple created by the comma operator. b+="," + r Was not doing exactly what I said. What it's doing is creating a new string from the one named by b, the string literal "," , and the one named by r. After creating the string it assigns the name b to the new string. --michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ On 10/15/07, Michael Langford wrote: > > Use > b+=","+r > instead. That will add the , to the string named by b, and will > concatenate the string named by r to the end. > > --Michael > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > > On 10/15/07, ddm2 at sfu.ca wrote: > > > > Hi, > > > > I'm new to Python, and found some problems on the internet that would be > > a > > good start to begin. The problem I have is that my conversion program > > (which > > currently only converts unsigned integers) also prints all these > > brackets > > and commas. Here is my code and the result: > > CODE: > > print "" > > print "--------------------" > > print "Unsigned Binary" > > print "--------------------" > > print "" > > n = int(raw_input("Please enter an integer: ")) > > b = '' > > while n > 0: > > r = n%2 > > n = n/2 > > b = r,b > > print b > > > > (ex: n = 15) > > RESULT: > > (1, (1, (1, (1, '')))) > > > > I think the problem is in the line of code 'b = r,b', but am not sure > > how to > > fix it. The tip given for the problem says I should 'append' r to b, but > > since b is not a list, 'b = r,b' was the only thing that came to my > > mind. > > > > Thanks in advance. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/9306818e/attachment-0001.htm From christopher.henk at allisontransmission.com Mon Oct 15 22:15:02 2007 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Mon, 15 Oct 2007 16:15:02 -0400 Subject: [Tutor] Decimal Conversion In-Reply-To: <82b4f5810710151217n5b58c198r3817f3ee62a5c516@mail.gmail.com> Message-ID: However since r is an int and b is a string, you will get an error when you try and concatenate them. >>> b='' >>> b+=1 Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects So you need to convert r to a string before you assign it to b >>> b="" >>> n=5 >>> r=str(n%2) >>> b=r+b >>> print b 1 >>> n=n/2 >>> r=str(n%2) >>> b=r+b >>> print b 01 >>> n=n/2 >>> r=str(n%2) >>> b=r+b >>> print b 101 Chris Henk tutor-bounces at python.org wrote on 10/15/2007 03:17:13 PM: > After sending the last email, I was more and more unsatisfied with it's level of detail I provided. > > Your original statement: > > b=b,r > > was doing nothing like you intended. The comma operator in this instance is making a tuple. The name b was being > reassigned to the new tuple created by the comma operator. > > b+="," + r > > Was not doing exactly what I said. What it's doing is creating a new string from the one named by b, the string > literal "," , and the one named by r. After creating the string it assigns the name b to the new string. > > --michael > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > On 10/15/07, Michael Langford < mlangford.cs03 at gtalumni.org> wrote: > Use > b+=","+r > instead. That will add the , to the string named by b, and will concatenate the string named by r to the end. > > --Michael > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > > On 10/15/07, ddm2 at sfu.ca wrote: > Hi, > > I'm new to Python, and found some problems on the internet that would be a > good start to begin. The problem I have is that my conversion program (which > currently only converts unsigned integers) also prints all these brackets > and commas. Here is my code and the result: > CODE: > print "" > print "--------------------" > print "Unsigned Binary" > print "--------------------" > print "" > n = int(raw_input("Please enter an integer: ")) > b = '' > while n > 0: > r = n%2 > n = n/2 > b = r,b > print b > > (ex: n = 15) > RESULT: > (1, (1, (1, (1, '')))) > > I think the problem is in the line of code 'b = r,b', but am not sure how to > fix it. The tip given for the problem says I should 'append' r to b, but > since b is not a list, 'b = r,b' was the only thing that came to my mind. > > Thanks in advance. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/7f04bb6c/attachment.htm From jonvspython at gmail.com Mon Oct 15 22:16:31 2007 From: jonvspython at gmail.com (jon vspython) Date: Mon, 15 Oct 2007 22:16:31 +0200 Subject: [Tutor] newbie question In-Reply-To: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> Message-ID: <4d070c130710151316y43b5eadavb0bb5a793ad6d784@mail.gmail.com> There's also a specially tailored solution for dictionaries: print "%(breakfast)s %(lunch)s %(dinner)s" % menu_specials -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/983184ce/attachment.htm From rdm at rcblue.com Mon Oct 15 23:17:20 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 15 Oct 2007 14:17:20 -0700 Subject: [Tutor] 2 problems in a small script Message-ID: <20071015211729.EADB81E403D@bag.python.org> At 04:36 AM 10/15/2007, Kent Johnson wrote: >Dick Moores wrote: > >>>If your interested, this could be done succinctly with set types. >>>(no iterating required!) > >>Done. I had no idea set could be used that way! With a couple of >>modifications, I used your ideas in both and >> (see the thread I started, < >>http://www.nabble.com/An-idea-for-a-script-tf4603558.html#a13149808 >). > >You might as well create the set of disallowed letters just once: >astr = set(ascii_letters + digits + '-_') Kent, do you mean that in every time well_formed() is used it recreates set(astr) (but not the string astr)? I think you do, but I'd like to make sure.. Thanks, Dick From alan.gauld at btinternet.com Mon Oct 15 23:48:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 22:48:21 +0100 Subject: [Tutor] Decimal Conversion References: <200710151717.l9FHH2Nd014578@rm-rstar.sfu.ca> Message-ID: wrote > print "" > print "--------------------" > print "Unsigned Binary" > print "--------------------" > print "" You don;t need the empty quotes to print a newline. In fact the whole of the above is easier done using triple quotes print """ -------------------- Unsigned Binary -------------------- """ It has nothing to do with your problem but for future reference... To the real issue: > n = int(raw_input("Please enter an integer: ")) > b = '' so n is an integer and b is a string. > while n > 0: > r = n%2 > n = n/2 > b = r,b Michael has already explained that this is building a tuple of tuples. But you want to create strings. So first convert r to a string using str(r) Now you can append using the plus operation for strings b = r+b or just b += r HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Oct 15 23:40:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 22:40:36 +0100 Subject: [Tutor] newbie question References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> <4d070c130710151316y43b5eadavb0bb5a793ad6d784@mail.gmail.com> Message-ID: "jon vspython" wrote > There's also a specially tailored solution for dictionaries: > > print "%(breakfast)s %(lunch)s %(dinner)s" % menu_specials Good catch! I keep forgetting about that. I really must get into the habit of using it more often when working with dictionaries. Thanks, Alan G. From alan.gauld at btinternet.com Mon Oct 15 23:56:16 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Oct 2007 22:56:16 +0100 Subject: [Tutor] (no subject) References: <138982.84959.qm@web56406.mail.re3.yahoo.com> Message-ID: "Latasha Marks" wrote > Need help write a bowling progam for 10 frame have to print score > and frames Please, don't just reply to another message (especially one with No Subject!), start a new thread and provide a sensible subject.It makes it much more likely that your message will actually be seen and responded too. Now some information is needed. This sounds like homework which limits how much help we can give - ie we won't write it for you. Can you describe the problem in more detail? What are the rules of bowling? Since you mention frames I'll assume you don't mean lawn bowls? How is it scored? Can you state the algorithm that you are trying to program in English first? Next what ideas do you have for writing the program? What is your background? How long have you been working with Python (or any other language?) These things assist us to guage the level of help you need. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mlangford.cs03 at gtalumni.org Tue Oct 16 00:56:49 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 15 Oct 2007 18:56:49 -0400 Subject: [Tutor] Decimal Conversion In-Reply-To: References: <200710151717.l9FHH2Nd014578@rm-rstar.sfu.ca> Message-ID: <82b4f5810710151556l1ba58676yd4eb3aa456a3448e@mail.gmail.com> >Michael has already explained that this is building >a tuple of tuples. But you want to create strings. >So first convert r to a string using str(r) Yeah sorry about that....read some java over the weekend (source code to http://reprap.org)...and then munged some of its syntactic sugar into the python area of my brain. Python does not support that operation for + --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ On 10/15/07, Alan Gauld wrote: > > wrote > > > print "" > > print "--------------------" > > print "Unsigned Binary" > > print "--------------------" > > print "" > > You don;t need the empty quotes to print a newline. > > In fact the whole of the above is easier done using triple quotes > > print """ > -------------------- > Unsigned Binary > -------------------- > """ > > It has nothing to do with your problem but for future reference... > > To the real issue: > > > n = int(raw_input("Please enter an integer: ")) > > b = '' > > so n is an integer and b is a string. > > > while n > 0: > > r = n%2 > > n = n/2 > > b = r,b > > Michael has already explained that this is building > a tuple of tuples. But you want to create strings. > So first convert r to a string using str(r) > Now you can append using the plus operation for strings > > b = r+b > > or just > > b += r > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/387398b6/attachment-0001.htm From andrewwu at gmail.com Tue Oct 16 01:03:10 2007 From: andrewwu at gmail.com (Andrew Wu) Date: Mon, 15 Oct 2007 16:03:10 -0700 Subject: [Tutor] Help with packages and namespaces please In-Reply-To: <4710C5DF.2080201@tds.net> References: <99acdf3c0710121248g2632355buaddedc36060d712b@mail.gmail.com> <4710C5DF.2080201@tds.net> Message-ID: <99acdf3c0710151603j78265d34red2724f3e180dad7@mail.gmail.com> Hmmm ... thank you very much for the detailed explanations. This is a very simplified version of some actual code I'm currently using and attempting to rework on each individual file (about 60+ of them). If it's not feasible then I guess I'm stuck with the rework. =( More comments inline ... On 10/13/07, Kent Johnson wrote: > > Andrew Wu wrote: > > > Let's say I have these files in one directory: > > > > PrintBase.py > > PrintHello.py > > PrintBye.py > > > I'd like to reorganize the files so they're like the Sound example in > > the Python tutorial: > > > > PrintMe/ > > PrintMe/PrintBase/PrintBase.py > > PrintMe/PrintHello/PrintHello.py > > PrintMe/PrintBye/PrintBye.py > > Will there be more modules in each subdirectory? I'm not sure if this is > just for learning or if it is a simplification of a real problem, but > from your description of the classes it sounds like they belong in the > same package. Yes - there will be more modules in each subdirectory (I only had one in the example for my own testing purposes and for simplification). > I've created empty __init__.py files in each of the subdirectories. > > Here I run into a number of problems and get confused - my goal is to > > keep the import statements as they are (the actual files I'd be editing > > are many and I'd rather avoid having to edit them all) - is there > > something I can put in the __init__.py files so that the modules are > > brought into namespace w/o having to use absolute module notation? > > You can bring names into the package namespace, but the actual code will > still run in the module where it is defined. For example, in > PrintMe/PrintBase/__init__.py you can say > from PrintBase import Printbase > > Hmm. I'm not sure if this will work the way you want because of the name > collisions. Using the sound example where the names are unique, suppose > wavread.py includes a function read_wav(). Then in Formats/__init__.py > you can say > from wavread import read_wav This imports the name read_wav into the Formats package namespace so > other code will be able to say > from Sound.Formats import read_wav > > In your example, *without* the import in PrintBase/__init__.py it is > already valid to say > from PrintMe.PrintBase import PrintBase > which will access the *module* PrintBase. When you add the line > from PrintBase import Printbase > to __init__.py then there are two possible meanings for > PrintMe.PrintBase.PrintBase and I don't know which one will have > priority. My guess is that the module import will win but I don't know. > > At best this seems like a recipe for endless confusion - you have three > entities named PrintBase - a package, a module and a class. Hmmm ... this could be due to the poor naming convention (which also afflicts the actual code I'm modeling - the use of the same name for the class and file) ... If the import in __init__ promotes the class as you want, it still won't > help with the imports in PrintHello.py - it will still have to say at > least > from PrintMe.PrintBase import PrintBase > > Why do you want to do this? It looks like a confusing mess to me. > > > > As simple tests, I've tried running different import commands in the > > python interpreter: > > > > I've tried adding the absolute directory paths to __path__ in each > > __init__.py per subdirectory, and adding the paths to sys.path. > > Yuck. What is the point of the directories and packages if you are going > to put every thing on sys.path anyway? But I think it should work if you > put each of the subdirectories of PrintMe on sys.path. My hope was to avoid having to edit the individual files but if that leads to a gobbled mess then I'd rather do it more correctly. > When I > > do that and run the python intepreter and try 'from PrintMe.PrintHello > > import PrintHello' I get an error saying 'Error when calling the > > metaclass bases, module.__init__() takes at most 2 arguments (3 > > given)'. The same code functioned fine when all the files were in the > > same directory, so I'm confused about why the interpreter thinks I'm > > passing 3 arguments along. > > You get an error on the import? Please show the traceback. It could be I'm doing it all wrong. Hmmm ... I can't get it to happen again. If / when I do I'll post the traceback. Thanks! Andrew Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/c408d1e5/attachment.htm From paulino1 at sapo.pt Tue Oct 16 01:40:50 2007 From: paulino1 at sapo.pt (Paulino) Date: Tue, 16 Oct 2007 00:40:50 +0100 Subject: [Tutor] File upload from python shell In-Reply-To: <471352AB.906@tds.net> References: <471165EA.2050502@sapo.pt> <471352AB.906@tds.net> Message-ID: <4713FA82.2010301@sapo.pt> Kent Johnson escreveu: > Paulino wrote: >> Hello! >> >> >> How can I upload a file from python? >> >> If it is a form to fill with values it's simple: >> >> >> urlopen("http://site.com/action?key1=value1;key2=value2") and I get >> the form filled. >> >> >> What about uploading a file programmaticaly? > > This might help: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 > > Kent > > Thank You very much Luke, Alan, David and Kent. I used Nokia's forum recipe (sugested by David) it's very simple and works perfectly! here is it (a few variables changed) import httplib, urllib import base64, os.path def uploadToURL( aPath ): # read the binary data of the pdf data = open(aPath, 'rb').read() # encoded it to base64 encodedData = base64.encodestring( data ) headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" } params = urllib.urlencode({ 'filename': os.path.split(aPath)[1], 'file_data':encodedData}) conn = httplib.HTTPConnection( "localhost:8080" ) conn.request( "POST", "/rendas/rec/uploadtxt", params, headers ) response = conn.getresponse( ) # returns "True" or "False" if failed print response.read( ) # status for debugging #print response.status conn.close( ) if __name__ == "__main__": uploadToURL("/home/paulino/ola230.pdf") And here is the turbogears server method that handles the file: @expose() def uploadtxt(self, file_data, **kw): data = base64.decodestring(file_data) f = open(kw['filename'], 'wb') f.write(data) f.close() return "Success" From kpsingh at gmail.com Tue Oct 16 01:45:46 2007 From: kpsingh at gmail.com (Kamal) Date: Mon, 15 Oct 2007 16:45:46 -0700 Subject: [Tutor] Timers in Python In-Reply-To: <47052186.5030400@airtelbroadband.in> References: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> <4704C35D.7090501@tds.net> <47052186.5030400@airtelbroadband.in> Message-ID: <333eea650710151645y52cf1466n497a4ba601539c8c@mail.gmail.com> Thanks everyone for the useful feedback. On 10/4/07, Noufal Ibrahim wrote: > > Kent Johnson wrote: > > Kamal wrote: > >> hello everyone, > >> > >> Is there a method in Python which does what > >> setInterval('someFunction()',5000) does in Javascript. > >> > >> Basically, I want to call functionOne() every x minutes, and wondering > >> whats the best way to do it. > > You can also look at the sched module that comes with the standard > distribution. > > > > > -- > ~noufal > http://nibrahim.net.in/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Thanks, Kamal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/33006e43/attachment.htm From andrewwu at gmail.com Tue Oct 16 01:52:16 2007 From: andrewwu at gmail.com (Andrew Wu) Date: Mon, 15 Oct 2007 16:52:16 -0700 Subject: [Tutor] Help with packages and namespaces please In-Reply-To: <4710C5DF.2080201@tds.net> References: <99acdf3c0710121248g2632355buaddedc36060d712b@mail.gmail.com> <4710C5DF.2080201@tds.net> Message-ID: <99acdf3c0710151652i34331445jdd533259e6f0e30@mail.gmail.com> After a more careful perusing and sifting of your response, I discovered this helped my understanding a lot better: > > You can bring names into the package namespace, but the actual code will > still run in the module where it is defined. For example, in > PrintMe/PrintBase/__init__.py you can say > from PrintBase import Printbase > > Hmm. I'm not sure if this will work the way you want because of the name > collisions. Using the sound example where the names are unique, suppose > wavread.py includes a function read_wav(). Then in Formats/__init__.py > you can say > from wavread import read_wav > > This imports the name read_wav into the Formats package namespace so > other code will be able to say > from Sound.Formats import read_wav This above seems to be closest to what I'm hoping to achieve ... I will try this out and see how it goes. Thanks again! Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/51229270/attachment.htm From rabidpoobear at gmail.com Tue Oct 16 02:07:31 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 15 Oct 2007 19:07:31 -0500 Subject: [Tutor] Decimal Conversion In-Reply-To: <82b4f5810710151556l1ba58676yd4eb3aa456a3448e@mail.gmail.com> References: <200710151717.l9FHH2Nd014578@rm-rstar.sfu.ca> <82b4f5810710151556l1ba58676yd4eb3aa456a3448e@mail.gmail.com> Message-ID: <471400C3.8090507@gmail.com> Michael Langford wrote: > > >Michael has already explained that this is building > >a tuple of tuples. But you want to create strings. > >So first convert r to a string using str(r) > > Yeah sorry about that....read some java over the weekend (source code > to http://reprap.org)...and then munged > some of its syntactic sugar into the python area of my brain. Python > does not support that operation for + You can append ints to strings in Java using +? -Luke From allen.fowler at yahoo.com Tue Oct 16 02:33:34 2007 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 15 Oct 2007 17:33:34 -0700 (PDT) Subject: [Tutor] __getattr__(): Is this right? Message-ID: <842121.36051.qm@web45603.mail.sp1.yahoo.com> I seem to be having an issue with __getattr__() being called even if the proporite already exists... I thought that this was not supposed to happen. Is there a typo somewhere, or I do i misunderstand things? class someclass(object): def __init__(self, **kargs): self.valid_props = [ 'foo', 'bar', 'baz' ] for prop in self.valid_props: if kargs.has_key(prop): self.__setattr__(prop, kargs[prop]) def __getattr__(self,attr): if attr in self.valid_props: # This print should throw an exception, # but it does not. It shows the value. print "Oh no.. This was not found: %s" % self.__dict__[attr] return 'n/a' else: raise AttributeError, attr --------------------------------- Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/fb8490fd/attachment-0001.htm From kent37 at tds.net Tue Oct 16 02:55:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Oct 2007 20:55:08 -0400 Subject: [Tutor] __getattr__(): Is this right? In-Reply-To: <842121.36051.qm@web45603.mail.sp1.yahoo.com> References: <842121.36051.qm@web45603.mail.sp1.yahoo.com> Message-ID: <47140BEC.8020402@tds.net> Allen Fowler wrote: > I seem to be having an issue with __getattr__() being called even if the > proporite already exists... I thought that this was not supposed to happen. > > Is there a typo somewhere, or I do i misunderstand things? > > class someclass(object): > > > def __init__(self, **kargs): > > self.valid_props = [ 'foo', 'bar', 'baz' ] > > for prop in self.valid_props: > if kargs.has_key(prop): > self.__setattr__(prop, kargs[prop]) > > def __getattr__(self,attr): > if attr in self.valid_props: > # This print should throw an exception, > # but it does not. It shows the value. > print "Oh no.. This was not found: %s" % self.__dict__[attr] > return 'n/a' > else: > raise AttributeError, attr It works as I expect: In [28]: s=someclass(foo='FOO') In [29]: s.foo Out[29]: 'FOO' In [30]: s.bar ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in File "", line 11, in __getattr__ : 'bar' What did you try? What happened? What did you expect? Kent From brunson at brunson.com Tue Oct 16 03:54:56 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 15 Oct 2007 19:54:56 -0600 Subject: [Tutor] __getattr__(): Is this right? In-Reply-To: <842121.36051.qm@web45603.mail.sp1.yahoo.com> References: <842121.36051.qm@web45603.mail.sp1.yahoo.com> Message-ID: <471419F0.2060406@brunson.com> Allen Fowler wrote: > I seem to be having an issue with __getattr__() being called even if > the proporite already exists... I thought that this was not supposed > to happen. I think you've misunderstood. __getattr__() should always be called, it allows you to intercept and reimplement the behavior of a attribute lookup to suit your needs. Typically, my __getattrs__() look like this: def __getattr__( self, attr ): if has_attr( usuallysomethingotherthanself, attr ): do_one_thing() else: do_something_else() > > Is there a typo somewhere, or I do i misunderstand things? > > class someclass(object): > > > def __init__(self, **kargs): > > self.valid_props = [ 'foo', 'bar', 'baz' ] > > for prop in self.valid_props: > if kargs.has_key(prop): > self.__setattr__(prop, kargs[prop]) > > def __getattr__(self,attr): > if attr in self.valid_props: > # This print should throw an exception, > # but it does not. It shows the value. > print "Oh no.. This was not found: %s" % self.__dict__[attr] > return 'n/a' > else: > raise AttributeError, attr > > > ------------------------------------------------------------------------ > Boardwalk for $500? In 2007? Ha! > Play Monopoly Here and Now > > (it's updated for today's economy) at Yahoo! Games. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Tue Oct 16 04:06:43 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 15 Oct 2007 19:06:43 -0700 Subject: [Tutor] All Apress Titles 50% off sale Message-ID: <20071016022657.798CF1E4031@bag.python.org> That includes some titles that aren't out yet, such as: The Definitive Guide to Django: Web Development Done Right Beginning Game Development with Python and Pygame: From Novice to Professional Dick Moores From allen.fowler at yahoo.com Tue Oct 16 04:56:47 2007 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 15 Oct 2007 19:56:47 -0700 (PDT) Subject: [Tutor] __getattr__(): Is this right? In-Reply-To: <471419F0.2060406@brunson.com> Message-ID: <337154.31554.qm@web45604.mail.sp1.yahoo.com> Eric Brunson wrote: Allen Fowler wrote: > I seem to be having an issue with __getattr__() being called even if > the proporite already exists... I thought that this was not supposed > to happen. I think you've misunderstood. __getattr__() should always be called, it allows you to intercept and reimplement the behavior of a attribute lookup to suit your needs. Typically, my __getattrs__() look like this: See: http://docs.python.org/ref/attribute-access.html This would lead me to think not that way... "Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance." --------------------------------- Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/085119e6/attachment.htm From brunson at brunson.com Tue Oct 16 05:03:20 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 15 Oct 2007 21:03:20 -0600 Subject: [Tutor] __getattr__(): Is this right? In-Reply-To: <337154.31554.qm@web45604.mail.sp1.yahoo.com> References: <337154.31554.qm@web45604.mail.sp1.yahoo.com> Message-ID: <471429F8.9020405@brunson.com> Allen Fowler wrote: > > > */Eric Brunson /* wrote: > > Allen Fowler wrote: > > I seem to be having an issue with __getattr__() being called > even if > > the proporite already exists... I thought that this was not > supposed > > to happen. > > I think you've misunderstood. __getattr__() should always be > called, it > allows you to intercept and reimplement the behavior of a attribute > lookup to suit your needs. Typically, my __getattrs__() look like > this: > > > > See: > http://docs.python.org/ref/attribute-access.html > > > This would lead me to think not that way... > > > "Note that if the attribute is found through the normal mechanism, > __getattr__() is not called. (This is an intentional asymmetry between > __getattr__() and __setattr__().) This is done both for efficiency > reasons and because otherwise __setattr__() would have no way to > access other attributes of the instance." There you go, you are right and I am not. I guess because I don't actually set the attribute of self, I can intercept both the get and set. "Learn one new thing every day". Done. :-) > > > > ------------------------------------------------------------------------ > Building a website is a piece of cake. > Yahoo! Small Business gives you all the tools to get online. > From allen.fowler at yahoo.com Tue Oct 16 05:09:24 2007 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 15 Oct 2007 20:09:24 -0700 (PDT) Subject: [Tutor] __getattr__(): Is this right? [w/ new code] In-Reply-To: <47140BEC.8020402@tds.net> Message-ID: <932914.12714.qm@web45614.mail.sp1.yahoo.com> What did you try? What happened? What did you expect? Kent Narrowed things down a bit..... Given this class: ------------------------------- class sc(object): def __init__(self, **kargs): self.valid_props = [ 'foo', 'bar', 'baz' ] for prop in self.valid_props: if kargs.has_key(prop): self.__setattr__(prop, kargs[prop]) def __getattr__(self,attr): if attr in self.valid_props: print "__getattr__ was called for %s" % attr return 'n/a' else: raise AttributeError, attr This is my in/output: --------------------------------- In [1]: some_string_a = 'foo' In [2]: some_string_b = 'FOO' In [3]: s = sc( foo=some_string_b ) In [4]: s.foo Out[4]: 'FOO' In [5]: eval('s.' + some_string_a) Out[5]: 'FOO' In [6]: s.__getattr__(some_string_a) __getattr__ was called for foo Out[6]: 'n/a' In [7]: s.__getattr__('foo') __getattr__ was called for foo Out[7]: 'n/a' In [8]: s.bar __getattr__ was called for bar __getattr__ was called for bar Out[8]: 'n/a' In [9]: s.__getattr__('bar') __getattr__ was called for bar Out[9]: 'n/a' Here is what I expected: ---------------------------------- Outputs 4 and 5 are fine. Outputs 6 and 7 should have returned 'FOO' Outputs 8 and 9 are fine. (But why two prints on 8?) Thank you all. --------------------------------- Don't let your dream ride pass you by. Make it a reality with Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/d71891d5/attachment.htm From allen.fowler at yahoo.com Tue Oct 16 05:12:31 2007 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 15 Oct 2007 20:12:31 -0700 (PDT) Subject: [Tutor] __getattr__(): Is this right? In-Reply-To: <471429F8.9020405@brunson.com> Message-ID: <64047.3973.qm@web45616.mail.sp1.yahoo.com> > "Note that if the attribute is found through the normal mechanism, > __getattr__() is not called. (This is an intentional asymmetry between > __getattr__() and __setattr__().) This is done both for efficiency > reasons and because otherwise __setattr__() would have no way to > access other attributes of the instance." There you go, you are right and I am not. I guess because I don't actually set the attribute of self, I can intercept both the get and set. "Learn one new thing every day". Done. :-) Happy to help.... :) You may be interested in: __getattribute__ http://docs.python.org/ref/new-style-attribute-access.html That will get ALL requests. Read the warnings, though. --------------------------------- Tonight's top picks. What will you watch tonight? Preview the hottest shows on Yahoo! TV. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/34aa06b3/attachment.htm From eric at abrahamsen.com Tue Oct 16 05:28:05 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Tue, 16 Oct 2007 11:28:05 +0800 Subject: [Tutor] reading POST method in cgi script Message-ID: I'm trying to learn the fundamentals of cgi scripting, before moving on to actually using the cgi module and, eventually, mod_python. I've grasped that, if users submit a form to my cgi script, I can read the form contents from os.environ['QUERY_STRING'] if it was stuck in the URL via method=get, and from sys.stdin if it was sent via method=post. The get method works fine, but when it comes to post I can't actually read anything off sys.stdin. What's particularly odd is that in my test script below, the returnform() function should only be called if len(sys.stdin.read())!=0, and yet when I submit a word and the script runs returnform(), it tells me that len(sys.stdin.read()) is equal to 0. If that's the case, how did returnform() get called in the first place? Why didn't it just re-run printform()? At first I tried printing each line of sys.stdin to the HTML page, so I could see the details of how post works. Nothing was printed, and that's when I tried using len() to see whether sys.stdin contained anything. Then, thinking that stdin was getting reset somehow, I tried calling returnform() and directly passing in stdin as a parameter. That had the same result. Now, I'm thoroughly confused... Any help would be much appreciated. Yours, Eric ************ #!/Library/Frameworks/Python.framework/Versions/Current/bin/python import sys import cgitb;cgitb.enable() def main(): if len(sys.stdin.read())!=0: returnform() else: printform() def printform(): print "Content-Type: text/html\n\n" print """

Send us a word.

""" def returnform(): print "Content-Type: text/html\n\n" print """

Here's what results for standard in:

""" print "

Length of stdin is %s

" % len(sys.stdin.read()) print """ """ main() From allen.fowler at yahoo.com Tue Oct 16 06:01:55 2007 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 15 Oct 2007 21:01:55 -0700 (PDT) Subject: [Tutor] __getattr__(): Is this right? [w/ new code] In-Reply-To: <932914.12714.qm@web45614.mail.sp1.yahoo.com> Message-ID: <833715.93565.qm@web45611.mail.sp1.yahoo.com> Umm... well. obviously I left out an __setattr__() call.. sigh. thanks anyway... Allen Fowler wrote: What did you try? What happened? What did you expect? Kent Narrowed things down a bit..... Given this class: ------------------------------- class sc(object): def __init__(self, **kargs): self.valid_props = [ 'foo', 'bar', 'baz' ] for prop in self.valid_props: if kargs.has_key(prop): self.__setattr__(prop, kargs[prop]) def __getattr__(self,attr): if attr in self.valid_props: print "__getattr__ was called for %s" % attr return 'n/a' else: raise AttributeError, attr This is my in/output: --------------------------------- In [1]: some_string_a = 'foo' In [2]: some_string_b = 'FOO' In [3]: s = sc( foo=some_string_b ) In [4]: s.foo Out[4]: 'FOO' In [5]: eval('s.' + some_string_a) Out[5]: 'FOO' In [6]: s.__getattr__(some_string_a) __getattr__ was called for foo Out[6]: 'n/a' In [7]: s.__getattr__('foo') __getattr__ was called for foo Out[7]: 'n/a' In [8]: s.bar __getattr__ was called for bar __getattr__ was called for bar Out[8]: 'n/a' In [9]: s.__getattr__('bar') __getattr__ was called for bar Out[9]: 'n/a' Here is what I expected: ---------------------------------- Outputs 4 and 5 are fine. Outputs 6 and 7 should have returned 'FOO' Outputs 8 and 9 are fine. (But why two prints on 8?) Thank you all. --------------------------------- Don't let your dream ride pass you by. Make it a reality with Yahoo! Autos. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071015/12177555/attachment.htm From rabidpoobear at gmail.com Tue Oct 16 06:22:49 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 15 Oct 2007 23:22:49 -0500 Subject: [Tutor] reading POST method in cgi script In-Reply-To: References: Message-ID: <47143C99.7090807@gmail.com> Eric Abrahamsen wrote: > I'm trying to learn the fundamentals of cgi scripting, before moving > on to actually using the cgi module and, eventually, mod_python. I've > grasped that, if users submit a form to my cgi script, I can read the > form contents from os.environ['QUERY_STRING'] if it was stuck in the > URL via method=get, and from sys.stdin if it was sent via method=post. > > The get method works fine, but when it comes to post I can't actually > read anything off sys.stdin. Yeah, you can. > What's particularly odd is that in my > test script below, the returnform() function should only be called if > len(sys.stdin.read())!=0, and yet when I submit a word and the script > runs returnform(), it tells me that len(sys.stdin.read()) is equal to > 0. If that's the case, how did returnform() get called in the first > place? Why didn't it just re-run printform()? > Because you're confused about what sys.stdin.read() does. Imagine stdin is a string: "Hello, Eric!" now if I call sys.stdin.read(5) it will return "Hello," and the contents of sys.stdin.read() will now be " Eric!" or, to be more accurate, the current-position pointer will be set to offset 5, so that future reads will start at that position. To understand why they would do it this way, consider you want to read in 5 characters at a time from a file. Say the file is 6 GB. If you were to read in the whole file and loop over it 5 characters at a time, you'd probably overflow your memory. However, if you tell the OS you want to open the file for reading, and you then read 5 characters at a time from the file, you won't have to load everything into memory. This is accomplished using pointers inside the file, so you know where you last read. Even though sys.stdin in this case is not a file, it works the same way, because it's a "File-Like Object." Python uses Duck Typing, wherein the feature set of a particular item determines its type, rather than something arbitrary you define. So if any item has read(), write(), and seek() methods, you can usually use these in place of file objects. This is true no matter what your functions actually do. In other words, your read() function could just count how many times it's called, but do nothing with the value, or anything else you may want it to do. > At first I tried printing each line of sys.stdin to the HTML page, so > I could see the details of how post works. Nothing was printed, and > that's when I tried using len() to see whether sys.stdin contained > anything. Then, thinking that stdin was getting reset somehow, It's not getting reset, really. > I > tried calling returnform() and directly passing in stdin as a > parameter. That had the same result. Usually when you get to the point where you're trying random things hoping something will work, you've reached the time when you either sleep on it or ask someone for help. Even if you reach a solution through exhaustive testing, you still haven't learned anything, which is pretty useless to you in the long run. > Now, I'm thoroughly confused... > Don't worry about it. It's good you asked. > Any help would be much appreciated. > > Yours, > Eric > > ************ > > #!/Library/Frameworks/Python.framework/Versions/Current/bin/python > import sys > import cgitb;cgitb.enable() > > def main(): > if len(sys.stdin.read())!=0: > This is your problem right here. len(sys.stdin.read()) is calling len() on a string returned by sys.stdin.read() As mentioned earlier, calling this function sets the current-location pointer to one after the last-read position. Since you passed no maximum to read(), the whole stdin contents were read into this variable, leaving the pointer at the end of the file. Thus on subsequent calls, sys.stdin.read() will return nothing. Try changing this to len(sys.stdin.read(3)) and then pass your program a string longer than 3 characters. Your length output in returnform should then be 3 less than your expected value, or 0, whichever is greater. > returnform() > else: > printform() > > def printform(): > [snip printing form] > > def returnform(): > This name is a bit confusing, because the function doesn't return anything. Perhaps display_form_contents would be a better name? > print "Content-Type: text/html\n\n" > You could include this in the block print statement, if you wanted. It's fine to keep the header separate, though, and probably a good idea. > print """ > > > >

Here's what results for standard in:

""" > print "

Length of stdin is %s

" % len(sys.stdin.read()) > So here when you're reading the length of sys.stdin.read() it's reading in from stdin again, and since the pointer is at the end of the file, len() is getting an empty string. You could reset the pointer to 0 if you wanted, using seek(), but I'd say just read the data once, in your main, and pass it as an argument to returnform. That makes your returnform function more versatile, as well, because then if I wanted to have a different form's contents printed that I had saved in a file, for example, I could just pass it to your function, without having to jump through the hoops of redirecting sys.stdin to my file. Also I doubt it'd be a problem to have a block-printed format string. I.E. just do it this way: print """

Here's what results for standard in:

Length of stdin is %s

""" % len(sys.stdin.read()) Perhaps this seems less intuitive to you. It's really just a preference thing, but it makes for slightly more readable code in my opinion. > main() A neat trick is to do this: if __name__ == "__main__": main() The __name__ variable is set to "__main__" only when the script is executed directly. So if I call form.py, for example. However, if I write my own python program, and I want to use your printform() function, I can do import form which will import your functions into my namespace, and I can then do form.printform() If you don't have the above 2 lines, then when I import your form.py module, main() will be run every time, causing all the main() stuff to be executed even if I really just wanted to use one of your functions, which in almost every case is an "unwanted side-effect." Hope this has helped in some way, -Luke From eric at abrahamsen.com Tue Oct 16 09:28:50 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Tue, 16 Oct 2007 15:28:50 +0800 Subject: [Tutor] reading POST method in cgi script In-Reply-To: <47143C99.7090807@gmail.com> References: <47143C99.7090807@gmail.com> Message-ID: Thanks for the detailed help. I'm dumping sys.stdin into a variable at the very start now, and operating on that variable for everything else, and all is well. Thanks again, E On Oct 16, 2007, at 12:22 PM, Luke Paireepinart wrote: > Eric Abrahamsen wrote: >> I'm trying to learn the fundamentals of cgi scripting, before >> moving on to actually using the cgi module and, eventually, >> mod_python. I've grasped that, if users submit a form to my cgi >> script, I can read the form contents from os.environ >> ['QUERY_STRING'] if it was stuck in the URL via method=get, and >> from sys.stdin if it was sent via method=post. >> >> The get method works fine, but when it comes to post I can't >> actually read anything off sys.stdin. > Yeah, you can. >> What's particularly odd is that in my test script below, the >> returnform() function should only be called if len(sys.stdin.read >> ())!=0, and yet when I submit a word and the script runs >> returnform(), it tells me that len(sys.stdin.read()) is equal to >> 0. If that's the case, how did returnform() get called in the >> first place? Why didn't it just re-run printform()? >> > Because you're confused about what sys.stdin.read() does. > Imagine stdin is a string: > "Hello, Eric!" > now if I call > sys.stdin.read(5) > it will return > "Hello," > and the contents of sys.stdin.read() will now be > " Eric!" > or, to be more accurate, the current-position pointer will be set > to offset 5, so that future reads will start at that position. > > To understand why they would do it this way, consider you want to > read in 5 characters at a time from a file. > Say the file is 6 GB. If you were to read in the whole file and > loop over it 5 characters at a time, > you'd probably overflow your memory. > However, if you tell the OS you want to open the file for reading, > and you then read 5 characters at a time from the file, > you won't have to load everything into memory. This is > accomplished using pointers inside the file, so you know where you > last read. > > Even though sys.stdin in this case is not a file, it works the same > way, because it's a "File-Like Object." > Python uses Duck Typing, wherein the feature set of a particular > item determines its type, rather than something arbitrary you define. > So if any item has read(), write(), and seek() methods, you can > usually use these in place of file objects. > This is true no matter what your functions actually do. > In other words, your read() function could just count how many > times it's called, but do nothing with the value, or anything else > you may want it to do. >> At first I tried printing each line of sys.stdin to the HTML page, >> so I could see the details of how post works. Nothing was >> printed, and that's when I tried using len() to see whether >> sys.stdin contained anything. Then, thinking that stdin was >> getting reset somehow, > It's not getting reset, really. >> I tried calling returnform() and directly passing in stdin as a >> parameter. That had the same result. > Usually when you get to the point where you're trying random things > hoping something will work, > you've reached the time when you either sleep on it or ask someone > for help. > Even if you reach a solution through exhaustive testing, you still > haven't learned anything, which is pretty useless to you in the > long run. >> Now, I'm thoroughly confused... >> > Don't worry about it. It's good you asked. >> Any help would be much appreciated. >> >> Yours, >> Eric >> >> ************ >> >> #!/Library/Frameworks/Python.framework/Versions/Current/bin/python >> import sys >> import cgitb;cgitb.enable() >> >> def main(): >> if len(sys.stdin.read())!=0: >> > This is your problem right here. > len(sys.stdin.read()) is calling len() on a string returned by > sys.stdin.read() > As mentioned earlier, calling this function sets the current- > location pointer to one after the last-read position. > Since you passed no maximum to read(), the whole stdin contents > were read into this variable, leaving > the pointer at the end of the file. Thus on subsequent calls, > sys.stdin.read() will return nothing. > Try changing this to len(sys.stdin.read(3)) and then pass your > program a string longer than 3 characters. > Your length output in returnform should then be 3 less than your > expected value, or 0, whichever is greater. >> returnform() >> else: >> printform() >> >> def printform(): >> [snip printing form] >> >> def returnform(): >> > This name is a bit confusing, because the function doesn't return > anything. > Perhaps display_form_contents would be a better name? >> print "Content-Type: text/html\n\n" >> > You could include this in the block print statement, if you > wanted. It's fine to keep the header separate, though, > and probably a good idea. >> print """ >> >> >> >>

Here's what results for standard in:

""" >> print "

Length of stdin is %s

" % len(sys.stdin.read()) >> > So here when you're reading the length of sys.stdin.read() it's > reading in from stdin again, > and since the pointer is at the end of the file, len() is getting > an empty string. > You could reset the pointer to 0 if you wanted, using seek(), but > I'd say just read the data once, > in your main, and pass it as an argument to returnform. > > That makes your returnform function more versatile, as well, > because then if I wanted to have a different form's contents > printed that I had saved in a file, for example, I could just pass > it to your function, without having to jump through the hoops > of redirecting sys.stdin to my file. > > Also I doubt it'd be a problem to have a block-printed format string. > I.E. just do it this way: > > print """ > > > >

Here's what results for standard in:

>

Length of stdin is %s

> > """ % len(sys.stdin.read()) > > > Perhaps this seems less intuitive to you. It's really just a > preference thing, but it makes for slightly more readable code in > my opinion. >> main() > A neat trick is to do this: > > if __name__ == "__main__": > main() > > The __name__ variable is set to "__main__" only when the script is > executed directly. > So if I call form.py, for example. > However, if I write my own python program, and I want to use your > printform() function, I can do > import form > which will import your functions into my namespace, and I can then do > form.printform() > If you don't have the above 2 lines, then when I import your > form.py module, main() will be run every time, > causing all the main() stuff to be executed even if I really just > wanted to use one of your functions, which in almost every case is > an "unwanted side-effect." > > Hope this has helped in some way, > -Luke > From bhaaluu at gmail.com Tue Oct 16 09:33:12 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 16 Oct 2007 03:33:12 -0400 Subject: [Tutor] All Apress Titles 50% off sale In-Reply-To: <20071016022657.798CF1E4031@bag.python.org> References: <20071016022657.798CF1E4031@bag.python.org> Message-ID: On 10/15/07, Dick Moores wrote: > > That includes some titles that aren't out yet, such as: > > The Definitive Guide to Django: Web Development Done Right > > > Beginning Game Development with Python and Pygame: From Novice to Professional > > > Dick Moores FYI: Will McGugan, author of _Beginning Game Development with Python and Pygame_ has a free chapter available: http://www.willmcgugan.com/2007/10/04/free-chapter-of-beginning-game-development-with-python-and-pygame/ It is Chapter 7, "Take Me to Your Leader" which discusses Artificial Intelligence. There is also a download of sample source code for the Ant Simulation as well as a required gameobjects library. Chapter 7 is a PDF file, and the other files are ZIP archived. The Table of Contents of the book can be viewed at: http://www.willmcgugan.com/2007/10/07/table-of-contents-for-pygame-book/ The book will be available October 24th. Happy Programming! -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From timmichelsen at gmx-topmail.de Tue Oct 16 13:45:18 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 16 Oct 2007 11:45:18 +0000 (UTC) Subject: [Tutor] symbol encoding and processing problem Message-ID: Dear list, I have encountered a problem with encoding of user input and variables. I want to read in user defined coordinates as a string like: 121? 55' 5.55'' Furthermore I would like to extract the degrees (integer number before the " ? " sign), the minutes (integer number before the " ' " sign) and the seconds (floating point number before the " '' " sign). When reading and processing the degree part I get some errors: Heres my test script: 1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 from easygui import easygui 4 import sys 5 #raw = sys.argv[1] 6 raw = easygui.enterbox(message="Enter something.", title="", argDefaultText="20? 12' 33''") 7 #unicode = unicode(raw) 8 #conv = raw.encoding('latin-1') 9 split = raw.split('?') 10 out = raw 11 print out 12 easygui.msgbox(out) Here ist my output: 20? 12' 33'' Traceback (most recent call last): File "C:\python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "D:\python\scripts\encoding-test.py", line 22, in ? split = raw.split('?') UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 0: ordinal not in range(128) Traceback (most recent call last): File "C:\python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "D:\python\scripts\encoding-test.py", line 22, in ? split = raw.split('?') UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 0: ordinal not in range(128) Therefore my question: * How can I split at the "?" without getting a charater encoding error? * How do I have to encode the "?"-symbol that it gets correctly displayed in the Easygui msgbox at line 6? Thanks inadvance for answering, Timmie From kent37 at tds.net Tue Oct 16 13:55:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Oct 2007 07:55:39 -0400 Subject: [Tutor] All Apress Titles 50% off sale In-Reply-To: <20071016022657.798CF1E4031@bag.python.org> References: <20071016022657.798CF1E4031@bag.python.org> Message-ID: <4714A6BB.3070304@tds.net> Dick Moores wrote: > Broken at the moment...but to clarify, IIUC it is Bookpool that is having the sale, not Apress. http://www.bookpool.com/ Kent > That includes some titles that aren't out yet, such as: > > The Definitive Guide to Django: Web Development Done Right > > > Beginning Game Development with Python and Pygame: From Novice to Professional > > > Dick Moores > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Tue Oct 16 14:06:01 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 16 Oct 2007 05:06:01 -0700 Subject: [Tutor] All Apress Titles 50% off sale In-Reply-To: <4714A6BB.3070304@tds.net> References: <20071016022657.798CF1E4031@bag.python.org> <4714A6BB.3070304@tds.net> Message-ID: <20071016120616.848BF1E400E@bag.python.org> At 04:55 AM 10/16/2007, Kent Johnson wrote: >Dick Moores wrote: > > > >Broken at the moment...but to clarify, IIUC it is Bookpool that is >having the sale, not Apress. >http://www.bookpool.com/ Certainly is. Thanks, Kent. Dick From linpeiheng at 163.com Tue Oct 16 13:52:50 2007 From: linpeiheng at 163.com (Linpeiheng) Date: Tue, 16 Oct 2007 19:52:50 +0800 Subject: [Tutor] Decimal Conversion Message-ID: <4714A9AC.0CB1F0.30130@m5-83.163.com> There is one small mistake in Michael's answer. Variable 'r' should not be put behind but ahead. So operator '+=' could not be used here. You can use the following statement instead. b = r + ',' + b Operator '+' concatenate string together to make a new string. In this statement it concatenate three strings together, 'r' and 'b' are str type varible, ',' is str type value. From evert.rol at gmail.com Tue Oct 16 15:14:12 2007 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 16 Oct 2007 14:14:12 +0100 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: Message-ID: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> Hi Tim, > Heres my test script: > > 1 #!/usr/bin/env python > 2 # -*- coding: utf-8 -*- > 3 from easygui import easygui > 4 import sys > 5 #raw = sys.argv[1] > 6 raw = easygui.enterbox(message="Enter something.", title="", > argDefaultText="20? 12' 33''") > 7 #unicode = unicode(raw) > 8 #conv = raw.encoding('latin-1') > 9 split = raw.split('?') > 10 out = raw > 11 print out > 12 easygui.msgbox(out) > > Here ist my output: > > 20? 12' 33'' > Traceback (most recent call last): > File "C:\python24\Lib\site-packages\pythonwin\pywin\framework > \scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "D:\python\scripts\encoding-test.py", line 22, in ? > split = raw.split('?') > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in > position 0: ordinal > not in range(128) > Traceback (most recent call last): > File "C:\python24\Lib\site-packages\pythonwin\pywin\framework > \scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "D:\python\scripts\encoding-test.py", line 22, in ? > split = raw.split('?') > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in > position 0: ordinal > not in range(128) > > Therefore my question: > * How can I split at the "?" without getting a charater encoding > error? > * How do I have to encode the "?"-symbol that it gets correctly > displayed in the > Easygui msgbox at line 6? I don't know all the details about unicode, but here's what works for me: # -*- coding: utf-8 -*- import easygui raw = unicode("121? 55' 5.55''", 'utf-8') print raw.encode('utf-8') lines = raw.split(unicode('?', 'utf-8')) print lines easygui.enterbox(message="Enter something.", title="", argDefaultText=raw) So you may need to explicitly define the encoding (and encode the degree sign in the split argument as well). Google a bit for Python and unicode to get some more info, if you didn't do so already. (I'm really hoping that with Python 3 all this messy stuff does go away.) I had no problem with the easygui box, either my way or hardcoding the string to argDefaultText as you did. Perhaps it's an underlying problem with Tkinter, which may not support unicode on your system? A simple test (not sure how definite that would be), is to start up a Python cmdline, and do >>> import Tkinter >>> Tkinter._test() And see if you get a ?. Good luck, Evert From kent37 at tds.net Tue Oct 16 14:19:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Oct 2007 08:19:28 -0400 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: Message-ID: <4714AC50.5000209@tds.net> Tim Michelsen wrote: > Dear list, > I have encountered a problem with encoding of user input and variables. > Heres my test script: Posting without the line numbers would make it easier to try your code. > > 1 #!/usr/bin/env python > 2 # -*- coding: utf-8 -*- > 3 from easygui import easygui > 4 import sys > 5 #raw = sys.argv[1] > 6 raw = easygui.enterbox(message="Enter something.", title="", > argDefaultText="20? 12' 33''") > 7 #unicode = unicode(raw) > 8 #conv = raw.encoding('latin-1') > 9 split = raw.split('?') try a unicode string: split = raw.split(u'?') > 10 out = raw > 11 print out > 12 easygui.msgbox(out) > > Here ist my output: > > 20? 12' 33'' How do you get this output? The print is after the statement causing the traceback. Are you showing the same code as you ran? > Traceback (most recent call last): > File "C:\python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "D:\python\scripts\encoding-test.py", line 22, in ? > split = raw.split('?') > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 0: ordinal > not in range(128) > Traceback (most recent call last): > File "C:\python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "D:\python\scripts\encoding-test.py", line 22, in ? > split = raw.split('?') > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 0: ordinal > not in range(128) > > Therefore my question: > * How can I split at the "?" without getting a charater encoding error? > * How do I have to encode the "?"-symbol that it gets correctly displayed in the > Easygui msgbox at line 6? It displays correctly for me (on MacOS X). Are you sure your source is actually encoded in utf-8? What platform are you on? Kent From timmichelsen at gmx-topmail.de Tue Oct 16 14:58:50 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 16 Oct 2007 12:58:50 +0000 (UTC) Subject: [Tutor] symbol encoding and processing problem References: <4714AC50.5000209@tds.net> Message-ID: > How do you get this output? The print is after the statement causing the > traceback. Are you showing the same code as you ran? Yes. I created this file in PythonWin and run it with IPython. > It displays correctly for me (on MacOS X). Are you sure your source is > actually encoded in utf-8? Not really. The thing is that I am exchanging my files from Linux (Ubuntu with UTF-8 default) to Windows. > What platform are you on? Yesterday I run the code on windows. From spitfire2525 at gmail.com Tue Oct 16 18:21:11 2007 From: spitfire2525 at gmail.com (Peter Mexbacher) Date: Tue, 16 Oct 2007 18:21:11 +0200 Subject: [Tutor] Regex parsing and writing to file Message-ID: <4714E4F7.7040909@gmail.com> Hello, first post here :-) I have the following task: 1) read in a file line by line 2) parse each line with a regular expression, and substitute certain patterns 3) end result: the old file with the substituted stuff (and of course everything which did not need substitution) My question: Do I have to write each line out to a new file, and then rename, or can I substitute "in place" - that the changes are incorporated in the old file automatically? Regards, Peter From trilokgk at gmail.com Tue Oct 16 18:25:20 2007 From: trilokgk at gmail.com (Trilok Khairnar) Date: Tue, 16 Oct 2007 21:55:20 +0530 Subject: [Tutor] Timers in Python In-Reply-To: <47052186.5030400@airtelbroadband.in> References: <333eea650710032235q7d39d6pc43f17a4c9aa72ae@mail.gmail.com> <4704C35D.7090501@tds.net> <47052186.5030400@airtelbroadband.in> Message-ID: <013a01c81011$285fe200$df2d580a@persistent.co.in> Doug Hellmann's PyMotW (Python Module of the Week) series recently covered sched http://feeds.feedburner.com/~r/PyMOTW/~3/161303668/pymotw-sched.html He always provides an overview supported by examples. You think of a functionality in some context, and it tends to appear in the series. :-) Regards, Trilok. -----Original Message----- From: tutor-bounces+trilokgk=gmail.com at python.org [mailto:tutor-bounces+trilokgk=gmail.com at python.org] On Behalf Of Noufal Ibrahim Sent: Thursday, October 04, 2007 10:53 PM To: Kamal Cc: tutor at python.org Subject: Re: [Tutor] Timers in Python Kent Johnson wrote: > Kamal wrote: >> hello everyone, >> >> Is there a method in Python which does what >> setInterval('someFunction()',5000) does in Javascript. >> >> Basically, I want to call functionOne() every x minutes, and >> wondering whats the best way to do it. You can also look at the sched module that comes with the standard distribution. -- ~noufal http://nibrahim.net.in/ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From mail at timgolden.me.uk Tue Oct 16 19:44:19 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Oct 2007 18:44:19 +0100 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <4714E4F7.7040909@gmail.com> References: <4714E4F7.7040909@gmail.com> Message-ID: <4714F873.70501@timgolden.me.uk> Peter Mexbacher wrote: > Hello, > > first post here :-) > > I have the following task: > > 1) read in a file line by line > 2) parse each line with a regular expression, and substitute certain > patterns > 3) end result: the old file with the substituted stuff (and of course > everything which did not need substitution) > > My question: > > Do I have to write each line out to a new file, and then rename, or can > I substitute "in place" - that the changes are incorporated in the old > file automatically? The "write out to new file" approach is the generally accepted method. FWIW, if the file were small enough, you could read it in in its entirety and overwrite immediately without the rename step, but you obviously have no fallback then if things go wrong! TJG From kent37 at tds.net Tue Oct 16 19:57:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Oct 2007 13:57:26 -0400 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <4714E4F7.7040909@gmail.com> References: <4714E4F7.7040909@gmail.com> Message-ID: <4714FB86.7090802@tds.net> Peter Mexbacher wrote: > I have the following task: > > 1) read in a file line by line > 2) parse each line with a regular expression, and substitute certain > patterns > 3) end result: the old file with the substituted stuff (and of course > everything which did not need substitution) > > Do I have to write each line out to a new file, and then rename, or can > I substitute "in place" - that the changes are incorporated in the old > file automatically? If you use the fileinput module with inplace=1 it will take care of this for you and even make a backup file if you like. Kent From janos.juhasz at VELUX.com Wed Oct 17 10:35:02 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 17 Oct 2007 10:35:02 +0200 Subject: [Tutor] The name of the module Message-ID: Dear Tutors, there was a thread some weeks ago about how can we find out what is the name of the current module, where the function was loaded from, where the function running from or so, with some magic. I can't find it in the archive. May someone help me with some reference about it ? Yours sincerely, ______________________________ J?nos Juh?sz From timmichelsen at gmx-topmail.de Wed Oct 17 13:43:33 2007 From: timmichelsen at gmx-topmail.de (Timmie) Date: Wed, 17 Oct 2007 11:43:33 +0000 (UTC) Subject: [Tutor] symbol encoding and processing problem References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> Message-ID: I tried your advice yesterday evening. > And see if you get a ?. I see this character. from easygui import easygui raw = unicode("121? 55' 5.55''", 'utf-8') => gets a encoding error raw = unicode("121? 55' 5.55''", 'cp1250') => this works while coding on windows. How do I make it work really crossplatform: On both Linux and Windows? lines = raw.split(unicode('?', 'cp1250')) => again work on windows print lines easygui.msgbox(raw) => prints a strange symbol instead of "?" import Tkinker Tkinter._test() => this test test the expected result. From finalyugi at sapo.pt Wed Oct 17 13:54:17 2007 From: finalyugi at sapo.pt (Rolando Pereira) Date: Wed, 17 Oct 2007 12:54:17 +0100 Subject: [Tutor] The name of the module In-Reply-To: References: Message-ID: <4715F7E9.3000107@sapo.pt> J?nos Juh?sz wrote: > Dear Tutors, > > there was a thread some weeks ago about > how can we find out > what is the name of the current module, > where the function was loaded from, > where the function running from or so, > with some magic. > > I can't find it in the archive. > > May someone help me with some reference about it ? > > Yours sincerely, > ______________________________ > J?nos Juh?sz > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > I can only find something back in February of this year. http://mail.python.org/pipermail/tutor/2007-February/052914.html Don't know if that's what you're after though. -- _ ASCII ribbon campaign ( ) - against HTML email X & vCards / \ From kent37 at tds.net Wed Oct 17 14:07:37 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Oct 2007 08:07:37 -0400 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> Message-ID: <4715FB09.70503@tds.net> Timmie wrote: > I tried your advice yesterday evening. > >> And see if you get a ?. > I see this character. > > from easygui import easygui > raw = unicode("121? 55' 5.55''", 'utf-8') > => gets a encoding error Then your source file is not really in UTF-8. BTW you can simply say raw = u"121? 55' 5.55''" > raw = unicode("121? 55' 5.55''", 'cp1250') > => this works while coding on windows. > How do I make it work really crossplatform: On both Linux and Windows? Get an editor on Windows that can edit UTF-8 text files and file transfer software that doesn't change the text encoding. Work with UTF-8 exclusively. Kent From timmichelsen at gmx-topmail.de Wed Oct 17 14:34:17 2007 From: timmichelsen at gmx-topmail.de (Timmie) Date: Wed, 17 Oct 2007 12:34:17 +0000 (UTC) Subject: [Tutor] symbol encoding and processing problem References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> Message-ID: > > from easygui import easygui > > raw = unicode("121? 55' 5.55''", 'utf-8') > > => gets a encoding error > > Then your source file is not really in UTF-8. This really helped! > Get an editor on Windows that can edit UTF-8 text files and file > transfer software that doesn't change the text encoding. Work with UTF-8 > exclusively. Thanks. This sounds really trivial but the thing is that one cannot define file encoding in PythonWin. I will have to either use a advanced editor like Notepad++ and run the script via console or use Geany as IDE. Since it didn't work in IPython as well I assume that I need to change the encoding of the IPython shell to UTF-8, too. Still need to find out where. The following code works on windows when saved to a UTF-8 encoded file: # -*- coding: utf-8 -*- # the file needs to be set to UTF-8 encoding if working on windows from easygui import easygui raw = unicode("125? 15' 5.55''", 'utf-8') print raw.encode('utf-8') lines = raw.split(unicode('?', 'utf-8')) print lines entertext = easygui.enterbox(message="Enter something.", title="", argDefaultText=raw) print entertext degrees = lines[0] print "degrees: ", str(degrees) Thanks for your support, so far. Timmie From mail at timgolden.me.uk Wed Oct 17 14:50:19 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 17 Oct 2007 13:50:19 +0100 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> Message-ID: <4716050B.6020303@timgolden.me.uk> Timmie wrote: >>> from easygui import easygui >>> raw = unicode("121? 55' 5.55''", 'utf-8') >>> => gets a encoding error >> Then your source file is not really in UTF-8. > This really helped! > > >> Get an editor on Windows that can edit UTF-8 text files and file >> transfer software that doesn't change the text encoding. Work with UTF-8 >> exclusively. > Thanks. This sounds really trivial but the thing is that one cannot define file > encoding in PythonWin. > I will have to either use a advanced editor like Notepad++ and run the script > via console or use Geany as IDE. I'm sure there'll be lots of other suggestions, but the SciTE editor (whose name I'm never sure how to prononunce without blushing) understands the same encoding directive as Python. It's quite lightweight, and also allows you to run Python scripts directly, although there are limitations. Worth looking at, anyhow. http://www.scintilla.org/SciTE.html TJG From kent37 at tds.net Wed Oct 17 14:58:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Oct 2007 08:58:05 -0400 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> Message-ID: <471606DD.3090401@tds.net> Timmie wrote: >> Get an editor on Windows that can edit UTF-8 text files and file >> transfer software that doesn't change the text encoding. Work with UTF-8 >> exclusively. > Thanks. This sounds really trivial but the thing is that one cannot define file > encoding in PythonWin. Really! That is surprising. Anyone else know how to set the file encoding for the PythonWin editor? > Since it didn't work in IPython as well I assume that I need to change the > encoding of the IPython shell to UTF-8, too. Still need to find out where. Was the problem with the print statements? Maybe changing the console encoding would help. I have some notes here: http://personalpages.tds.net/~kent37/stories/00018.html > The following code works on windows when saved to a UTF-8 encoded file: > > # -*- coding: utf-8 -*- > # the file needs to be set to UTF-8 encoding if working on windows > from easygui import easygui > raw = unicode("125? 15' 5.55''", 'utf-8') Again, I think this can be simplified to raw = u"125? 15' 5.55''" Kent From timmichelsen at gmx-topmail.de Wed Oct 17 15:05:17 2007 From: timmichelsen at gmx-topmail.de (Timmie) Date: Wed, 17 Oct 2007 13:05:17 +0000 (UTC) Subject: [Tutor] symbol encoding and processing problem References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> Message-ID: OK, I found out. > Since it didn't work in IPython as well I assume that I need to change the > encoding of the IPython shell to UTF-8, too. Still need to find out where. Put a file called 'sitecustomize.py' into any directory on your PYTHONPATH. write the folowing two lines in that file: import sys sys.setdefaultencoding('utf-8') To test, start ipython and type import sys sys.getdefaultencoding() It should be utf-9 now. Again, may sound trivial. for some. But I started my Python adventures on Ubuntu Linux which it set to UTF-8 as default encoding. Due to some software environments I am currently forced to use Windows. After installing Python and some modules with setup.exe I never new that I even have to care for this... From kent37 at tds.net Wed Oct 17 15:15:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Oct 2007 09:15:19 -0400 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> Message-ID: <47160AE7.9080707@tds.net> Timmie wrote: > OK, I found out. >> Since it didn't work in IPython as well I assume that I need to change the >> encoding of the IPython shell to UTF-8, too. Still need to find out where. > Put a file called 'sitecustomize.py' into any directory on your PYTHONPATH. > > write the folowing two lines in that file: > > import sys > sys.setdefaultencoding('utf-8') Just be aware that this affects portability of your scripts; they will require this same change to run on other systems. For this reason you might want to change the code instead. If you give a specific example of what is failing I will try to help. Kent From timmichelsen at gmx-topmail.de Wed Oct 17 15:23:19 2007 From: timmichelsen at gmx-topmail.de (Timmie) Date: Wed, 17 Oct 2007 13:23:19 +0000 (UTC) Subject: [Tutor] OT [Re: symbol encoding and processing problem] References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <4716050B.6020303@timgolden.me.uk> Message-ID: > I'm sure there'll be lots of other suggestions, but the SciTE > editor (whose name I'm never sure how to prononunce without > blushing) understands the same encoding directive as Python. > It's quite lightweight, and also allows you to run Python scripts > directly, although there are limitations. Worth looking at, anyhow. > > http://www.scintilla.org/SciTE.html I am using Notepad++ which is based on scintilla, too. http://notepad-plus.sourceforge.net/de/site.htm For a lightweight IDE look at Geany: http://geany.uvena.de/ It can also run your programs and change file encodings. From mail at timgolden.me.uk Wed Oct 17 15:31:54 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 17 Oct 2007 14:31:54 +0100 Subject: [Tutor] OT [Re: symbol encoding and processing problem] In-Reply-To: References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <4716050B.6020303@timgolden.me.uk> Message-ID: <47160ECA.9020002@timgolden.me.uk> Timmie wrote: >> I'm sure there'll be lots of other suggestions, but the SciTE >> editor (whose name I'm never sure how to prononunce without >> blushing) understands the same encoding directive as Python. >> It's quite lightweight, and also allows you to run Python scripts >> directly, although there are limitations. Worth looking at, anyhow. >> >> http://www.scintilla.org/SciTE.html > I am using Notepad++ which is based on scintilla, too. > http://notepad-plus.sourceforge.net/de/site.htm Well you're obviously well set up, then. > For a lightweight IDE look at Geany: http://geany.uvena.de/ > It can also run your programs and change file encodings. Amazing! No matter how much I think I know the landscape, there's always something which has escaped my attention. I notice it's GTK-based and I'm running on Win32 where GTK seems to be a bit clunky, but thanks for the heads-up nonetheless. TJG From scorpio.negi at gmail.com Wed Oct 17 15:38:43 2007 From: scorpio.negi at gmail.com (Abhishek Negi) Date: Wed, 17 Oct 2007 19:08:43 +0530 Subject: [Tutor] aBSOLUTE BEGINNER Message-ID: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> Hello all, I am an absolute beginner for python.....currently i am working under mainframe technology....but getting kinda bored from it and want to learn a good scripting language...so chose python...please give me link to a pdf which is suitable for beginners. -- take care bye Abhishek Negi -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071017/8fca68a3/attachment.htm From kent37 at tds.net Wed Oct 17 16:06:55 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Oct 2007 10:06:55 -0400 Subject: [Tutor] aBSOLUTE BEGINNER In-Reply-To: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> Message-ID: <471616FF.8090402@tds.net> Abhishek Negi wrote: > Hello all, > I am an absolute beginner for python.....currently i am working under > mainframe technology....but getting kinda bored from it and want to > learn a good scripting language...so chose python...please give me link > to a pdf which is suitable for beginners. I don't know about pdf but many beginner resources here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From slewin at bmts.com Wed Oct 17 16:46:46 2007 From: slewin at bmts.com (Scott) Date: Wed, 17 Oct 2007 10:46:46 -0400 Subject: [Tutor] aBSOLUTE BEGINNER In-Reply-To: <471616FF.8090402@tds.net> References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> <471616FF.8090402@tds.net> Message-ID: <47162056.2020408@bmts.com> >> Hello all, >> I am an absolute beginner for python.....currently i am working under >> mainframe technology....but getting kinda bored from it and want to >> learn a good scripting language...so chose python...please give me link >> to a pdf which is suitable for beginners. This is my favourite all time beginner book http://ibiblio.org/obp/thinkCS/python/english2e/html/index.html. IT is in html, I don't know if you can get it in pdf. > > I don't know about pdf but many beginner resources here: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) From evert.rol at gmail.com Wed Oct 17 17:48:57 2007 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 17 Oct 2007 16:48:57 +0100 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: <471606DD.3090401@tds.net> References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <471606DD.3090401@tds.net> Message-ID: >> raw = unicode("125? 15' 5.55''", 'utf-8') > > Again, I think this can be simplified to > raw = u"125? 15' 5.55''" It does, but it's getting confusing when I compare the following: >>> raw = u"125? 15' 5.55''" 125? 15' 5.55'' >>> print u"125? 15' 5.55''" UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-4: ordinal not in range(128) >>> print u"125? 15' 5.55''".encode('utf-8') 125? 15' 5.55'' >>> print unicode("125? 15' 5.55''") UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 3: ordinal not in range(128) >>> print unicode("125? 15' 5.55''", 'utf-8') UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in position 3: ordinal not in range(128) So apart from the errors all being slightly different, is there perhaps some difference between the str() and repr() functions (looks like repr uses escape backslashes)? Or does it simply have to do with my locale, which is set to the default "C" (terminal = standard Mac OS X terminal, with UTF-8 encoding)? Although that wouldn't explain to me why the third statement works. And checking the default encoding inside the python cmdline, I see that my sys module doesn't actually have a setdefaultencoding() method; was that something that should have been properly configured at compile time? The documentation mentions something about the site module, but I can't find it there either. Any enlightenment on this is welcome. Evert From kent37 at tds.net Wed Oct 17 18:07:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Oct 2007 12:07:49 -0400 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <471606DD.3090401@tds.net> Message-ID: <47163355.7050609@tds.net> Evert Rol wrote: >>> raw = unicode("125? 15' 5.55''", 'utf-8') >> Again, I think this can be simplified to >> raw = u"125? 15' 5.55''" > > It does, but it's getting confusing when I compare the following: > > >>> raw = u"125? 15' 5.55''" > 125? 15' 5.55'' Where does that output come from? > > >>> print u"125? 15' 5.55''" > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 3-4: ordinal not in range(128) print must encode unicode strings. It tries to encode them using the default encoding which doesnt' work because the source is not ascii. > > >>> print u"125? 15' 5.55''".encode('utf-8') > 125? 15' 5.55'' That is the way to get it to work. > >>> print unicode("125? 15' 5.55''") > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position > 3: ordinal not in range(128) Here the problem is trying to create the unicode string using the default encoding, again it doesn't work because the source contains non-ascii characters. > >>> print unicode("125? 15' 5.55''", 'utf-8') > UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in > position 3: ordinal not in range(128) This is the same as the first encode error. > So apart from the errors all being slightly different, is there > perhaps some difference between the str() and repr() functions (looks > like repr uses escape backslashes)? Right. > And checking the default encoding inside the python cmdline, I see > that my sys module doesn't actually have a setdefaultencoding() > method; was that something that should have been properly configured > at compile time? The documentation mentions something about the site > module, but I can't find it there either. The setdefaultencoding() function (it's not a method, it is a module-level function) is removed from the sys module as part of startup (I think by the site module). That is why you have to call it from sitecustomize.py. You can also reload(sys) to restore it but it's better to write your app so it doesn't require the default encoding to be changed. Kent From evert.rol at gmail.com Wed Oct 17 18:28:23 2007 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 17 Oct 2007 17:28:23 +0100 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: <47163355.7050609@tds.net> References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <471606DD.3090401@tds.net> <47163355.7050609@tds.net> Message-ID: <9A842072-B234-4E0E-8FDF-B2F749E169DA@gmail.com> >>>> raw = unicode("125? 15' 5.55''", 'utf-8') >>> Again, I think this can be simplified to >>> raw = u"125? 15' 5.55''" >> It does, but it's getting confusing when I compare the following: >> >>> raw = u"125? 15' 5.55''" >> 125? 15' 5.55'' > > Where does that output come from? sorry, my bad: over-hastily copy of non-existant output. >> >>> print u"125? 15' 5.55''" >> UnicodeEncodeError: 'ascii' codec can't encode characters in >> position 3-4: ordinal not in range(128) > > print must encode unicode strings. It tries to encode them using > the default encoding which doesnt' work because the source is not > ascii. >> >>> print u"125? 15' 5.55''".encode('utf-8') >> 125? 15' 5.55'' > > That is the way to get it to work. > >> >>> print unicode("125? 15' 5.55''") >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in >> position 3: ordinal not in range(128) > > Here the problem is trying to create the unicode string using the > default encoding, again it doesn't work because the source contains > non-ascii characters. > >> >>> print unicode("125? 15' 5.55''", 'utf-8') >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' >> in position 3: ordinal not in range(128) > > This is the same as the first encode error. This is the thing I don't get; or only partly: I'm sending a utf-8 encoded string to print. print apparently ignores that, and still tries to print things using ascii encoding. If I'm correct in that assessment, then why would print ignore that? >> So apart from the errors all being slightly different, is there >> perhaps some difference between the str() and repr() functions >> (looks like repr uses escape backslashes)? > > Right. > >> And checking the default encoding inside the python cmdline, I >> see that my sys module doesn't actually have a setdefaultencoding >> () method; was that something that should have been properly >> configured at compile time? The documentation mentions something >> about the site module, but I can't find it there either. > > The setdefaultencoding() function (it's not a method, it is a > module-level function) yes, sorry, got my terminology wrong there. > is removed from the sys module as part of startup (I think by the > site module). That is why you have to call it from > sitecustomize.py. You can also > reload(sys) > to restore it but it's better to write your app so it doesn't > require the default encoding to be changed. Ie, use encode('utf-8') where necessary? But I did see some examples pass by using import sys sys.setdefaultencoding('utf-8') ?? Oh well, in general I tend to play long enough with things like this that 1) I get it (script) working, and 2) I have a decent feeling (90%) that I actually understand what is going on, and why other things failed. Which is roughly where I am now ;-). Evert From kent37 at tds.net Wed Oct 17 18:53:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Oct 2007 12:53:26 -0400 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: <9A842072-B234-4E0E-8FDF-B2F749E169DA@gmail.com> References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <471606DD.3090401@tds.net> <47163355.7050609@tds.net> <9A842072-B234-4E0E-8FDF-B2F749E169DA@gmail.com> Message-ID: <47163E06.3030007@tds.net> Evert Rol wrote: >>> >>> print unicode("125? 15' 5.55''", 'utf-8') >>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in >>> position 3: ordinal not in range(128) >> >> This is the same as the first encode error. > > This is the thing I don't get; or only partly: I'm sending a utf-8 > encoded string to print. No, you are sending a unicode string to print. unicode("125? 15' 5.55''", 'utf-8') means the same as "125? 15' 5.55''".decode('utf-8') which is, "create a unicode string from this utf-8-encoded byte string". Once you have decoded to Unicode it is no longer utf-8. > print apparently ignores that, and still tries > to print things using ascii encoding. If I'm correct in that assessment, > then why would print ignore that? print just knows that you want to print a unicode string. stdout is byte-oriented so the unicode chars have to be converted to a byte stream. This is done by encoding with sys.getdefaultencoding(), i.e. print unicode("125? 15' 5.55''", 'utf-8') is the same as print u"125? 15' 5.55''" which is the same as print u"125? 15' 5.55''".encode(sys.getdefaultencoding()) > Ie, use encode('utf-8') where necessary? Yes. > But I did see some examples pass by using > > import sys > sys.setdefaultencoding('utf-8') Yes, that will make the examples pass, it just isn't the recommended solution. > Oh well, in general I tend to play long enough with things like this > that 1) I get it (script) working, and 2) I have a decent feeling (90%) > that I actually understand what is going on, and why other things > failed. Which is roughly where I am now ;-). The key thing is to realize that there are implicit conversions between str and unicode and they will break if the data is not ascii. The best fix is to make the conversions explicit by providing the correct encoding. Kent From alan.gauld at btinternet.com Wed Oct 17 20:09:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Oct 2007 19:09:24 +0100 Subject: [Tutor] aBSOLUTE BEGINNER References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> Message-ID: "Abhishek Negi" wrote in message news:65ec44550710170638v581ddd31h7c2f6400ff056339 at mail.gmail.com... > Hello all, > I am an absolute beginner for python.....currently i am working > under > mainframe technology....but getting kinda bored from it and want to > learn a > good scripting language...so chose python...please give me link to a > pdf > which is suitable for beginners. There are many beginners tutorials available from the Python web site: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers However if it must be a pdf you use then you can get my tutorial in PDF by navigating to the bottom of the contents frame and clicking the PDF link there. My tutor is very basic, designer for non programmers to get them to the point where they can understand the discussions on internet fora (like this one!) If you are a programmer already then the official tutorial is a better starting point. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ddm2 at sfu.ca Wed Oct 17 20:32:41 2007 From: ddm2 at sfu.ca (ddm2 at sfu.ca) Date: Wed, 17 Oct 2007 11:32:41 -0700 Subject: [Tutor] String module; Count Message-ID: <200710171832.l9HIWfrw017250@rm-rstar.sfu.ca> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20071017/910fb162/attachment.txt From andrewwu at gmail.com Wed Oct 17 22:42:02 2007 From: andrewwu at gmail.com (Andrew Wu) Date: Wed, 17 Oct 2007 13:42:02 -0700 Subject: [Tutor] Help with packages and namespaces please In-Reply-To: <99acdf3c0710151652i34331445jdd533259e6f0e30@mail.gmail.com> References: <99acdf3c0710121248g2632355buaddedc36060d712b@mail.gmail.com> <4710C5DF.2080201@tds.net> <99acdf3c0710151652i34331445jdd533259e6f0e30@mail.gmail.com> Message-ID: <99acdf3c0710171342g60b071e0n4ec4fc65f80906c9@mail.gmail.com> Thanks again for your help. I guess I should ask a more basic question about hierarchical directory structures and packages. If I have a bunch of files in a flat (single) directory structure that I want to reorganize into a hierarchical directory structure, do I necessarily have to turn them into package files (i.e. add the __init__.py files, or can I simply place them into a subdirectory structure and do something else so python can find the modules? Or is it better practice whenever a hierarchical directory structure exists to treat it as a package? Thanks! Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071017/4d0b5fd6/attachment.htm From kent37 at tds.net Wed Oct 17 22:57:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Oct 2007 16:57:00 -0400 Subject: [Tutor] Help with packages and namespaces please In-Reply-To: <99acdf3c0710171342g60b071e0n4ec4fc65f80906c9@mail.gmail.com> References: <99acdf3c0710121248g2632355buaddedc36060d712b@mail.gmail.com> <4710C5DF.2080201@tds.net> <99acdf3c0710151652i34331445jdd533259e6f0e30@mail.gmail.com> <99acdf3c0710171342g60b071e0n4ec4fc65f80906c9@mail.gmail.com> Message-ID: <4716771C.2000401@tds.net> Andrew Wu wrote: > Thanks again for your help. > > I guess I should ask a more basic question about hierarchical directory > structures and packages. If I have a bunch of files in a flat (single) > directory structure that I want to reorganize into a hierarchical > directory structure, do I necessarily have to turn them into package > files ( i.e. add the __init__.py files, or can I simply place them into > a subdirectory structure and do something else so python can find the > modules? You can put the subdirectories on the Python search path. > Or is it better practice whenever a hierarchical directory structure > exists to treat it as a package? That is more common. Kent From bensherman at gmail.com Wed Oct 17 23:02:56 2007 From: bensherman at gmail.com (Ben Sherman) Date: Wed, 17 Oct 2007 17:02:56 -0400 Subject: [Tutor] String module; Count In-Reply-To: <200710171832.l9HIWfrw017250@rm-rstar.sfu.ca> References: <200710171832.l9HIWfrw017250@rm-rstar.sfu.ca> Message-ID: <5a56471e0710171402ud92de3dl7fbbbe31204b1856@mail.gmail.com> You can only count one at a time. count = conversion(n).count("0") + conversion(n).count("1") count is a string method, so it operates directly on the string - you don't have to call it like you did. import string string.count(mystr, "cheese") is the same as mystr.count("cheese") At least it is in newer versions of python. Let me know if that helped. Cheers, Ben On 10/17/07, ddm2 at sfu.ca wrote: > I am having trouble getting the string.count function to work. I want it to > count the amount of digits (0 or 1) in the string, but I keep getting an > error stating the string.count was expecting a character buffer object. > CODE: > count = string.count(conversion(n),["0","1"]) > > ERROR: > Traceback (most recent call last): > File "/Users//Desktop/Project 1.py", line 59, in -toplevel- > signed_mag() > File "/Users//Desktop/Project 1.py", line 29, in signed_mag > count = string.count(conversion(n),["0","1"]) > File > "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/string.py" > , line 348, in count > return s.count(*args) > TypeError: expected a character buffer object > > I'm trying to make a decimal to binary converter that has the option to > select the amount of bits for Signed Binary. I've thought of a way (not > tested yet) on how to implement the bits, but I first need to count the > amount of digits in the original conversion. Thanks in advance. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Oct 17 23:41:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Oct 2007 17:41:33 -0400 Subject: [Tutor] String module; Count In-Reply-To: <200710171832.l9HIWfrw017250@rm-rstar.sfu.ca> References: <200710171832.l9HIWfrw017250@rm-rstar.sfu.ca> Message-ID: <4716818D.3060608@tds.net> ddm2 at sfu.ca wrote: > I am having trouble getting the string.count function to work. I want it to > count the amount of digits (0 or 1) in the string, but I keep getting an > error stating the string.count was expecting a character buffer object. > CODE: > count = string.count(conversion(n),["0","1"]) If conversion(n) is already a string containing only 0 and 1 you could just use len(conversion(n)) Kent From jonvspython at gmail.com Wed Oct 17 23:42:13 2007 From: jonvspython at gmail.com (jon vspython) Date: Wed, 17 Oct 2007 23:42:13 +0200 Subject: [Tutor] aBSOLUTE BEGINNER In-Reply-To: <47162056.2020408@bmts.com> References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> <471616FF.8090402@tds.net> <47162056.2020408@bmts.com> Message-ID: <4d070c130710171442r495605a3w8bdb7c262b54661c@mail.gmail.com> > > This is my favourite all time beginner book > http://ibiblio.org/obp/thinkCS/python/english2e/html/index.html. IT is > in html, I don't know if you can get it in pdf. > You can find an revised PDF version here: http://www.greenteapress.com/thinkpython/ It should be more up to date. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071017/b9e5faaf/attachment.htm From bhaaluu at gmail.com Thu Oct 18 02:07:08 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 17 Oct 2007 20:07:08 -0400 Subject: [Tutor] aBSOLUTE BEGINNER In-Reply-To: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> Message-ID: On 10/17/07, Abhishek Negi wrote: > Hello all, > I am an absolute beginner for python.....currently i am working under > mainframe technology.... What does that mean... "mainframe technology"? Are you a programmer? If so, which programming languages are you 'working' with? If you're already programming, what type of programming are you doing? SysAdmin? Database? Application? Other? > but getting kinda bored from it and want to learn a > good scripting language... I don't understand how you can get 'bored' with your work? Work is work, but how is the 'mainframe technology' you are working under, boring? Why do you think a good scripting language will help the "boredom"? > so chose python...please give me link to a pdf > which is suitable for beginners. Why did you pick on Python? What did Python ever do to you? Lessee now... working under mainframe technology, but 'bored' with it, and looking for a good scripting language to help with the boredom.... Hmmmm. Python is anything but boring! I doubt we can help you! > -- > take care > bye > Abhishek Negi Bye! =) -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From bryan.fodness at gmail.com Thu Oct 18 04:48:21 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Wed, 17 Oct 2007 22:48:21 -0400 Subject: [Tutor] accessing data in a usable format Message-ID: I have a data file 'data1.dat', *a* *b* *c* *d* 1 0.1 0.11 0.111 2 0.2 0.22 0.222 3 0.3 0.33 0.333 9 0.9 0.99 0.999 and I want to be able to access the values of *b*, *c*, or *d* depending on a value of *a*. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071017/5e6978dc/attachment.htm From john at fouhy.net Thu Oct 18 05:05:38 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 18 Oct 2007 16:05:38 +1300 Subject: [Tutor] accessing data in a usable format In-Reply-To: References: Message-ID: <5e58f2e40710172005s72149fadhdf2efeffb833b9ef@mail.gmail.com> On 18/10/2007, Bryan Fodness wrote: > I have a data file 'data1.dat', > > a b c d > > 1 0.1 0.11 0.111 > 2 0.2 0.22 0.222 > 3 0.3 0.33 0.333 > > 9 0.9 0.99 0.999 > > and I want to be able to access the values of b, c, or d depending on a > value of a. Hi Bryan, Hve a look at the tutorial (on python.org) section on reading from files. You'll also need to read about string methods in the standard library (specifically, the split() method) and dictionaries (in the tutorial, again). If you get stuck, show us what you've tried and we'll try to help. -- John. From alan.gauld at btinternet.com Thu Oct 18 11:53:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Oct 2007 10:53:22 +0100 Subject: [Tutor] aBSOLUTE BEGINNER References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> Message-ID: "bhaaluu" wrote > What does that mean... "mainframe technology"? I'll take a guess at what it means. A true mainframe is usually one of (or a clone of) IBM or ICLmainframe hardware running an OS like OS/390. It is primarily used for large volume data crunching and the applications use text only screens such as 3270 terminals running LU6.2 protocol. LU6.2 is somewhat like CGI on the web(*). A user is presented with a form which they fill in and submit as a job to the mainframe. The job executes and presents the results in the shape of another form. The coordination between transactions is managed by a system such as IBM's CICS. (*)I've often thought a mainframe wouldmake the ultimate web server, but sadly I'll never find out as web apps are usually considered far too trivial to waste a mainframe on... For the programmer or 'operator'(sys admin) the system involves a lot of small executables (programs) each wrapped up as a "job" in a script written in JCL (Job Control Language) which will define how much memory should be allocated, when the job should start, when it should terminate (regardless of whether it has finished), its schedulling priority, and so on. Any scripting in the python sense tends to be done using REXX, but it still needs to be wrapped in JCL. Everything is a job on a mainframe. Mainframe people tend to regard Unix boxes in the same way Unix guys regard PCs - little more than grown up toys. Mainframes hardly ever fail, they run the world's top businesses. But they are expensive, they are used for data centric rathger than user-centric applications and so many people working on them find them a tad dull, or boring... I know I spent a very instructive year wotking on a mainframe project. I'm glad I did it, I learned a lot about writing super reliable programs , but I don't want to do another one - ever! Now I may be assuming too much but I'm guerssing that's what the OP is referring to. > Python is anything but boring! I doubt we can help you! Well, Python is much more fun than either REXX or JCL so learning Python may well bring some light relief. Alan G. From nogentstanford at yahoo.fr Thu Oct 18 04:34:13 2007 From: nogentstanford at yahoo.fr (pileux systeme) Date: Thu, 18 Oct 2007 04:34:13 +0200 (CEST) Subject: [Tutor] open a webpage which may be unavailable Message-ID: <534763.38796.qm@web27312.mail.ukl.yahoo.com> Hello, I am trying to retrieve data from several webpages. My problem is the following: after a random number of requests, the page I'm trying to open is unavailable (and I get an IOError). Note that the page may become available if I try again after some time. Since I have thousands pages to explore, I'd like to be able to continue the program in spite of this error. I've thought of trying to raise an exception such as: try: usock = urllib.urlopen('http:// ') except: < something > else: usock = urllib.urlopen('http:// ') However, this doesn't work because the page can become unavailable between the time when I run the 'try' and the 'else'. [for instance, assume that my internet connection stops for a couple seconds every random amount of time]. Would anyone know how to solve this problem? [Another way to look at it is as follows: I'd like to be able to check whether the page is available AND copy it if it is AT THE SAME TIME] Thanks a lot for your answer, N. --------------------------------- Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/614cdb6c/attachment.htm From jonvspython at gmail.com Thu Oct 18 13:04:42 2007 From: jonvspython at gmail.com (jon vspython) Date: Thu, 18 Oct 2007 13:04:42 +0200 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <4714FB86.7090802@tds.net> References: <4714E4F7.7040909@gmail.com> <4714FB86.7090802@tds.net> Message-ID: <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> Hi, I tried this on a file: for line in fileinput.input("myfile",inplace=1): re.sub(r'LOOP',r'PRUEBALOOP',line) and for lines like this: PT_WT_INIT: LOOP I got this: 'PT_WT_INIT: PRUEBALOOP\r\n' I also tried without raw strings: re.sub('LOOP','PRUEBALOOP',line) but I got the same result. Any hint? Thanks, Jon. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/3005275b/attachment.htm From jonvspython at gmail.com Thu Oct 18 13:09:48 2007 From: jonvspython at gmail.com (jon vspython) Date: Thu, 18 Oct 2007 13:09:48 +0200 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> References: <4714E4F7.7040909@gmail.com> <4714FB86.7090802@tds.net> <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> Message-ID: <4d070c130710180409j37e2ee55vfaa0c1a2255aedb7@mail.gmail.com> Sorry, I think I should have explained what I was expecting to get. I wanted plain text back in my file. Real line feed and carrier returns instead of \r and \n, and so on. Thanks again, Jon. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/7907cea2/attachment.htm From kent37 at tds.net Thu Oct 18 13:35:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Oct 2007 07:35:19 -0400 Subject: [Tutor] open a webpage which may be unavailable In-Reply-To: <534763.38796.qm@web27312.mail.ukl.yahoo.com> References: <534763.38796.qm@web27312.mail.ukl.yahoo.com> Message-ID: <471744F7.1000407@tds.net> pileux systeme wrote: > Hello, > > I am trying to retrieve data from several webpages. My problem is the > following: after a random number of requests, the page I'm trying to > open is unavailable (and I get an IOError). Note that the page may > become available if I try again after some time. Since I have thousands > pages to explore, I'd like to be able to continue the program in spite > of this error. > I've thought of trying to raise an exception such as: > try: > usock = urllib.urlopen('http:// ') > except: > < something > > else: > usock = urllib.urlopen('http:// ') I'm confused about the code above. First, it is catching an exception, not raising it. Second, the 'else' clause, which will run if there is no exception, seems to do the same thing as the 'try' clause; I don't understand you intent. > However, this doesn't work because the page can become unavailable > between the time when I run the 'try' and the 'else'. [for instance, > assume that my internet connection stops for a couple seconds every > random amount of time]. > > Would anyone know how to solve this problem? > > [Another way to look at it is as follows: I'd like to be able to check > whether the page is available AND copy it if it is AT THE SAME TIME] There are several steps to fetching a web page. A socket connection is established, a GET request is sent to the server and the response is read from the socket, then the socket is closed. So it is not possible to do all this at the same time. What you can do is wrap the entire operation in a single try/except handler. I think you just need something like this: try: f = = urllib.urlopen('http:// ') data = f.read() f.close() # do something with data except: import traceback traceback.print_exc() I put code in the exception handler to print a stack trace, this will help figure out where the errors are coming from. Kent From kent37 at tds.net Thu Oct 18 13:38:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Oct 2007 07:38:46 -0400 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> References: <4714E4F7.7040909@gmail.com> <4714FB86.7090802@tds.net> <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> Message-ID: <471745C6.8000509@tds.net> jon vspython wrote: > Hi, > I tried this on a file: > > for line in fileinput.input("myfile",inplace=1): > re.sub(r'LOOP',r'PRUEBALOOP',line) I'm not sure why you got any output at all. Were you running this in a shell that prints out loop values for you (e.g. IPython)? re.sub returns the modified line. Try import sys sys.stdout.write(re.sub(r'LOOP',r'PRUEBALOOP',line)) I used stdout.write() instead of print because you already have the needed line endings in place. Kent > > and for lines like this: > > PT_WT_INIT: LOOP > > I got this: > > 'PT_WT_INIT: PRUEBALOOP\r\n' > > I also tried without raw strings: > > re.sub('LOOP','PRUEBALOOP',line) > > but I got the same result. > > Any hint? > Thanks, Jon. > > From alan.gauld at btinternet.com Thu Oct 18 13:43:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Oct 2007 12:43:29 +0100 Subject: [Tutor] open a webpage which may be unavailable References: <534763.38796.qm@web27312.mail.ukl.yahoo.com> Message-ID: "pileux systeme" wrote > I am trying to retrieve data from several webpages. > My problem is the following: after a random number of requests, > the page I'm trying to open is unavailable (and I get an IOError). > Note that the page may become available if I try again This is similar to the problem faced by marketeers doing outbound phone calls. The customer may not be home so you have to try again later (maybe several times). The normal solution to this is to buoild a list of failed addresses and then after processing the original list go back and process the exceptions list. Repeat for N iterations or until exceptions list is empty. This approach saves multiple attempts in clise proximitry to a faulty address when you could be processing productive addresses so is time efficient. The only snag is if you have to process the addresses in a given sequence. In that case you may need to create a list of groups and if any address within a group fails put the entire group in the exceptions list. Coincidentally, given my recent message on Mainframe technologies, this is the same technique used in high volume data processing (on mainframes) where millions of orders or bills etc need to be processed quickly. Rather than delay the multitude to fix errors on a case by case basis a quick pass is made collecting faulty records and a second pass (maybe with a more rigorouds algorithm) is made of the exceptions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jonvspython at gmail.com Thu Oct 18 14:05:36 2007 From: jonvspython at gmail.com (jon vspython) Date: Thu, 18 Oct 2007 14:05:36 +0200 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <471745C6.8000509@tds.net> References: <4714E4F7.7040909@gmail.com> <4714FB86.7090802@tds.net> <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> <471745C6.8000509@tds.net> Message-ID: <4d070c130710180505g677c7c84kb9b10d0333289ec7@mail.gmail.com> I was not trying to get any output. I was trying to modify a source file in place, I just want to replace file content text automatically. So I tried first from python shell in linux. This is what I did: [jon at pc-600713 aut]$ python Python 2.4.3 (#1, Oct 23 2006, 14:19:47) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import fileinput >>> import re >>> for line in fileinput.input("ets.AUT1",inplace=1): ... re.sub('LOOP','PRUEBALOOP',line) ... >>> But for an entry like the following in file "ets.AUT1": PT_WT_INIT: LOOP TRANS (EvtMaint,ETSL_MAINTENANCE) TRANS (EvtTout,ETSL8) ELSE_SLEEP This is what I got "ets.AUT1" content like this one: '\r\n' 'PT_WT_INIT: PRUEBALOOP\r\n' ' TRANS (EvtMaint,ETSL_MAINTENANCE)\r\n' ' TRANS (EvtTout,ETSL8)\r\n' ' ELSE_SLEEP\r\n' '\r\n' The file I got as a result won't work. I just wan't the pattern replaced. Do you know how could I do it? Thanks again, Jon. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/ef3c5ff9/attachment.htm From kent37 at tds.net Thu Oct 18 14:18:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Oct 2007 08:18:27 -0400 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <4d070c130710180505g677c7c84kb9b10d0333289ec7@mail.gmail.com> References: <4714E4F7.7040909@gmail.com> <4714FB86.7090802@tds.net> <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> <471745C6.8000509@tds.net> <4d070c130710180505g677c7c84kb9b10d0333289ec7@mail.gmail.com> Message-ID: <47174F13.7050503@tds.net> jon vspython wrote: > The file I got as a result won't work. I just wan't the pattern replaced. > Do you know how could I do it? Try my suggestion in previous email. Kent From jonvspython at gmail.com Thu Oct 18 14:42:09 2007 From: jonvspython at gmail.com (jon vspython) Date: Thu, 18 Oct 2007 14:42:09 +0200 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <47174F13.7050503@tds.net> References: <4714E4F7.7040909@gmail.com> <4714FB86.7090802@tds.net> <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> <471745C6.8000509@tds.net> <4d070c130710180505g677c7c84kb9b10d0333289ec7@mail.gmail.com> <47174F13.7050503@tds.net> Message-ID: <4d070c130710180542i77bccfc2k11134669b847ef02@mail.gmail.com> Cool! It works :-) But I don't get it. Where is the redirection? Thanks Ken. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/7b4308b2/attachment.htm From kent37 at tds.net Thu Oct 18 15:00:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Oct 2007 09:00:45 -0400 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <4d070c130710180542i77bccfc2k11134669b847ef02@mail.gmail.com> References: <4714E4F7.7040909@gmail.com> <4714FB86.7090802@tds.net> <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> <471745C6.8000509@tds.net> <4d070c130710180505g677c7c84kb9b10d0333289ec7@mail.gmail.com> <47174F13.7050503@tds.net> <4d070c130710180542i77bccfc2k11134669b847ef02@mail.gmail.com> Message-ID: <471758FD.1080703@tds.net> jon vspython wrote: > Cool! It works :-) > > But I don't get it. Where is the redirection? The fileinput module redirects stdout when you use inplace=1. See the section "Optional in-place filtering" here: http://docs.python.org/lib/module-fileinput.html You can read the source to fileinput (Lib/fileinput.py) if you want to see the details of how this works. Kent From jonvspython at gmail.com Thu Oct 18 15:11:10 2007 From: jonvspython at gmail.com (jon vspython) Date: Thu, 18 Oct 2007 15:11:10 +0200 Subject: [Tutor] Regex parsing and writing to file In-Reply-To: <471758FD.1080703@tds.net> References: <4714E4F7.7040909@gmail.com> <4714FB86.7090802@tds.net> <4d070c130710180404j194abebcw866defaf5231c23e@mail.gmail.com> <471745C6.8000509@tds.net> <4d070c130710180505g677c7c84kb9b10d0333289ec7@mail.gmail.com> <47174F13.7050503@tds.net> <4d070c130710180542i77bccfc2k11134669b847ef02@mail.gmail.com> <471758FD.1080703@tds.net> Message-ID: <4d070c130710180611s3cbf85bep25ad65e617a672bd@mail.gmail.com> Thanks Kent. I didn't see it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/23d1a893/attachment.htm From timmichelsen at gmx-topmail.de Thu Oct 18 19:22:42 2007 From: timmichelsen at gmx-topmail.de (Timmie) Date: Thu, 18 Oct 2007 17:22:42 +0000 (UTC) Subject: [Tutor] symbol encoding and processing problem References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <47160AE7.9080707@tds.net> Message-ID: > Just be aware that this affects portability of your scripts; they will > require this same change to run on other systems. For this reason you > might want to change the code instead. > If you give a specific example of what is failing I will try to help. >From the previous posts I learned that I should save the file as utf-8 encoded and use unicode where possible. Atleast I hope that I understood this correctly. By that method my inital posted code worked well. I still have the problem that the same code works on some machines and others not when I am unsing IPython. IPython apparently uses its own encoding or the encoding of the underlying platform. How can I avoid this problem? From timmichelsen at gmx-topmail.de Thu Oct 18 19:26:02 2007 From: timmichelsen at gmx-topmail.de (Timmie) Date: Thu, 18 Oct 2007 17:26:02 +0000 (UTC) Subject: [Tutor] symbol encoding and processing problem References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <471606DD.3090401@tds.net> Message-ID: > Was the problem with the print statements? Maybe changing the console > encoding would help. I have some notes here: > http://personalpages.tds.net/~kent37/stories/00018.html Thanks, I read it yesterday evening. I still don't know why there is such a encoding mess on Python. For me this totally neglects the statement that python code is easily portable or executable on other platforms. For instance, I am also unsing some IDL code. There I open the IDLE and code right away without worring about the encoding. Kind regards, Timmie From Barry.Carroll at datalogic.com Thu Oct 18 19:30:08 2007 From: Barry.Carroll at datalogic.com (Carroll, Barry) Date: Thu, 18 Oct 2007 10:30:08 -0700 Subject: [Tutor] Mainframe Technology (was: aBSOLUTE BEGINNER) (OT) In-Reply-To: Message-ID: <2BBAEE949D384D40A2B851287ADB6A430879BDF4@eugsrv400.psc.pscnet.com> > -----Original Message----- > Date: Thu, 18 Oct 2007 10:53:22 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] aBSOLUTE BEGINNER > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > "bhaaluu" wrote > > > What does that mean... "mainframe technology"? > > I'll take a guess at what it means. > A true mainframe is usually one of (or a clone of) IBM > or ICLmainframe hardware running an OS like OS/390. It is > primarily used for large volume data crunching and the > applications use text only screens such as 3270 terminals > running LU6.2 protocol. LU6.2 is somewhat like CGI > on the web(*). A user is presented with a form which they > fill in and submit as a job to the mainframe. The job > executes and presents the results in the shape of > another form. The coordination between transactions > is managed by a system such as IBM's CICS. > > (*)I've often thought a mainframe wouldmake the ultimate > web server, but sadly I'll never find out as web apps are > usually considered far too trivial to waste a mainframe on... > > For the programmer or 'operator'(sys admin) the system > involves a lot of small executables (programs) each > wrapped up as a "job" in a script written in JCL > (Job Control Language) which will define how much > memory should be allocated, when the job should start, > when it should terminate (regardless of whether it has > finished), its schedulling priority, and so on. > > Any scripting in the python sense tends to be done > using REXX, but it still needs to be wrapped in JCL. > Everything is a job on a mainframe. > > Mainframe people tend to regard Unix boxes in the > same way Unix guys regard PCs - little more than > grown up toys. Mainframes hardly ever fail, they run > the world's top businesses. But they are expensive, > they are used for data centric rathger than user-centric > applications and so many people working on them > find them a tad dull, or boring... I know I spent a very > instructive year wotking on a mainframe project. > I'm glad I did it, I learned a lot about writing super > reliable programs , but I don't want to do another > one - ever! > > Now I may be assuming too much but I'm guerssing > that's what the OP is referring to. > > > Python is anything but boring! I doubt we can help you! > > Well, Python is much more fun than either REXX or JCL so > learning Python may well bring some light relief. > > Alan G. > > ------------------------------ Greetings: An interesting side note: IBM's mainframes are now constructed out of massively pararallel arrays of MPUs. In other words, all that number crunching is done by hundreds or thousands of souped up PCs, all connected together and stuffed into a single box. Regards, Barry barry.carroll at datalogic.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From kent37 at tds.net Thu Oct 18 19:52:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Oct 2007 13:52:27 -0400 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <471606DD.3090401@tds.net> Message-ID: <47179D5B.6060602@tds.net> Timmie wrote: >> Was the problem with the print statements? Maybe changing the console >> encoding would help. I have some notes here: >> http://personalpages.tds.net/~kent37/stories/00018.html > Thanks, I read it yesterday evening. > > I still don't know why there is such a encoding mess on Python. For me this > totally neglects the statement that python code is easily portable or executable > on other platforms. I don't think this is entirely fair. For example at the start you had a file containing cp1252 data but told Python it was utf-8. You can't really expect Python to just do the right thing in such circumstances. Encoding issues require a certain amount of understanding of the underlying issues. In my experience most programmers find it confusing at first but it eventually sorts out. > For instance, I am also unsing some IDL code. There I open the IDLE and code > right away without worring about the encoding. Does you IDL code include non-ascii characters? Perhaps you would do better if you stuck with ascii for your Python source code, too - there is no need to include non-ascii characters directly, you can use \x string escapes to insert them into your strings. Kent From jonvspython at gmail.com Thu Oct 18 22:49:19 2007 From: jonvspython at gmail.com (jon vspython) Date: Thu, 18 Oct 2007 22:49:19 +0200 Subject: [Tutor] newbie question In-Reply-To: References: <8f9268760710150801u415c6890j9d057c928632ad2@mail.gmail.com> <4d070c130710151316y43b5eadavb0bb5a793ad6d784@mail.gmail.com> Message-ID: <4d070c130710181349t305b1339j863516c8ff943923@mail.gmail.com> >From http://diveintopython.org/getting_to_know_python/index.html, we can get this solution which works no matter the size of the dictionaries: print ' '.join(["%s" % (v,) for k,v in menu_specials.items()]) It generates a formatted string for value in the dictionary and then joins them using white spaces. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/499c465f/attachment.htm From john at fouhy.net Thu Oct 18 23:11:07 2007 From: john at fouhy.net (John Fouhy) Date: Fri, 19 Oct 2007 10:11:07 +1300 Subject: [Tutor] accessing data in a usable format In-Reply-To: References: <5e58f2e40710172005s72149fadhdf2efeffb833b9ef@mail.gmail.com> Message-ID: <5e58f2e40710181411x2137978x99e45569afe06814@mail.gmail.com> On 19/10/2007, Bryan Fodness wrote: > for line in file('findvalue.dat'): > print[float(x) for x in line.split()] > > which returns: > > [1.0, 0.80000000000000004, 0.91000000000000003, 0.879] > [2.0, 0.86199999999999999, 0.93000000000000005, 0.92700000000000005] > [3.0, 0.90100000000000002, 0.94499999999999995, 0.95299999999999996] > [4.0, 0.92700000000000005 , 0.95399999999999996, 0.97199999999999998] > [5.0, 0.94199999999999995, 0.96399999999999997, 0.97699999999999998] > > how can I access the second and third part of the list beginning with 3.0 I would suggest building a dictionary. You want to have a dictionary that looks like this: findvalueDict = { 1.0: (0.80000000000000004, 0.91000000000000003, 0.879), 2.0: (0.86199999999999999, 0.93000000000000005, 0.92700000000000005), # etc } Then you can access data by doing things like findvalueDict[3.0][1] (will return 0.94499999999999995). Can you see how to do that? PS. Please use "reply to all" when you reply. -- John. From alan.gauld at btinternet.com Thu Oct 18 23:16:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Oct 2007 22:16:34 +0100 Subject: [Tutor] Mainframe Technology (was: aBSOLUTE BEGINNER) (OT) References: <2BBAEE949D384D40A2B851287ADB6A430879BDF4@eugsrv400.psc.pscnet.com> Message-ID: "Carroll, Barry" wrote > IBM's mainframes are now constructed out of massively pararallel > arrays > of MPUs. In other words, all that number crunching is done by > hundreds > or thousands of souped up PCs, all connected together and stuffed > into a > single box. The processors may be the same, the architecture is significantly different. Data, memory and programs all have their own busses etc for one thing and there are multiple IO channels for disk along with multiple DMA controllers and in some cases dedicated ALUs and FPUs alongside those built into the chips. All of which keep the data sliding along smoothly. These are all part of the reason that mainframes often look slow on paper - often with 1GHz CPUs etc - but the architecture around them more than compensates for the data processing they are designed for. I find it interesting that in our company we have been able to gradually replace (over a 15 year period) a suite of 30 mainframes with 3. And we only really use 3 for resilience/backup reasons! Alan G. From jonvspython at gmail.com Thu Oct 18 23:35:35 2007 From: jonvspython at gmail.com (jon vspython) Date: Thu, 18 Oct 2007 23:35:35 +0200 Subject: [Tutor] accessing data in a usable format In-Reply-To: <5e58f2e40710181411x2137978x99e45569afe06814@mail.gmail.com> References: <5e58f2e40710172005s72149fadhdf2efeffb833b9ef@mail.gmail.com> <5e58f2e40710181411x2137978x99e45569afe06814@mail.gmail.com> Message-ID: <4d070c130710181435j28b6df00w8dc94b6b6ed05aab@mail.gmail.com> What about this? dic = {} for line in file("findvalue.dat"): a,b,c,d = line.split() dic [a] = (float(b), float(c), float(d)) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/f4cbfdb2/attachment.htm From bryan.fodness at gmail.com Fri Oct 19 00:11:19 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Thu, 18 Oct 2007 18:11:19 -0400 Subject: [Tutor] accessing data in a usable format In-Reply-To: <4d070c130710181435j28b6df00w8dc94b6b6ed05aab@mail.gmail.com> References: <5e58f2e40710172005s72149fadhdf2efeffb833b9ef@mail.gmail.com> <5e58f2e40710181411x2137978x99e45569afe06814@mail.gmail.com> <4d070c130710181435j28b6df00w8dc94b6b6ed05aab@mail.gmail.com> Message-ID: > > Thank you both options work easily with my problem. Bryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071018/191a255d/attachment.htm From scorpio.negi at gmail.com Fri Oct 19 07:41:04 2007 From: scorpio.negi at gmail.com (Abhishek Negi) Date: Fri, 19 Oct 2007 11:11:04 +0530 Subject: [Tutor] aBSOLUTE BEGINNER In-Reply-To: References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> Message-ID: <65ec44550710182241w2d939047x40057294d51f5afa@mail.gmail.com> Hi all thanks for your help guys...I ll explain my condition, I am an application programmer doing maintenance and enhancement work basically on CICS and a little bit in DB2....i had been working patiently on JCL and learn COBOL but haven't learn REXX.....but the problem is that whenever i want to do something as per my wish the mainframe server discards the change as it is a client server which i am working on so very few option to test and try and also i am using my PC to read texts on the fix procedures used in the programming can't use mainframe environment on home desktop and i want to do something good... i learn C and C++ but m not a master of it.....I chose python through articles and recommendation from my friends who is unable to help me with tutorials as he working on it a long time ago....i think u all started at some time of your life as a beginner please consider me that for python but not for programming. On 10/18/07, Alan Gauld wrote: > > "bhaaluu" wrote > > > What does that mean... "mainframe technology"? > > I'll take a guess at what it means. > A true mainframe is usually one of (or a clone of) IBM > or ICLmainframe hardware running an OS like OS/390. It is > primarily used for large volume data crunching and the > applications use text only screens such as 3270 terminals > running LU6.2 protocol. LU6.2 is somewhat like CGI > on the web(*). A user is presented with a form which they > fill in and submit as a job to the mainframe. The job > executes and presents the results in the shape of > another form. The coordination between transactions > is managed by a system such as IBM's CICS. > > (*)I've often thought a mainframe wouldmake the ultimate > web server, but sadly I'll never find out as web apps are > usually considered far too trivial to waste a mainframe on... > > For the programmer or 'operator'(sys admin) the system > involves a lot of small executables (programs) each > wrapped up as a "job" in a script written in JCL > (Job Control Language) which will define how much > memory should be allocated, when the job should start, > when it should terminate (regardless of whether it has > finished), its schedulling priority, and so on. > > Any scripting in the python sense tends to be done > using REXX, but it still needs to be wrapped in JCL. > Everything is a job on a mainframe. > > Mainframe people tend to regard Unix boxes in the > same way Unix guys regard PCs - little more than > grown up toys. Mainframes hardly ever fail, they run > the world's top businesses. But they are expensive, > they are used for data centric rathger than user-centric > applications and so many people working on them > find them a tad dull, or boring... I know I spent a very > instructive year wotking on a mainframe project. > I'm glad I did it, I learned a lot about writing super > reliable programs , but I don't want to do another > one - ever! > > Now I may be assuming too much but I'm guerssing > that's what the OP is referring to. > > > Python is anything but boring! I doubt we can help you! > > Well, Python is much more fun than either REXX or JCL so > learning Python may well bring some light relief. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- take care bye Abhishek Negi -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071019/8680e557/attachment.htm From alan.gauld at btinternet.com Fri Oct 19 09:34:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Oct 2007 08:34:36 +0100 Subject: [Tutor] aBSOLUTE BEGINNER References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> <65ec44550710182241w2d939047x40057294d51f5afa@mail.gmail.com> Message-ID: "Abhishek Negi" wrote > some time of your life as a beginner please consider me that for > python but > not for programming. In that case start with the official Python tutorial (included in the Windows download) and top it up with Dive into Python (included in the ActiveState download). If you are on Windows I recommend the ActiveState version since it includes a lot of extras pertinent to Windows people... And ask questions here as they arise. Post short code samples and full error messages for best results. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jonvspython at gmail.com Fri Oct 19 10:03:39 2007 From: jonvspython at gmail.com (jon vspython) Date: Fri, 19 Oct 2007 10:03:39 +0200 Subject: [Tutor] aBSOLUTE BEGINNER In-Reply-To: References: <65ec44550710170638v581ddd31h7c2f6400ff056339@mail.gmail.com> <65ec44550710182241w2d939047x40057294d51f5afa@mail.gmail.com> Message-ID: <4d070c130710190103kddc3781r5a0c9c07788e9cc2@mail.gmail.com> You can find Dive into Python online here: http://diveintopython.org/toc/index.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071019/f8088f14/attachment.htm From billa_lazarus at yahoo.com Fri Oct 19 15:11:30 2007 From: billa_lazarus at yahoo.com (Lazarus billa) Date: Fri, 19 Oct 2007 06:11:30 -0700 (PDT) Subject: [Tutor] Tutor Digest, Vol 44, Issue 62 In-Reply-To: Message-ID: <575007.35110.qm@web56106.mail.re3.yahoo.com> Dear Sir., I need computer Training through Tutor-Request at Python Organisation to maintain my Computer. I also need Books., Litterature and needed help. Please attach me to some Org if u r not able to Justify my request. I am a social worker caring Orphans and Aged Widows. I need thorouh knowledge on computer to correspond with my Friends., Wellwishers and Sponsers Thanking u sir With Regards Lazarus billa_lazarus at yahoo.com Good Shepherd Premises Guntur 522004 India Ph:91 98481 57835 91 863 2260143 --- tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, > visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body > 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it > is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: accessing data in a usable format (jon > vspython) > 2. Re: accessing data in a usable format (Bryan > Fodness) > 3. Re: aBSOLUTE BEGINNER (Abhishek Negi) > 4. Re: aBSOLUTE BEGINNER (Alan Gauld) > 5. Re: aBSOLUTE BEGINNER (jon vspython) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 18 Oct 2007 23:35:35 +0200 > From: "jon vspython" > Subject: Re: [Tutor] accessing data in a usable > format > To: "John Fouhy" > Cc: Tutor > Message-ID: > > <4d070c130710181435j28b6df00w8dc94b6b6ed05aab at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > What about this? > > dic = {} > for line in file("findvalue.dat"): > a,b,c,d = line.split() > dic [a] = (float(b), float(c), float(d)) > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20071018/f4cbfdb2/attachment-0001.htm > > > ------------------------------ > > Message: 2 > Date: Thu, 18 Oct 2007 18:11:19 -0400 > From: "Bryan Fodness" > Subject: Re: [Tutor] accessing data in a usable > format > To: "jon vspython" > Cc: Tutor > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > > > > Thank you both options work easily with my > problem. > > > > Bryan > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20071018/191a255d/attachment-0001.htm > > > ------------------------------ > > Message: 3 > Date: Fri, 19 Oct 2007 11:11:04 +0530 > From: "Abhishek Negi" > Subject: Re: [Tutor] aBSOLUTE BEGINNER > To: "Alan Gauld" > Cc: tutor at python.org > Message-ID: > > <65ec44550710182241w2d939047x40057294d51f5afa at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi all thanks for your help guys...I ll explain my > condition, I am an > application programmer doing maintenance and > enhancement work basically on > CICS and a little bit in DB2....i had been working > patiently on JCL and > learn COBOL but haven't learn REXX.....but the > problem is that whenever i > want to do something as per my wish the mainframe > server discards the change > as it is a client server which i am working on so > very few option to test > and try and also i am using my PC to read texts on > the fix procedures used > in the programming can't use mainframe environment > on home desktop and i > want to do something good... > > i learn C and C++ but m not a master of it.....I > chose python through > articles and recommendation from my friends who is > unable to help me with > tutorials as he working on it a long time ago....i > think u all started at > some time of your life as a beginner please consider > me that for python but > not for programming. > > On 10/18/07, Alan Gauld > wrote: > > > > "bhaaluu" wrote > > > > > What does that mean... "mainframe technology"? > > > > I'll take a guess at what it means. > > A true mainframe is usually one of (or a clone of) > IBM > > or ICLmainframe hardware running an OS like > OS/390. It is > > primarily used for large volume data crunching and > the > > applications use text only screens such as 3270 > terminals > > running LU6.2 protocol. LU6.2 is somewhat like CGI > > on the web(*). A user is presented with a form > which they > > fill in and submit as a job to the mainframe. The > job > > executes and presents the results in the shape of > > another form. The coordination between > transactions > > is managed by a system such as IBM's CICS. > > > > (*)I've often thought a mainframe wouldmake the > ultimate > > web server, but sadly I'll never find out as web > apps are > > usually considered far too trivial to waste a > mainframe on... > > > > For the programmer or 'operator'(sys admin) the > system > > involves a lot of small executables (programs) > each > > wrapped up as a "job" in a script written in JCL > > (Job Control Language) which will define how much > > memory should be allocated, when the job should > start, > > when it should terminate (regardless of whether it > has > > finished), its schedulling priority, and so on. > > > > Any scripting in the python sense tends to be done > > using REXX, but it still needs to be wrapped in > JCL. > > Everything is a job on a mainframe. > > > > Mainframe people tend to regard Unix boxes in the > > same way Unix guys regard PCs - little more than > > grown up toys. Mainframes hardly ever fail, they > run > > the world's top businesses. But they are > expensive, > > they are used for data centric rathger than > user-centric > > applications and so many people working on them > > find them a tad dull, or boring... I know I spent > a very > > instructive year wotking on a mainframe project. > > I'm glad I did it, I learned a lot about writing > super > > reliable programs , but I don't want to do another > > one - ever! > > > > Now I may be assuming too much but I'm guerssing > > that's what the OP is referring to. > > > > > Python is anything but boring! I doubt we can > help you! > > > > Well, Python is much more fun than either REXX or > JCL so > > learning Python may well bring some light relief. > > > > Alan G. > === message truncated === __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From timmichelsen at gmx-topmail.de Fri Oct 19 16:49:39 2007 From: timmichelsen at gmx-topmail.de (Timmie) Date: Fri, 19 Oct 2007 14:49:39 +0000 (UTC) Subject: [Tutor] symbol encoding and processing problem References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <471606DD.3090401@tds.net> <47179D5B.6060602@tds.net> Message-ID: > > I still don't know why there is such a encoding mess on Python. For me > this > > totally neglects the statement that python code is easily portable or > executable > > on other platforms. > > I don't think this is entirely fair. For example at the start you had a > file containing cp1252 data but told Python it was utf-8. You can't > really expect Python to just do the right thing in such circumstances. Here you are right. I was (without knowing it) doeing the wrong thing. Well, my judgement was based on a confusion that I haven't been able to clear so far: At first my file was encoded differently than the python default encoding and I coded even a different encoding in the file head. After I'd adaped all this correctly my code worked well. I tried to use the same code interactively on the IPython shell. As I said from my previous post, the shell uses again a different encoding. Therefore, the same code that worked well from file did fail. When I found out that I could set the default encoding to UTF-8 you warned me of a lesser portability. I am totally lost: * python has ascii as default encoding * my linux uses UTF-8 (therefore all files created on linux are UTF-8) * windows uses cp1250 * IPtyhon something else: on the machine where I am currently on stdin is set to cp850 So what encoding to I use to display and process characters that exeeed the standard english alphabet? > Does you IDL code include non-ascii characters? Perhaps you would do > better if you stuck with ascii for your Python source code, too - there > is no need to include non-ascii characters directly, you can use \x > string escapes to insert them into your strings. My initial question was: 1) get a coordinate (DEG? MIN' SEC'') as input from user via easygui 2) split that string into its subscripts: degrees, minutes and secons 3) do some processing of the 3 varaibles 4) print the output with easygui. I am not really interested which is the best encoding. I want to know: * how I do this that I don't get a encoding error? * how do I code it that the code runs on linux and windows from file and in IPython Thanks again for your support. I don't want any misunderstandings. You were a good tutor to me and are helping patiently many user stepping into python. Kind regards, Timmie From bryan.fodness at gmail.com Fri Oct 19 17:20:25 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Fri, 19 Oct 2007 11:20:25 -0400 Subject: [Tutor] populating an array or using a dictionary Message-ID: I have a data file that I would like to extract data from: FS 1 2 3 4 5 1.5 1.000 1.000 1.000 1.000 1.000 2.0 0.985 0.994 0.997 0.996 0.996 2.5 0.967 0.976 0.981 0.981 0.982 3.0 0.949 0.958 0.965 0.966 0.967 3.5 0.925 0.937 0.945 0.948 0.951 4.0 0.901 0.916 0.925 0.930 0.934 4.5 0.882 0.896 0.906 0.912 0.917 5.0 0.863 0.876 0.887 0.893 0.899 The first row is a variable d, and the first column is FS. Any suggestions on the best way to do this. Bryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071019/f07959d4/attachment.htm From kent37 at tds.net Fri Oct 19 17:35:18 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 Oct 2007 11:35:18 -0400 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: References: Message-ID: <4718CEB6.9070508@tds.net> Bryan Fodness wrote: > I have a data file that I would like to extract data from: > > FS 1 2 3 4 5 > 1.5 1.000 1.000 1.000 1.000 1.000 > 2.0 0.985 0.994 0.997 0.996 0.996 > 2.5 0.967 0.976 0.981 0.981 0.982 > 3.0 0.949 0.958 0.965 0.966 0.967 > 3.5 0.925 0.937 0.945 0.948 0.951 > 4.0 0.901 0.916 0.925 0.930 0.934 > 4.5 0.882 0.896 0.906 0.912 0.917 > 5.0 0.863 0.876 0.887 0.893 0.899 > > > The first row is a variable d, and the first column is FS. Any > suggestions on the best way to do this. This looks the same as the question you asked on Wednesday...do you have some code already? It helps if you can show what you have already done and ask for help with changes. Kent From mail at timgolden.me.uk Fri Oct 19 17:46:08 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 19 Oct 2007 16:46:08 +0100 Subject: [Tutor] symbol encoding and processing problem In-Reply-To: References: <9411802F-1450-4E39-96F4-D67521682208@gmail.com> <4715FB09.70503@tds.net> <471606DD.3090401@tds.net> <47179D5B.6060602@tds.net> Message-ID: <4718D140.8070500@timgolden.me.uk> Timmie wrote: > I am totally lost: > * python has ascii as default encoding > * my linux uses UTF-8 (therefore all files created on linux are UTF-8) > * windows uses cp1250 > * IPtyhon something else: on the machine where I am currently on stdin is set to > cp850 > > So what encoding to I use to display and process characters that exeeed the > standard english alphabet? > My initial question was: > > 1) get a coordinate (DEG? MIN' SEC'') as input from user via easygui > 2) split that string into its subscripts: degrees, minutes and secons > 3) do some processing of the 3 varaibles > 4) print the output with easygui. > > I am not really interested which is the best encoding. I want to know: > * how I do this that I don't get a encoding error? > * how do I code it that the code runs on linux and windows > from file and in IPython I realise that I am running the risk of confusing you further, but I'm afraid that your attitude of "This isn't my problem; it's Python's" isn't really going to wash. If you're going to be using characters which fall outside the realm of 7-bit ASCII you're going to have to get some understanding of how the various input, output and language mechanisms deal with them. And all the more so if you're trying to do this cross-platform. Maybe there's some kind of sealed environment in some other language or operating system which takes care of all of this for you transparently. I wouldn't know. What I do know is that, if you're using the Python interpreter under Windows and Linux and whatever else then you're at the mercy of those operating systems at a certain level. There are at least two points you have to understand: 1) Python needs to know what encoding was used to save a text file which it is compiling to bytecode: usually a .py file. It has a default which you can override in a couple of ways. If whatever encoding you've specified turns out not to match the text in, say, a literal string with a degree symbol, then Python will not know what to do and will stop with an exception. Of course how you encoded the file in question is between you and your editor. 2) When you are reading or writing text to or from a console or GUI window or database or PDF or whatever, you also need to know what encoding to use. If you're writing out, then whatever you're writing to will be able to make sense of the encoding you're supplying -- and you may need to say which one it was. If you're reading in, you are at the mercy of libraries: some will always return unicode (BeautifulSoup springs to mind), others will return raw bytes leaving it up to you to decode, others will return an encoded string. This is pretty much an historical artefact (or, sadly in some cases, a case of ignorance) and you're going to have to cope with it. On my windows box, easygui handles unicode perfectly well, and the console running cp437 displays the degree sign. If if didn't, I'd have to compromise on the display (or use chcp to switch code pages first). To illustrate, the following program works: import easygui sample = u"DEG\u00b0 MIN' SEC\"" from_user = easygui.enterbox (u"Enter" + sample) # # Paste in values from your email since I can't # be bothered to work out how to get the degree # sign # print from_user and from_user is a perfectly good unicode string. Now, if you want to write that out to a file, or a database or what-have-you which can't store unicode natively, then you'll have to encode it, probably as UTF8 which can encode anything. For this email, I've used the unicode-escape, but if -- as you did -- you wanted to use the string literal, then you'd need to save the .py file in a certain encoding and to place a line at the top of the file indicating what that encoding was. If you're happy using unicode-escapes then that saves a bit of finnicking about. TJG From bryan.fodness at gmail.com Fri Oct 19 17:47:26 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Fri, 19 Oct 2007 11:47:26 -0400 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: <4718CEB6.9070508@tds.net> References: <4718CEB6.9070508@tds.net> Message-ID: The data file is larger than shown, and I was wondering if it would be better to populate an array or create a dictionary. Which would be easier? On 10/19/07, Kent Johnson wrote: > > Bryan Fodness wrote: > > I have a data file that I would like to extract data from: > > > > FS 1 2 3 4 5 > > 1.5 1.000 1.000 1.000 1.000 1.000 > > 2.0 0.985 0.994 0.997 0.996 0.996 > > 2.5 0.967 0.976 0.981 0.981 0.982 > > 3.0 0.949 0.958 0.965 0.966 0.967 > > 3.5 0.925 0.937 0.945 0.948 0.951 > > 4.0 0.901 0.916 0.925 0.930 0.934 > > 4.5 0.882 0.896 0.906 0.912 0.917 > > 5.0 0.863 0.876 0.887 0.893 0.899 > > > > > > The first row is a variable d, and the first column is FS. Any > > suggestions on the best way to do this. > > This looks the same as the question you asked on Wednesday...do you have > some code already? > > It helps if you can show what you have already done and ask for help > with changes. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071019/f002ad34/attachment-0001.htm From brunson at brunson.com Fri Oct 19 18:02:48 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 19 Oct 2007 10:02:48 -0600 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: References: <4718CEB6.9070508@tds.net> Message-ID: <4718D528.2070206@brunson.com> Bryan Fodness wrote: > The data file is larger than shown, and I was wondering if it would be > better to populate an array or create a dictionary. Which would be > easier? > A dictionary is an array with an index, if you need an index into your data, use a dictionary, if not use an array. > > On 10/19/07, *Kent Johnson* > > wrote: > > Bryan Fodness wrote: > > I have a data file that I would like to extract data from: > > > > FS 1 2 3 4 5 > > 1.5 1.000 1.000 1.000 1.000 1.000 > > 2.0 0.985 0.994 0.997 0.996 0.996 > > 2.5 0.967 0.976 0.981 0.981 0.982 > > 3.0 0.949 0.958 0.965 0.966 0.967 > > 3.5 0.925 0.937 0.945 0.948 0.951 > > 4.0 0.901 0.916 0.925 0.930 0.934 > > 4.5 0.882 0.896 0.906 0.912 0.917 > > 5.0 0.863 0.876 0.887 0.893 0.899 > > > > > > The first row is a variable d, and the first column is FS. Any > > suggestions on the best way to do this. > > This looks the same as the question you asked on Wednesday...do > you have > some code already? > > It helps if you can show what you have already done and ask for help > with changes. > > Kent > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Oct 19 21:24:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Oct 2007 20:24:40 +0100 Subject: [Tutor] Tutor Digest, Vol 44, Issue 62 References: <575007.35110.qm@web56106.mail.re3.yahoo.com> Message-ID: "Lazarus billa" wrote > I need computer Training through Tutor-Request > at Python Organisation to maintain my Computer. The Python tutor mailing list provides support for those learning the Python programming language. We do not offer general computing tuition. If your computer is running Linux then you can find a wealth of online resources to help you to work with your computer. If you are running any other operating system then you may find rather less for free. > I also need Books., Litterature and needed help. > Please attach me to some Org if u r not able to > Justify my request. For linux start with http://www.linux.org For Windows try the Microsoft web site For MacOS try the Apple web site. For Books try any online bookseller. For example the Amazon Marketplace scheme offers access to second hand books. For general computing help try this site or any of the others available http://www.refdesk.com/factbeg.html HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jtp at nc.rr.com Sat Oct 20 04:14:16 2007 From: jtp at nc.rr.com (James) Date: Fri, 19 Oct 2007 22:14:16 -0400 Subject: [Tutor] "standard output: Broken pipe" Message-ID: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> Hi, I have a snippet of code in a Python script I'm whipping up that's causing a not-so-pretty output. Here's the code: subprocess.call( "yes '' | make oldconfig" , shell=True ) When I run this code, Python loyally executes the command, and then I see the following error on my console: ----- yes: standard output: Broken pipe yes: write error ----- I did some Googling and I believe found the reason for this error ("yes" executes forever, and complains when Python kills the process off). However, I'd like to figure out a way to get rid of the error (or hide it) so that it's not visible to the person running the script (it's not the prettiest thing to see scroll by your screen :)). Thoughts / ideas? Thanks! .james From alan.gauld at btinternet.com Sat Oct 20 10:19:02 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Oct 2007 09:19:02 +0100 Subject: [Tutor] "standard output: Broken pipe" References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> Message-ID: "James" wrote in message > I have a snippet of code in a Python script I'm whipping up that's > causing a not-so-pretty output. Here's the code: > > subprocess.call( "yes '' | make oldconfig" , shell=True ) > ----- > yes: standard output: Broken pipe > yes: write error > ----- > off). However, I'd like to figure out a way to get rid of the error > (or hide it) so that it's not visible to the person running the Can you capture stdout (actually its probably stderr) and save it to a logfile? Or even just discard it? I know the Popen class can do that but I can't recall if call() has a stdout= option. If not just convert the code to use Popen... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mwalsh at groktech.org Sat Oct 20 11:42:32 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sat, 20 Oct 2007 04:42:32 -0500 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> Message-ID: <4719CD88.3060109@groktech.org> James wrote: > Hi, > > I have a snippet of code in a Python script I'm whipping up that's > causing a not-so-pretty output. Here's the code: > > subprocess.call( "yes '' | make oldconfig" , shell=True ) > > When I run this code, Python loyally executes the command, and then I > see the following error on my console: > > ----- > > yes: standard output: Broken pipe > yes: write error > > Thoughts / ideas? File this one under 'wicked scary hack', but my first thought would be to redirect stderr of 'yes' to /dev/null, while preserving stderr of 'make oldconfig'. Something like this: import subprocess as sp sp.call("yes '' 2> /dev/null | make oldconfig", shell=True) ... or ... import subprocess as sp p1 = sp.Popen("yes ''", shell=True, stdout=sp.PIPE, stderr=file('/dev/null', 'w')) p2 = sp.Popen('make oldconfig', shell=True, stdin=p1.stdout) However, since the 'equivalent' shell command doesn't seem to result in a broken pipe error there must be a better way. Upon further inspection: $ strace yes 'Spam' | head -n 10 <...> --- SIGPIPE (Broken pipe) @ 0 (0) --- +++ killed by SIGPIPE +++ <...> We may need to handle SIGPIPE. A quick search leads here: http://article.gmane.org/gmane.comp.python.devel/88798/ ... so, thanks to Mr. Woodcraft ... import subprocess as sp import signal # warning: uses the system default action # for SIGPIPE for all children, use subprocess # preexec_fn arg if this is not desirable signal.signal(signal.SIGPIPE, signal.SIG_DFL) sp.call("yes 'Spam' | head -n 10", shell=True) HTH, Marty From chiselchip at earthlink.net Sat Oct 20 23:53:07 2007 From: chiselchip at earthlink.net (LandSurveyor) Date: Sat, 20 Oct 2007 17:53:07 -0400 (GMT-04:00) Subject: [Tutor] upgrading Python Message-ID: <20987150.1192917187636.JavaMail.root@elwamui-karabash.atl.sa.earthlink.net> If I could be so bold...as to return for a moment to my long since buried question: What happened to the once pleasant relation between Python & digraphs. Given that digraphs are a form offered by Vim (not intrinsic to Python[?]), they worked when I was using Python 2.3. Now, with the upgrade to Python 2.5.1, digraphs do not work. Googling offers me any number of arcane and generalized theories. Not a lot of use to me. I would like to know what will work. From jtp at nc.rr.com Sun Oct 21 00:28:44 2007 From: jtp at nc.rr.com (James) Date: Sat, 20 Oct 2007 18:28:44 -0400 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <4719CD88.3060109@groktech.org> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <4719CD88.3060109@groktech.org> Message-ID: <779ECE21-CC37-4695-8B05-A0544C8E583C@nc.rr.com> It seems that adding this line: signal.signal(signal.SIGPIPE, signal.SIG_DFL) Before the snippet of code I included in my original e-mail (subprocess.call( "yes '' | make oldconfig" , shell=True )) got rid of the error. I can't seem to figure out precisely what the signal.signal() function does (as shown above). Any ideas? I'd like to fully understand what it does before I add it to my program. :) Thanks! .james On Oct 20, 2007, at 5:42 AM, Martin Walsh wrote: > James wrote: >> Hi, >> >> I have a snippet of code in a Python script I'm whipping up that's >> causing a not-so-pretty output. Here's the code: >> >> subprocess.call( "yes '' | make oldconfig" , shell=True ) >> >> When I run this code, Python loyally executes the command, and then I >> see the following error on my console: >> >> ----- >> >> yes: standard output: Broken pipe >> yes: write error >> >> Thoughts / ideas? > > File this one under 'wicked scary hack', but my first thought would be > to redirect stderr of 'yes' to /dev/null, while preserving stderr of > 'make oldconfig'. Something like this: > > import subprocess as sp > sp.call("yes '' 2> /dev/null | make oldconfig", shell=True) > > ... or ... > > import subprocess as sp > p1 = sp.Popen("yes ''", shell=True, stdout=sp.PIPE, > stderr=file('/dev/null', 'w')) > p2 = sp.Popen('make oldconfig', shell=True, > stdin=p1.stdout) > > However, since the 'equivalent' shell command doesn't seem to > result in > a broken pipe error there must be a better way. Upon further > inspection: > > $ strace yes 'Spam' | head -n 10 > <...> > --- SIGPIPE (Broken pipe) @ 0 (0) --- > +++ killed by SIGPIPE +++ > <...> > > We may need to handle SIGPIPE. A quick search leads here: > http://article.gmane.org/gmane.comp.python.devel/88798/ > > ... so, thanks to Mr. Woodcraft ... > > import subprocess as sp > import signal > # warning: uses the system default action > # for SIGPIPE for all children, use subprocess > # preexec_fn arg if this is not desirable > signal.signal(signal.SIGPIPE, signal.SIG_DFL) > sp.call("yes 'Spam' | head -n 10", shell=True) > > HTH, > Marty > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hasbeck at arcor.de Sat Oct 20 21:31:40 2007 From: hasbeck at arcor.de (Leon Hasbeck) Date: Sat, 20 Oct 2007 21:31:40 +0200 Subject: [Tutor] How to print a %-sign Message-ID: Hi, I would like to give out a formatted string that includes a percent sign, that is not used as formatting sign.Example: print "Your chance to win is %4.2f %" %p This doesn't work, because the last %-sign is interpreted as formatting sign and thus leads to an error message. I tried \x25 instead, but that doesn't work as well (same error message). Can someone help me? Leon From kent37 at tds.net Sun Oct 21 01:08:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Oct 2007 19:08:02 -0400 Subject: [Tutor] upgrading Python In-Reply-To: <20987150.1192917187636.JavaMail.root@elwamui-karabash.atl.sa.earthlink.net> References: <20987150.1192917187636.JavaMail.root@elwamui-karabash.atl.sa.earthlink.net> Message-ID: <471A8A52.3040305@tds.net> LandSurveyor wrote: > If I could be so bold...as to return for a moment to my long since buried question: What happened to the once pleasant relation between Python & digraphs. Given that digraphs are a form offered by Vim (not intrinsic to Python[?]), they worked when I was using Python 2.3. Now, with the upgrade to Python 2.5.1, digraphs do not work. Googling offers me any number of arcane and generalized theories. Not a lot of use to me. I would like to know what will work. What is a digraph? Alan asked for an example, did you post one? I offered help with PEP 263, did you see that? Kent PS Please use Reply All to reply on list. From kent37 at tds.net Sun Oct 21 01:18:37 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Oct 2007 19:18:37 -0400 Subject: [Tutor] How to print a %-sign In-Reply-To: References: Message-ID: <471A8CCD.6010208@tds.net> Leon Hasbeck wrote: > Hi, > > I would like to give out a formatted string that includes a percent sign, > that > is not used as formatting sign.Example: > > print "Your chance to win is %4.2f %" %p Just double the %: print "Your chance to win is %4.2f %%" %p Kent > > This doesn't work, because the last %-sign is interpreted as formatting > sign and > thus leads to an error message. I tried \x25 instead, but that doesn't > work as well > (same error message). > > Can someone help me? > > Leon > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sun Oct 21 01:34:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Oct 2007 00:34:31 +0100 Subject: [Tutor] "standard output: Broken pipe" References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com><4719CD88.3060109@groktech.org> <779ECE21-CC37-4695-8B05-A0544C8E583C@nc.rr.com> Message-ID: "James" wrote > signal.signal(signal.SIGPIPE, signal.SIG_DFL) > > Before the snippet of code I included in my original e-mail > (subprocess.call( "yes '' | make oldconfig" , shell=True )) got rid > of the error. I can't seem to figure out precisely what the > signal.signal() function does (as shown above). A signal is basically an interrupt. Its raised by the OS. signal.signal catches the named signal(s) and handles it. The default handler appears to just swallow the signal silently. Its a bit like, in Python, doing try: someFunc() except SomeError: pass The except clause catches the error but ignores it. signal.signal is doing much the same but at the OS level. My personal approach is to avoid using signal to trap and ignore signals since they can be needed by other processes running concurrently on the machine, but in this case it appears harmless. But in general, any approach which could interfere in unpredicable ways with other processes on the computer is a risky strategy IMHO. HTH, Alan G. From jtp at nc.rr.com Sun Oct 21 01:38:54 2007 From: jtp at nc.rr.com (James) Date: Sat, 20 Oct 2007 19:38:54 -0400 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com><4719CD88.3060109@groktech.org> <779ECE21-CC37-4695-8B05-A0544C8E583C@nc.rr.com> Message-ID: <258C3A91-1BC8-4A4B-B5A4-2720168C3BA6@nc.rr.com> Thanks for the response, Alan. Given this explanation, it's probably not a great idea to use signal.signal() then. ;) Any other thoughts? I've tried about redirecting my output using subprocess.Popen( ... , stdout=*something* ), but I haven't had much luck. The error still appears. Or should I be redirecting the "stderr" instead of "stdout"? Any ideas on how to use subprocess.Popen() to make this lovely little error disappear? Thanks! .james On Oct 20, 2007, at 7:34 PM, Alan Gauld wrote: > "James" wrote > >> signal.signal(signal.SIGPIPE, signal.SIG_DFL) >> >> Before the snippet of code I included in my original e-mail >> (subprocess.call( "yes '' | make oldconfig" , shell=True )) got rid >> of the error. I can't seem to figure out precisely what the >> signal.signal() function does (as shown above). > > A signal is basically an interrupt. Its raised by the OS. > signal.signal catches the named signal(s) and handles it. > The default handler appears to just swallow the signal > silently. > > Its a bit like, in Python, doing > > try: someFunc() > except SomeError: pass > > The except clause catches the error but ignores it. > > signal.signal is doing much the same but at the OS level. > > My personal approach is to avoid using signal to trap > and ignore signals since they can be needed by other > processes running concurrently on the machine, > but in this case it appears harmless. But in general, > any approach which could interfere in unpredicable > ways with other processes on the computer is a > risky strategy IMHO. > > HTH, > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Oct 21 08:43:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Oct 2007 07:43:32 +0100 Subject: [Tutor] "standard output: Broken pipe" References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com><4719CD88.3060109@groktech.org><779ECE21-CC37-4695-8B05-A0544C8E583C@nc.rr.com> <258C3A91-1BC8-4A4B-B5A4-2720168C3BA6@nc.rr.com> Message-ID: "James" wrote > Given this explanation, it's probably not a great idea to use > signal.signal() then. ;) I'm probabably painting too black a picture, its just that I've had problems using signal in the past. Where the signal is specific to a single process it should be OK. > Any other thoughts? I've tried about redirecting my output using > subprocess.Popen( ... , stdout=*something* ), but I haven't had much > luck. The error still appears. Or should I be redirecting the > "stderr" instead of "stdout"? It will almost certainly be stderr that you need to redirect: the stdout of yes is a stream of 'y's so the error message must be to stderr. > Any ideas on how to use subprocess.Popen() to make this lovely > little > error disappear? I think you can just change stdout= to stderr= in the Popen call. /dev/null might even work! (assuming you are on Unix - and since you are using yes that seems likely!) Alan G. From aditya.n.lal at gmail.com Sun Oct 21 10:45:42 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Sun, 21 Oct 2007 14:15:42 +0530 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: <4718D528.2070206@brunson.com> References: <4718CEB6.9070508@tds.net> <4718D528.2070206@brunson.com> Message-ID: <5df213700710210145r73400eccnffea1bc0ddc6a10e@mail.gmail.com> If the ease of use is the only answer then the size of the file should not matter ideally. btw, how large is the file ? is it in MBs or GBs ? For performance reasons, typically you should not have any problems using either dictionary, array or list for file size of few KBs. Like Kent said, if you can sent some code it will throw light on how you plan to use the data because the right data structure depends upon the access pattern. On 10/19/07, Eric Brunson wrote: > > Bryan Fodness wrote: > > The data file is larger than shown, and I was wondering if it would be > > better to populate an array or create a dictionary. Which would be > > easier? > > > > A dictionary is an array with an index, if you need an index into your > data, use a dictionary, if not use an array. > > > > > > On 10/19/07, *Kent Johnson* > > > wrote: > > > > Bryan Fodness wrote: > > > I have a data file that I would like to extract data from: > > > > > > FS 1 2 3 4 5 > > > 1.5 1.000 1.000 1.000 1.000 1.000 > > > 2.0 0.985 0.994 0.997 0.996 0.996 > > > 2.5 0.967 0.976 0.981 0.981 0.982 > > > 3.0 0.949 0.958 0.965 0.966 0.967 > > > 3.5 0.925 0.937 0.945 0.948 0.951 > > > 4.0 0.901 0.916 0.925 0.930 0.934 > > > 4.5 0.882 0.896 0.906 0.912 0.917 > > > 5.0 0.863 0.876 0.887 0.893 0.899 > > > > > > > > > The first row is a variable d, and the first column is FS. Any > > > suggestions on the best way to do this. > > > > This looks the same as the question you asked on Wednesday...do > > you have > > some code already? > > > > It helps if you can show what you have already done and ask for help > > with changes. > > > > Kent > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/ab4857a7/attachment-0001.htm From swartmumba at yahoo.com Sun Oct 21 14:47:18 2007 From: swartmumba at yahoo.com (SwartMumba snake) Date: Sun, 21 Oct 2007 05:47:18 -0700 (PDT) Subject: [Tutor] python help Message-ID: <419450.43953.qm@web44814.mail.sp1.yahoo.com> I have tried to find out the solution my self, and have failed to do so. So here is my problem: I want to submit text into an edit box on a web page. ie the equivalent of me typing text into the edit box and clicking the submit button. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/8b3f8fc7/attachment.htm From mlangford.cs03 at gtalumni.org Sun Oct 21 17:30:42 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 21 Oct 2007 11:30:42 -0400 Subject: [Tutor] python help In-Reply-To: <82b4f5810710210830s509a4c30l4e66cf13e5d58885@mail.gmail.com> References: <419450.43953.qm@web44814.mail.sp1.yahoo.com> <82b4f5810710210830s509a4c30l4e66cf13e5d58885@mail.gmail.com> Message-ID: <82b4f5810710210830m3647a772kcb6dfd805caef1ac@mail.gmail.com> http://developer.yahoo.com/python/python-rest.html#post On 10/21/07, SwartMumba snake wrote: > I have tried to find out the solution my self, and have failed to do so. > So here is my problem: > > I want to submit text into an edit box on a web page. ie the equivalent of > me typing text into the edit box and clicking the submit button. > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/0ab4c6b1/attachment.htm From mlangford.cs03 at gtalumni.org Sun Oct 21 18:07:21 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 21 Oct 2007 12:07:21 -0400 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> Message-ID: <82b4f5810710210907x3f6b046fi806c0d60dc87f449@mail.gmail.com> I think Alan is exaggerating the danger of signal handlers. They are *not* dangerous at all, but you should know what each signal means before you install a handler over its default, so you don't surprise yourself with behavior. For instance, you can capture ctrl-C which usually send a SIGINT. Python does this in the interactive shell, and prints out the words "KeyboardInterrupt". You can send SIGTSTP (which means pause the program for now, but let it be resumed later) with ctrl-Z. Python doesn't do this by default on at least my linux 2.4.4 release, as you'll see the application stop. But if you then type "fg", it will resume pythin by sending the SIGCONT signal. This signal is not something you care about. All SIGPIPE means is that the source of the signal found itself writing to a pipe with no sender. Your line "signal.signal(signal.SIGPIPE, signal.SIG_DFL)" means use the default signal handler for SIGPIPE. While this works (as the default signal handler is the ignore handler, you actually want to explicitly use the IGN handler, which will just ignore the signal. To do this use "signal.signal( signal.SIGPIPE, signal.SIG_IGN)" The reason you don't see the error on the shell is that the bash shell does not print notifications of SIGPIPE when running interactively. If you instead copied your snippit of scripting into a shell script then called that with "bash foo.sh", you'd see the exact same broken pipe. Here is what all the signals available do: http://www.delorie.com/gnu/docs/glibc/libc_471.html Just learn what a signal does before you mess with it, and remember to keep your signal handlers respectful of the original intent of the signal. If you're writing any serious program that *must* shutdown cleanly, signal handling is an essential item to put into your program. --Michael On 10/19/07, James wrote: > > Hi, > > I have a snippet of code in a Python script I'm whipping up that's > causing a not-so-pretty output. Here's the code: > > subprocess.call( "yes '' | make oldconfig" , shell=True ) > > When I run this code, Python loyally executes the command, and then I > see the following error on my console: > > ----- > > yes: standard output: Broken pipe > yes: write error > > ----- > > I did some Googling and I believe found the reason for this error > ("yes" executes forever, and complains when Python kills the process > off). However, I'd like to figure out a way to get rid of the error > (or hide it) so that it's not visible to the person running the > script (it's not the prettiest thing to see scroll by your screen :)). > > Thoughts / ideas? > > Thanks! > .james > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/efd0052e/attachment.htm From alan.gauld at btinternet.com Sun Oct 21 18:46:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Oct 2007 17:46:58 +0100 Subject: [Tutor] "standard output: Broken pipe" References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <82b4f5810710210907x3f6b046fi806c0d60dc87f449@mail.gmail.com> Message-ID: "Michael Langford" wrote >I think Alan is exaggerating the danger of signal handlers. Indeed, thats why I sent the follow up. They aren't *dangerous* but they can be inconsistent across OS. Plus some signals are wider in scope that the curent process (eg ISTR Stop-A on a Sun can be broadcast to all processes dependant on kernel settings) Also if a process is run under the cotrol of a parent process interfering with how that parent process deals with signals can result in inconsistent behaviour. So the signals and signal handling mechanism per se is not dangerous, simply that using them can create "strangeness" in a system which can be a devil to debug. Hopefully my other email clarified what I meant... Alan G From bryan.fodness at gmail.com Sun Oct 21 20:21:01 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Sun, 21 Oct 2007 14:21:01 -0400 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: <4718CEB6.9070508@tds.net> References: <4718CEB6.9070508@tds.net> Message-ID: Here is my code. dic2 = {} for line in file('21Ex6MV_tmr.dat'): d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18, fs19, fs20, fs21, fs22, fs23, fs24, fs25, fs26, fs27, fs28, fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, fs37, fs38, fs39, fs40 = line.split() dic2[d] = (float(d), float(fs1), float(fs2), float(fs3), float(fs4), float(fs5), float(fs6), float(fs7), float(fs8), float(fs9), float(fs10), float(fs11), float(fs12), float(fs13), float(fs14), float(fs15), float(fs16), float(fs17), float(fs18), float(fs19), float(fs20), float(fs21), float(fs22), float(fs23), float(fs24), float(fs25), float(fs26), float(fs27), float(fs28), float(fs29), float(fs30), float(fs31), float(fs32), float(fs33), float(fs34), float(fs35), float(fs36), float(fs37), float(fs38), float(fs39), float(fs40)) print dic2[d] and, here is my error Check\eDoseCheck.py", line 44, in d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, NameError: name 'd' is not defined -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/26b8363d/attachment.htm From alan.gauld at btinternet.com Sun Oct 21 20:59:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Oct 2007 19:59:51 +0100 Subject: [Tutor] populating an array or using a dictionary References: <4718CEB6.9070508@tds.net> Message-ID: "Bryan Fodness" wrote in > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, > fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18, fs19, > fs20, fs21, fs22, fs23, fs24, fs25, fs26, fs27, fs28, > fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, fs37, > fs38, fs39, fs40 = line.split() Because your tuple spans multiple lines I think you will need to put parens round it. >>> a,b,c,d Traceback (most recent call last): File "", line 1, in ? NameError: name 'a' is not defined >>> (a,b,c,d ... So starting with a paren tells Python to ignore the newline. Without it it gets confused about what you want to do. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bryan.fodness at gmail.com Sun Oct 21 21:11:34 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Sun, 21 Oct 2007 15:11:34 -0400 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: References: <4718CEB6.9070508@tds.net> Message-ID: it doesn't fix the problem, now it says there is a syntax error on the equal sign. On 10/21/07, Alan Gauld wrote: > > > "Bryan Fodness" wrote in > > > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, > > fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18, fs19, > > fs20, fs21, fs22, fs23, fs24, fs25, fs26, fs27, fs28, > > fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, fs37, > > fs38, fs39, fs40 = line.split() > > Because your tuple spans multiple lines I think you > will need to put parens round it. > > >>> a,b,c,d > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'a' is not defined > >>> (a,b,c,d > ... > > So starting with a paren tells Python to ignore the newline. > Without it it gets confused about what you want to do. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/0277d088/attachment-0001.htm From bryan.fodness at gmail.com Sun Oct 21 21:49:31 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Sun, 21 Oct 2007 15:49:31 -0400 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: References: <4718CEB6.9070508@tds.net> Message-ID: it works well if it is on the same line, but I would like to wrap it for readability On 10/21/07, Bryan Fodness wrote: > > it doesn't fix the problem, now it says there is a syntax error on the > equal sign. > > On 10/21/07, Alan Gauld wrote: > > > > > > "Bryan Fodness" wrote in > > > > > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, > > > fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18, fs19, > > > fs20, fs21, fs22, fs23, fs24, fs25, fs26, fs27, fs28, > > > fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, fs37, > > > fs38, fs39, fs40 = line.split() > > > > Because your tuple spans multiple lines I think you > > will need to put parens round it. > > > > >>> a,b,c,d > > Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'a' is not defined > > >>> (a,b,c,d > > ... > > > > So starting with a paren tells Python to ignore the newline. > > Without it it gets confused about what you want to do. > > > > HTH, > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/d0e341f0/attachment.htm From mlangford.cs03 at gtalumni.org Sun Oct 21 21:50:18 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 21 Oct 2007 15:50:18 -0400 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: References: <4718CEB6.9070508@tds.net> Message-ID: <82b4f5810710211250s29fa8f21m924b7d9d240bd595@mail.gmail.com> Using the attached foo.dat and no linebreaks, what you're doing works perfectly: dic2 = {} for line in file('foo.dat'): d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18, fs19, fs20, fs21, fs22, fs23, fs24, fs25, fs26, fs27, fs28, fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, fs37, fs38, fs39, fs40 = line.split() dic2[d] = (float(d), float(fs1), float(fs2), float(fs3), float(fs4), float(fs5), float(fs6), float(fs7), float(fs8), float(fs9), float(fs10), float(fs11), float(fs12), float(fs13), float(fs14), float(fs15), float(fs16), float(fs17), float(fs18), float(fs19), float(fs20), float(fs21), float(fs22), float(fs23), float(fs24), float(fs25), float(fs26), float(fs27), float(fs28), float(fs29), float(fs30), float(fs31), float(fs32), float(fs33), float(fs34), float(fs35), float(fs36), float(fs37), float(fs38), float(fs39), float(fs40)) print dic2 A neater way to do it looks like: dic2 = {} countOfVars=40 for line in file('foo.dat'): tokens = line.split() dval = tokens[0] ls = [] for i in range(1,countOfVars+1): ls.append(float(tokens[i])) dic2[dval]=tuple(ls) print dic2 --Michael On 10/21/07, Bryan Fodness < bryan.fodness at gmail.com> wrote: > > Here is my code. > > dic2 = {} > for line in file('21Ex6MV_tmr.dat'): > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, > fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18, fs19, > fs20, fs21, fs22, fs23, fs24, fs25, fs26, fs27, fs28, > fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, fs37, > fs38, fs39, fs40 = line.split() > dic2[d] = (float(d), float(fs1), float(fs2), float(fs3), > float(fs4), float(fs5), float(fs6), float(fs7), > float(fs8), float(fs9), float(fs10), float(fs11), > float(fs12), float(fs13), float(fs14), float(fs15), > float(fs16), float(fs17), float(fs18), float(fs19), > float(fs20), float(fs21), float(fs22), float(fs23), > float(fs24), float(fs25), float(fs26), float(fs27), > float(fs28), float(fs29), float(fs30), float(fs31), > float(fs32), float(fs33), float(fs34), float(fs35), > float(fs36), float(fs37), float(fs38), float(fs39), > float(fs40)) > print dic2[d] > > and, here is my error > > Check\eDoseCheck.py", line 44, in > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, > NameError: name 'd' is not defined > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/e312d27e/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: foo.dat Type: application/octet-stream Size: 4380 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20071021/e312d27e/attachment.obj From pierre.cutellic at gmail.com Sun Oct 21 21:58:12 2007 From: pierre.cutellic at gmail.com (pierre cutellic) Date: Sun, 21 Oct 2007 21:58:12 +0200 Subject: [Tutor] how to read from an excel file? Message-ID: <3c8b20230710211258ye779a2cp1444fa414885b3c3@mail.gmail.com> Hi, I'm actually trying to understand how to read data from an excel file but i'm pretty stuck here: I have already used makepy to generate the excel modules and its ID, which looks like : 00020813-0000-0000-C000-000000000046 But i don't really know what are the next steps. I presume that it should start by: import win32com.client xl = win32com.client.Dispatch("Excel.Application") Does anybody could tell me the way to open an excel file and then read some selected data? Because i'm a non-programmer, i still have some difficulties for learning such basics tricks :) Cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/c075f73b/attachment.htm From kent37 at tds.net Sun Oct 21 22:00:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 21 Oct 2007 16:00:25 -0400 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: References: <4718CEB6.9070508@tds.net> Message-ID: <471BAFD9.4090008@tds.net> Bryan Fodness wrote: > it doesn't fix the problem, now it says there is a syntax error on the > equal sign. Please, post your code and the exact error message and traceback! Don't make us guess what you are doing! My guess is you forgot the closing ) but I have no way to know for sure. Kent > > On 10/21/07, *Alan Gauld* > wrote: > > > "Bryan Fodness" > wrote in > > > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, > > fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18, fs19, > > fs20, fs21, fs22, fs23, fs24, fs25, fs26, fs27, fs28, > > fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, fs37, > > fs38, fs39, fs40 = line.split() > > Because your tuple spans multiple lines I think you > will need to put parens round it. > > >>> a,b,c,d > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'a' is not defined > >>> (a,b,c,d > ... > > So starting with a paren tells Python to ignore the newline. > Without it it gets confused about what you want to do. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sun Oct 21 22:13:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 21 Oct 2007 16:13:02 -0400 Subject: [Tutor] populating an array or using a dictionary In-Reply-To: <82b4f5810710211250s29fa8f21m924b7d9d240bd595@mail.gmail.com> References: <4718CEB6.9070508@tds.net> <82b4f5810710211250s29fa8f21m924b7d9d240bd595@mail.gmail.com> Message-ID: <471BB2CE.1040301@tds.net> Michael Langford wrote: > A neater way to do it looks like: > > dic2 = {} > countOfVars=40 > for line in file('foo.dat'): > tokens = line.split() > dval = tokens[0] > ls = [] > for i in range(1,countOfVars+1): > ls.append(float(tokens[i])) > dic2[dval]=tuple(ls) > print dic2 This is not very idiomatic. You can iterate tokens like this: ls = [] for token in tokens: ls.append(float(token)) This can easily be replaced with a list comprehension: ls = [ float(token) for token in tokens ] or it can be written using map() (one of the few situations where I prefer map() to a list comp): ls = map(float, tokens) Kent Kent From jtp at nc.rr.com Sun Oct 21 23:54:50 2007 From: jtp at nc.rr.com (James) Date: Sun, 21 Oct 2007 17:54:50 -0400 Subject: [Tutor] Looping + Variables Message-ID: Hi. :) I'm trying to write a loop to simplify my life (and code :)). The loop is going to iterate over a list of values that I have to change in a file. I think my problem is better described with some code. :) # variables interface = "eth0" address = "192.168.1.5" mask = "255.255.255.0" gateway = "192.168.1.1" def replaceText( old , new , file ): for line in fileinput.FileInput( file , inplace = 1 ): line = line.replace( old , new ) sys.stdout.write( line ) editValues = ( 'interface' , 'address' , 'mask' , 'gateway' ) for value in editValues: foo( '$' + value + '$' , value , '/etc/conf.d/net' ) I need to edit the values listed in "editValues" in a specific file. The file looks something like this before the code runs: config_$interface$=( "$address$ netmask $mask$" ) routes_$interface$=( "default via $gateway$" ) As you can see, the values that I want to edit are originally in the file as $variable$. The goal of my loop is to iterate over the editValues tuple and edit the $variable$ and put the ACTUAL variable value. :) After running my code, the file looks like this: config_interface=( "address netmask mask" ) routes_interface=( "default via gateway" ) If I put some debug statements in the function replaceText(), it shows that what is passed in is actually the value "address" and "interface", instead of "192.168.1.5" or "eth0". Obviously that's not what I want. :) I imagine I'm missing something obvious. Doh! Thoughts? Ideas? Thanks! .james From alan.gauld at btinternet.com Mon Oct 22 00:37:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Oct 2007 23:37:46 +0100 Subject: [Tutor] how to read from an excel file? References: <3c8b20230710211258ye779a2cp1444fa414885b3c3@mail.gmail.com> Message-ID: "pierre cutellic" wrote > But i don't really know what are the next steps. I presume that it > should > start by: > > import win32com.client > xl = win32com.client.Dispatch("Excel.Application") Before you try using COM to read the spreadsheet I'd consider using some of the various Excel modules, like PyExcelerator. (You need to download PyExcelerator its not a standard library module. And there are at least 2 other modules for the same job...) Or if possible, save the spreadsheet as a CSV file and use the CSV module to process the data. Both of these are likely to be easier than using COM. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mwalsh at groktech.org Mon Oct 22 03:17:12 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 21 Oct 2007 20:17:12 -0500 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <258C3A91-1BC8-4A4B-B5A4-2720168C3BA6@nc.rr.com> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com><4719CD88.3060109@groktech.org> <779ECE21-CC37-4695-8B05-A0544C8E583C@nc.rr.com> <258C3A91-1BC8-4A4B-B5A4-2720168C3BA6@nc.rr.com> Message-ID: <471BFA18.40307@groktech.org> James wrote: > Given this explanation, it's probably not a great idea to use > signal.signal() then. ;) In this case, it seems to me that setting the SIG_DFL action for SIGPIPE is precisely what one would want to do. This is pure speculation, but if you were to re-implement some of the subprocess module functionality for a similar task (using the os module methods for processes and pipes), you could wrap the appropriate calls in a try/except to trap a broken pipe. IIUC, this is exactly the reason python sets SIGPIPE signals to SIG_IGN (see the signal module docs: http://docs.python.org/lib/module-signal.html). A casual attempt appears to reveal that the subprocess module swallows these exceptions. I hope I'm wrong, because I tend to think that trapping with a try/except would be the preferred approach to this problem. Perhaps someone can confirm, or help to clarify? My previous signal example was a bit careless. I agree with Alan, it's seems best to exercise some caution when messing with signals. It may be safer to restrict the sigpipe signal changes to processes only when you need to. Fortunately, you can accomplish this by passing a function as the preexec_fn argument to subprocess 'call', 'Popen', and perhaps others. Consider the following (credit to Matthew Woodcraft, posted to the python-dev list in Jul 2007): import signal import subprocess as sp def permit_sigpipe(): signal.signal(signal.SIGPIPE, signal.SIG_DFL) # no broken pipe, preexec_fn is called inside the child process # thus setting sigpipe/sig_dfl for this process only sp.call("yes 'Spam' | head -n 10", shell=True, preexec_fn=permit_sigpipe) # oops, we should get a broken pipe message sp.call("yes 'Spam' | head -n 10", shell=True) > > Any other thoughts? I've tried about redirecting my output using > subprocess.Popen( ... , stdout=*something* ), but I haven't had much > luck. The error still appears. Or should I be redirecting the > "stderr" instead of "stdout"? yes :) but only stderr of the 'yes' command. If the 'make oldconfig' command writes to stderr I presume you want to see it. > > Any ideas on how to use subprocess.Popen() to make this lovely little > error disappear? > Use two Popen objects, redirect stderr from the left-side process ('yes') to /dev/null (or a log file, if you want to inspect), and connect stdin of right-side process ('make oldconfig') to stdout of the left-side by way of a subprocess.PIPE. Here's an example: import subprocess as sp # replace /dev/null below to a path of your choosing # to send stderr to a file for later review leftside = sp.Popen("yes ''", shell=True, stdout=sp.PIPE, stderr=file('/dev/null', 'w')) rightside = sp.Popen('make oldconfig', shell=True, stdin=leftside.stdout) IMHO, I think this approach is 'ok' for your purposes, since you are unlikely to care about most stderr messages from 'yes'. However, I wouldn't recommend it as a general practice. Also beware, if you do this ... import subprocess as sp sp.call("yes '' | make oldconfig", shell=True, stderr=file('/dev/null', 'w')) ... stderr from 'make oldconfig' will be sent to /dev/null as well. HTH, Marty > Thanks! > .james > > On Oct 20, 2007, at 7:34 PM, Alan Gauld wrote: > >> "James" wrote >> >>> signal.signal(signal.SIGPIPE, signal.SIG_DFL) >>> >>> Before the snippet of code I included in my original e-mail >>> (subprocess.call( "yes '' | make oldconfig" , shell=True )) got rid >>> of the error. I can't seem to figure out precisely what the >>> signal.signal() function does (as shown above). >> A signal is basically an interrupt. Its raised by the OS. >> signal.signal catches the named signal(s) and handles it. >> The default handler appears to just swallow the signal >> silently. >> >> Its a bit like, in Python, doing >> >> try: someFunc() >> except SomeError: pass >> >> The except clause catches the error but ignores it. >> >> signal.signal is doing much the same but at the OS level. >> >> My personal approach is to avoid using signal to trap >> and ignore signals since they can be needed by other >> processes running concurrently on the machine, >> but in this case it appears harmless. But in general, >> any approach which could interfere in unpredicable >> ways with other processes on the computer is a >> risky strategy IMHO. >> >> HTH, >> >> Alan G. From mwalsh at groktech.org Mon Oct 22 03:27:34 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 21 Oct 2007 20:27:34 -0500 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <82b4f5810710210907x3f6b046fi806c0d60dc87f449@mail.gmail.com> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <82b4f5810710210907x3f6b046fi806c0d60dc87f449@mail.gmail.com> Message-ID: <471BFC86.8040809@groktech.org> Michael Langford wrote: > > This signal is not something you care about. All SIGPIPE means is that > the source of the signal found itself writing to a pipe with no sender. > Your line "signal.signal(signal.SIGPIPE, signal.SIG_DFL)" means use the > default signal handler for SIGPIPE. While this works (as the default > signal handler is the ignore handler, you actually want to explicitly > use the IGN handler, which will just ignore the signal. To do this use > " signal.signal(signal.SIGPIPE, signal.SIG_IGN)" I don't think this is quite right, but please correct me if I'm misinformed, or just plain wrong. :) Using "signal.signal(signal.SIGPIPE, signal.SIG_IGN)" (kernel 2.6.20, bash 3.2, python2.5) still produces a broken pipe with the following code: import signal import subprocess as sp signal.signal(signal.SIGPIPE, signal.SIG_IGN) sp.call("yes 'Spam' | head -n 10", shell=True) My understanding is that python is *already* overriding with a SIG_IGN for SIGPIPE, and child processes inherit, which explains the difference in behavior when running the command from a shell terminal (on my system at least) vs. a python subprocess object. This is referenced in the signal module docs (http://docs.python.org/lib/module-signal.html), and appears to be confirmed in the python2.5 source (pythonrun.c). Also, while it is unclear in the signal module docs (to me at least), my take on the use of SIG_DFL is to revert (if necessary) to the *system* default action for a signal, not the python default (which is SIG_IGN). Again, this is my interpretation based on a very minimal understanding -- please correct me if I'm wrong. > > The reason you don't see the error on the shell is that the bash shell > does not print notifications of SIGPIPE when running interactively. If > you instead copied your snippit of scripting into a shell script then > called that with "bash foo.sh", you'd see the exact same broken pipe. Ok, this isn't true on my system either -- I don't get a broken pipe from a bash script. So, perhaps this is due to the differences in our kernel or bash versions. The version of bash on my system (3.2) has a DONT_REPORT_SIGPIPE define that is honored in both interactive and non-interactive shells. Presumably, this is how the ubuntu binary was compiled. > > Here is what all the signals available do: > http://www.delorie.com/gnu/docs/glibc/libc_471.html > Excellent link, thanks! IMO, the signal manpage ('man signal') is also a good resource. On my system, it contains a table of default actions. Here's what it has to say about SIGPIPE: """ Signal Value Action Comment ------------------------------------- SIGPIPE 13 Term Broken pipe: write to pipe with no readers """ and, the 'Term' action is defined as follows: """ Term Default action is to terminate the process. """ Thanks! Marty From ddm2 at sfu.ca Mon Oct 22 03:41:27 2007 From: ddm2 at sfu.ca (ddm2 at sfu.ca) Date: Sun, 21 Oct 2007 18:41:27 -0700 Subject: [Tutor] String module; Count Message-ID: <200710220141.l9M1fRMK009386@rm-rstar.sfu.ca> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20071021/fd736cc1/attachment.txt From mwalsh at groktech.org Mon Oct 22 04:47:12 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 21 Oct 2007 21:47:12 -0500 Subject: [Tutor] Looping + Variables In-Reply-To: References: Message-ID: <471C0F30.5010706@groktech.org> James wrote: > Hi. :) > > I'm trying to write a loop to simplify my life (and code :)). The > loop is going to iterate over a list of values that I have to change > in a file. I think my problem is better described with some code. :) Use a dictionary instead of a tuple ... # variables editValues = { "interface": "eth0", "address": "192.168.1.5", "mask": "255.255.255.0", "gateway": "192.168.1.1" } > def replaceText( old , new , file ): > for line in fileinput.FileInput( file , inplace = 1 ): > line = line.replace( old , new ) > sys.stdout.write( line ) > for key in editValues.keys(): replaceText('$' + key + '$' , editValues[key] , '/etc/conf.d/net' ) > > config_$interface$=( "$address$ netmask $mask$" ) > routes_$interface$=( "default via $gateway$" ) Are you locked into this substitution format? If not, then how about something like this: # /etc/conf.d/net config_%(interface)s=( "%(address)s netmask %(mask)s" ) routes_%(interface)s=( "default via %(gateway)s" ) You can then use python string formating (described here: http://docs.python.org/lib/typesseq-strings.html), and pass the dict directly. Note: if your file already contains '%' symbols that won't be substituted, you must escape (prefix) them with an additional '%'. valuedict = { "interface": "eth0", "address": "192.168.1.5", "mask": "255.255.255.0", "gateway": "192.168.1.1" } template = """\ # /etc/conf.d/net config_%(interface)s=( "%(address)s netmask %(mask)s" ) routes_%(interface)s=( "default via %(gateway)s" ) """ print template % valuedict ... prints ... # /etc/conf.d/net config_eth0=( "192.168.1.5 netmask 255.255.255.0" ) routes_eth0=( "default via 192.168.1.1" ) HTH, Marty From brunson at brunson.com Mon Oct 22 04:56:08 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 21 Oct 2007 20:56:08 -0600 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> Message-ID: <471C1148.4030806@brunson.com> I'm coming in late to the discussion and thought that someone would explain it succinctly, but there have been so many correct statements which I feel fail to nail down the problem that I thought I'd chime in. Here's the important concepts to understand. The pipe is a construct of the shell, you are spawning a shell to run your entire command line. When the "make" finishes and stops accepting the input from "yes", the kernel sends a SIGPIPE to the parent process, i.e. the shell. The shell's default behavior when receiving the SIGPIPE is to print an error message. Your problem, as I interpret it, is that you don't like seeing the error message. So you have two choices: 1) find some way to filter it, because all it is is a message, or 2) get rid of the shell and handle the management of the subprocesses yourself. It's been discussed how to suppress the output and it's been discussed how to intercept the signal, but I don't thing that anyone has pointed to the definitive python construct to handle it properly. You've had several responses that correctly tell you how to handle a signal, but without any testing I'm pretty sure that none of that will do you any good with the subprocess.call() construct you're using. The shell is your subprocess and it is already handling the signal, so you should never see it. The trick is to spawn both processes via python *without* an intervening shell to interfere. Here's the canonical example: http://docs.python.org/lib/node536.html. You can spawn each subprocess, 'yes' and 'make' without the shell being required to pipe the output of one to the other, you can do it all completely in python. Again, sorry to come in late, but while reading many absolutely factual an correct responses, they all seemed to be either handling the output or discussing signal handling without, in my mind, pointing out that it's the shell that's giving you the problems. I think it's Python's default behavior to ignore SIGPIPE, as Martin comments on in his latest reply. It's just that the shell has already accepted and handled the signal. Interestingly, when you eliminate the shell and use something similar to the example code from above, you can pretty easily see how to get rid of the 'yes' and just feed the make subprocess input yourself, further simplifying the code. I'll admit, I've stated all this without actually running any test, so please, if anyone can show differently, I'm happy to have my understanding corrected. I hope that helps, not only with your specific problem, but from a "big picture" standpoint, also. Nothing I hate more than writing code that I don't really understand. :-) e. James wrote: > Hi, > > I have a snippet of code in a Python script I'm whipping up that's > causing a not-so-pretty output. Here's the code: > > subprocess.call( "yes '' | make oldconfig" , shell=True ) > > When I run this code, Python loyally executes the command, and then I > see the following error on my console: > > ----- > > yes: standard output: Broken pipe > yes: write error > > ----- > > I did some Googling and I believe found the reason for this error > ("yes" executes forever, and complains when Python kills the process > off). However, I'd like to figure out a way to get rid of the error > (or hide it) so that it's not visible to the person running the > script (it's not the prettiest thing to see scroll by your screen :)). > > Thoughts / ideas? > > Thanks! > .james > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bryan.fodness at gmail.com Mon Oct 22 04:56:13 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Sun, 21 Oct 2007 22:56:13 -0400 Subject: [Tutor] calling a variable name Message-ID: I want to get a variable name dependent on another variable. I have tried, 'fs' + str(int(round(unblockedFS))) for fs13 and I get an invalid literal. If I code in the fs13, everything works. Is it possible to do this? unblockedFS=13.4 for line in file('21Ex6MV_tmr.dat'): d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18 = line.split() if float(d) == round(calc_depth): b = float(fs13) print float(fs13) Thanks, Bryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071021/73f69c6b/attachment.htm From alan.gauld at btinternet.com Mon Oct 22 09:22:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Oct 2007 08:22:36 +0100 Subject: [Tutor] String module; Count References: <200710220141.l9M1fRMK009386@rm-rstar.sfu.ca> Message-ID: wrote > think), but since I'm new to this thing, I thought I'd do the safe > thing and > try a second time. I personally didn't see the earlier one so can't say if it got here or not. But I'll throw in some comments below. But first I will say that you seem to be going out of your way to make easy things hard! > CODE: > def conversion(n): > b = '' > while n > 0: So this returns the empty string when n is negative. Is that really what you want? > r = n%2 > n = n/2 > r = str(r) > b = r+b > return b No real comments other than you might consider putting the code to pad with zeros in here. Then in the main code you only need to convert the leftmost bit to 1 if negative... In fact you could move that here too sonce arguably its part of conversion... > def signed_mag(): > n = int(raw_input("Please enter a signed integer: ")) > bits = int(raw_input("Please enter the number of bits: ")) > count = conversion(n).count("0") + conversion(n).count("1") \ count = len(conversion(n)) But recall from above that conversion(n) returns an empty string for negative numbers. Also to save calling conversion(n) multiple times you could introduce a new variable to store the result. > #count the amount of digits to know how many 0s to add > append_zeros = bits - count > if bits - 1 < count: > print "Out of range." > else: > if n < 0: > n = abs(n) Now you change n so that conversion(n) will now work on negative inputs... > if append_zeros > 0: > print -n," is encoded as","1"+(append_zeros-4)*"0" \ > +conversion(n),"in Signed Magnitude." This confused me, why are you subtracting 4? Surely you just want to change a single bit? > elif n > 0: > if append_zeros > 0: > print n,"is encoded as","0" + (append_zeros-1)*"0" \ > +conversion(n),"in Signed Magnitude." And why subtract 1 then add a "0"? Why not just append_zeros*"0" > else: > print "That is not an valid signed interger." Why is zero not a valid signed integer? > I know the problem is at the '(append_zeros-4)' bit, but I'm not > sure what > to change/add. Thanks in advance. I think a problem may also be in the fact that the first call to conversion(n) returns "" whereas subsequent calls return a bit pattern. In general it would be better to get your conversion function to handle all of the bit generation , padding and signing of the number. That only leaves the presentation logic outside in signed_mag() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Oct 22 09:38:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Oct 2007 08:38:59 +0100 Subject: [Tutor] calling a variable name References: Message-ID: "Bryan Fodness" wrote >I want to get a variable name dependent on another variable. Thats usually a bad idea, but... > I have tried, > > 'fs' + str(int(round(unblockedFS))) for fs13 I have no idea what you think this will do. It gives a syntax error for me, which is what I expected. > and I get an invalid literal. Can you post real code and real error messages please? > If I code in the fs13, everything works. Is > it possible to do this? I'm not sure because I'm not sure what you are really trying to do. Creating new variable names on the fly is usually not the best approach but without a context we can't offer an alternative. The code snippet above is no help since it is not valid Python. > unblockedFS=13.4 > > for line in file('21Ex6MV_tmr.dat'): > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, > fs13, > fs14, fs15, fs16, fs17, fs18 = line.split() BTW, Since all your variables are of the form fsNN it is probably as easy(and less typing) to do: fs = line.split() and just refer to them by index (extracting d if required): > if float(d) == round(calc_depth): if float(fs[0]) == round(calc_depth) > b = float(fs13) b = float(fs[13]) etc... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bryan.fodness at gmail.com Mon Oct 22 12:57:26 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Mon, 22 Oct 2007 06:57:26 -0400 Subject: [Tutor] calling a variable name In-Reply-To: References: Message-ID: Here is the actual snippet of code calc_depth = 8.1 # which is actually d unblockedFS = 13.4 # which is the indexed fs for line in file('21Ex6MV_tmr.dat'): d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, fs13, fs14, fs15, fs16, fs17, fs18, fs19, fs20, fs21, fs22, fs23, fs24, fs25, fs26, fs27, fs28, fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, fs37, fs38, fs39, fs40 = line.split() if float(d) == round(calc_depth): print float('fs' + str(int(round(unblockedFS)))) On 10/22/07, Alan Gauld wrote: > > "Bryan Fodness" wrote > > >I want to get a variable name dependent on another variable. > > Thats usually a bad idea, but... > > > I have tried, > > > > 'fs' + str(int(round(unblockedFS))) for fs13 > > I have no idea what you think this will do. > It gives a syntax error for me, which is what I expected. > > > and I get an invalid literal. > > Can you post real code and real error messages please? > > > If I code in the fs13, everything works. Is > > it possible to do this? > > I'm not sure because I'm not sure what you are really > trying to do. Creating new variable names on the fly > is usually not the best approach but without a context > we can't offer an alternative. The code snippet above > is no help since it is not valid Python. > > > unblockedFS=13.4 > > > > for line in file('21Ex6MV_tmr.dat'): > > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, > > fs13, > > fs14, fs15, fs16, fs17, fs18 = line.split() > > BTW, Since all your variables are of the form fsNN it is probably > as easy(and less typing) to do: > > fs = line.split() > > and just refer to them by index (extracting d if required): > > > if float(d) == round(calc_depth): > > if float(fs[0]) == round(calc_depth) > > b = float(fs13) > > b = float(fs[13]) > > etc... > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071022/008bc7f6/attachment.htm From tinoloc at gmail.com Mon Oct 22 12:54:48 2007 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 22 Oct 2007 06:54:48 -0400 Subject: [Tutor] calling a variable name In-Reply-To: References: Message-ID: On 10/21/07, Bryan Fodness wrote: > > > I want to get a variable name dependent on another variable. I have > tried, > > 'fs' + str(int(round(unblockedFS))) for fs13 > > and I get an invalid literal. If I code in the fs13, everything works. Is > it possible to do this? > > > > unblockedFS=13.4 > > for line in file('21Ex6MV_tmr.dat'): > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, > fs13, fs14, fs15, fs16, fs17, fs18 = line.split() > if float(d) == round(calc_depth): > b = float( fs13) > print float(fs13) > > Thanks, > Bryan > Hi Bryan, Have you thought about using a dictionary instead of slew of variables? IHMO, that will cut down on the number of variables that you have to juggle. So instead of fs1,fs2,fs3....... you would have fs={} fs[1]=........ ... fs[18=...... -HTH, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071022/4ee8cbc3/attachment.htm From mwalsh at groktech.org Mon Oct 22 13:25:38 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Mon, 22 Oct 2007 06:25:38 -0500 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <471C1148.4030806@brunson.com> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <471C1148.4030806@brunson.com> Message-ID: <471C88B2.7050500@groktech.org> Eric Brunson wrote: > I'm coming in late to the discussion and thought that someone would > explain it succinctly, but there have been so many correct statements > which I feel fail to nail down the problem that I thought I'd chime in. > Hi Eric, Thank you for your considerate response. Your analysis is spot on -- speaking for myself, of course -- I'm mostly just flailing here; not having a very strong grasp of how all the components work together (kernel, shell, python, and the subprocess module). But I'm really enjoying this thread and learning a lot in the 'process' ... ahem, sorry for the pun ... painful :) > Here's the important concepts to understand. The pipe is a construct of > the shell, you are spawning a shell to run your entire command line. > When the "make" finishes and stops accepting the input from "yes", the > kernel sends a SIGPIPE to the parent process, i.e. the shell. The > shell's default behavior when receiving the SIGPIPE is to print an error > message. You're right. Considering the shell is definitely important and I missed it. Yet given the following, slightly adapted from the subprocess module docs (your reference link below) ... from subprocess import Popen, PIPE p1 = Popen(["yes", "Hello"], stdout=PIPE) p2 = Popen(["head", "-n", "10"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] ... still produces ... yes: standard output: Broken pipe yes: write error If run as a script, the message above shows up in the terminal after the python script terminates (or apparently so; shell prompt first, then error). And when using the interactive interpreter... nothing until exiting the interpreter, when the message again appears in the terminal. Perhaps this is some peculiarity of my environment, or more likely I am still missing something. > Your problem, as I interpret it, is that you don't like seeing the error > message. So you have two choices: 1) find some way to filter it, > because all it is is a message, or 2) get rid of the shell and handle > the management of the subprocesses yourself. It's been discussed how to > suppress the output and it's been discussed how to intercept the signal, > but I don't thing that anyone has pointed to the definitive python > construct to handle it properly. > > You've had several responses that correctly tell you how to handle a > signal, but without any testing I'm pretty sure that none of that will > do you any good with the subprocess.call() construct you're using. The > shell is your subprocess and it is already handling the signal, so you > should never see it. The trick is to spawn both processes via python > *without* an intervening shell to interfere. Here's the canonical > example: http://docs.python.org/lib/node536.html. You can spawn each > subprocess, 'yes' and 'make' without the shell being required to pipe > the output of one to the other, you can do it all completely in python. Based on my own tests, I don't think it makes a difference. I suspect the python override for sigpipe is inherited by all child processes, shell or otherwise, and the SIG_IGN is allowing 'yes' to see the broken pipe, report it and terminate -- where the default action would normally be to terminate only. This is, of course, not that far from wild speculation. Though, I am curious if others observe the same behavior. Then again, the error is *not* displayed for any of tests where signal.signal(signal.SIGPIPE, signal.SIG_DFL) is added, in either the global scope or in the form of a preexec_fn argument passed to subprocess, with shell=True or without. IMHO, this is certainly a tripping point if true. Granted, probably a fringe case and relatively rare since it requires spawning a subprocess, which writes to a pipe that is broken before the subprocess ends, and is not implemented to handle the event gracefully. But I still find it weirdly intriguing. > > Again, sorry to come in late, but while reading many absolutely factual As far as I'm concerned, no apologies are necessary -- not that you are apologizing to me necessarily :) But nonetheless, thank you for helping. In fact, a big thank you to all the tutors. I've been a member of the list for quite a few years now, reaping the benefits of your collective experience (like many others I would imagine), mostly by lurking. You provide a tremendous service to the python community, especially those new to python or programming in general, with near super-human patience and skill. Quite a feat! FWIW, thanks. Marty > an correct responses, they all seemed to be either handling the output > or discussing signal handling without, in my mind, pointing out that > it's the shell that's giving you the problems. I think it's Python's > default behavior to ignore SIGPIPE, as Martin comments on in his latest > reply. It's just that the shell has already accepted and handled the > signal. > > Interestingly, when you eliminate the shell and use something similar to > the example code from above, you can pretty easily see how to get rid of > the 'yes' and just feed the make subprocess input yourself, further > simplifying the code. > > I'll admit, I've stated all this without actually running any test, so > please, if anyone can show differently, I'm happy to have my > understanding corrected. > > I hope that helps, not only with your specific problem, but from a "big > picture" standpoint, also. Nothing I hate more than writing code that I > don't really understand. :-) > > e. > > James wrote: >> Hi, >> >> I have a snippet of code in a Python script I'm whipping up that's >> causing a not-so-pretty output. Here's the code: >> >> subprocess.call( "yes '' | make oldconfig" , shell=True ) >> >> When I run this code, Python loyally executes the command, and then I >> see the following error on my console: >> >> ----- >> >> yes: standard output: Broken pipe >> yes: write error >> >> ----- >> >> I did some Googling and I believe found the reason for this error >> ("yes" executes forever, and complains when Python kills the process >> off). However, I'd like to figure out a way to get rid of the error >> (or hide it) so that it's not visible to the person running the >> script (it's not the prettiest thing to see scroll by your screen :)). >> >> Thoughts / ideas? >> >> Thanks! >> .james >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Mon Oct 22 13:46:17 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Oct 2007 07:46:17 -0400 Subject: [Tutor] calling a variable name In-Reply-To: References: Message-ID: <471C8D89.5080902@tds.net> Bryan Fodness wrote: > Here is the actual snippet of code > > > calc_depth = 8.1 # which is actually d > unblockedFS = 13.4 # which is the indexed fs > > for line in file('21Ex6MV_tmr.dat'): > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, > fs13, fs14, fs15, fs16, fs17, fs18, fs19, fs20, fs21, fs22, fs23, fs24, > fs25, fs26, fs27, fs28, fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, > fs37, fs38, fs39, fs40 = line.split() > if float(d) == round(calc_depth): > print float('fs' + str(int(round(unblockedFS)))) I think I would just keep the data in a list and index it: for line in file('21Ex6MV_tmr.dat'): data = line.split() d = data[0] if float(d) == round(calc_depth): print float(data[int(round(unblockedFS))]) Kent From evert.rol at gmail.com Mon Oct 22 14:06:18 2007 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 22 Oct 2007 13:06:18 +0100 Subject: [Tutor] calling a variable name In-Reply-To: <471C8D89.5080902@tds.net> References: <471C8D89.5080902@tds.net> Message-ID: <4A535029-2F73-4E0B-9ECA-771010CADE05@gmail.com> >> Here is the actual snippet of code >> >> >> calc_depth = 8.1 # which is actually d >> unblockedFS = 13.4 # which is the indexed fs >> >> for line in file('21Ex6MV_tmr.dat'): >> d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, >> fs13, fs14, fs15, fs16, fs17, fs18, fs19, fs20, fs21, fs22, fs23, >> fs24, >> fs25, fs26, fs27, fs28, fs29, fs30, fs31, fs32, fs33, fs34, fs35, >> fs36, >> fs37, fs38, fs39, fs40 = line.split() >> if float(d) == round(calc_depth): >> print float('fs' + str(int(round(unblockedFS)))) Totally beside the point, but isn't it a bad idea in general to compare two floats like that? It'll probably work, thanks to the round function I guess (although shouldn't then 'float(d)' also be rounded?), but I would have compared for a minimal difference between two floats. From brunson at brunson.com Mon Oct 22 16:33:39 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 22 Oct 2007 08:33:39 -0600 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <471C88B2.7050500@groktech.org> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <471C1148.4030806@brunson.com> <471C88B2.7050500@groktech.org> Message-ID: <471CB4C3.1050107@brunson.com> Martin Walsh wrote: > Eric Brunson wrote: > >> I'm coming in late to the discussion and thought that someone would >> explain it succinctly, but there have been so many correct statements >> which I feel fail to nail down the problem that I thought I'd chime in. >> >> > > Hi Eric, > > Thank you for your considerate response. Your analysis is spot on -- > speaking for myself, of course -- I'm mostly just flailing here; not > having a very strong grasp of how all the components work > together (kernel, shell, python, and the subprocess module). But I'm > really enjoying this thread and learning a lot in the 'process' ... > ahem, sorry for the pun ... painful :) > > >> Here's the important concepts to understand. The pipe is a construct of >> the shell, you are spawning a shell to run your entire command line. >> When the "make" finishes and stops accepting the input from "yes", the >> kernel sends a SIGPIPE to the parent process, i.e. the shell. The >> shell's default behavior when receiving the SIGPIPE is to print an error >> message. >> > > You're right. Considering the shell is definitely important and I missed > it. Yet given the following, slightly adapted from the subprocess module > docs (your reference link below) ... > > from subprocess import Popen, PIPE > p1 = Popen(["yes", "Hello"], stdout=PIPE) > p2 = Popen(["head", "-n", "10"], stdin=p1.stdout, stdout=PIPE) > output = p2.communicate()[0] > > ... still produces ... > > yes: standard output: Broken pipe > yes: write error > Looks like the "yes" command is getting the SIGPIPE and not the shell, as I originally thought. I must have glossed over the "yes:" at the beginning. > If run as a script, the message above shows up in the terminal after the > python script terminates (or apparently so; shell prompt first, then > error). And when using the interactive interpreter... nothing until > exiting the interpreter, when the message again appears in the terminal. > Perhaps this is some peculiarity of my environment, or more likely I am > still missing something. > > >> Your problem, as I interpret it, is that you don't like seeing the error >> message. So you have two choices: 1) find some way to filter it, >> because all it is is a message, or 2) get rid of the shell and handle >> the management of the subprocesses yourself. It's been discussed how to >> suppress the output and it's been discussed how to intercept the signal, >> but I don't thing that anyone has pointed to the definitive python >> construct to handle it properly. >> >> You've had several responses that correctly tell you how to handle a >> signal, but without any testing I'm pretty sure that none of that will >> do you any good with the subprocess.call() construct you're using. The >> shell is your subprocess and it is already handling the signal, so you >> should never see it. The trick is to spawn both processes via python >> *without* an intervening shell to interfere. Here's the canonical >> example: http://docs.python.org/lib/node536.html. You can spawn each >> subprocess, 'yes' and 'make' without the shell being required to pipe >> the output of one to the other, you can do it all completely in python. >> > > Based on my own tests, I don't think it makes a difference. I suspect > the python override for sigpipe is inherited by all child processes, > shell or otherwise, and the SIG_IGN is allowing 'yes' to see the broken > pipe, report it and terminate -- where the default action would normally > be to terminate only. This is, of course, not that far from wild > speculation. Though, I am curious if others observe the same behavior. > I'd have to break out some documentation to review signal mask inheritance, it's been so long it escapes me. > Then again, the error is *not* displayed for any of tests where > signal.signal(signal.SIGPIPE, signal.SIG_DFL) is added, in either the > global scope or in the form of a preexec_fn argument passed to > subprocess, with shell=True or without. > > IMHO, this is certainly a tripping point if true. Granted, probably a > fringe case and relatively rare since it requires spawning a subprocess, > which writes to a pipe that is broken before the subprocess ends, and is > not implemented to handle the event gracefully. But I still find it > weirdly intriguing. > Since "yes" is designed to spit out its output indefinitely, it seems like a bad behavior to print a message on SIGPIPE. It's always going to happen, it's the expected result. The versions of "yes" on my linux box here and a solaris box at work don't seem to elicit the same error message. Just another reason why I would look for a solution that would avoid the "yes" altogether. :-) >> Again, sorry to come in late, but while reading many absolutely factual >> > > > As far as I'm concerned, no apologies are necessary -- not that you are > apologizing to me necessarily :) But nonetheless, thank you for helping. > > In fact, a big thank you to all the tutors. I've been a member of the > list for quite a few years now, reaping the benefits of your collective > experience (like many others I would imagine), mostly by lurking. You > provide a tremendous service to the python community, especially those > new to python or programming in general, with near super-human patience > and skill. Quite a feat! FWIW, thanks. > > Even being one of the more vocal on the list, I'll add my vote to your commendations. I learn just as much on the list as I feel I teach, it's a great forum with some great participants. > Marty > > >> an correct responses, they all seemed to be either handling the output >> or discussing signal handling without, in my mind, pointing out that >> it's the shell that's giving you the problems. I think it's Python's >> default behavior to ignore SIGPIPE, as Martin comments on in his latest >> reply. It's just that the shell has already accepted and handled the >> signal. >> >> Interestingly, when you eliminate the shell and use something similar to >> the example code from above, you can pretty easily see how to get rid of >> the 'yes' and just feed the make subprocess input yourself, further >> simplifying the code. >> >> I'll admit, I've stated all this without actually running any test, so >> please, if anyone can show differently, I'm happy to have my >> understanding corrected. >> >> I hope that helps, not only with your specific problem, but from a "big >> picture" standpoint, also. Nothing I hate more than writing code that I >> don't really understand. :-) >> >> e. >> >> James wrote: >> >>> Hi, >>> >>> I have a snippet of code in a Python script I'm whipping up that's >>> causing a not-so-pretty output. Here's the code: >>> >>> subprocess.call( "yes '' | make oldconfig" , shell=True ) >>> >>> When I run this code, Python loyally executes the command, and then I >>> see the following error on my console: >>> >>> ----- >>> >>> yes: standard output: Broken pipe >>> yes: write error >>> >>> ----- >>> >>> I did some Googling and I believe found the reason for this error >>> ("yes" executes forever, and complains when Python kills the process >>> off). However, I'd like to figure out a way to get rid of the error >>> (or hide it) so that it's not visible to the person running the >>> script (it's not the prettiest thing to see scroll by your screen :)). >>> >>> Thoughts / ideas? >>> >>> Thanks! >>> .james >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bryan.fodness at gmail.com Mon Oct 22 16:51:59 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Mon, 22 Oct 2007 10:51:59 -0400 Subject: [Tutor] calling a variable name In-Reply-To: <471C8D89.5080902@tds.net> References: <471C8D89.5080902@tds.net> Message-ID: Thank you. This works well. I am still trying to figure out the pros and cons of using an array, dictionary or list. On 10/22/07, Kent Johnson wrote: > > Bryan Fodness wrote: > > Here is the actual snippet of code > > > > > > calc_depth = 8.1 # which is actually d > > unblockedFS = 13.4 # which is the indexed fs > > > > for line in file('21Ex6MV_tmr.dat'): > > d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, > > fs13, fs14, fs15, fs16, fs17, fs18, fs19, fs20, fs21, fs22, fs23, fs24, > > fs25, fs26, fs27, fs28, fs29, fs30, fs31, fs32, fs33, fs34, fs35, fs36, > > fs37, fs38, fs39, fs40 = line.split() > > if float(d) == round(calc_depth): > > print float('fs' + str(int(round(unblockedFS)))) > > I think I would just keep the data in a list and index it: > > for line in file('21Ex6MV_tmr.dat'): > data = line.split() > d = data[0] > if float(d) == round(calc_depth): > print float(data[int(round(unblockedFS))]) > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071022/18bfe717/attachment.htm From kent37 at tds.net Mon Oct 22 17:00:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Oct 2007 11:00:47 -0400 Subject: [Tutor] calling a variable name In-Reply-To: References: <471C8D89.5080902@tds.net> Message-ID: <471CBB1F.30905@tds.net> Bryan Fodness wrote: > Thank you. This works well. I am still trying to figure out the pros > and cons of using an array, dictionary or list. Array is specialized, you probably want list or dict. Use list when you want a sequence of items indexed by sequential integers. Lists - preserve order - are fast for indexed lookup - are relatively slow (O(n)) for adding, deleting and searching (though for small lists this should not be a consideration) Use dict when you want to index by something other than sequential integers Dicts - do not preserve order - are fast for adding, deleting and lookup - can be used to replace a list search with a lookup I'm sure there is more that I have missed. For your case I would start with a list, I don't see anything requiring a dict. Kent From pierre.cutellic at gmail.com Mon Oct 22 18:01:39 2007 From: pierre.cutellic at gmail.com (pierre cutellic) Date: Mon, 22 Oct 2007 18:01:39 +0200 Subject: [Tutor] how to read from a csv file? Message-ID: <3c8b20230710220901qa6bda78s169e6f33268e95a7@mail.gmail.com> Hi, this is a module i wrote to catch some data from a csv file: ########## #module csv data reader # open a csv file and return its data import csv import sys def __init__(self): rawdata = [] f = open('datalisting_000.csv','r') try: reader = csv.reader(f) for row in reader: rawdata.append(row) finally: f.close() def rawdata(): return rawdata if __name__ == "__main__": print "This is a module. You can't run it directly. Try to import it." raw_input("\n\nPress any key to exit.") ######### But when i try to use like: ########## import csvdatareader print csvdatareader.rawdata() ########## It didn't print anything. Where is the mistake? Cheers. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071022/da91b456/attachment.htm From mail at timgolden.me.uk Mon Oct 22 18:15:10 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 22 Oct 2007 17:15:10 +0100 Subject: [Tutor] how to read from a csv file? In-Reply-To: <3c8b20230710220901qa6bda78s169e6f33268e95a7@mail.gmail.com> References: <3c8b20230710220901qa6bda78s169e6f33268e95a7@mail.gmail.com> Message-ID: <471CCC8E.5090005@timgolden.me.uk> pierre cutellic wrote: > Hi, this is a module i wrote to catch some data from a csv file: > > ########## > #module csv data reader > # open a csv file and return its data > > import csv > import sys > > def __init__(self): > Stop right there. You're confusing modules and classes. A class has a (meaningful) __init__ method, which is called when the class is instantiated. You *can* have an __init__ in a module, but it doesn't do anything special. You really just want to rename __init__ to rawdata and drop the redundant "return rawdata" function. TJG From sulfurfff at hotmail.com Mon Oct 22 18:29:29 2007 From: sulfurfff at hotmail.com (=?iso-8859-1?Q?Ismael_Farf=E1n_Estrada?=) Date: Mon, 22 Oct 2007 16:29:29 +0000 Subject: [Tutor] pgdb and unicode Message-ID: Hi there. I have a small system in production with wxPython and PostgreSQL running on a machine with Centos 5. At first everytihing was running ok but now a weird bug was discovered: they can't insert characters like ? ? ? ? ? ? ? ? .... (non english characters) Does anyone knows how can I make pgdb accept that kind of characters? I wrote a little script... But first CREATE DATABASE test; CREATE TABLE tabla( cad character varying ) ; #!/usr/bin/python # -*- coding: utf8 -*- import pgdb con = pgdb.connect(user="farfan", password='000000', host='localhost', database='test') cur = con.cursor() cur.execute("INSERT INTO tabla VALUES ('?')") con.commit() cur.execute(u"INSERT INTO tabla VALUES ('?')") con.commit() and this is the result python Aplicacion.py Traceback (most recent call last): File "Aplicacion.py", line 10, in ? cur.execute(u"INSERT INTO tabla VALUES ('?')") File "/usr/lib/python2.4/site-packages/pgdb.py", line 175, in execute self.executemany(operation, (params,)) File "/usr/lib/python2.4/site-packages/pgdb.py", line 198, in executemany raise OperationalError, "internal error in '%s': %s" % (sql,err) pg.OperationalError[farfan at Kriemhild ~]$ python Aplicacion.py Traceback (most recent call last): File "Aplicacion.py", line 8, in ? cur.execute(u"INSERT INTO tabla VALUES ('?')") File "/usr/lib/python2.4/site-packages/pgdb.py", line 175, in execute self.executemany(operation, (params,)) File "/usr/lib/python2.4/site-packages/pgdb.py", line 198, in executemany raise OperationalError, "internal error in '%s': %s" % (sql,err) pg.OperationalError As you can see, the first insert statement is executed in ascii format and is succeful, the second, which is in Unicode, fails the problem is thas wxPython will allways send the script in unicode format... any ideas on how to fix it? rb3m dijo: Un buen programador no es uno que se sepa un lenguaje al derecho y al rev?s, sino el que sabe resolver un problema y despu?s implementar la soluci?n en el lenguaje m?s adecuado. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kent37 at tds.net Mon Oct 22 18:58:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Oct 2007 12:58:21 -0400 Subject: [Tutor] pgdb and unicode In-Reply-To: References: Message-ID: <471CD6AD.7040302@tds.net> Ismael Farf?n Estrada wrote: > Hi there. > I have a small system in production with wxPython and PostgreSQL running on > a machine with Centos 5. > At first everytihing was running ok but now a weird bug was discovered: > they can't insert characters like ? ? ? ? ? ? ? ? .... (non english characters) > Does anyone knows how can I make pgdb accept that kind of characters? > I wrote a little script... > > But first > CREATE DATABASE test; > CREATE TABLE tabla( > cad character varying > ) ; > > #!/usr/bin/python > # -*- coding: utf8 -*- > import pgdb > con = pgdb.connect(user="farfan", password='000000', host='localhost', database='test') > cur = con.cursor() > cur.execute("INSERT INTO tabla VALUES ('?')") > con.commit() > cur.execute(u"INSERT INTO tabla VALUES ('?')") > con.commit() > > As you can see, the first insert statement is executed in ascii format and is succeful, > the second, which is in Unicode, fails Why do you need the whole statement to be Unicode? It looks like the database wants utf-8. Probably you should encode the data as utf-8 first. > the problem is thas wxPython will allways send the script in unicode format... What is coming from wxPython? I guess it is just the data value, not the SQL statement or the entire script. Try something like data= u'?' # Unicode data from wxPython data = data.encode('utf-8') cur.execute('INSERT INTO tabla VALUES (%s)', [data]) Note I am passing the data as a separate list, not using string interpolation. Let the database worry about quoting, etc. Kent From eric at ericwalstad.com Mon Oct 22 19:07:15 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Mon, 22 Oct 2007 10:07:15 -0700 Subject: [Tutor] how to read from a csv file? In-Reply-To: <471CCC8E.5090005@timgolden.me.uk> References: <3c8b20230710220901qa6bda78s169e6f33268e95a7@mail.gmail.com> <471CCC8E.5090005@timgolden.me.uk> Message-ID: <471CD8C3.9020400@ericwalstad.com> Tim Golden wrote: > You really just want to rename __init__ to rawdata > and drop the redundant "return rawdata" function. But remember to include the line: return rawdata at the end of your function or else nothing will be printed when print csvdatareader.rawdata() is called. Also, I'd consider using different names for the function and list variable. From sulfurfff at hotmail.com Mon Oct 22 19:44:18 2007 From: sulfurfff at hotmail.com (=?iso-8859-1?Q?Ismael_Farf=E1n_Estrada?=) Date: Mon, 22 Oct 2007 17:44:18 +0000 Subject: [Tutor] pgdb and unicode In-Reply-To: <471CD6AD.7040302@tds.net> References: <471CD6AD.7040302@tds.net> Message-ID: >Ismael Farf?n Estrada wrote: >> Hi there. >> I have a small system in production with wxPython and PostgreSQL running on >> a machine with Centos 5. >> At first everytihing was running ok but now a weird bug was discovered: >> they can't insert characters like ? ? ? ? ? ? ? ? .... (non english characters) >> Does anyone knows how can I make pgdb accept that kind of characters? >> I wrote a little script... >> >> But first >> CREATE DATABASE test; >> CREATE TABLE tabla( >> cad character varying >> ) ; >> >> #!/usr/bin/python >> # -*- coding: utf8 -*- >> import pgdb >> con = pgdb.connect(user="farfan", password='000000', host='localhost', database='test') >> cur = con.cursor() >> cur.execute("INSERT INTO tabla VALUES ('?')") >> con.commit() >> cur.execute(u"INSERT INTO tabla VALUES ('?')") >> con.commit() >> >> As you can see, the first insert statement is executed in ascii format and is succeful, >> the second, which is in Unicode, fails > >Why do you need the whole statement to be Unicode? It looks like the >database wants utf-8. Probably you should encode the data as utf-8 first. > >> the problem is thas wxPython will allways send the script in unicode format... > >What is coming from wxPython? I guess it is just the data value, not the >SQL statement or the entire script. Try something like > >data= u'?' # Unicode data from wxPython >data = data.encode('utf-8') >cur.execute('INSERT INTO tabla VALUES (%s)', [data]) Tanks, that did the trick: data = [] data.append(self.marca.GetLineText(0))#.encode('utf-8')) sql = "INSERT INTO Marca (marca) VALUES (%s);" cur.execute(sql, data) > >Note I am passing the data as a separate list, not using string >interpolation. Let the database worry about quoting, etc. > >Kent It seems that just by sending the data in a list fixed the problem though adding the encode doesn't harm either ... I'll have to make a looot of changes. by the way, does sending the data as a list prevent SQL injection? I haven't worried for that yet. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From brunson at brunson.com Mon Oct 22 19:56:56 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 22 Oct 2007 11:56:56 -0600 Subject: [Tutor] pgdb and unicode In-Reply-To: <471CD6AD.7040302@tds.net> References: <471CD6AD.7040302@tds.net> Message-ID: <471CE468.9020507@brunson.com> Kent Johnson wrote: > Ismael Farf?n Estrada wrote: > >> Hi there. >> I have a small system in production with wxPython and PostgreSQL running on >> a machine with Centos 5. >> At first everytihing was running ok but now a weird bug was discovered: >> they can't insert characters like ? ? ? ? ? ? ? ? .... (non english characters) >> Does anyone knows how can I make pgdb accept that kind of characters? >> I wrote a little script... >> >> But first >> CREATE DATABASE test; >> CREATE TABLE tabla( >> cad character varying >> ) ; >> >> #!/usr/bin/python >> # -*- coding: utf8 -*- >> import pgdb >> con = pgdb.connect(user="farfan", password='000000', host='localhost', database='test') >> cur = con.cursor() >> cur.execute("INSERT INTO tabla VALUES ('?')") >> con.commit() >> cur.execute(u"INSERT INTO tabla VALUES ('?')") >> con.commit() >> >> As you can see, the first insert statement is executed in ascii format and is succeful, >> the second, which is in Unicode, fails >> > > Why do you need the whole statement to be Unicode? It looks like the > database wants utf-8. Probably you should encode the data as utf-8 first. > > >> the problem is thas wxPython will allways send the script in unicode format... >> > > What is coming from wxPython? I guess it is just the data value, not the > SQL statement or the entire script. Try something like > > data= u'?' # Unicode data from wxPython > data = data.encode('utf-8') > cur.execute('INSERT INTO tabla VALUES (%s)', [data]) > Dear Mr. Johnson, Thank you for doing your part to help eradicate SQL injection attacks. :-) Sincerely, The World (Seriously, though, after the discussion of last week, I always appreciate seeing good coding practices, even in example and meta code). > Note I am passing the data as a separate list, not using string > interpolation. Let the database worry about quoting, etc. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Oct 22 19:58:41 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Oct 2007 13:58:41 -0400 Subject: [Tutor] pgdb and unicode In-Reply-To: References: <471CD6AD.7040302@tds.net> Message-ID: <471CE4D1.6000502@tds.net> Ismael Farf?n Estrada wrote: > by the way, does sending the data as a list prevent SQL injection? Yes. > I haven't worried for that yet. If you are accepting user input and putting it into the database, you should worry about it. See http://xkcd.com/327/ for a humorous take on this ;-) Kent From ddm2 at sfu.ca Mon Oct 22 19:37:24 2007 From: ddm2 at sfu.ca (ddm2 at sfu.ca) Date: Mon, 22 Oct 2007 10:37:24 -0700 Subject: [Tutor] Negative Signed Binary Conversion Message-ID: <200710221737.l9MHbOVT013192@rm-rstar.sfu.ca> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20071022/bfc4f12c/attachment.txt From brunson at brunson.com Mon Oct 22 20:09:27 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 22 Oct 2007 12:09:27 -0600 Subject: [Tutor] Negative Signed Binary Conversion In-Reply-To: <200710221737.l9MHbOVT013192@rm-rstar.sfu.ca> References: <200710221737.l9MHbOVT013192@rm-rstar.sfu.ca> Message-ID: <471CE757.30504@brunson.com> Why not find the sign, calculate the binary of the absolute value, then make the result negative (twos complement) if necessary? Just a thought. ddm2 at sfu.ca wrote: > Hi, > I'm trying to get this binary converter working, but I can't seem to get the > negatives to work properly. If the integer is too low, the 0's that are > added for the amount of bits gets out of whack. I've tried to solve the > problem by adding another 'count' meter by which I can then tell if there > are too many 0's, but it hasn't worked at all. > CODE: > def conversion(n): > b = '' > while n > 0: > r = n%2 > n = n/2 > r = str(r) > b = r+b > return b > > def positive(n,bits,count): > append_zeros = bits - count > if append_zeros > 0: > return "0" + (append_zeros-1)*"0" + conversion(n) > > def negative(n,bits,count,new_count): > n = abs(n) > append_zeros = bits - count > while new_count > bits and new_count < bits-count: > append_zeros = append_zeros - 2 > continue > if append_zeros > 0: > return "1" + (append_zeros-6)*"0" + conversion(n) > > def signed_mag(): > print "" > print "--------------------" > print "Signed Binary" > print "--------------------" > print "" > n = int(raw_input("Please enter a signed integer: ")) > bits = int(raw_input("Please enter the number of bits: ")) > count = conversion(n).count("0") + conversion(n).count("1") > new_count = 0 > new_count = negative(n,bits,count,new_count).count("0") \ > + negative(n,bits,count,new_count).count("1") > if bits - 1 < count: > print "Out of range." > else: > if n < 0: > print n,"is encoded as", negative(n,bits,count,new_count), \ > "in Signed Binary." > elif n > 0: > print n,"is encoded as", positive(n,bits,count), \ > "in Signed Binary." > else: > print "That is not an valid signed interger." > > Any help will be greatly appreciated. Thanks in advance. > > Cheers, > Devon > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Mon Oct 22 21:14:47 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 22 Oct 2007 13:14:47 -0600 Subject: [Tutor] Negative Signed Binary Conversion In-Reply-To: <200710221815.l9MIFlai024458@rm-rstar.sfu.ca> References: <200710221815.l9MIFlai024458@rm-rstar.sfu.ca> Message-ID: <471CF6A7.50707@brunson.com> So far I've gotten five copies of this. It could be mailman doing something wrong, but if you're resending because you don't see your reply, please be patient, this list is not always instantaneous. I think you're missing the gist of what I'm saying. Calculate the binary of the absolute. I'm not going to debug your code for you, I'm just offering a suggestion to simplify your logic. Here's the way I might do it: def toBinary( num ): bits = [] negative = num < 0 n = abs( num ) while not bits or n: n, bit = divmod(n,2) bits.append( str(bit) ) bits.reverse() binary = "".join( bits ) if negative: return( twoscomplement( binary ) ) else: return( binary ) For what it's worth... ddm2 at sfu.ca wrote: > For Two's Complement, I would have to re-assign the 1's to 0's, and vice > versa, then add one in binary. That's my second step, and I'm pretty sure I > can get it to work IF I could get this negative signed binary part to work. > > On Mon, 22 Oct 2007 12:09:27 -0600 brunson at brunson.com wrote: > >> Why not find the sign, calculate the binary of the absolute value, then >> make the result negative (twos complement) if necessary? >> >> Just a thought. >> >> ddm2 at sfu.ca wrote: >> >>> Hi, >>> I'm trying to get this binary converter working, but I can't seem to >>> >> get the >> >>> negatives to work properly. If the integer is too low, the 0's that are >>> added for the amount of bits gets out of whack. I've tried to solve the >>> problem by adding another 'count' meter by which I can then tell if >>> > there > >>> are too many 0's, but it hasn't worked at all. >>> CODE: >>> def conversion(n): >>> b = '' >>> while n > 0: >>> r = n%2 >>> n = n/2 >>> r = str(r) >>> b = r+b >>> return b >>> >>> def positive(n,bits,count): >>> append_zeros = bits - count >>> if append_zeros > 0: >>> return "0" + (append_zeros-1)*"0" + conversion(n) >>> >>> def negative(n,bits,count,new_count): >>> n = abs(n) >>> append_zeros = bits - count >>> while new_count > bits and new_count < bits-count: >>> append_zeros = append_zeros - 2 >>> continue >>> if append_zeros > 0: >>> return "1" + (append_zeros-6)*"0" + conversion(n) >>> >>> def signed_mag(): >>> print "" >>> print "--------------------" >>> print "Signed Binary" >>> print "--------------------" >>> print "" >>> n = int(raw_input("Please enter a signed integer: ")) >>> bits = int(raw_input("Please enter the number of bits: ")) >>> count = conversion(n).count("0") + conversion(n).count("1") >>> new_count = 0 >>> new_count = negative(n,bits,count,new_count).count("0") \ >>> + negative(n,bits,count,new_count).count("1") >>> if bits - 1 < count: >>> print "Out of range." >>> else: >>> if n < 0: >>> print n,"is encoded as", negative(n,bits,count,new_count), \ >>> "in Signed Binary." >>> elif n > 0: >>> print n,"is encoded as", positive(n,bits,count), \ >>> "in Signed Binary." >>> else: >>> print "That is not an valid signed interger." >>> >>> Any help will be greatly appreciated. Thanks in advance. >>> >>> Cheers, >>> Devon >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> From tinoloc at gmail.com Mon Oct 22 21:44:44 2007 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 22 Oct 2007 15:44:44 -0400 Subject: [Tutor] multithreaded debugger Message-ID: Hi Everybody, Is there a multi-threaded debugger in Python? I running into some problems and a debugger would be very helpful here. Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071022/43ac5480/attachment.htm From kent37 at tds.net Mon Oct 22 22:15:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Oct 2007 16:15:33 -0400 Subject: [Tutor] multithreaded debugger In-Reply-To: References: Message-ID: <471D04E5.9020200@tds.net> Tino Dai wrote: > Hi Everybody, > > Is there a multi-threaded debugger in Python? I running into some > problems and a debugger would be very helpful here. Maybe Winpdb would help: http://www.digitalpeers.com/pythondebugger/ Kent From jtp at nc.rr.com Mon Oct 22 22:39:22 2007 From: jtp at nc.rr.com (James) Date: Mon, 22 Oct 2007 16:39:22 -0400 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <471CB4C3.1050107@brunson.com> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <471C1148.4030806@brunson.com> <471C88B2.7050500@groktech.org> <471CB4C3.1050107@brunson.com> Message-ID: <2C69871B-2D73-4F09-9DCD-4151DA30CEAA@nc.rr.com> That's not a half-baked idea. ;) I'm not really sure how I would replace 'yes', though, in this situation. Thoughts? .james On Oct 22, 2007, at 10:33 AM, Eric Brunson wrote: > Just another reason why I would look for a solution that would > avoid the > "yes" altogether. :-) From brunson at brunson.com Mon Oct 22 22:55:06 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 22 Oct 2007 14:55:06 -0600 Subject: [Tutor] Negative Signed Binary Conversion In-Reply-To: <200710222031.l9MKVhLb000642@rm-rstar.sfu.ca> References: <200710222031.l9MKVhLb000642@rm-rstar.sfu.ca> Message-ID: <471D0E2A.6090001@brunson.com> No worries. I said it could be mailman, and apparently it was. :-) ddm2 at sfu.ca wrote: > Hi, > I also got this email five times, and several rejection emails from the > moderator. I'm very sorry for this, but I swear I only sent the email once. > If this Apology email is also sent multiple times, I'll use a different > email account to post on lists. Again, very sorry for the inconvenience. > > Devon > > From brunson at brunson.com Mon Oct 22 23:41:05 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 22 Oct 2007 15:41:05 -0600 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <471BFC86.8040809@groktech.org> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <82b4f5810710210907x3f6b046fi806c0d60dc87f449@mail.gmail.com> <471BFC86.8040809@groktech.org> Message-ID: <471D18F1.6060801@brunson.com> Martin Walsh wrote: > Michael Langford wrote: > >> This signal is not something you care about. All SIGPIPE means is that >> the source of the signal found itself writing to a pipe with no sender. >> Your line "signal.signal(signal.SIGPIPE, signal.SIG_DFL)" means use the >> default signal handler for SIGPIPE. While this works (as the default >> signal handler is the ignore handler, you actually want to explicitly >> use the IGN handler, which will just ignore the signal. To do this use >> " signal.signal(signal.SIGPIPE, signal.SIG_IGN)" >> > > I don't think this is quite right, but please correct me if I'm > misinformed, or just plain wrong. :) > > Using "signal.signal(signal.SIGPIPE, signal.SIG_IGN)" (kernel 2.6.20, > bash 3.2, python2.5) I just noticed something, Martin. subprocess.call() on my machine is calling the shell as /bin/sh, not /bin/bash. This changes the behavior of bash, possibly causing it to print the message. (Anyone else think that subprocess should honor the SHELL environment variable?) I can't get any invocation of the commands to generate the error message, only when it's called from python does the ouput get generated. Quite interesting, I'd love to know the explanation for that. Still poking at it, though. > still produces a broken pipe with the following code: > > import signal > import subprocess as sp > signal.signal(signal.SIGPIPE, signal.SIG_IGN) > sp.call("yes 'Spam' | head -n 10", shell=True) > > My understanding is that python is *already* overriding with a SIG_IGN > for SIGPIPE, and child processes inherit, which explains the difference > in behavior when running the command from a shell terminal (on my system > at least) vs. a python subprocess object. This is referenced in the > signal module docs (http://docs.python.org/lib/module-signal.html), and > appears to be confirmed in the python2.5 source (pythonrun.c). > > Also, while it is unclear in the signal module docs (to me at least), my > take on the use of SIG_DFL is to revert (if necessary) to the *system* > default action for a signal, not the python default (which is SIG_IGN). > Again, this is my interpretation based on a very minimal understanding > -- please correct me if I'm wrong. > > >> The reason you don't see the error on the shell is that the bash shell >> does not print notifications of SIGPIPE when running interactively. If >> you instead copied your snippit of scripting into a shell script then >> called that with "bash foo.sh", you'd see the exact same broken pipe. >> > > Ok, this isn't true on my system either -- I don't get a broken pipe > from a bash script. So, perhaps this is due to the differences in our > kernel or bash versions. The version of bash on my system (3.2) has a > DONT_REPORT_SIGPIPE define that is honored in both interactive and > non-interactive shells. Presumably, this is how the ubuntu binary was > compiled. > > >> Here is what all the signals available do: >> http://www.delorie.com/gnu/docs/glibc/libc_471.html >> >> > > Excellent link, thanks! IMO, the signal manpage ('man signal') is also a > good resource. On my system, it contains a table of default actions. > Here's what it has to say about SIGPIPE: > > """ > Signal Value Action Comment > ------------------------------------- > SIGPIPE 13 Term Broken pipe: write to pipe with no readers > """ > > and, the 'Term' action is defined as follows: > > """ > Term Default action is to terminate the process. > """ > > Thanks! > Marty > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Oct 23 00:41:04 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Oct 2007 23:41:04 +0100 Subject: [Tutor] "standard output: Broken pipe" References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <471C1148.4030806@brunson.com><471C88B2.7050500@groktech.org> <471CB4C3.1050107@brunson.com> <2C69871B-2D73-4F09-9DCD-4151DA30CEAA@nc.rr.com> Message-ID: "James" wrote > I'm not really sure how I would replace 'yes', though, in this > situation. Thoughts? Just read the output of Popen from stdout and respond with a 'y' to stdin until the process finishes. See the example in the documentation of Popen replacing os.popen... Or look in the OS topic of my tutorial near the end... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Oct 23 00:44:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Oct 2007 23:44:08 +0100 Subject: [Tutor] Negative Signed Binary Conversion References: <200710221737.l9MHbOVT013192@rm-rstar.sfu.ca> Message-ID: wrote > I'm trying to get this binary converter working, but I can't seem to > get the > negatives to work properly. I already sent a reply on this, but: > def conversion(n): > b = '' > while n > 0: This line means you only ever return an empty string for a negative n... > n = int(raw_input("Please enter a signed integer: ")) > bits = int(raw_input("Please enter the number of bits: ")) > count = conversion(n).count("0") + conversion(n).count("1") And you call it with anegative n here and use the empty string to calculate the count... => 0. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From brunson at brunson.com Tue Oct 23 01:30:10 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 22 Oct 2007 17:30:10 -0600 Subject: [Tutor] Offtopic Reply, was: Negative Signed Binary Conversion In-Reply-To: References: <200710221737.l9MHbOVT013192@rm-rstar.sfu.ca> Message-ID: <471D3282.1090908@brunson.com> You know, Alan, I remember you commenting that you had some flakey behavior from this list a few of weeks ago, then over the weekend I received about two dozen emails from threads as far back as August. Something is definitely wonky (technical term ;-) about this list server. Alan Gauld wrote: > wrote > > >> I'm trying to get this binary converter working, but I can't seem to >> get the >> negatives to work properly. >> > > I already sent a reply on this, but: > > >> def conversion(n): >> b = '' >> while n > 0: >> > > This line means you only ever return an empty string for a negative > n... > > >> n = int(raw_input("Please enter a signed integer: ")) >> bits = int(raw_input("Please enter the number of bits: ")) >> count = conversion(n).count("0") + conversion(n).count("1") >> > > And you call it with anegative n here and use the empty > string to calculate the count... => 0. > > HTH, > > > From washakie at gmail.com Tue Oct 23 02:40:47 2007 From: washakie at gmail.com (John) Date: Tue, 23 Oct 2007 02:40:47 +0200 Subject: [Tutor] URLLIB / GLOB Message-ID: Hello, I would like to write a program which looks in a web directory for, say *.gif files. Then processes those files in some manner. What I need is something like glob which will return a directory listing of all the files matching the search pattern (or just a simply a certain extension). Is there a way to do this with urllib? Any other suggestions? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071023/b6db491c/attachment.htm From kent37 at tds.net Tue Oct 23 03:09:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Oct 2007 21:09:26 -0400 Subject: [Tutor] URLLIB / GLOB In-Reply-To: References: Message-ID: <471D49C6.9010907@tds.net> John wrote: > Hello, > > I would like to write a program which looks in a web directory for, say > *.gif files. Then processes those files in some manner. What I need is > something like glob which will return a directory listing of all the > files matching the search pattern (or just a simply a certain extension). > > Is there a way to do this with urllib? Any other suggestions? If the directory is only available as a web page you will have to fetch the web directory listing itself with urllib or urllib2 and parse the HTML returned to get the list of files. You might want to use BeautifulSoup to parse the HTML. http://www.crummy.com/software/BeautifulSoup/ Kent From mwalsh at groktech.org Tue Oct 23 07:46:17 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Tue, 23 Oct 2007 00:46:17 -0500 Subject: [Tutor] "standard output: Broken pipe" In-Reply-To: <471D18F1.6060801@brunson.com> References: <125C59D8-5100-46AB-A5BF-B2A0F718C6F8@nc.rr.com> <82b4f5810710210907x3f6b046fi806c0d60dc87f449@mail.gmail.com> <471BFC86.8040809@groktech.org> <471D18F1.6060801@brunson.com> Message-ID: <471D8AA9.3080801@groktech.org> Eric Brunson wrote: > Martin Walsh wrote: >> Michael Langford wrote: >> I don't think this is quite right, but please correct me if I'm >> misinformed, or just plain wrong. :) >> >> Using "signal.signal(signal.SIGPIPE, signal.SIG_IGN)" (kernel 2.6.20, >> bash 3.2, python2.5) > > I just noticed something, Martin. subprocess.call() on my machine is > calling the shell as /bin/sh, not /bin/bash. This changes the behavior > of bash, possibly causing it to print the message. (Anyone else think > that subprocess should honor the SHELL environment variable?) Yeah, I thought that was strange too, and I completely agree that the SHELL env var would seem the obvious choice -- or perhaps, a mechanism to change the shell command. Now that you mention the behavior of /bin/bash when called as /bin/sh, I guess it could have something to do with posix compliance, but I don't really understand the implications. Maybe a quick modification of the subprocess source will shed some light; setting it to /bin/bash, instead of /bin/sh (or '/bin/bash --posix'): """ def _execute_child( ... ): if shell: args = ["/bin/bash", "-c"] + args """ Unfortunately, no change in the odd SIGPIPE behavior. Another factoid -- Ubuntu /bin/sh is a symlink to dash. After your advice to pay closer attention to the shell sub-process, I thought dash might be the culprit. But alas, it produced the same behavior. And, of course, changing the symlink to point to bash didn't make a difference either. > > I can't get any invocation of the commands to generate the error > message, only when it's called from python does the ouput get > generated. Quite interesting, I'd love to know the explanation for that. I'm seeing the same thing, error message from python and not from shell or shell scripts. I am still leaning toward signal inheritance as a likely contributor, which I think would also indicate that the subprocess module is rolling up an exception and not passing it along. As I mentioned it's almost all gut-reaction at this point, so far I haven't found any definitive proof to substantiate. Slow going for me I'm afraid, to many tangential paths to follow to fill gaps in my understanding. But it sure is fun. Again, thanks for you insight Eric! Marty > > Still poking at it, though. > >> still produces a broken pipe with the following code: >> >> import signal >> import subprocess as sp >> signal.signal(signal.SIGPIPE, signal.SIG_IGN) >> sp.call("yes 'Spam' | head -n 10", shell=True) >> >> My understanding is that python is *already* overriding with a SIG_IGN >> for SIGPIPE, and child processes inherit, which explains the difference >> in behavior when running the command from a shell terminal (on my system >> at least) vs. a python subprocess object. This is referenced in the >> signal module docs (http://docs.python.org/lib/module-signal.html), and >> appears to be confirmed in the python2.5 source (pythonrun.c). >> >> Also, while it is unclear in the signal module docs (to me at least), my >> take on the use of SIG_DFL is to revert (if necessary) to the *system* >> default action for a signal, not the python default (which is SIG_IGN). >> Again, this is my interpretation based on a very minimal understanding >> -- please correct me if I'm wrong. >> >> >>> The reason you don't see the error on the shell is that the bash shell >>> does not print notifications of SIGPIPE when running interactively. If >>> you instead copied your snippit of scripting into a shell script then >>> called that with "bash foo.sh", you'd see the exact same broken pipe. >>> >> >> Ok, this isn't true on my system either -- I don't get a broken pipe >> from a bash script. So, perhaps this is due to the differences in our >> kernel or bash versions. The version of bash on my system (3.2) has a >> DONT_REPORT_SIGPIPE define that is honored in both interactive and >> non-interactive shells. Presumably, this is how the ubuntu binary was >> compiled. >> >> >>> Here is what all the signals available do: >>> http://www.delorie.com/gnu/docs/glibc/libc_471.html >>> >>> >> >> Excellent link, thanks! IMO, the signal manpage ('man signal') is also a >> good resource. On my system, it contains a table of default actions. >> Here's what it has to say about SIGPIPE: >> >> """ >> Signal Value Action Comment >> ------------------------------------- >> SIGPIPE 13 Term Broken pipe: write to pipe with no readers >> """ >> >> and, the 'Term' action is defined as follows: >> >> """ >> Term Default action is to terminate the process. >> """ >> >> Thanks! >> Marty >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> From chenyinghe at gmail.com Tue Oct 23 10:21:59 2007 From: chenyinghe at gmail.com (Yinghe Chen) Date: Tue, 23 Oct 2007 08:21:59 +0000 Subject: [Tutor] How to implement function like this? Message-ID: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> Hello gurus, I have a question, a function like below, it is implemented by me, :) def funcA(tarray): a = [2,3,4] if len(tarray) >=3: return a[0],a[1], a[2] elif len(tarray) == 2: return a[0],a[1], funcB(1)[0] elif len(tarray) == 1: return a[0], funcB(2)[0], funcB(2)[1] else: return funcB(3)[0], funcB(3)[1], funcB(3)[2] The return of funcA is always 3 values, but depending on the length of tarray, I need to return different values accordingly. if tarray lenght is 2, I need to get another one value from funcB, if tarray length is 0, I need to get all three values from funcB. Is there a brief way to achieve it? Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071023/215f4dc3/attachment.htm From alan.gauld at btinternet.com Tue Oct 23 12:55:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Oct 2007 11:55:53 +0100 Subject: [Tutor] How to implement function like this? References: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> Message-ID: "Yinghe Chen" wrote > def funcA(tarray): > a = [2,3,4] > if len(tarray) >=3: > return a[0],a[1], a[2] > elif len(tarray) == 2: > return a[0],a[1], funcB(1)[0] > elif len(tarray) == 1: > return a[0], funcB(2)[0], funcB(2)[1] > else: > return funcB(3)[0], funcB(3)[1], funcB(3)[2] > > > Is there a brief way to achieve it? It looks fairly brief to me. There are a couple of things I might consider changing. def funcA(tArray, defs = (2,3,4), func = funcB): if len(tArray) >= 3: return defs elif len(tArray) == 2: return defs[0],defs[1], func(2)[1] elif.... By making defs a tuple you can return it directly and by making it a defaulted parameter you can change the values if needed without changing the funcA code. Similarly by making funcB a default parameter you have the flexibility to change the algorithm used without changing funcA. But because they are default parameters you can still call it with just tArray as an argument. A small change but may significantly improve the flexibility and possible reuse capability of funcA HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Oct 23 13:45:03 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Oct 2007 07:45:03 -0400 Subject: [Tutor] How to implement function like this? In-Reply-To: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> References: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> Message-ID: <471DDEBF.6040409@tds.net> Yinghe Chen wrote: > Hello gurus, > > I have a question, a function like below, it is implemented by me, :) > > def funcA(tarray): > a = [2,3,4] > if len(tarray) >=3: > return a[0],a[1], a[2] > elif len(tarray) == 2: > return a[0],a[1], funcB(1)[0] > elif len(tarray) == 1: > return a[0], funcB(2)[0], funcB(2)[1] > else: > return funcB(3)[0], funcB(3)[1], funcB(3)[2] > > > The return of funcA is always 3 values, but depending on the length of > tarray, I need to return different values accordingly. if tarray lenght > is 2, I need to get another one value from funcB, if tarray length is 0, > I need to get all three values from funcB. I think this works; not sure if it is better. The list() calls are not needed if tarray and the result of funcB are already lists; the tuple calls may not be needed either: def funcA(tarray): a = [2,3,4] if len(tarray) >=3: return tuple(a) result = list(tarray) + list(funcB(3-len(tarray))) return tuple(result[:3]) Kent From ricaraoz at gmail.com Tue Oct 23 14:37:43 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 23 Oct 2007 09:37:43 -0300 Subject: [Tutor] calling a variable name In-Reply-To: <471CBB1F.30905@tds.net> References: <471C8D89.5080902@tds.net> <471CBB1F.30905@tds.net> Message-ID: <471DEB17.9080208@bigfoot.com> Kent Johnson wrote: > Bryan Fodness wrote: >> Thank you. This works well. I am still trying to figure out the pros >> and cons of using an array, dictionary or list. > > Array is specialized, you probably want list or dict. > > Use list when you want a sequence of items indexed by sequential integers. > Lists > - preserve order > - are fast for indexed lookup > - are relatively slow (O(n)) for adding, deleting and searching (though > for small lists this should not be a consideration) Are you sure they take O(n) for adding? I would have thought it would take O(1). From ricaraoz at gmail.com Tue Oct 23 15:28:15 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 23 Oct 2007 10:28:15 -0300 Subject: [Tutor] How to implement function like this? In-Reply-To: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> References: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> Message-ID: <471DF6EF.6010108@bigfoot.com> Yinghe Chen wrote: > Hello gurus, > > I have a question, a function like below, it is implemented by me, :) > > def funcA(tarray): > a = [2,3,4] > if len(tarray) >=3: > return a[0],a[1], a[2] > elif len(tarray) == 2: > return a[0],a[1], funcB(1)[0] > elif len(tarray) == 1: > return a[0], funcB(2)[0], funcB(2)[1] > else: > return funcB(3)[0], funcB(3)[1], funcB(3)[2] > > > The return of funcA is always 3 values, but depending on the length of > tarray, I need to return different values accordingly. if tarray lenght > is 2, I need to get another one value from funcB, if tarray length is 0, > I need to get all three values from funcB. > > > Is there a brief way to achieve it? > def funcA(tArray) : a = [2,3,4] L = min(len(tArray), 3) return tuple(i for n, i in enumerate(a) if n < L)+tuple(funcB(len(a)-L)) From rdm at rcblue.com Wed Oct 24 00:55:52 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 23 Oct 2007 15:55:52 -0700 Subject: [Tutor] A new Kent essay: A Brief Introduction to Beautiful Soup Message-ID: <20071023225601.987821E4023@bag.python.org> Dick Moores From eric at ericwalstad.com Wed Oct 24 01:15:07 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Tue, 23 Oct 2007 16:15:07 -0700 Subject: [Tutor] A new Kent essay: A Brief Introduction to Beautiful Soup In-Reply-To: <20071023225601.987821E4023@bag.python.org> References: <20071023225601.987821E4023@bag.python.org> Message-ID: <471E807B.8020101@ericwalstad.com> Dick Moores wrote: > That looks like a very nice, concise tutorial that should help soup noobs like me to get up and running quickly. I like the added value of comments like: "Under the hood, attribute access is actually a search for the first tag of the correct type, so soup.title will also access the first tag." I haven't needed BeautifulSoup yet, but I know I will some day. Thanks for sharing, Kent. From tedroche at gmail.com Wed Oct 24 01:23:56 2007 From: tedroche at gmail.com (Ted Roche) Date: Tue, 23 Oct 2007 19:23:56 -0400 Subject: [Tutor] A new Kent essay: A Brief Introduction to Beautiful Soup In-Reply-To: <20071023225601.987821E4023@bag.python.org> References: <20071023225601.987821E4023@bag.python.org> Message-ID: <c9415b010710231623q4b4e3393s46196cbfba86918@mail.gmail.com> On 10/23/07, Dick Moores <rdm at rcblue.com> wrote: > <http://personalpages.tds.net/~kent37/kk/00009.html> And if you're in the Manchester, New Hampshire, USA area, perhaps you can stop by Thursday night and witness Kent himself presenting his essay and a follow-on scrum using Beautiful Soup to parse out a couple of web pages: http://dlslug.org/pipermail/python-talk/2007-October/000639.html -- Ted Roche Ted Roche & Associates, LLC http://www.tedroche.com From brunson at brunson.com Wed Oct 24 02:07:29 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 23 Oct 2007 18:07:29 -0600 Subject: [Tutor] A new Kent essay: A Brief Introduction to Beautiful Soup In-Reply-To: <c9415b010710231623q4b4e3393s46196cbfba86918@mail.gmail.com> References: <20071023225601.987821E4023@bag.python.org> <c9415b010710231623q4b4e3393s46196cbfba86918@mail.gmail.com> Message-ID: <471E8CC1.4030900@brunson.com> That's funny. Knowing Alan is from the UK, when I saw Kent was from Manchester I thought he was Alan's countrymate. You know the British (at least my cousins) make fun of us for always having to say our state. "Paris, Texas", "Boston, Mass", "Tampa, FL". But, we just have so many more towns, everyone started reusing the names, not to mention that most of the names we didn't steal from the natives, we jacked from the old world. ;-) Ted Roche wrote: > On 10/23/07, Dick Moores <rdm at rcblue.com> wrote: > >> <http://personalpages.tds.net/~kent37/kk/00009.html> >> > > And if you're in the Manchester, New Hampshire, USA area, perhaps you > can stop by Thursday night and witness Kent himself presenting his > essay and a follow-on scrum using Beautiful Soup to parse out a couple > of web pages: > > http://dlslug.org/pipermail/python-talk/2007-October/000639.html > > From wormwood_3 at yahoo.com Wed Oct 24 03:15:56 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 23 Oct 2007 18:15:56 -0700 (PDT) Subject: [Tutor] Logging in Linux Message-ID: <83364.12546.qm@web32413.mail.mud.yahoo.com> Hello tutors, I have become familiar with the basic use of the logging module. I have a program that prints out warning messages as well as info messages as it runs, merely dumping them into stdout. When I make such a script into a cron job, I simply redirect this output to /dev/null. Now, what I would like to do is instead send this output to one or more of the standard linux log files. First though, I am wondering, what is the standard procedure in a case like this? Is it more appropriate to make a totally separate log file for all user-added scripts (or one a piece), and put them in /var/log or elsewhere? Where have you all found to be helpful places to log messages from automated scripts on Linux systems? The end goal is simply to have a place that I can check to see that the script is running as expected, or troubleshoot issues if need arise. Thanks for any help or tips, Sam From kent37 at tds.net Wed Oct 24 04:10:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Oct 2007 22:10:24 -0400 Subject: [Tutor] calling a variable name In-Reply-To: <471DEB17.9080208@bigfoot.com> References: <fbf64d2b0710211956s2f2bc209m2846991aed80a247@mail.gmail.com> <ffhk2n$c59$1@ger.gmane.org> <fbf64d2b0710220357v483edd9do8cd072e1a81ed5e6@mail.gmail.com> <471C8D89.5080902@tds.net> <fbf64d2b0710220751l3968920er337e39586bf3024e@mail.gmail.com> <471CBB1F.30905@tds.net> <471DEB17.9080208@bigfoot.com> Message-ID: <471EA990.60606@tds.net> Ricardo Ar?oz wrote: > Kent Johnson wrote: >> Use list when you want a sequence of items indexed by sequential integers. >> Lists >> - preserve order >> - are fast for indexed lookup >> - are relatively slow (O(n)) for adding, deleting and searching (though >> for small lists this should not be a consideration) > > Are you sure they take O(n) for adding? I would have thought it would > take O(1). Perhaps I was a bit hasty. Lists are implemented as arrays of references. I believe they are - amortized O(1) for append - occasionally the list must be reallocated and copied - O(1) for delete from the end ? - O(n) for insert and delete not at the end - the values above the insert/delete must be copied - O(n) for search which is sequential search Kent From kent37 at tds.net Wed Oct 24 04:14:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Oct 2007 22:14:30 -0400 Subject: [Tutor] How to implement function like this? In-Reply-To: <471DF6EF.6010108@bigfoot.com> References: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> <471DF6EF.6010108@bigfoot.com> Message-ID: <471EAA86.4030505@tds.net> Ricardo Ar?oz wrote: > Yinghe Chen wrote: >> Hello gurus, >> >> I have a question, a function like below, it is implemented by me, :) >> >> def funcA(tarray): >> a = [2,3,4] >> if len(tarray) >=3: >> return a[0],a[1], a[2] >> elif len(tarray) == 2: >> return a[0],a[1], funcB(1)[0] >> elif len(tarray) == 1: >> return a[0], funcB(2)[0], funcB(2)[1] >> else: >> return funcB(3)[0], funcB(3)[1], funcB(3)[2] > def funcA(tArray) : > a = [2,3,4] > L = min(len(tArray), 3) > return tuple(i for n, i in enumerate(a) if n < L)+tuple(funcB(len(a)-L)) tuple(i for n, i in enumerate(a) if n < L) can be written tuple(a[:L]) funcB(len(a)-L) does not do what the OP requested. For example if len(a) is 10, L will be 3 and you will call funcB(7). Kent From dyoo at cs.wpi.edu Wed Oct 24 02:17:33 2007 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Tue, 23 Oct 2007 20:17:33 -0400 (EDT) Subject: [Tutor] Complexity of list operations Message-ID: <Pine.LNX.4.63.0710232002440.31262@cs.wpi.edu> >> Use list when you want a sequence of items indexed by sequential >> integers. Lists >> - preserve order >> - are fast for indexed lookup >> - are relatively slow (O(n)) for adding, deleting and searching (though >> for small lists this should not be a consideration) > > Are you sure they take O(n) for adding? I would have thought it would > take O(1). One thing to be careful of: Python "lists" are not linked lists: they really are sequential array-like things that auto-expand. That means inserts can be potentially expensive depending on where we do the insert. The worst case scenario for Python's list operations (insert, delete) happens when we're applying those operations to the very head of the list. The reasoning is because inserting an element forces us to move all the other elements all up by one place: they've got to make room for their new neighbor! By the same reasoning, deletes from the front can also be a linear-time operation because it forces the remainder of the elements to fill in the gap. (For the math heads out there: if it takes some constant 'k' time to move an element, and if we start with an empty list and spam it with N inserts at the front, then the total amount of time it takes to do those N operations will be 0 + 1*k + 2*k + ... + (N-1)*k, and that's a "Gauss sum" that collapses to (N*(N-1)/2)*k. That is, in this worst case scenario, it takes time quadratic in the number of elements to insert N elements!) That being said, if all our operations are applied only at the end of the list, the time complexity of those two operations look better. We can argue for O(1) behavior under that particular restriction. But I think Kent was considering the worst-case behavior, since it's an upper bound on how bad things can get. From dkuhlman at rexx.com Wed Oct 24 05:40:29 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 23 Oct 2007 20:40:29 -0700 Subject: [Tutor] Complexity of list operations In-Reply-To: <Pine.LNX.4.63.0710232002440.31262@cs.wpi.edu> References: <Pine.LNX.4.63.0710232002440.31262@cs.wpi.edu> Message-ID: <20071024034029.GA66963@cutter.rexx.com> On Tue, Oct 23, 2007 at 08:17:33PM -0400, Danny Yoo wrote: [helpful explanation snipped] > > That being said, if all our operations are applied only at the end of the > list, the time complexity of those two operations look better. We can > argue for O(1) behavior under that particular restriction. But I think > Kent was considering the worst-case behavior, since it's an upper bound on > how bad things can get. Danny - Thanks for this explanation. I've wondered about the costs of using a list as a FIFO data structure (first in, first out), and doing, for example: lst.insert(0, obj) and: obj = lst.pop() Also, this is probably a good place to mention deque (http://docs.python.org/lib/deque-objects.html), which attempts to reduce those costs. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dkuhlman at rexx.com Wed Oct 24 05:55:32 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 23 Oct 2007 20:55:32 -0700 Subject: [Tutor] calling a variable name In-Reply-To: <471EA990.60606@tds.net> References: <fbf64d2b0710211956s2f2bc209m2846991aed80a247@mail.gmail.com> <ffhk2n$c59$1@ger.gmane.org> <fbf64d2b0710220357v483edd9do8cd072e1a81ed5e6@mail.gmail.com> <471C8D89.5080902@tds.net> <fbf64d2b0710220751l3968920er337e39586bf3024e@mail.gmail.com> <471CBB1F.30905@tds.net> <471DEB17.9080208@bigfoot.com> <471EA990.60606@tds.net> Message-ID: <20071024035532.GB66963@cutter.rexx.com> On Tue, Oct 23, 2007 at 10:10:24PM -0400, Kent Johnson wrote: [snip] > > Perhaps I was a bit hasty. > > Lists are implemented as arrays of references. I believe they are > - amortized O(1) for append - occasionally the list must be reallocated > and copied OK. I'm groping here. Wikipedia tells me that O(1) means constant increase. So, what does "amortized O(1)" mean. My understanding is that appending in lists is optimized in the sense that when more space is needed, Python allocates space for additional elements so that allocation does not need to happen at every append. Here is a comment from the Python source code (Python-2.5.1/Objects/listobject.c): /* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, but is * enough to give linear-time amortized behavior over a long * sequence of appends() in the presence of a poorly-performing * system realloc(). * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... */ Hmmm. There is that "amortized" thing again. Very suspicious. For a non-math and non-financial type like me, is it sort of like saying that the costs are averaged out over a sequence of appends? Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Wed Oct 24 12:47:52 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Oct 2007 06:47:52 -0400 Subject: [Tutor] calling a variable name In-Reply-To: <20071024035532.GB66963@cutter.rexx.com> References: <fbf64d2b0710211956s2f2bc209m2846991aed80a247@mail.gmail.com> <ffhk2n$c59$1@ger.gmane.org> <fbf64d2b0710220357v483edd9do8cd072e1a81ed5e6@mail.gmail.com> <471C8D89.5080902@tds.net> <fbf64d2b0710220751l3968920er337e39586bf3024e@mail.gmail.com> <471CBB1F.30905@tds.net> <471DEB17.9080208@bigfoot.com> <471EA990.60606@tds.net> <20071024035532.GB66963@cutter.rexx.com> Message-ID: <471F22D8.6060504@tds.net> Dave Kuhlman wrote: > On Tue, Oct 23, 2007 at 10:10:24PM -0400, Kent Johnson wrote: > > [snip] > >> Perhaps I was a bit hasty. >> >> Lists are implemented as arrays of references. I believe they are >> - amortized O(1) for append - occasionally the list must be reallocated >> and copied > > OK. I'm groping here. Wikipedia tells me that O(1) means constant > increase. So, what does "amortized O(1)" mean. > > My understanding is that appending in lists is optimized in the > sense that when more space is needed, Python allocates space for > additional elements so that allocation does not need to happen at > every append. Here is a comment from the Python source code > (Python-2.5.1/Objects/listobject.c): > > /* This over-allocates proportional to the list size, making room > * for additional growth. The over-allocation is mild, but is > * enough to give linear-time amortized behavior over a long > * sequence of appends() in the presence of a poorly-performing > * system realloc(). > * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... > */ > > Hmmm. There is that "amortized" thing again. Very suspicious. > For a non-math and non-financial type like me, is it sort of like > saying that the costs are averaged out over a sequence of appends? Yes, that is exactly right. Most of the time - when there is room at the end of the allocated block - append is O(1) and very fast. Occasionally, when there is not enough room, append is O(n) and slow, requiring the entire list to be copied. Because the size of the new allocation is proportional to the size of the list, the reallocation happens only each 1/n appends, so if you average out the cost of the reallocation, each append is O(1) (with a higher constant). That is what amortized cost means - sometimes the cost is greater than the specified cost but it averages out. Note that if the reallocation added a fixed amount of extra space each time the cost would not average out over n inserts and it would not be O(1) amortized cost. It's important that the new allocation be proportional to the existing space. Kent From noufal at airtelbroadband.in Wed Oct 24 15:29:44 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 24 Oct 2007 18:59:44 +0530 Subject: [Tutor] Logging in Linux In-Reply-To: <83364.12546.qm@web32413.mail.mud.yahoo.com> References: <83364.12546.qm@web32413.mail.mud.yahoo.com> Message-ID: <471F48C8.6050608@airtelbroadband.in> wormwood_3 wrote: > Now, what I would like to do is instead send this output to one or > more of the standard linux log files. First though, I am wondering, what > is the standard procedure in a case like this? You can either have a config file to specify a log area or use syslog to do the logging. The standard logging module has a RotatingFileHandler and a SysLogHandler for both these methods. > Is it more appropriate to > make a totally separate log file for all user-added scripts (or one a > piece), and put them in /var/log or elsewhere? Where have you all found > to be helpful places to log messages from automated scripts on Linux > systems? The end goal is simply to have a place that I can check to see > that the script is running as expected, or troubleshoot issues if need > arise. /var/log looks nice. I think you should just make it configurable enough so that people can relocate if they want to. -- ~noufal http://nibrahim.net.in/ From rdm at rcblue.com Wed Oct 24 10:23:53 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 24 Oct 2007 01:23:53 -0700 Subject: [Tutor] Looking to improve my stopWatch.py Message-ID: <20071024144708.1CFB61E400F@bag.python.org> Please give me constructive criticism of <http://www.rcblue.com/Python/stopWatchForWeb14-a.py> (secsToHMS() was perfected with much Tutor help in this thread: <http://www.nabble.com/print-question-tf4591532.html#a13107550>) Thanks, Dick Moores 4444444444 From bhaaluu at gmail.com Wed Oct 24 17:46:22 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 24 Oct 2007 11:46:22 -0400 Subject: [Tutor] Looking to improve my stopWatch.py In-Reply-To: <20071024144708.1CFB61E400F@bag.python.org> References: <20071024144708.1CFB61E400F@bag.python.org> Message-ID: <ea979d70710240846r430b2d02u1a52522e79ec4e3e@mail.gmail.com> On 10/24/07, Dick Moores <rdm at rcblue.com> wrote: > Please give me constructive criticism of > <http://www.rcblue.com/Python/stopWatchForWeb14-a.py> $ python Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import msvcrt Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named msvcrt >>> > > (secsToHMS() was perfected with much Tutor help in this thread: > <http://www.nabble.com/print-question-tf4591532.html#a13107550>) > > Thanks, > > Dick Moores 4444444444 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > HTH -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From aezell at gmail.com Wed Oct 24 18:39:36 2007 From: aezell at gmail.com (Alex Ezell) Date: Wed, 24 Oct 2007 11:39:36 -0500 Subject: [Tutor] Calling a Method with a Reserved Name Message-ID: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> I am working on building a SOAP client. Unfortunately, one of the methods the SOAP server provides is named "import." The SOAP server is written in PHP. So, my problem is that Python really doesn't like me using the word "import" to call the SOAP method. The call should look something like this: self.call_response = self.soap.import(self.soap_auth, file_name, import_groups, soap_flags) Is there any way to call this method despite it's name being a reserved word. /alex From kent37 at tds.net Wed Oct 24 18:51:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Oct 2007 12:51:33 -0400 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> Message-ID: <471F7815.7070701@tds.net> Alex Ezell wrote: > I am working on building a SOAP client. Unfortunately, one of the > methods the SOAP server provides is named "import." The SOAP server is > written in PHP. > > So, my problem is that Python really doesn't like me using the word > "import" to call the SOAP method. The call should look something like > this: > > self.call_response = self.soap.import(self.soap_auth, file_name, > import_groups, soap_flags) > > Is there any way to call this method despite it's name being a reserved word. You could try introspection: importFunc = getattr(self.soap, 'import') self.call_response = importFunc(self.soap_auth, file_name, import_groups, soap_flags) I don't know if this will work here or not, I assume self.soap is already doing some attribute magic. Kent From aezell at gmail.com Wed Oct 24 20:35:45 2007 From: aezell at gmail.com (Alex Ezell) Date: Wed, 24 Oct 2007 13:35:45 -0500 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <471F7815.7070701@tds.net> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> <471F7815.7070701@tds.net> Message-ID: <71dd7f400710241135n56c5e07eke4a526cc30757a5f@mail.gmail.com> On 10/24/07, Kent Johnson <kent37 at tds.net> wrote: > Alex Ezell wrote: > > I am working on building a SOAP client. Unfortunately, one of the > > methods the SOAP server provides is named "import." The SOAP server is > > written in PHP. > > > > So, my problem is that Python really doesn't like me using the word > > "import" to call the SOAP method. The call should look something like > > this: > > > > self.call_response = self.soap.import(self.soap_auth, file_name, > > import_groups, soap_flags) > > > > Is there any way to call this method despite it's name being a reserved word. > > You could try introspection: > > importFunc = getattr(self.soap, 'import') > self.call_response = importFunc(self.soap_auth, file_name, > import_groups, soap_flags) Thanks Kent. I tried it and it seem like importFunc is now something like 'import.__str__'. I could maybe do some string operations to just get import out of that, but is there something I could do with getattr() for that reference to come back the way I need. Thanks again. /alex From bgailer at alum.rpi.edu Wed Oct 24 20:39:33 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 24 Oct 2007 14:39:33 -0400 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> Message-ID: <471F9165.3080505@alum.rpi.edu> Alex Ezell wrote: > I am working on building a SOAP client. Unfortunately, one of the > methods the SOAP server provides is named "import." The SOAP server is > written in PHP. > > So, my problem is that Python really doesn't like me using the word > "import" to call the SOAP method. This seems unfortunate and too restrictive, to not allow keywords to be used for other purposes, when the context makes it clear that its use is not as a keyword. PL/I works that way: one may code if if = then then then = else else else = if Not that that is recommended coding style. From kent37 at tds.net Wed Oct 24 21:10:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Oct 2007 15:10:25 -0400 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <71dd7f400710241135n56c5e07eke4a526cc30757a5f@mail.gmail.com> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> <471F7815.7070701@tds.net> <71dd7f400710241135n56c5e07eke4a526cc30757a5f@mail.gmail.com> Message-ID: <471F98A1.5080105@tds.net> Alex Ezell wrote: >> You could try introspection: >> >> importFunc = getattr(self.soap, 'import') >> self.call_response = importFunc(self.soap_auth, file_name, >> import_groups, soap_flags) > > Thanks Kent. I tried it and it seem like importFunc is now something > like 'import.__str__'. I could maybe do some string operations to just > get import out of that, but is there something I could do with > getattr() for that reference to come back the way I need. I guess you will have to dig into the implementation of the client a bit and find out what self.soap.import does and duplicate that somehow. What client code are you using? I would look for a __getattr__ method in the class implementing self.soap, for starters. Kent From kent37 at tds.net Wed Oct 24 21:32:55 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Oct 2007 15:32:55 -0400 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <71dd7f400710241135n56c5e07eke4a526cc30757a5f@mail.gmail.com> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> <471F7815.7070701@tds.net> <71dd7f400710241135n56c5e07eke4a526cc30757a5f@mail.gmail.com> Message-ID: <471F9DE7.70407@tds.net> Alex Ezell wrote: > On 10/24/07, Kent Johnson <kent37 at tds.net> wrote: >> Alex Ezell wrote: >>> I am working on building a SOAP client. Unfortunately, one of the >>> methods the SOAP server provides is named "import." The SOAP server is >>> written in PHP. >>> >>> So, my problem is that Python really doesn't like me using the word >>> "import" to call the SOAP method. The call should look something like >>> this: >>> >>> self.call_response = self.soap.import(self.soap_auth, file_name, >>> import_groups, soap_flags) >>> >>> Is there any way to call this method despite it's name being a reserved word. >> You could try introspection: >> >> importFunc = getattr(self.soap, 'import') >> self.call_response = importFunc(self.soap_auth, file_name, >> import_groups, soap_flags) > > Thanks Kent. I tried it and it seem like importFunc is now something > like 'import.__str__'. I could maybe do some string operations to just > get import out of that, but is there something I could do with > getattr() for that reference to come back the way I need. Hmm, with a quick look at the code for SOAPpy (v 0.11.6) I don't see why the getattr() method would not work. Can you show the code you tried and why you think the result was a string? BTW pulling 'import' out of the string won't help; you need the import *function*. Kent From brunson at brunson.com Wed Oct 24 15:36:55 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 24 Oct 2007 07:36:55 -0600 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <471F9165.3080505@alum.rpi.edu> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> <471F9165.3080505@alum.rpi.edu> Message-ID: <471F4A77.6030304@brunson.com> bob gailer wrote: > Alex Ezell wrote: > >> I am working on building a SOAP client. Unfortunately, one of the >> methods the SOAP server provides is named "import." The SOAP server is >> written in PHP. >> >> So, my problem is that Python really doesn't like me using the word >> "import" to call the SOAP method. >> > This seems unfortunate and too restrictive, to not allow keywords to be > used for other purposes, when the context makes it clear that its use is > not as a keyword. > Python isn't the only language, try compiling this with a C compiler: int main(){ int char = 1; } test.c:3: error: expected identifier or ?(? before ?=? token or a C++ compiler: test.C:3: error: expected unqualified-id before ?=? token Or running this through a PHP interpreter: <?php function require() { print( "Hello World" ); } ?> PHP Parse error: syntax error, unexpected T_REQUIRE, expecting T_STRING in test.php on line 2 Oh, well. :-) > PL/I works that way: one may code > if if = then then > then = else > else > else = if > > Not that that is recommended coding style. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at alum.rpi.edu Wed Oct 24 23:14:51 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 24 Oct 2007 17:14:51 -0400 Subject: [Tutor] Looking to improve my stopWatch.py In-Reply-To: <20071024144708.1CFB61E400F@bag.python.org> References: <20071024144708.1CFB61E400F@bag.python.org> Message-ID: <471FB5CB.6050203@alum.rpi.edu> Dick Moores wrote: > Please give me constructive criticism of > <http://www.rcblue.com/Python/stopWatchForWeb14-a.py> > 1 - lapCounter is not used. 2 - simplify: if lapTimeFlag == False: print "Total Time is", secsToHMS(totalTime) print "StopWatch is continuing to time.." else: currentLapTime = markTime - lapEnd print "Current time of this lap, Lap %d, is %s" % (lapNum, secsToHMS(currentLapTime)) print "Total Time is", secsToHMS(totalTime) print "StopWatch is continuing to time.." new version: if lapTimeFlag: currentLapTime = markTime - lapEnd print "Current time of this lap, Lap %d, is %s" % (lapNum, secsToHMS(currentLapTime)) print "Total Time is", secsToHMS(totalTime) print "StopWatch is continuing to time.." From aezell at gmail.com Wed Oct 24 23:39:06 2007 From: aezell at gmail.com (Alex Ezell) Date: Wed, 24 Oct 2007 16:39:06 -0500 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <71dd7f400710241436i28dea4dfy9408786f2523f45a@mail.gmail.com> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> <471F7815.7070701@tds.net> <71dd7f400710241135n56c5e07eke4a526cc30757a5f@mail.gmail.com> <471F9DE7.70407@tds.net> <71dd7f400710241315m5da2e533l4d672233900c8b4f@mail.gmail.com> <71dd7f400710241436i28dea4dfy9408786f2523f45a@mail.gmail.com> Message-ID: <71dd7f400710241439m1d1894dclfba4ef5d3afaa280@mail.gmail.com> Oops, meant to send to the list. Sorry, Kent. > > > >>> I am working on building a SOAP client. Unfortunately, one of the > > > >>> methods the SOAP server provides is named "import." The SOAP server is > > > >>> written in PHP. > > > >>> > > > >>> So, my problem is that Python really doesn't like me using the word > > > >>> "import" to call the SOAP method. The call should look something like > > > >>> this: > > > >>> > > > >>> self.call_response = self.soap.import(self.soap_auth, file_name, > > > >>> import_groups, soap_flags) > > > >>> > > > >>> Is there any way to call this method despite it's name being a reserved word. > > > >> You could try introspection: > > > >> > > > >> importFunc = getattr(self.soap, 'import') > > > >> self.call_response = importFunc(self.soap_auth, file_name, > > > >> import_groups, soap_flags) > > > > > > > > Thanks Kent. I tried it and it seem like importFunc is now something > > > > like 'import.__str__'. I could maybe do some string operations to just > > > > get import out of that, but is there something I could do with > > > > getattr() for that reference to come back the way I need. > > > > > > Hmm, with a quick look at the code for SOAPpy (v 0.11.6) I don't see why > > > the getattr() method would not work. Can you show the code you tried and > > > why you think the result was a string? > > > > > > BTW pulling 'import' out of the string won't help; you need the import > > > *function*. > > > > Got ya on the string bit. That was actually my fault. I think I am the > > victim of my own poorly written exception handling method. Or at > > least, I can't correctly read the errors that it tells me. :) > > > > The introspection bit you offered seems to work fine. The error is now > > within the call to the SOAP server. > > > > Sorry for getting everyone confused. I'm off to ask my fellow > > developer if the SOAP server really does what it says does since she > > wrote it :) > > > > /alex Heh, I am still having problems with this. This is the whole method: def importer(self, file_name, import_groups, import_flags): soap_flags = self.dict_to_key_value(import_flags) try: # TODO figure out how to call this soap method with reserved name self.call_response = self.soap.import(self.soap_auth, file_name, import_groups, soap_flags) except Exception, e: method_name = sys._getframe().f_code.co_name method_args = '(%s,%s,%s)' %(file_name,str(import_groups),str(import_flags)) self.handle_exception(method_name + method_args,e) raise return self.call_response I tried to replace the import() call with these two lines: importFunc = getattr(self.soap, 'import') self.call_response = self.soap.importFunc(self.soap_auth, file_name, import_groups, soap_flags) and this was the error: AttributeError: importFunc module body in sync_members.py at line 143 function main in sync_members.py at line 138 function sforce_to_members in sync_members.py at line 80 function do_import in sync_members.py at line 70 function importer in emma_ws.py at line 84 function __getattr__ in WSDL.py at line 96 Thanks again for working with me this far. I am certainly on the very precipitous edge of my Python "knowledge." /alex From kent37 at tds.net Thu Oct 25 00:16:03 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Oct 2007 18:16:03 -0400 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <71dd7f400710241439m1d1894dclfba4ef5d3afaa280@mail.gmail.com> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> <471F7815.7070701@tds.net> <71dd7f400710241135n56c5e07eke4a526cc30757a5f@mail.gmail.com> <471F9DE7.70407@tds.net> <71dd7f400710241315m5da2e533l4d672233900c8b4f@mail.gmail.com> <71dd7f400710241436i28dea4dfy9408786f2523f45a@mail.gmail.com> <71dd7f400710241439m1d1894dclfba4ef5d3afaa280@mail.gmail.com> Message-ID: <471FC423.4070408@tds.net> Alex Ezell wrote: > # TODO figure out how to call this soap method with reserved name > self.call_response = self.soap.import(self.soap_auth, > file_name, import_groups, soap_flags) > I tried to replace the import() call with these two lines: > importFunc = getattr(self.soap, 'import') > self.call_response = self.soap.importFunc(self.soap_auth, file_name, > import_groups, soap_flags) this should be self.call_response = importFunc(self.soap_auth, file_name, import_groups, soap_flags) importFunc *is* the function you want to call, it is not an attribute of self.soap. Kent From aezell at gmail.com Thu Oct 25 00:19:16 2007 From: aezell at gmail.com (Alex Ezell) Date: Wed, 24 Oct 2007 17:19:16 -0500 Subject: [Tutor] Calling a Method with a Reserved Name In-Reply-To: <471FC423.4070408@tds.net> References: <71dd7f400710240939t3de4d996q7e45b77e94ed5607@mail.gmail.com> <471F7815.7070701@tds.net> <71dd7f400710241135n56c5e07eke4a526cc30757a5f@mail.gmail.com> <471F9DE7.70407@tds.net> <71dd7f400710241315m5da2e533l4d672233900c8b4f@mail.gmail.com> <71dd7f400710241436i28dea4dfy9408786f2523f45a@mail.gmail.com> <71dd7f400710241439m1d1894dclfba4ef5d3afaa280@mail.gmail.com> <471FC423.4070408@tds.net> Message-ID: <71dd7f400710241519j7b36040aga17089e474f201d2@mail.gmail.com> On 10/24/07, Kent Johnson <kent37 at tds.net> wrote: > Alex Ezell wrote: > > > # TODO figure out how to call this soap method with reserved name > > self.call_response = self.soap.import(self.soap_auth, > > file_name, import_groups, soap_flags) > > > I tried to replace the import() call with these two lines: > > importFunc = getattr(self.soap, 'import') > > self.call_response = self.soap.importFunc(self.soap_auth, file_name, > > import_groups, soap_flags) > > this should be > self.call_response = importFunc(self.soap_auth, file_name, > import_groups, soap_flags) > > importFunc *is* the function you want to call, it is not an attribute of > self.soap. > > Kent Awesome. I knew I had just been looking at it for too long. Thanks so much, Kent! Maybe one day, I will help you with something. ;) /alex From alan.gauld at btinternet.com Thu Oct 25 01:04:19 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Oct 2007 00:04:19 +0100 Subject: [Tutor] Looking to improve my stopWatch.py References: <20071024144708.1CFB61E400F@bag.python.org> <ea979d70710240846r430b2d02u1a52522e79ec4e3e@mail.gmail.com> Message-ID: <ffoj1o$39v$1@ger.gmane.org> "bhaaluu" <bhaaluu at gmail.com> wrote >>>> import msvcrt > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ImportError: No module named msvcrt >>>> You are on Linux so you'll need to port it to use curses instead of msvcrt... Alan G From bhaaluu at gmail.com Thu Oct 25 02:14:22 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 24 Oct 2007 20:14:22 -0400 Subject: [Tutor] Looking to improve my stopWatch.py In-Reply-To: <ffoj1o$39v$1@ger.gmane.org> References: <20071024144708.1CFB61E400F@bag.python.org> <ea979d70710240846r430b2d02u1a52522e79ec4e3e@mail.gmail.com> <ffoj1o$39v$1@ger.gmane.org> Message-ID: <ea979d70710241714p2e167d1axf2a8e512102d5623@mail.gmail.com> On 10/24/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > "bhaaluu" <bhaaluu at gmail.com> wrote > > >>>> import msvcrt > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > ImportError: No module named msvcrt > >>>> > > You are on Linux so you'll need to port it to use curses instead of > msvcrt... > > Alan G Thanks Alan! I had absolutely no clue what mscrt was. >>> help ("curses") Whew! There's quite a bit in that one! -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From bryan.fodness at gmail.com Thu Oct 25 04:15:17 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Wed, 24 Oct 2007 22:15:17 -0400 Subject: [Tutor] trouble with if Message-ID: <fbf64d2b0710241915k6f0ff2ccke77b9ab056c04b3c@mail.gmail.com> I have the following code, it keeps giving me a value of 1 for e. for line in file('21Ex6MV_oaf.dat'): oa, openoa, w15, w30, w45, w60 = line.split() if (float(oa) == round(offaxis)) and (eff_depth < 10 and unblockedFS > 15): e = float(openoa) else: e = 1 If I comment out the else, I get the correct value for line in file('21Ex6MV_oaf.dat'): oa, openoa, w15, w30, w45, w60 = line.split() if (float(oa) == round(offaxis)) and (eff_depth < 10 and unblockedFS > 15): e = float(openoa) # else: # e = 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071024/a69b30eb/attachment.htm From john at fouhy.net Thu Oct 25 04:25:47 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 25 Oct 2007 15:25:47 +1300 Subject: [Tutor] trouble with if In-Reply-To: <fbf64d2b0710241915k6f0ff2ccke77b9ab056c04b3c@mail.gmail.com> References: <fbf64d2b0710241915k6f0ff2ccke77b9ab056c04b3c@mail.gmail.com> Message-ID: <5e58f2e40710241925q3da48d0cxcb9bf26987664849@mail.gmail.com> On 25/10/2007, Bryan Fodness <bryan.fodness at gmail.com> wrote: > I have the following code, it keeps giving me a value of 1 for e. > > for line in file('21Ex6MV_oaf.dat'): > oa, openoa, w15, w30, w45, w60 = line.split() > if (float(oa) == round(offaxis)) and (eff_depth < 10 and unblockedFS > > 15): > e = float(openoa) > else: > e = 1 > > If I comment out the else, I get the correct value > > for line in file('21Ex6MV_oaf.dat'): > oa, openoa, w15, w30, w45, w60 = line.split() > if (float(oa) == round(offaxis)) and (eff_depth < 10 and unblockedFS > > 15): > e = float(openoa) > # else: > # e = 1 Maybe you need a 'break' statement after 'e = float(openoa)'? As written, e will have whatever value is appropriate for the last line of your input file. -- John. From rdm at rcblue.com Thu Oct 25 06:00:23 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 24 Oct 2007 21:00:23 -0700 Subject: [Tutor] Looking to improve my stopWatch.py In-Reply-To: <471FB5CB.6050203@alum.rpi.edu> References: <20071024144708.1CFB61E400F@bag.python.org> <471FB5CB.6050203@alum.rpi.edu> Message-ID: <20071025040034.A7EFC1E4009@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071024/5131e838/attachment-0001.htm From john at fouhy.net Thu Oct 25 06:41:50 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 25 Oct 2007 17:41:50 +1300 Subject: [Tutor] Looking to improve my stopWatch.py In-Reply-To: <20071025040034.A7EFC1E4009@bag.python.org> References: <20071024144708.1CFB61E400F@bag.python.org> <471FB5CB.6050203@alum.rpi.edu> <20071025040034.A7EFC1E4009@bag.python.org> Message-ID: <5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.com> On 25/10/2007, Dick Moores <rdm at rcblue.com> wrote: > I'm wondering about "if lapTimeFlag:". Following "The Zen of Python", by > Tim Peters ("Explicit is better than implicit"), isn't "if lapTimeFlag == > True" preferable? No :-) Otherwise, maybe we should make it even more explicit: if (lapTimeFlag == True) == True: ...but that still requires the reader to understand that the body of the if: block will only execute if ((lapTimeFlag == True) == True) == True.. (hmm, reminds me of Lewis Carroll's modus ponens paradox) -- John. From samrobertsmith at gmail.com Thu Oct 25 07:16:09 2007 From: samrobertsmith at gmail.com (linda.s) Date: Wed, 24 Oct 2007 22:16:09 -0700 Subject: [Tutor] where is the function from Message-ID: <1d987df30710242216v6296e98eyd94d202b8a43bf39@mail.gmail.com> How can I know where a function such as abc is from (from which module)? >>> abc <built-in function abc> From detroit371 at gmail.com Thu Oct 25 06:45:38 2007 From: detroit371 at gmail.com (Lawrence Shafer) Date: Wed, 24 Oct 2007 23:45:38 -0500 Subject: [Tutor] underlying C/C++ object has been deleted Message-ID: <47201F72.3010600@gmail.com> I am trying to convert a program with hand coded QT over to using UI files from QT Designer. I am getting the error below and do not understand what's going on. I have a feeling I need to add self. to something in here, but I'm not sure what. Is this enough code for you to see whats going on?? If not I can upload the project somewhere. Thanks, Lawrence The error, Traceback (most recent call last): File "atf.py", line 113, in on_actionOpen_triggered self.open() File "atf.py", line 56, in open if self.isUntitled and self.textBrowser.document().isEmpty() and not self.isWindowModified(): RuntimeError: underlying C/C++ object has been deleted Here is the first part of the code. #!/usr/bin/env python # iaC.py - A Qt4 Calculator example import sys from math import pi from PyQt4 import QtCore, QtGui from iac_ui import Ui_mainWindow from filterEdit2_ui import Ui_filterEdit class iaC(QtGui.QMainWindow): sequenceNumber = 1 windowList = [] @QtCore.pyqtSignature("") def __init__(self, fileName=None, parent=None): QtGui.QMainWindow.__init__(self, parent) self.init() if fileName: self.loadFile(fileName) else: self.setCurrentFile(QtCore.QString()) self.ui = Ui_mainWindow() self.ui.setupUi(self) # ================Set up delete, up, and down buttons on the main form================== if self.ui.listWidget.count() < 1: self.ui.deleteButton.setEnabled(False) else: self.ui.deleteButton.setEnabled(True) if self.ui.listWidget.count() < 2: self.ui.upButton.setEnabled(False) self.ui.downButton.setEnabled(False) else: self.ui.downButton.setEnabled(True) self.ui.upButton.setEnabled(True) # ================Save settings on close?======================================= def closeEvent(self, event): if self.maybeSave(): self.writeSettings() event.accept() else: event.ignore() # ===============Open File================================================= @QtCore.pyqtSignature("") def open(self): fileName = QtGui.QFileDialog.getOpenFileName(self) print "Loading fileName", fileName if not fileName.isEmpty(): if self.isUntitled and self.textBrowser.document().isEmpty() and not self.isWindowModified(): self.loadFile(fileName) else: other = MainWindow(fileName) if other.isUntitled: del other return From brunson at brunson.com Thu Oct 25 07:28:32 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 24 Oct 2007 23:28:32 -0600 Subject: [Tutor] where is the function from In-Reply-To: <1d987df30710242216v6296e98eyd94d202b8a43bf39@mail.gmail.com> References: <1d987df30710242216v6296e98eyd94d202b8a43bf39@mail.gmail.com> Message-ID: <47202980.5090802@brunson.com> linda.s wrote: > How can I know where a function such as abc is from (from which module)? > >>>> abc >>>> > <built-in function abc> > You could: 1. look it up in the index of the library reference (http://www.python.org/doc/current/lib/genindex.html), 2. try "pydoc", 3. examine abc.__module__ Let us know if none of those help. e. From rdm at rcblue.com Thu Oct 25 08:06:11 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 24 Oct 2007 23:06:11 -0700 Subject: [Tutor] Looking to improve my stopWatch.py In-Reply-To: <5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.co m> References: <20071024144708.1CFB61E400F@bag.python.org> <471FB5CB.6050203@alum.rpi.edu> <20071025040034.A7EFC1E4009@bag.python.org> <5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.com> Message-ID: <20071025060618.9096E1E4473@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071024/56e76419/attachment.htm From swartmumba at yahoo.com Thu Oct 25 08:59:28 2007 From: swartmumba at yahoo.com (SwartMumba snake) Date: Wed, 24 Oct 2007 23:59:28 -0700 (PDT) Subject: [Tutor] urllib2 and cookies Message-ID: <982618.46736.qm@web44810.mail.sp1.yahoo.com> I want to read the html source off a site but the site requires cookies. What code must I use to handle my cookies, instead of me typing them out? NB I want to use urllib2 to open the site, not urllib. I am currently using python 2.5 This is what I have done so far, but I do not want to type out all the cookies. import urllib2 data = urllib2.Request(url = "http://www.example.com", data = 'COOKIE:<xx;xx...>') htmlSource = urllib2.urlopen(data).read() Thanks in advance... __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071024/30fd6d8a/attachment.htm From alan.gauld at btinternet.com Thu Oct 25 09:13:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Oct 2007 08:13:34 +0100 Subject: [Tutor] Looking to improve my stopWatch.py References: <20071024144708.1CFB61E400F@bag.python.org><ea979d70710240846r430b2d02u1a52522e79ec4e3e@mail.gmail.com><ffoj1o$39v$1@ger.gmane.org> <ea979d70710241714p2e167d1axf2a8e512102d5623@mail.gmail.com> Message-ID: <ffpfn3$6jn$1@ger.gmane.org> "bhaaluu" <bhaaluu at gmail.com> wrote > I had absolutely no clue what mscrt was. The MicroSoftVisualCRunTime library. >>>> help ("curses") > > Whew! > There's quite a bit in that one! Yep its a full "Gui" toolkit for text based terminals. Fortunately you only need a couple of functions. Check out my Event Driven Programming topic for a very simple example using msvcrt/curses. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Oct 25 09:17:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Oct 2007 08:17:27 +0100 Subject: [Tutor] Looking to improve my stopWatch.py References: <20071024144708.1CFB61E400F@bag.python.org><471FB5CB.6050203@alum.rpi.edu><20071025040034.A7EFC1E4009@bag.python.org><5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.com> <5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.co m> <20071025060618.9096E1E4473@bag.python.org> Message-ID: <ffpfuc$77d$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > > Tim Peters ("Explicit is better than implicit"), isn't "if > lapTimeFlag == > > True" preferable? > > if (lapTimeFlag == True) == True: > > Well, how about "Readability counts"? Thats the point. By calling the variable a "Flag" you are implying that it is a boolean that can only be True/False thus if Flag: is completely readable. There is no need for the == True part. The same is true of a predicate function. By naming it isXXX you imply that it is a predicate and returns True/False so you can write if isXXX(): rather than if isXXX() == True: HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Oct 25 09:27:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Oct 2007 08:27:51 +0100 Subject: [Tutor] underlying C/C++ object has been deleted References: <47201F72.3010600@gmail.com> Message-ID: <ffpghs$8v5$1@ger.gmane.org> "Lawrence Shafer" <detroit371 at gmail.com> wrote > files from QT Designer. I am getting the error below and do not > understand what's going on. Neither do I but try debugging it to find out which object causes the error > File "atf.py", line 56, in open > if self.isUntitled and self.textBrowser.document().isEmpty() and > not > self.isWindowModified(): > RuntimeError: underlying C/C++ object has been deleted That line refers to 3 objects (not counting self) Try splitting it so: if self.isUntitled: if self.textBrowser: d = self.TextBrowser.document() if d.isEmpty(): if self.isWindowModified(): # your code here... Should return the error at the line with the dead reference Alternatively use a debugger (IDLE/winpdb?) to stop at the line immediately before the if test and examoine the various values. Once you know which object is the problem you have some chance of fiinding out why... Beyond that I can't help since I've never used Qt. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Oct 25 09:35:04 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Oct 2007 08:35:04 +0100 Subject: [Tutor] where is the function from References: <1d987df30710242216v6296e98eyd94d202b8a43bf39@mail.gmail.com> Message-ID: <ffpgvd$a90$1@ger.gmane.org> "linda.s" <samrobertsmith at gmail.com> wrote > How can I know where a function such as abc is from (from which > module)? >>>> abc > <built-in function abc> <Obligitary Lecture> Look at your import statements. Provided you have nbeen using recommended practice you will have used from module import name1,name2,... or just import module. If the latter you need to access abc as module.abc So you know which module its from - thats why its the recommended approach - after all more than one module may have an abc.... OTOH if you used the non recommended from module import * You're left guessing... </End Lecture :-) > Although you can use introspection from Python to find out. try: >>> import sys >>> sys.exit <built-in function exit> >>> sys.exit.__module__ 'sys' >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Thu Oct 25 09:54:03 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 25 Oct 2007 00:54:03 -0700 Subject: [Tutor] Looking to improve my stopWatch.py In-Reply-To: <ffpfuc$77d$1@ger.gmane.org> References: <20071024144708.1CFB61E400F@bag.python.org> <471FB5CB.6050203@alum.rpi.edu> <20071025040034.A7EFC1E4009@bag.python.org> <5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.com> <5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.co m> <20071025060618.9096E1E4473@bag.python.org> <ffpfuc$77d$1@ger.gmane.org> Message-ID: <20071025075417.3360E1E400A@bag.python.org> At 12:17 AM 10/25/2007, Alan Gauld wrote: >"Dick Moores" <rdm at rcblue.com> wrote > > > > Tim Peters ("Explicit is better than implicit"), isn't "if > > lapTimeFlag == > > > True" preferable? > > > > if (lapTimeFlag == True) == True: > > > > Well, how about "Readability counts"? > >Thats the point. >By calling the variable a "Flag" you are implying that >it is a boolean that can only be True/False thus > >if Flag: > >is completely readable. There is no need for the == True part. > >The same is true of a predicate function. By naming it >isXXX you imply that it is a predicate and returns True/False >so you can write > >if isXXX(): > >rather than > >if isXXX() == True: Got it. Thanks, Alan. I've also seen things like this: >>> a = [] >>> if not a: ... print 'a is empty' ... a is empty >>> Isn't this preferable?: >>> a = [] >>> if a == []: ... print 'a is empty' ... a is empty >>> Dick From meiermic at ee.ethz.ch Thu Oct 25 10:26:39 2007 From: meiermic at ee.ethz.ch (Michael Meier) Date: Thu, 25 Oct 2007 10:26:39 +0200 Subject: [Tutor] urllib2 and cookies Message-ID: <1193300799.23336.4.camel@tardis-b04.ee.ethz.ch> Hi ASPN has a very verbose example of cookielib usage at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 Many things are very OS, especially Windows, specific. You can surely phase out the relevant parts :) Probably the solution with cookielib is the easiest way to go. Cookielib is documented at http://docs.python.org/lib/module-cookielib.html Cheers, Michael From kent37 at tds.net Thu Oct 25 12:51:29 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Oct 2007 06:51:29 -0400 Subject: [Tutor] Looking to improve my stopWatch.py In-Reply-To: <20071025075417.3360E1E400A@bag.python.org> References: <20071024144708.1CFB61E400F@bag.python.org> <471FB5CB.6050203@alum.rpi.edu> <20071025040034.A7EFC1E4009@bag.python.org> <5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.com> <5e58f2e40710242141y4b1017fax1e941b7fddfd3e94@mail.gmail.co m> <20071025060618.9096E1E4473@bag.python.org> <ffpfuc$77d$1@ger.gmane.org> <20071025075417.3360E1E400A@bag.python.org> Message-ID: <47207531.6080004@tds.net> Dick Moores wrote: > I've also seen things like this: > >>> a = [] > >>> if not a: > ... print 'a is empty' > ... > a is empty > >>> > > Isn't this preferable?: > >>> a = [] > >>> if a == []: > ... print 'a is empty' > ... > a is empty I like the simplicity and consistency of if a or if not a which will test for empty if a is a list, dict, string or set. Of course strictly speaking if a and if a == [] are not equivalent unless you can guarantee that a references a list (not None or any other kind of object) but for many purposes they are. Kent Kent From kent37 at tds.net Thu Oct 25 13:01:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Oct 2007 07:01:36 -0400 Subject: [Tutor] urllib2 and cookies In-Reply-To: <1193300799.23336.4.camel@tardis-b04.ee.ethz.ch> References: <1193300799.23336.4.camel@tardis-b04.ee.ethz.ch> Message-ID: <47207790.50509@tds.net> Michael Meier wrote: > Hi > > ASPN has a very verbose example of cookielib usage at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 There is a writeup of this recipe here: http://www.voidspace.org.uk/python/articles/cookielib.shtml This is way more complicated than you need, though, at least if you are using Python 2.4 or 2.5 you can just use cookielib. The first example here shows how simple it can be: http://docs.python.org/lib/cookielib-examples.html Note that you may have to open two pages with the same urlopener - the page that sets the cookie (perhaps a login page?) and the page that requires the cookie. Kent From detroit371 at gmail.com Thu Oct 25 16:50:52 2007 From: detroit371 at gmail.com (Lawrence Shafer) Date: Thu, 25 Oct 2007 09:50:52 -0500 Subject: [Tutor] underlying C/C++ object has been deleted In-Reply-To: <47201F72.3010600@gmail.com> References: <47201F72.3010600@gmail.com> Message-ID: <4720AD4C.8040200@gmail.com> Here's the whole code. Any help appreciated! http://shaferlabs.pastebin.com/m32c82193 Also I was thinking I could set the progressbar to 64% like this. self.progressBar.setProperty("value",QtCore.QVariant(64)) but it doesn't work. (AttributeError: progressBar) I think it has something to do with some stupid way I'm initializing the iac_ui.py file. Like I said, I'm not used to QTDesigner and complex programs like this. Again, any help appreciated! Lawrence Shafer wrote: > I am trying to convert a program with hand coded QT over to using UI > files from QT Designer. I am getting the error below and do not > understand what's going on. I have a feeling I need to add self. to > something in here, but I'm not sure what. Is this enough code for you to > see whats going on?? If not I can upload the project somewhere. Thanks, > Lawrence > > The error, > > Traceback (most recent call last): > File "atf.py", line 113, in on_actionOpen_triggered > self.open() > File "atf.py", line 56, in open > if self.isUntitled and self.textBrowser.document().isEmpty() and not > self.isWindowModified(): > RuntimeError: underlying C/C++ object has been deleted > > > Here is the first part of the code. > > #!/usr/bin/env python > # iaC.py - A Qt4 Calculator example > > import sys > from math import pi > from PyQt4 import QtCore, QtGui > from iac_ui import Ui_mainWindow > from filterEdit2_ui import Ui_filterEdit > > > class iaC(QtGui.QMainWindow): > sequenceNumber = 1 > windowList = [] > > @QtCore.pyqtSignature("") > def __init__(self, fileName=None, parent=None): > QtGui.QMainWindow.__init__(self, parent) > > self.init() > if fileName: > self.loadFile(fileName) > else: > self.setCurrentFile(QtCore.QString()) > > self.ui = Ui_mainWindow() > self.ui.setupUi(self) > > # ================Set up delete, up, and down buttons on the main > form================== > if self.ui.listWidget.count() < 1: > self.ui.deleteButton.setEnabled(False) > else: > self.ui.deleteButton.setEnabled(True) > > if self.ui.listWidget.count() < 2: > self.ui.upButton.setEnabled(False) > self.ui.downButton.setEnabled(False) > else: > self.ui.downButton.setEnabled(True) > self.ui.upButton.setEnabled(True) > > # ================Save settings on > close?======================================= > def closeEvent(self, event): > if self.maybeSave(): > self.writeSettings() > event.accept() > else: > event.ignore() > > # ===============Open File================================================= > @QtCore.pyqtSignature("") > def open(self): > fileName = QtGui.QFileDialog.getOpenFileName(self) > print "Loading fileName", fileName > if not fileName.isEmpty(): > > if self.isUntitled and self.textBrowser.document().isEmpty() > and not self.isWindowModified(): > self.loadFile(fileName) > else: > other = MainWindow(fileName) > if other.isUntitled: > del other > return > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rdm at rcblue.com Thu Oct 25 18:33:58 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 25 Oct 2007 09:33:58 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code Message-ID: <20071025163428.A2F241E400A@bag.python.org> Please give me constructive criticism of <http://www.rcblue.com/Python/chessTimerForWebV6.py> Thanks, Dick From bryan.fodness at gmail.com Thu Oct 25 21:34:55 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Thu, 25 Oct 2007 15:34:55 -0400 Subject: [Tutor] rounding to the nearest 0.5 Message-ID: <fbf64d2b0710251234u2abfe8f1mb0e8d6aa28d84344@mail.gmail.com> Is there a built-in function that will round to the nearest 0.5? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071025/0a1c771f/attachment.htm From brunson at brunson.com Thu Oct 25 22:20:28 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 25 Oct 2007 14:20:28 -0600 Subject: [Tutor] rounding to the nearest 0.5 In-Reply-To: <fbf64d2b0710251234u2abfe8f1mb0e8d6aa28d84344@mail.gmail.com> References: <fbf64d2b0710251234u2abfe8f1mb0e8d6aa28d84344@mail.gmail.com> Message-ID: <4720FA8C.4090109@brunson.com> Bryan Fodness wrote: > > Is there a built-in function that will round to the nearest 0.5? Not that I know of, but "round( 2 * n ) / 2" will give you what you're looking for. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From conorleister at gmail.com Fri Oct 26 00:36:03 2007 From: conorleister at gmail.com (Conor Leister) Date: Thu, 25 Oct 2007 18:36:03 -0400 Subject: [Tutor] Using dictionary to find the mode of a list Message-ID: <34c4a10a0710251536u380de279x431590ef3ef1eec6@mail.gmail.com> I'm just trying to get the mode of a list. Here's the code I have that gathers the data and sorts it. i just need to be able to get the mode of a using a dictionary and i can't seem to figure out anything. i'm completely lost. this code works fine, i just need to add to it and i'm not great with dictionaries. #gather data a=[] prompt='Enter numbers, blank line to finish:' inVal=raw_input(prompt) while inVal: a.append(int(inVal)) inVal=raw_input(prompt) print 'The values you entered:' print a #Bubble Sort i=0 while i<len(a): j=1 while j<len(a)-i: if a[j-1]>a[j]: temp=a[j] a[j]=a[j-1] a[j-1]=temp j=j+1 i=i+1 print 'Values sorted: ' ,a -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071025/dea93b69/attachment.htm From ricaraoz at gmail.com Fri Oct 26 01:26:24 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 25 Oct 2007 20:26:24 -0300 Subject: [Tutor] How to implement function like this? In-Reply-To: <471EAA86.4030505@tds.net> References: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> <471DF6EF.6010108@bigfoot.com> <471EAA86.4030505@tds.net> Message-ID: <47212620.9040904@bigfoot.com> Kent Johnson wrote: > Ricardo Ar?oz wrote: >> Yinghe Chen wrote: >>> Hello gurus, >>> >>> I have a question, a function like below, it is implemented by me, :) >>> >>> def funcA(tarray): >>> a = [2,3,4] >>> if len(tarray) >=3: >>> return a[0],a[1], a[2] >>> elif len(tarray) == 2: >>> return a[0],a[1], funcB(1)[0] >>> elif len(tarray) == 1: >>> return a[0], funcB(2)[0], funcB(2)[1] >>> else: >>> return funcB(3)[0], funcB(3)[1], funcB(3)[2] > >> def funcA(tArray) : >> a = [2,3,4] >> L = min(len(tArray), 3) >> return tuple(i for n, i in enumerate(a) if n < >> L)+tuple(funcB(len(a)-L)) > > tuple(i for n, i in enumerate(a) if n < L) can be written > tuple(a[:L]) Doh... Of course! Your code is much nicer. > > funcB(len(a)-L) does not do what the OP requested. For example if len(a) > is 10, L will be 3 and you will call funcB(7). > Don't get it. The 3 is because the len(a) is 3, notice that a is hard coded and not a parameter. If you change 'a' then you should change the code accordingly. Anyway the confusion is the mixing of len(a) and 3 in the same code, it should probably be either 3 or len(a) all along, but that should be asked to the OP. Let's say we decide to use len(a), then the code would end up like : def funcA(tArray) : a = [2,3,4] L = min(len(tArray), len(a)) return tuple(a[:L]) + tuple(funcB(len(a) - L)) Too tired right now to check if it's ok. Cheers. From ricaraoz at gmail.com Fri Oct 26 01:34:06 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 25 Oct 2007 20:34:06 -0300 Subject: [Tutor] calling a variable name In-Reply-To: <471F22D8.6060504@tds.net> References: <fbf64d2b0710211956s2f2bc209m2846991aed80a247@mail.gmail.com> <ffhk2n$c59$1@ger.gmane.org> <fbf64d2b0710220357v483edd9do8cd072e1a81ed5e6@mail.gmail.com> <471C8D89.5080902@tds.net> <fbf64d2b0710220751l3968920er337e39586bf3024e@mail.gmail.com> <471CBB1F.30905@tds.net> <471DEB17.9080208@bigfoot.com> <471EA990.60606@tds.net> <20071024035532.GB66963@cutter.rexx.com> <471F22D8.6060504@tds.net> Message-ID: <472127EE.9040600@bigfoot.com> Kent Johnson wrote: > Dave Kuhlman wrote: >> On Tue, Oct 23, 2007 at 10:10:24PM -0400, Kent Johnson wrote: >> >> [snip] >> >>> Perhaps I was a bit hasty. >>> >>> Lists are implemented as arrays of references. I believe they are >>> - amortized O(1) for append - occasionally the list must be reallocated >>> and copied >> OK. I'm groping here. Wikipedia tells me that O(1) means constant >> increase. So, what does "amortized O(1)" mean. >> >> My understanding is that appending in lists is optimized in the >> sense that when more space is needed, Python allocates space for >> additional elements so that allocation does not need to happen at >> every append. Here is a comment from the Python source code >> (Python-2.5.1/Objects/listobject.c): >> >> /* This over-allocates proportional to the list size, making room >> * for additional growth. The over-allocation is mild, but is >> * enough to give linear-time amortized behavior over a long >> * sequence of appends() in the presence of a poorly-performing >> * system realloc(). >> * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... >> */ >> >> Hmmm. There is that "amortized" thing again. Very suspicious. >> For a non-math and non-financial type like me, is it sort of like >> saying that the costs are averaged out over a sequence of appends? > > Yes, that is exactly right. Most of the time - when there is room at the > end of the allocated block - append is O(1) and very fast. Occasionally, > when there is not enough room, append is O(n) and slow, requiring the > entire list to be copied. Because the size of the new allocation is > proportional to the size of the list, the reallocation happens only each > 1/n appends, so if you average out the cost of the reallocation, each > append is O(1) (with a higher constant). That is what amortized cost > means - sometimes the cost is greater than the specified cost but it > averages out. > > Note that if the reallocation added a fixed amount of extra space each > time the cost would not average out over n inserts and it would not be > O(1) amortized cost. It's important that the new allocation be > proportional to the existing space. > Actually if you would come to the point you need to make a distinction between amotized O(1) and O(1) then you will certainly be concerned with the initial amount of allocation and with the proportional constant. From alan.gauld at btinternet.com Fri Oct 26 01:58:13 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Oct 2007 00:58:13 +0100 Subject: [Tutor] Using dictionary to find the mode of a list References: <34c4a10a0710251536u380de279x431590ef3ef1eec6@mail.gmail.com> Message-ID: <ffraiq$go$1@ger.gmane.org> "Conor Leister" <conorleister at gmail.com> wrote > Here's the code I have that gathers the data and sorts it. My first question is why are you writing a bubble sort routine for your list? In almost every conceivable case the built-in sort method will be faster. > be able to get the mode of a using a dictionary > i'm completely lost. this code works fine, i just need to add > to it and i'm not great with dictionaries. If it works fine why do you need to add to it? And what do you find difficult with dictionaries? I'm not clear what exactly the problem is with which you want us to help you. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > > #gather data > a=[] > prompt='Enter numbers, blank line to finish:' > inVal=raw_input(prompt) > while inVal: > a.append(int(inVal)) > inVal=raw_input(prompt) > print 'The values you entered:' > print a > > #Bubble Sort > i=0 > while i<len(a): > j=1 > while j<len(a)-i: > if a[j-1]>a[j]: > temp=a[j] > a[j]=a[j-1] > a[j-1]=temp > j=j+1 > i=i+1 > print 'Values sorted: ' ,a > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Fri Oct 26 04:48:22 2007 From: samrobertsmith at gmail.com (linda.s) Date: Thu, 25 Oct 2007 19:48:22 -0700 Subject: [Tutor] about Tix Message-ID: <1d987df30710251948h2f2d4fbbtb94bafb0c2e01ec2@mail.gmail.com> I run the following code in Python 2.5 and got the error (when I do "import Tix", no error). Traceback (most recent call last): File "2.py", line 54, in <module> tkRoot = Tix.Tk( ) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", line 210, in __init__ self.tk.eval('package require Tix') _tkinter.TclError: can't find package Tix Source code: from __future__ import with_statement # <-- Python 2.5 ONLY import Tix import time class SplashScreen( object ): def __init__( self, tkRoot, imageFilename, minSplashTime=0 ): self._root = tkRoot self._image = Tix.PhotoImage( file=image ) self._splash = None self._minSplashTime = time.time() + minSplashTime def __enter__( self ): # Remove the app window from the display self._root.withdraw( ) # Calculate the geometry to center the splash image scrnWt = self._root.winfo_screenwidth( ) scrnHt = self._root.winfo_screenheight( ) imgWt = self._image.width() imgHt = self._image.height() imgXPos = (scrnWt / 2) - (imgWt / 2) imgYPos = (scrnHt / 2) - (imgHt / 2) # Create the splash screen self._splash = Tix.Toplevel() self._splash.overrideredirect(1) self._splash.geometry( '+%d+%d' % (imgXPos, imgYPos) ) Tix.Label( self._splash, image=self._image, cursor='watch' ).pack( ) # Force Tk to draw the splash screen outside of mainloop() self._splash.update( ) def __exit__( self, exc_type, exc_value, traceback ): # Make sure the minimum splash time has elapsed timeNow = time.time() if timeNow < self._minSplashTime: time.sleep( self._minSplashTime - timeNow ) # Destroy the splash window self._splash.destroy( ) # Display the application window self._root.deiconify( ) #-------------------------------------------- # Now putting up splash screens is simple # Create the tkRoot window tkRoot = Tix.Tk( ) with SplashScreen( tkRoot, 'splashImage.jpg', 3.0 ): initializeMyApplication( ) buildTheGUI( tkRoot ) tkRoot.mainloop( ) From bryan.fodness at gmail.com Fri Oct 26 05:08:21 2007 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Thu, 25 Oct 2007 23:08:21 -0400 Subject: [Tutor] trouble with if In-Reply-To: <5e58f2e40710241925q3da48d0cxcb9bf26987664849@mail.gmail.com> References: <fbf64d2b0710241915k6f0ff2ccke77b9ab056c04b3c@mail.gmail.com> <5e58f2e40710241925q3da48d0cxcb9bf26987664849@mail.gmail.com> Message-ID: <fbf64d2b0710252008s49ebe3fcg500f5d7e28c3ada@mail.gmail.com> I cannot get this to work either. woffaxis = 7 if woffaxis != 0: woaf_pos = input("What is Wedge Direction (N/A, Lateral, Towards Heal, Towards Toe)?") if woaf_pos == 'Towards Toe': woffaxis = woffaxis elif woaf_pos == 'Towards Heal': woffaxis = (woffaxis * -1) else: woffaxis = 0 On 10/24/07, John Fouhy <john at fouhy.net> wrote: > > On 25/10/2007, Bryan Fodness <bryan.fodness at gmail.com> wrote: > > I have the following code, it keeps giving me a value of 1 for e. > > > > for line in file('21Ex6MV_oaf.dat'): > > oa, openoa, w15, w30, w45, w60 = line.split() > > if (float(oa) == round(offaxis)) and (eff_depth < 10 and unblockedFS > > > > 15): > > e = float(openoa) > > else: > > e = 1 > > > > If I comment out the else, I get the correct value > > > > for line in file('21Ex6MV_oaf.dat'): > > oa, openoa, w15, w30, w45, w60 = line.split() > > if (float(oa) == round(offaxis)) and (eff_depth < 10 and unblockedFS > > > > 15): > > e = float(openoa) > > # else: > > # e = 1 > > Maybe you need a 'break' statement after 'e = float(openoa)'? > > As written, e will have whatever value is appropriate for the last > line of your input file. > > -- > John. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071025/35cee609/attachment.htm From aditya.n.lal at gmail.com Fri Oct 26 08:35:59 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Fri, 26 Oct 2007 12:05:59 +0530 Subject: [Tutor] trouble with if In-Reply-To: <fbf64d2b0710252008s49ebe3fcg500f5d7e28c3ada@mail.gmail.com> References: <fbf64d2b0710241915k6f0ff2ccke77b9ab056c04b3c@mail.gmail.com> <5e58f2e40710241925q3da48d0cxcb9bf26987664849@mail.gmail.com> <fbf64d2b0710252008s49ebe3fcg500f5d7e28c3ada@mail.gmail.com> Message-ID: <5df213700710252335k46eee59rc83e242eceeaa7b7@mail.gmail.com> I think you need to use "raw_input" instead of "input". input "eval" the input expression while "raw_input" just stores it. I find the module help very handy when I am in doubt. >>> print raw_input.__doc__ raw_input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. >>> print input.__doc__ input([prompt]) -> value Equivalent to eval(raw_input(prompt)). On 10/26/07, Bryan Fodness <bryan.fodness at gmail.com> wrote: > > I cannot get this to work either. > > woffaxis = 7 > > if woffaxis != 0: > woaf_pos = input("What is Wedge Direction (N/A, Lateral, Towards > Heal, Towards Toe)?") > > if woaf_pos == 'Towards Toe': > woffaxis = woffaxis > elif woaf_pos == 'Towards Heal': > woffaxis = (woffaxis * -1) > else: > woffaxis = 0 > > > > > > > On 10/24/07, John Fouhy <john at fouhy.net> wrote: > > > > On 25/10/2007, Bryan Fodness <bryan.fodness at gmail.com> wrote: > > > I have the following code, it keeps giving me a value of 1 for e. > > > > > > for line in file('21Ex6MV_oaf.dat'): > > > oa, openoa, w15, w30, w45, w60 = line.split() > > > if (float(oa) == round(offaxis)) and (eff_depth < 10 and > > unblockedFS > > > > 15): > > > e = float(openoa) > > > else: > > > e = 1 > > > > > > If I comment out the else, I get the correct value > > > > > > for line in file('21Ex6MV_oaf.dat'): > > > oa, openoa, w15, w30, w45, w60 = line.split() > > > if (float(oa) == round(offaxis)) and (eff_depth < 10 and > > unblockedFS > > > > 15): > > > e = float(openoa) > > > # else: > > > # e = 1 > > > > Maybe you need a 'break' statement after 'e = float(openoa)'? > > > > As written, e will have whatever value is appropriate for the last > > line of your input file. > > > > -- > > John. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071026/6bba5fb8/attachment.htm From alan.gauld at btinternet.com Fri Oct 26 09:35:00 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Oct 2007 08:35:00 +0100 Subject: [Tutor] trouble with if References: <fbf64d2b0710241915k6f0ff2ccke77b9ab056c04b3c@mail.gmail.com><5e58f2e40710241925q3da48d0cxcb9bf26987664849@mail.gmail.com> <fbf64d2b0710252008s49ebe3fcg500f5d7e28c3ada@mail.gmail.com> Message-ID: <ffs5ba$tnb$1@ger.gmane.org> "Bryan Fodness" <bryan.fodness at gmail.com> wrote >I cannot get this to work either. Brian, when you post please tell us exactly what does not work. If there is an error message send the whole error there is a lot of useful information in them. Otherwise we have to read your code and guess what might be happening. We need both code and error text. The easier you make it for the tutors the more likely you are to get a response! > woffaxis = 7 > > if woffaxis != 0: > woaf_pos = input("What is Wedge Direction (N/A, Lateral, Towards > Heal, > Towards Toe)?") Use raw_input() and convert the result rather than input(). Especially when the input is a string anyhow. Otherwise you are leaving yourself open to scurity breaches and even accidental damage to your data due to mistyping. This is because input() tries to interpret its value as a Python expression. Thus if the user enters a string Pyhon tries to evaluate that string. Unless the usser has put quotes around their input it will probably fail. I suspect that is your problem but without an error message I can't be sure. > if woaf_pos == 'Towards Toe': > woffaxis = woffaxis > elif woaf_pos == 'Towards Heal': > woffaxis = (woffaxis * -1) > else: > woffaxis = 0 Incidentally, you could replace this set of if statements with a dictionary lookup: responses = {"Towards Toe": 1, "Towards Head": -1} woffaxis *= responses.get(woaf_pos,0) Another tip is that when comparing user input to a string its usually better to have the master strings as all uppercase or all lowercase and then convert the input string to all lower case or all upper case as appropriate, and then compare. It reduces user frustration over simple typos. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Oct 26 10:07:07 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Oct 2007 09:07:07 +0100 Subject: [Tutor] about Tix References: <1d987df30710251948h2f2d4fbbtb94bafb0c2e01ec2@mail.gmail.com> Message-ID: <ffs77h$3e2$1@ger.gmane.org> Linda, >I run the following code in Python 2.5 and got the error (when I do > "import Tix", no error). Congratulations I think this might just be the first Tix question on the tutor list! :-) > Traceback (most recent call last): > File "2.py", line 54, in <module> > tkRoot = Tix.Tk( ) > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", > line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: can't find package Tix This looks to me like the Tix DLL hasn't been installed or it's installed in a folder where it can''t be found. The Tix module is just a wrapper round the Tix DLL so you need both. It works OK for me: >>> import Tix as t >>> tk = t.Tk() >>> w = t.Toplevel(tk) >>> b = t.Label(w, text="Hello") >>> b.pack() >>> t.mainloop() However, > from __future__ import with_statement # <-- Python 2.5 ONLY > import Tix > import time > > class SplashScreen( object ): ... > #-------------------------------------------- > # Now putting up splash screens is simple > > # Create the tkRoot window > tkRoot = Tix.Tk( ) > > with SplashScreen( tkRoot, 'splashImage.jpg', 3.0 ): I'm not sure you need the with statement here. (Although this might also be the first tutor example of a custom context manager! Two firsts in one mail...:) Couldn't you just call the SplashScreen directly? Then initialise and build the GUI? Its what I usually do and it seems to work. I'm trying to work out what advantage the with gives? > initializeMyApplication( ) > buildTheGUI( tkRoot ) > > tkRoot.mainloop( ) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Fri Oct 26 11:18:08 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 26 Oct 2007 02:18:08 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071025163428.A2F241E400A@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> Message-ID: <20071026091813.BE7CC1E401F@bag.python.org> At 09:33 AM 10/25/2007, Dick Moores wrote: >Please give me constructive criticism of ><http://www.rcblue.com/Python/chessTimerForWebV6.py> Hmm. Nothing. One problem may be that only people using Windows can run the script. I've developed chessTimer a bit further: <http://www.rcblue.com/Python/chessTimerFischerDelayForWebV2.py> I'm still hoping for some constructive criticism. But I also thought I'd mention the points I have doubts about: 1. Is wrapping the long lines where I have done so OK? 2. I've used 1 for White player, -1 for Black player, and (-1)*player to alternate players. Is there a better way? 3. I've used a lot of variables. Too Many? 4. Should more of the code be in functions? 5. Is there a way to collapse lines 107-114: if player == 1: # player is White whiteMoveCounter += 1 print "Black to make move %d" % (blackMoveCounter) remainingWhiteTime -= timeUsedThisMove elif player == -1: # player is Black blackMoveCounter += 1 print "White to make move %d" % (whiteMoveCounter) remainingBlackTime -= timeUsedThisMove Thanks, Dick Moores From kent37 at tds.net Fri Oct 26 12:28:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Oct 2007 06:28:08 -0400 Subject: [Tutor] Using dictionary to find the mode of a list In-Reply-To: <34c4a10a0710251536u380de279x431590ef3ef1eec6@mail.gmail.com> References: <34c4a10a0710251536u380de279x431590ef3ef1eec6@mail.gmail.com> Message-ID: <4721C138.1010409@tds.net> Conor Leister wrote: > I'm just trying to get the mode of a list. > Here's the code I have that gathers the data and sorts it. i just need > to be able to get the mode of a using a dictionary and i can't seem to > figure out anything. i'm completely lost. this code works fine, i just > need to add to it and i'm not great with dictionaries. OK. The mode is the number that appears the most times, so you need to count how many times each number appears. A dict works well for this; the dict key is the number and the dict value is the count. Can you write a loop through your list that accumulates counts? The next step is to find the largest count. Kent > > #gather data > a=[] > prompt='Enter numbers, blank line to finish:' > inVal=raw_input(prompt) > while inVal: > a.append(int(inVal)) > inVal=raw_input(prompt) > print 'The values you entered:' > print a > > #Bubble Sort > i=0 > while i<len(a): > j=1 > while j<len(a)-i: > if a[j-1]>a[j]: > temp=a[j] > a[j]=a[j-1] > a[j-1]=temp > j=j+1 > i=i+1 > print 'Values sorted: ' ,a > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Oct 26 12:32:50 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Oct 2007 06:32:50 -0400 Subject: [Tutor] How to implement function like this? In-Reply-To: <47212620.9040904@bigfoot.com> References: <6bea4dc50710230121k17cae1cdkb77c086d51713993@mail.gmail.com> <471DF6EF.6010108@bigfoot.com> <471EAA86.4030505@tds.net> <47212620.9040904@bigfoot.com> Message-ID: <4721C252.5010808@tds.net> Ricardo Ar?oz wrote: > Kent Johnson wrote: >> funcB(len(a)-L) does not do what the OP requested. For example if len(a) >> is 10, L will be 3 and you will call funcB(7). >> > > Don't get it. The 3 is because the len(a) is 3, notice that a is hard > coded and not a parameter. If you change 'a' then you should change the > code accordingly. Right, my mistake. Kent From bhaaluu at gmail.com Fri Oct 26 14:00:11 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 26 Oct 2007 08:00:11 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071026091813.BE7CC1E401F@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> Message-ID: <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> Greetings, On 10/26/07, Dick Moores <rdm at rcblue.com> wrote: > At 09:33 AM 10/25/2007, Dick Moores wrote: > >Please give me constructive criticism of > ><http://www.rcblue.com/Python/chessTimerForWebV6.py> > > Hmm. Nothing. One problem may be that only people using Windows can > run the script. The first thing I saw when I looked at the code was that it was for MS-Windows only, so I didn't waste anymore time with it. Recently, I ran across some code that tried MS-Windows, except if the user wasn't running MS-Windows, it assumed they were running some *nix variant, and loaded those modules instead. That certainly makes code more platform independent. This is what it looked like: try: # windows or dos import msvcrt getkey = msvcrt.getch except ImportError: # assume unix import tty, termios Since Python doesn't come bundled with MS-Windows, out-of-the-box, I don't think we should presume that "everyone" has Python on their MS-Windows computer? OTOH, Python is usually part of the base or core system on a GNU/Linux install. I'm not sure about Mac OS X.x? Of course, if you only want MS-Windows users to run your code, then.... nevermind! 8^D I'm still working my way through Python tutorials, and as yet, haven't written any code that makes use of any platform specific libraries. However, when I DO, and IF I forget to try:except: so other platforms can run my code, Please Slap Me, and show me THIS post! =) That being said: Besides msvcrt/curses, what other libraries are there that we should be aware of? I'd like to see them as pairs, if possible.... this looks like a perfect thing for a dictionary! =) I certainly think this is something that Newbies (like myself) should learn. But without a MS-Windows computer handy, I don't know? Is there a place that has this information? Happy Programming! -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html > > I've developed chessTimer a bit further: > <http://www.rcblue.com/Python/chessTimerFischerDelayForWebV2.py> > > I'm still hoping for some constructive criticism. But I also thought > I'd mention the points I have doubts about: > 1. Is wrapping the long lines where I have done so OK? > 2. I've used 1 for White player, -1 for Black player, and (-1)*player > to alternate players. Is there a better way? > 3. I've used a lot of variables. Too Many? > 4. Should more of the code be in functions? > 5. Is there a way to collapse lines 107-114: > if player == 1: # player is White > whiteMoveCounter += 1 > print "Black to make move %d" % (blackMoveCounter) > remainingWhiteTime -= timeUsedThisMove > elif player == -1: # player is Black > blackMoveCounter += 1 > print "White to make move %d" % (whiteMoveCounter) > remainingBlackTime -= timeUsedThisMove > > > Thanks, > > Dick Moores > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lists at sandipb.net Fri Oct 26 14:55:28 2007 From: lists at sandipb.net (Sandip Bhattacharya) Date: Fri, 26 Oct 2007 18:25:28 +0530 Subject: [Tutor] How can isfile really do what it claims Message-ID: <4721E3C0.9060509@sandipb.net> $ ls -l /usr/lib/xulrunner/libfreebl3.so lrwxrwxrwx 1 root root 20 2007-10-20 12:13 /usr/lib/xulrunner/libfreebl3.so -> ../nss/libfreebl3.so $ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os.path >>> os.path.isfile("/usr/lib/xulrunner/libfreebl3.so") True >>> print os.path.isfile.__doc__ Test whether a path is a regular file Is this because isfile follows symlinks? If that is the case, how can I NOT make it do that? - Sandip From kent37 at tds.net Fri Oct 26 15:36:06 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 26 Oct 2007 09:36:06 -0400 Subject: [Tutor] How can isfile really do what it claims In-Reply-To: <4721E3C0.9060509@sandipb.net> References: <4721E3C0.9060509@sandipb.net> Message-ID: <4721ED46.4060503@tds.net> Sandip Bhattacharya wrote: > $ ls -l /usr/lib/xulrunner/libfreebl3.so > lrwxrwxrwx 1 root root 20 2007-10-20 12:13 /usr/lib/xulrunner/libfreebl3.so -> ../nss/libfreebl3.so > > $ python > Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os.path >>>> os.path.isfile("/usr/lib/xulrunner/libfreebl3.so") > True >>>> print os.path.isfile.__doc__ > Test whether a path is a regular file > > > Is this because isfile follows symlinks? Yes; from the full docs: isfile( path) Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path. If that is the case, > how can I NOT make it do that? def isfile(path): return not os.path.islink(path) and os.path.isfile(path) Kent From allen.fowler at yahoo.com Fri Oct 26 20:13:10 2007 From: allen.fowler at yahoo.com (Allen Fowler) Date: Fri, 26 Oct 2007 11:13:10 -0700 (PDT) Subject: [Tutor] Pythonic way to "try a few times, then raise exception"? Message-ID: <32631.8789.qm@web45605.mail.sp1.yahoo.com> Hello, I have a block of code buried deep in a module that I expect to fail periodically. (Calls to other machines over slow network, and such.) Generally, though, trying it a second / third will work. Is there clean way to write this on Python? Thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071026/9cb13de5/attachment.htm From alan.gauld at btinternet.com Sat Oct 27 00:04:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Oct 2007 23:04:59 +0100 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code References: <20071025163428.A2F241E400A@bag.python.org><20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> Message-ID: <fftoai$mf3$1@ger.gmane.org> "bhaaluu" <bhaaluu at gmail.com> wrote > I certainly think this is something that Newbies (like myself) > should learn. > But without a MS-Windows computer handy, I don't know? Is there a > place that has this information? The Module documentation tells you which platforms are supported. But its more than modules. Some functions within modules work differently (or not at all!) on different OS platforms. Anything that is OS specific like sound, video, input/output handling etc will likely have platform restrictions. However many of these differences can be avoided by using higher level toolkits like PyGame, PIL, wxWindows etc. They abstract the interfaces to a common form and hide the differences internally. But usually at the cost of some flexibility, power or resource usage(memory/speed) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Oct 27 00:17:47 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Oct 2007 23:17:47 +0100 Subject: [Tutor] Pythonic way to "try a few times, then raise exception"? References: <32631.8789.qm@web45605.mail.sp1.yahoo.com> Message-ID: <fftp2h$omv$1@ger.gmane.org> "Allen Fowler" <allen.fowler at yahoo.com> wrote > I have a block of code buried deep in a module > that I expect to fail periodically. > (Calls to other machines over slow network, and such.) > > Generally, though, trying it a second / third will work. > > Is there clean way to write this on Python? There was a thread on this a few days ago but I can't find it now... In general if you only have a few (eg hundreds) things to check you can run a loop inside a loop and exit it with break if it works. Pdeudo code: for item in list: for attempt in range(3): result = accessItem(item) if result == OK: break else: sleep(T) # optional pause to regroup if needed... else: logError(item) But I'm not sure if that's what you count as clean! If the volumes being processed it is usually better to gather the failures up for seondary processing after getting through the successful ones. This is a much more efficient way of handling high data volumes. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jfabiani at yolo.com Sat Oct 27 01:44:05 2007 From: jfabiani at yolo.com (johnf) Date: Fri, 26 Oct 2007 16:44:05 -0700 Subject: [Tutor] Pythonic way to "try a few times, then raise exception"? In-Reply-To: <fftp2h$omv$1@ger.gmane.org> References: <32631.8789.qm@web45605.mail.sp1.yahoo.com> <fftp2h$omv$1@ger.gmane.org> Message-ID: <200710261644.05813.jfabiani@yolo.com> On Friday 26 October 2007 03:17:47 pm Alan Gauld wrote: > "Allen Fowler" <allen.fowler at yahoo.com> wrote > > > I have a block of code buried deep in a module > > that I expect to fail periodically. > > (Calls to other machines over slow network, and such.) > > > > Generally, though, trying it a second / third will work. > > > > Is there clean way to write this on Python? > > There was a thread on this a few days ago but I can't find it now... > > In general if you only have a few (eg hundreds) things to > check you can run a loop inside a loop and exit it with break > if it works. Pdeudo code: > > for item in list: > for attempt in range(3): > result = accessItem(item) > if result == OK: break > else: sleep(T) # optional pause to regroup if needed... > else: logError(item) > > But I'm not sure if that's what you count as clean! > > If the volumes being processed it is usually better to > gather the failures up for seondary processing after > getting through the successful ones. This is a much > more efficient way of handling high data volumes. > > HTH What about placing the "try" in a function and call the function from a loop passing the variable to check (computer name). Then each failure will not cause the app to stop processing. Use a counter in the calling procedure to the number of attempts. -- John Fabiani From rdm at rcblue.com Sat Oct 27 03:39:57 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 26 Oct 2007 18:39:57 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> Message-ID: <20071027013958.A91981E4002@bag.python.org> At 05:00 AM 10/26/2007, bhaaluu wrote: >Greetings, > >On 10/26/07, Dick Moores <rdm at rcblue.com> wrote: > > At 09:33 AM 10/25/2007, Dick Moores wrote: > > >Please give me constructive criticism of > > ><http://www.rcblue.com/Python/chessTimerForWebV6.py> > > > > Hmm. Nothing. One problem may be that only people using Windows can > > run the script. > >The first thing I saw when I looked at the code was that it was >for MS-Windows only, so I didn't waste anymore time with it. > >Recently, I ran across some code that tried MS-Windows, except >if the user wasn't running MS-Windows, it assumed they were >running some *nix variant, and loaded those modules instead. >That certainly makes code more platform independent. > >This is what it looked like: >try: > # windows or dos > import msvcrt > getkey = msvcrt.getch >except ImportError: > # assume unix > import tty, termios OK, here's a short script, which runs fine on Windows. What do I add to have it run on unix as well? #!/usr/bin/env python #coding=utf-8 try: # windows or dos import msvcrt while True: if msvcrt.kbhit(): key = msvcrt.getch() if key == "h": print "Hello, World!" break print "Bye, World!" except ImportError: # assume unix import tty, termios Dick From ryu.alex at gmail.com Sat Oct 27 08:53:01 2007 From: ryu.alex at gmail.com (Alex Ryu) Date: Fri, 26 Oct 2007 23:53:01 -0700 Subject: [Tutor] Error 403 when accessing wikipedia articles? Message-ID: <a828f96f0710262353p58b40eb9u3c5a8879af939232@mail.gmail.com> Hi all I'm trying to use python to automatically download and process a (small) number of wikipedia articles. However, I keep getting a 403 (Forbidden Error), when using urllib2: >>> import urllib2 >>> ip = urllib2.urlopen("http://en.wikipedia.org/wiki/Pythonidae") which gives this: Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> ip = urllib2.urlopen("http://en.wikipedia.org/wiki/Pythonidae") File "G:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "G:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "G:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "G:\Python25\lib\urllib2.py", line 418, in error return self._call_chain(*args) File "G:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "G:\Python25\lib\urllib2.py", line 499, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Now, when I use urllib instead of urllib2, something different happens: >>> import urllib >>> ip2 = urllib.urlopen("http://en.wikipedia.org/wiki/Pythonidae") >>> st = ip2.read() However, st does not contain the hoped-for page - instead it is a page of html and (maybe?) javascript, which ends in: >If reporting this error to the Wikimedia System Administrators, please include the following >details:<br/>\n<span style="font-style: >italic">\nRequest: GET http://en.wikipedia.org/wiki>/Pythonidae<http://en.wikipedia.org/wiki/Pythonidae>, from 98.195.188.89 via sq27.wikimedia.org (squid/2.6.STABLE13) >to >()<br/>\nError: ERR_ACCESS_DENIED, errno [No Error] at Sat, 27 Oct 2007 06:45:00 >GMT\n</span>\n</div>\n\n</body>\n</html>\n' Could anybody tell me what's going on, and what I should be doing differently? Thanks for your time Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071026/ca2d70d1/attachment.htm From alan.gauld at btinternet.com Sat Oct 27 10:13:45 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Oct 2007 09:13:45 +0100 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code References: <20071025163428.A2F241E400A@bag.python.org><20071026091813.BE7CC1E401F@bag.python.org><ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> Message-ID: <ffus00$3j6$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > OK, here's a short script, which runs fine on Windows. What do I add > to have it run on unix as well? Take a look at my Event Driven programming topic. It contains a simple key echo program using msvcrt and instructions for Linux users to convert it to use curses. >From that you should be able to create a dual platform version. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > #!/usr/bin/env python > #coding=utf-8 > > try: > # windows or dos > import msvcrt > while True: > if msvcrt.kbhit(): > key = msvcrt.getch() > if key == "h": > print "Hello, World!" > break > print "Bye, World!" > > except ImportError: > # assume unix > import tty, termios > > Dick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Oct 27 10:19:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Oct 2007 09:19:21 +0100 Subject: [Tutor] Error 403 when accessing wikipedia articles? References: <a828f96f0710262353p58b40eb9u3c5a8879af939232@mail.gmail.com> Message-ID: <ffusag$4a9$1@ger.gmane.org> "Alex Ryu" <ryu.alex at gmail.com> wrote > I'm trying to use python to automatically download and process a > (small) > number of wikipedia articles. However, I keep getting a 403 > (Forbidden > Error), when using urllib2: FWIW I had a similar problem in trying to use Google to illustrate the use of urlib2 in my tutorial. It seems some wevb sites implement measures to prevent robotic access. I assume you could spoof your browsers characteristics and fool the system but I tend to take the view that if the owner doesn't like robots then I'd better respect that, so I haven't tried. All of which reminds me that I really need to finish writing that topic! :-) > File "G:\Python25\lib\urllib2.py", line 499, in http_error_default > raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) > HTTPError: HTTP Error 403: Forbidden > > Now, when I use urllib instead of urllib2, something different > happens: > > from 98.195.188.89 via sq27.wikimedia.org (squid/2.6.STABLE13) >to >>()<br/>\nError: ERR_ACCESS_DENIED, errno [No Error] at Sat, 27 Oct >>2007 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sat Oct 27 13:21:50 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 27 Oct 2007 04:21:50 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <ffus00$3j6$1@ger.gmane.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <ffus00$3j6$1@ger.gmane.org> Message-ID: <20071027112156.950AE1E4027@bag.python.org> At 01:13 AM 10/27/2007, Alan Gauld wrote: >"Dick Moores" <rdm at rcblue.com> wrote > > > OK, here's a short script, which runs fine on Windows. What do I add > > to have it run on unix as well? > >Take a look at my Event Driven programming topic. It contains a >simple key echo program using msvcrt and instructions for Linux >users to convert it to use curses. > > From that you should be able to create a dual platform version. Thanks, Alan. I'll give it a try. Dick From rdm at rcblue.com Sat Oct 27 13:28:41 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 27 Oct 2007 04:28:41 -0700 Subject: [Tutor] question re type() Message-ID: <20071027112905.AFC3C1E4005@bag.python.org> I can't figure out how to test a variable n for its type. An example that is the wrong syntax, but shows what I want to do: if type(n) == 'int' or type(n) == 'long': do something elif type(n) == 'float': do something else elif type(n) == 'str': do something different What's the correct way? Thanks, Dick Moores From ricaraoz at gmail.com Sat Oct 27 13:34:58 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 27 Oct 2007 08:34:58 -0300 Subject: [Tutor] question re type() In-Reply-To: <20071027112905.AFC3C1E4005@bag.python.org> References: <20071027112905.AFC3C1E4005@bag.python.org> Message-ID: <47232262.6060004@bigfoot.com> Dick Moores wrote: > I can't figure out how to test a variable n for its type. > > An example that is the wrong syntax, but shows what I want to do: > > if type(n) == 'int' or type(n) == 'long': > do something > > elif type(n) == 'float': > do something else > > elif type(n) == 'str': > do something different > > What's the correct way? > Just take the quotes off : if type(n) == int or type(n) == long : HTH From rdm at rcblue.com Sat Oct 27 13:41:30 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 27 Oct 2007 04:41:30 -0700 Subject: [Tutor] question re type() In-Reply-To: <47232262.6060004@bigfoot.com> References: <20071027112905.AFC3C1E4005@bag.python.org> <47232262.6060004@bigfoot.com> Message-ID: <20071027114140.557F01E400E@bag.python.org> At 04:34 AM 10/27/2007, Ricardo Ar?oz wrote: >Just take the quotes off : > >if type(n) == int or type(n) == long : Thanks. I tried a lot of things, but not that one! Dick >HTH Oh, yeah! From vvinuv at gmail.com Sat Oct 27 13:56:38 2007 From: vvinuv at gmail.com (Vinu Vikram) Date: Sat, 27 Oct 2007 17:26:38 +0530 Subject: [Tutor] how to run function only for a pre-defined time Message-ID: <637563b70710270456i58dad9ear8695d7f3aeb3afb2@mail.gmail.com> Hi All Could anybody try to tell me whether it is possible to run a function only for a particular time period. In my python script I call some third party function which some time won't give results. I would like to write the script in such a way that, it will wait for the result from this function for some time, say 10 seconds, and if it fails to get any results within that time (10 seconds), the script should skip that function and stop the program. If I simplify more, how can I run an infinite loop (like in the bottom) only for 10 seconds. a=1 i=1 while a==1: print i i += 1 -- VINU VIKRAM http://iucaa.ernet.in/~vvinuv/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/faa5b78c/attachment.htm From alan.gauld at btinternet.com Sat Oct 27 14:03:18 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Oct 2007 13:03:18 +0100 Subject: [Tutor] question re type() References: <20071027112905.AFC3C1E4005@bag.python.org> Message-ID: <ffv9ed$6m3$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > if type(n) == 'int' or type(n) == 'long': > do something don't use strings if type(n) == int Or just use an instance of the same type: if type(n) == type(42) Alan G. From alan.gauld at btinternet.com Sat Oct 27 14:08:26 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Oct 2007 13:08:26 +0100 Subject: [Tutor] how to run function only for a pre-defined time References: <637563b70710270456i58dad9ear8695d7f3aeb3afb2@mail.gmail.com> Message-ID: <ffv9o1$7gd$1@ger.gmane.org> "Vinu Vikram" <vvinuv at gmail.com> wrote > Could anybody try to tell me whether it is possible to run a > function only > for a particular time period. In my python script I call some third > party > function which some time won't give results. I would like to write > the > script in such a way that, it will wait for the result from this > function > for some time, say 10 seconds, and if it fails to get any results > within > that time (10 seconds), the script should skip that function and > stop the > program. > I think you will need to use threading to launch your function in a separate thread. If the thread dopesn't end in time you can proceed in the main thread to kill the thread and exit the program. Read about Python threading here: http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From washakie at gmail.com Sat Oct 27 14:49:40 2007 From: washakie at gmail.com (John) Date: Sat, 27 Oct 2007 14:49:40 +0200 Subject: [Tutor] 'source' in python or preloading variables Message-ID: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> I have a file sitelocations: STN_id[1]=AAA STNlat[1]=58.800000 STNlon[1]=17.400000 STNelv[1]=20 STN_id[2]=BBB STNlat[2]=42.450000 STNlon[2]=25.583333 STNelv[2]=2925 which in shell scripts I can simple 'source'. In Python I have to: sitesFile=file('sitelocations','r') sites=sitesFile.readlines() i=0; for l in sites: if i==0: STN_id.append(l.split('=')[1].strip('\n')); i+=1; elif i==1: STNlat.append(l.split('=')[1].strip('\n')); i+=1; elif i==2: STNlon.append(l.split('=')[1].strip('\n')); i+=1; else: STNelv.append(l.split('=')[1].strip('\n')); i=0; Is there a better way?? Thanks! -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/86852af9/attachment.htm From ricaraoz at gmail.com Sat Oct 27 15:30:59 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 27 Oct 2007 10:30:59 -0300 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> Message-ID: <47233D93.7000307@bigfoot.com> John wrote: > I have a file sitelocations: > > STN_id[1]=AAA > STNlat[1]=58.800000 > STNlon[1]=17.400000 > STNelv[1]=20 > STN_id[2]=BBB > STNlat[2]=42.450000 > STNlon[2]=25.583333 > STNelv[2]=2925 > > which in shell scripts I can simple 'source'. In Python I have to: > sitesFile=file('sitelocations','r') > sites=sitesFile.readlines() > i=0; > for l in sites: > if i==0: > STN_id.append(l.split('=')[1].strip('\n')); i+=1; > elif i==1: > STNlat.append(l.split('=')[1].strip('\n')); i+=1; > elif i==2: > STNlon.append(l.split('=')[1].strip('\n')); i+=1; > else: > STNelv.append(l.split('=')[1].strip('\n')); i=0; > > Is there a better way?? > > Thanks! > In your code you don't define your lists before appending to them, I guess that will cause an error. >From the 'file()' entry in the Python manuals : """ When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)"). """ This might work : # Set initial conditions STN_id = list() STNlat = list() STNlon = list() STNelv = list() LDict = dict(STN_id=STN_id, STNlat=STNlat, STNlon=STNlon, STNelv=STNelv) # Do the job for L in open('sitelocations','r') : LDict[L.split('[')[0]].append(L.split('=')[1].strip('\n')) HTH From aditya.n.lal at gmail.com Sat Oct 27 15:42:43 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Sat, 27 Oct 2007 19:12:43 +0530 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> Message-ID: <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> You can source the file in python provided that you make it python friendly:- STN_id[1]='AAA' instead of STN_id[1]=AAA ... ----------- import re # Read the file fd = open('sitelocations') lines = fd.readlines() fd.close() # Make it python friendly: put all values in 'single quotes' cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in lines]) # Create variables as list of appropriate size with default values (assuming 0) max = 5 STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max # Execute the command and all your variables are populated ... exec(cmd) ------------------- Not sure if this is a better way :) But atleast it will make the file sitelocations order invariant - implies you can interchange the lines without breaking the logic. Caveat - list in python starts at 0 index so STN_id[1] is not the first element but the second element. But you can filter unwanted items from the list if you want as in - [ x for x in STN_id if x != 0 ] HTH Aditya On 10/27/07, John <washakie at gmail.com> wrote: > > I have a file sitelocations: > > STN_id[1]=AAA > STNlat[1]=58.800000 > STNlon[1]=17.400000 > STNelv[1]=20 > STN_id[2]=BBB > STNlat[2]=42.450000 > STNlon[2]=25.583333 > STNelv[2]=2925 > > which in shell scripts I can simple 'source'. In Python I have to: > sitesFile=file('sitelocations','r') > sites=sitesFile.readlines() > i=0; > for l in sites: > if i==0: > STN_id.append(l.split('=')[1].strip('\n')); i+=1; > elif i==1: > STNlat.append(l.split('=')[1].strip('\n')); i+=1; > elif i==2: > STNlon.append(l.split('=')[1].strip('\n')); i+=1; > else: > STNelv.append(l.split('=')[1].strip('\n')); i=0; > > Is there a better way?? > > Thanks! > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Five 1.4.1, > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > 4.1.1-51)], > PIL 1.1.6 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman<http://mail.python.org/mailman/listinfo/tutor> > /listinfo/tutor <http://mail.python.org/mailman/listinfo/tutor> > > -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/6ee46d87/attachment-0001.htm From aditya.n.lal at gmail.com Sat Oct 27 15:52:25 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Sat, 27 Oct 2007 19:22:25 +0530 Subject: [Tutor] question re type() In-Reply-To: <ffv9ed$6m3$1@ger.gmane.org> References: <20071027112905.AFC3C1E4005@bag.python.org> <ffv9ed$6m3$1@ger.gmane.org> Message-ID: <5df213700710270652i1c38571bl4a85edcfa54af977@mail.gmail.com> On 10/27/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > > "Dick Moores" <rdm at rcblue.com> wrote > > > if type(n) == 'int' or type(n) == 'long': > > do something > > don't use strings > > if type(n) == int > > Or just use an instance of the same type: > > if type(n) == type(42) > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > or use types module import types if type(n) == types.IntType or type(n) == types.LongType : blah! this comes handy especially for some unique conditions - like whether the function passed is a generator or a normal function (well I kinda had this problem ... :) ) ex. if type(f) == types.GeneratorType or type(f) == types.lambdaType : same blah! -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/5a11d464/attachment.htm From washakie at gmail.com Sat Oct 27 15:53:48 2007 From: washakie at gmail.com (John) Date: Sat, 27 Oct 2007 15:53:48 +0200 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> Message-ID: <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> Thanks! This is helpful.. I like the RE approach as it's conceivable to write a function... On 10/27/07, Aditya Lal <aditya.n.lal at gmail.com> wrote: > > You can source the file in python provided that you make it python > friendly:- > > STN_id[1]='AAA' instead of STN_id[1]=AAA > ... > > > ----------- > import re > # Read the file > fd = open('sitelocations') > lines = fd.readlines() > fd.close() > > > # Make it python friendly: put all values in 'single quotes' > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in > lines]) > > > # Create variables as list of appropriate size with default values > (assuming 0) > max = 5 > STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max > > > # Execute the command and all your variables are populated ... > exec(cmd) > > > ------------------- > Not sure if this is a better way :) But atleast it will make the file > sitelocations order invariant - implies you can interchange the lines > without breaking the logic. > > > Caveat - list in python starts at 0 index so STN_id[1] is not the first > element but the second element. But you can filter unwanted items from the > list if you want as in - > [ x for x in STN_id if x != 0 ] > > > HTH > Aditya > > On 10/27/07, John <washakie at gmail.com> wrote: > > > I have a file sitelocations: > > > > STN_id[1]=AAA > > STNlat[1]=58.800000 > > STNlon[1]=17.400000 > > STNelv[1]=20 > > STN_id[2]=BBB > > STNlat[2]=42.450000 > > STNlon[2]=25.583333 > > STNelv[2]=2925 > > > > which in shell scripts I can simple 'source'. In Python I have to: > > sitesFile=file('sitelocations','r') > > sites=sitesFile.readlines() > > i=0; > > for l in sites: > > if i==0: > > STN_id.append(l.split('=')[1].strip('\n')); i+=1; > > elif i==1: > > STNlat.append(l.split('=')[1].strip('\n')); i+=1; > > elif i==2: > > STNlon.append(l.split('=')[1].strip('\n')); i+=1; > > else: > > STNelv.append(l.split('=')[1].strip('\n')); i=0; > > > > Is there a better way?? > > > > Thanks! > > > > > > > > > > -- > > Configuration > > `````````````````````````` > > Plone 2.5.3-final, > > CMF-1.6.4, > > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > > Five 1.4.1, > > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > > 4.1.1-51)], > > PIL 1.1.6 > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman<http://mail.python.org/mailman/listinfo/tutor> > > /listinfo/tutor <http://mail.python.org/mailman/listinfo/tutor> > > > > > > > -- > Aditya > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/535d5a0c/attachment.htm From washakie at gmail.com Sat Oct 27 16:13:19 2007 From: washakie at gmail.com (John) Date: Sat, 27 Oct 2007 16:13:19 +0200 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> Message-ID: <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> Ok, so trying to convert it to a function: def source(ifile, *args): """ takes a file object and a list of variables as input. assumes, source file has variables in format: VAR[i]=variable """ import re # Read the file lines = fd.readlines() fd.close() # Make it python friendly: put all values in 'single quotes' cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in lines]) # Create variables as list of appropriate size with default IM STUCK HERE... HOW DO I DYNAMICALLY CONVERT THE LIST OF VARIABLE NAMES TO VARIABLES OF TYPE LIST # Execute the command and all your variables are populated ... exec(cmd) Thanks, > Thanks! This is helpful.. I like the RE approach as it's conceivable to > write a function... > > On 10/27/07, Aditya Lal <aditya.n.lal at gmail.com> wrote: > > > > You can source the file in python provided that you make it python > > friendly:- > > > > STN_id[1]='AAA' instead of STN_id[1]=AAA > > ... > > > > > > ----------- > > import re > > # Read the file > > fd = open('sitelocations') > > lines = fd.readlines() > > fd.close() > > > > > > # Make it python friendly: put all values in 'single quotes' > > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in > > lines]) > > > > > > # Create variables as list of appropriate size with default values > > (assuming 0) > > max = 5 > > STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max > > > > > > # Execute the command and all your variables are populated ... > > exec(cmd) > > > > > > ------------------- > > Not sure if this is a better way :) But atleast it will make the file > > sitelocations order invariant - implies you can interchange the lines > > without breaking the logic. > > > > > > Caveat - list in python starts at 0 index so STN_id[1] is not the first > > element but the second element. But you can filter unwanted items from the > > list if you want as in - > > [ x for x in STN_id if x != 0 ] > > > > > > HTH > > Aditya > > > > On 10/27/07, John < washakie at gmail.com> wrote: > > > > > I have a file sitelocations: > > > > > > STN_id[1]=AAA > > > STNlat[1]=58.800000 > > > STNlon[1]=17.400000 > > > STNelv[1]=20 > > > STN_id[2]=BBB > > > STNlat[2]=42.450000 > > > STNlon[2]=25.583333 > > > STNelv[2]=2925 > > > > > > which in shell scripts I can simple 'source'. In Python I have to: > > > sitesFile=file('sitelocations','r') > > > sites=sitesFile.readlines() > > > i=0; > > > for l in sites: > > > if i==0: > > > STN_id.append(l.split('=')[1].strip('\n')); i+=1; > > > elif i==1: > > > STNlat.append(l.split('=')[1].strip('\n')); i+=1; > > > elif i==2: > > > STNlon.append(l.split('=')[1].strip('\n')); i+=1; > > > else: > > > STNelv.append(l.split('=')[1].strip('\n')); i=0; > > > > > > Is there a better way?? > > > > > > Thanks! > > > > > > > > > > > > > > > -- > > > Configuration > > > `````````````````````````` > > > Plone 2.5.3-final, > > > CMF-1.6.4, > > > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > > > Five 1.4.1, > > > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > > > 4.1.1-51)], > > > PIL 1.1.6 > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman<http://mail.python.org/mailman/listinfo/tutor>/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > > > > > > > > > > > > -- > > Aditya > > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4 , > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Five 1.4.1, > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > 4.1.1-51)], > PIL 1.1.6 > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/fb1e8e34/attachment.htm From aditya.n.lal at gmail.com Sat Oct 27 16:51:09 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Sat, 27 Oct 2007 20:21:09 +0530 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> Message-ID: <5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com> On 10/27/07, John <washakie at gmail.com> wrote: > > Ok, so trying to convert it to a function: > > def source(ifile, *args): > """ takes a file object and a list of variables as input. > assumes, source file has variables in format: > VAR[i]=variable """ > > import re > # Read the file > lines = fd.readlines() > fd.close() > > # Make it python friendly: put all values in 'single quotes' > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v > in lines]) > > # Create variables as list of appropriate size with default > IM STUCK HERE... HOW DO I DYNAMICALLY CONVERT THE LIST OF VARIABLE NAMES > TO VARIABLES OF TYPE LIST > > # Execute the command and all your variables are populated ... > exec(cmd) > > > Thanks, > > > > > > > Thanks! This is helpful.. I like the RE approach as it's conceivable to > > write a function... > > > > On 10/27/07, Aditya Lal <aditya.n.lal at gmail.com > wrote: > > > > > > You can source the file in python provided that you make it python > > > friendly:- > > > > > > STN_id[1]='AAA' instead of STN_id[1]=AAA > > > ... > > > > > > > > > ----------- > > > import re > > > # Read the file > > > fd = open('sitelocations') > > > lines = fd.readlines() > > > fd.close() > > > > > > > > > # Make it python friendly: put all values in 'single quotes' > > > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in > > > lines]) > > > > > > > > > # Create variables as list of appropriate size with default values > > > (assuming 0) > > > max = 5 > > > STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max > > > > > > > > > # Execute the command and all your variables are populated ... > > > exec(cmd) > > > > > > > > > ------------------- > > > Not sure if this is a better way :) But atleast it will make the file > > > sitelocations order invariant - implies you can interchange the lines > > > without breaking the logic. > > > > > > > > > Caveat - list in python starts at 0 index so STN_id[1] is not the > > > first element but the second element. But you can filter unwanted items from > > > the list if you want as in - > > > [ x for x in STN_id if x != 0 ] > > > > > > > > > HTH > > > Aditya > > > > > > On 10/27/07, John < washakie at gmail.com > wrote: > > > > > > > I have a file sitelocations: > > > > > > > > STN_id[1]=AAA > > > > STNlat[1]=58.800000 > > > > STNlon[1]=17.400000 > > > > STNelv[1]=20 > > > > STN_id[2]=BBB > > > > STNlat[2]=42.450000 > > > > STNlon[2]=25.583333 > > > > STNelv[2]=2925 > > > > > > > > which in shell scripts I can simple 'source'. In Python I have to: > > > > sitesFile=file('sitelocations','r') > > > > sites=sitesFile.readlines() > > > > i=0; > > > > for l in sites: > > > > if i==0: > > > > STN_id.append(l.split('=')[1].strip('\n')); i+=1; > > > > elif i==1: > > > > STNlat.append(l.split('=')[1].strip('\n')); i+=1; > > > > elif i==2: > > > > STNlon.append(l.split('=')[1].strip('\n')); i+=1; > > > > else: > > > > STNelv.append(l.split('=')[1].strip('\n')); i=0; > > > > > > > > Is there a better way?? > > > > > > > > Thanks! > > > > > > > > > > > > > > > > > > > > -- > > > > Configuration > > > > `````````````````````````` > > > > Plone 2.5.3-final, > > > > CMF-1.6.4, > > > > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > > > > Five 1.4.1, > > > > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > > > > 4.1.1-51)], > > > > PIL 1.1.6 > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman<http://mail.python.org/mailman/listinfo/tutor>/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > > > > > > > > > > > > > > > > > -- > > > Aditya > > > > > > > > > > > -- > > Configuration > > `````````````````````````` > > Plone 2.5.3-final, > > CMF-1.6.4 , > > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > > Five 1.4.1, > > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > > 4.1.1-51)], > > PIL 1.1.6 > > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Five 1.4.1, > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > 4.1.1-51 )], > PIL 1.1.6 > Are you saying you don't know the name of the variables, eh ? For any access you *must* know the name of the variable somewhere in the program anyway. Frankly I feel its a lot simpler to just modify the file 'sitelocations' to make it python friendly and import it in the program - thats what I typically do for most of my code generation programs. Anyway, for dynamically defining the variables you can do the following (untested) : for line in open('sitelocations').readlines() : nline = re.sub(r'^([^=]+)=(.*)$', r"\1 = '\2'", line) try : exec(nline) except NameError : # define variable name vname = nline.split('=')[0] exec( 'global ' + vname + ';' + vname + ' = [0]*5') # to make it visible globally and set default value exec(nline) -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/cca803be/attachment-0001.htm From rdm at rcblue.com Sat Oct 27 17:06:02 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 27 Oct 2007 08:06:02 -0700 Subject: [Tutor] More type() puzzlement Message-ID: <20071027150614.6FE6B1E4027@bag.python.org> Win XP, Python 2.5.1 ======================== #!/usr/bin/env python #coding=utf-8 n = 10000000000 # 10 billion print "type of 10 billion is", type(n) n = 1000000000 # 1 billion print "type of 1 billion is", type(n) raw_input("press enter to continue") n = 10000000000 print type(n) while True: if type(n) == long: n -= 1000000 print n, type(n) else: break print n print type(n), 'HERE' ========================== As an exercise in using type() I was thinking I could use it to begin to find where (without looking it up) a long becomes an int. I show that the boundary is somewhere between 10 billion and 1 billion. But the above script never ends--never gets to 'HERE'. Here's part of the output: 6000000 <type 'long'> 5000000 <type 'long'> 4000000 <type 'long'> 3000000 <type 'long'> 2000000 <type 'long'> 1000000 <type 'long'> 0 <type 'long'> -1000000 <type 'long'> -2000000 <type 'long'> -3000000 <type 'long'> -4000000 <type 'long'> -5000000 <type 'long'> -6000000 <type 'long'> Note that it shows even 1 million and 0 to be longs, whereas >>> type(1000000) <type 'int'> >>> type(0) <type 'int'> >>> What's going on? Thanks, Dick Moores From washakie at gmail.com Sat Oct 27 17:23:41 2007 From: washakie at gmail.com (John) Date: Sat, 27 Oct 2007 17:23:41 +0200 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> <5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com> Message-ID: <aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com> The problem is the infies are also being used in a shell scripted environment, they are frequently updated and cannot be changed. So ideadly I could just define a function which sourced the file, assuming the variable names passed in the *args list. So, yes, I know the names, they just haven't been set in the program. I would like the source program to then define them. My re is not so great, but I'm assuming the statement here: cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in lines]) assumes the pattern VAR[i]=variable , and then makes it Python friendly. So it would look like: my_source(fid,['STN_id','STNlat','STNlon','STNelv']) then in the program, before exec(cmd) the *args list has to be converted into empy lists, preparing it for the cmd. Does that make sense?? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/47633bf5/attachment.htm From aditya.n.lal at gmail.com Sat Oct 27 17:33:47 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Sat, 27 Oct 2007 21:03:47 +0530 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> <5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com> <aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com> Message-ID: <5df213700710270833s380df440h3dc6f939faa3631a@mail.gmail.com> On 10/27/07, John <washakie at gmail.com> wrote: > > The problem is the infies are also being used in a shell scripted > environment, they are frequently updated and cannot be changed. > > So ideadly I could just define a function which sourced the file, assuming > the variable names passed in the *args list. So, yes, I know the names, they > just haven't been set in the program. I would like the source program to > then define them. My re is not so great, but I'm assuming the statement > here: > > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in > lines]) > > assumes the pattern VAR[i]=variable , and then makes it Python friendly. > > So it would look like: > > my_source(fid,['STN_id','STNlat','STNlon','STNelv']) > > then in the program, before exec(cmd) the *args list has to be converted > into empy lists, preparing it for the cmd. Does that make sense?? > > Thanks! > > the re expression just changes "lvalue=rvalue" to "lvalue='rvalue'". It doesn't know whether lvalue is array or something else. Anyway, you can initialize the variables as follows - for v in ['STN_id', ... ] : exec( 'global %s ; %s = [0]*5' % (v, v)) Unfortunately these variable need to be made global for them to be visible everywhere. HTH Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/f2728fa3/attachment.htm From aditya.n.lal at gmail.com Sat Oct 27 17:39:33 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Sat, 27 Oct 2007 21:09:33 +0530 Subject: [Tutor] More type() puzzlement In-Reply-To: <20071027150614.6FE6B1E4027@bag.python.org> References: <20071027150614.6FE6B1E4027@bag.python.org> Message-ID: <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com> On 10/27/07, Dick Moores <rdm at rcblue.com> wrote: > > Win XP, Python 2.5.1 > > ======================== > #!/usr/bin/env python > #coding=utf-8 > > n = 10000000000 # 10 billion > print "type of 10 billion is", type(n) > n = 1000000000 # 1 billion > print "type of 1 billion is", type(n) > > raw_input("press enter to continue") > > n = 10000000000 > print type(n) > while True: > if type(n) == long: > n -= 1000000 > print n, type(n) > else: > break > print n > print type(n), 'HERE' > ========================== > > As an exercise in using type() I was thinking I could use it to begin > to find where (without looking it up) a long becomes an int. I show > that the boundary is somewhere between 10 billion and 1 billion. But > the above script never ends--never gets to 'HERE'. > > Here's part of the output: > > 6000000 <type 'long'> > 5000000 <type 'long'> > 4000000 <type 'long'> > 3000000 <type 'long'> > 2000000 <type 'long'> > 1000000 <type 'long'> > 0 <type 'long'> > -1000000 <type 'long'> > -2000000 <type 'long'> > -3000000 <type 'long'> > -4000000 <type 'long'> > -5000000 <type 'long'> > -6000000 <type 'long'> > > Note that it shows even 1 million and 0 to be longs, whereas > >>> type(1000000) > <type 'int'> > >>> type(0) > <type 'int'> > >>> > > What's going on? > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Dick, I would expect that a type change will happen if there is a need. Hence if type(n) is already long it does not have to get converted to int to accommodate something small. I changed your program to increase from 1B to 10B and the results are as expected :) <snip> - your old code n = 1000000000 # 1 billion print type(n) while n < 10000000000 : # 10 billion if type(n) == int: n += 1000000 print n, type(n) else : break <snip> - your old code HTH Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/92818315/attachment.htm From washakie at gmail.com Sat Oct 27 18:12:43 2007 From: washakie at gmail.com (John) Date: Sat, 27 Oct 2007 18:12:43 +0200 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <5df213700710270833s380df440h3dc6f939faa3631a@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> <5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com> <aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com> <5df213700710270833s380df440h3dc6f939faa3631a@mail.gmail.com> Message-ID: <aaf235960710270912i1d677294j35f0f23059ac656f@mail.gmail.com> Here's where I am: def source(filename, vList): """ takes a file object and a list of variables as input """ import re # Read the file fid=open(filename,'r') lines = fid.readlines() fid.close() #how many variables ns=len(lines)/len(vList) #predefine the varibles for v in vList: exec( 'global %s ; %s = [0]*(ns+1)' % (v, v)) # Make it python friendly: put all values in 'single quotes' cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in lines]) exec(cmd) for v in vList: exec( '%s=%s[1:]' % (v,v)) source('infile.py',['files','nfiles','nreleases']) print files print nreleases print nfiles But oddly, my output is: [0, 'ASP_200603', 'ASP_200604', 'ASP_200605'] [0, '248', '240', '248'] [0, '3', '3', '3'] So, I am not properly getting rid of the list[0], is it something with the 'global' nature of the vairables... it looks like it's only changing locallly in my source function. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/7e06c657/attachment.htm From washakie at gmail.com Sat Oct 27 18:15:14 2007 From: washakie at gmail.com (John) Date: Sat, 27 Oct 2007 18:15:14 +0200 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <aaf235960710270912i1d677294j35f0f23059ac656f@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> <5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com> <aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com> <5df213700710270833s380df440h3dc6f939faa3631a@mail.gmail.com> <aaf235960710270912i1d677294j35f0f23059ac656f@mail.gmail.com> Message-ID: <aaf235960710270915g57543fddubf9ae909485b2ef1@mail.gmail.com> Note, i need the ns+1 because the 'source files are not zero indexed. On 10/27/07, John <washakie at gmail.com> wrote: > > Here's where I am: > > > def source(filename, vList): > """ takes a file object and a list of variables as input """ > import re > # Read the file > fid=open(filename,'r') > lines = fid.readlines() > fid.close() > #how many variables > ns=len(lines)/len(vList) > #predefine the varibles > for v in vList: > exec( 'global %s ; %s = [0]*(ns+1)' % (v, v)) > > # Make it python friendly: put all values in 'single quotes' > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in > lines]) > exec(cmd) > for v in vList: > exec( '%s=%s[1:]' % (v,v)) > > source('infile.py',['files','nfiles','nreleases']) > > print files > print nreleases > print nfiles > > > > But oddly, my output is: > > [0, 'ASP_200603', 'ASP_200604', 'ASP_200605'] > [0, '248', '240', '248'] > [0, '3', '3', '3'] > > > > So, I am not properly getting rid of the list[0], is it something with the > 'global' nature of the vairables... it looks like it's only changing > locallly in my source function. > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/26767751/attachment-0001.htm From rdm at rcblue.com Sat Oct 27 18:52:59 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 27 Oct 2007 09:52:59 -0700 Subject: [Tutor] More type() puzzlement In-Reply-To: <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com > References: <20071027150614.6FE6B1E4027@bag.python.org> <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com> Message-ID: <20071027165329.A67D21E4015@bag.python.org> At 08:39 AM 10/27/2007, Aditya Lal wrote: >I would expect that a type change will happen if there is a need. Hey, I HAD a need! OK, a made-up one. > Hence if type(n) is already long it does not have to get converted > to int to accommodate something small. And that's not a bug? >I changed your program to increase from 1B to 10B and the results >are as expected :) > ><snip> - your old code > >n = 1000000000 # 1 billion >print type(n) >while n < 10000000000 : # 10 billion > if type(n) == int: > n += 1000000 > print n, type(n) > else : > break > ><snip> - your old code Thanks, Aditya. Successively using greater and greater ints, and augmenting n by smaller and smaller amounts, I used finally n = 2147483000 print n, type(n) while n < 10000000000 : # 10 billion if type(n) == int: n += 1 else: print n, type(n) break outputs 2147483000 <type 'int'> 2147483648 <type 'long'> And then I can show this: >>> type(2147483648) <type 'long'> >>> type(2147483647) <type 'int'> >>> So the largest int is 2147483647, or 2**31 - 1. (I know this is all obvious to most, but I still get a kick out of doing it.) Dick From sli1que at yahoo.com Sat Oct 27 18:55:05 2007 From: sli1que at yahoo.com (Eric Walker) Date: Sat, 27 Oct 2007 09:55:05 -0700 (PDT) Subject: [Tutor] system call Message-ID: <456243.62506.qm@web60122.mail.yahoo.com> Hello, I am trying to run a timing script but I need the python program to stop and wait for the executable to finish. Does anyone have any examples of doing this? Thanks Python Newbie __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/0b2aacc7/attachment.htm From aditya.n.lal at gmail.com Sat Oct 27 19:16:24 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Sat, 27 Oct 2007 22:46:24 +0530 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <aaf235960710270915g57543fddubf9ae909485b2ef1@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> <5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com> <aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com> <5df213700710270833s380df440h3dc6f939faa3631a@mail.gmail.com> <aaf235960710270912i1d677294j35f0f23059ac656f@mail.gmail.com> <aaf235960710270915g57543fddubf9ae909485b2ef1@mail.gmail.com> Message-ID: <5df213700710271016i31627a76n16231d0300672065@mail.gmail.com> On 10/27/07, John <washakie at gmail.com> wrote: > > Note, i need the ns+1 because the 'source files are not zero indexed. > > On 10/27/07, John <washakie at gmail.com > wrote: > > > > Here's where I am: > > > > > > def source(filename, vList): > > """ takes a file object and a list of variables as input """ > > import re > > # Read the file > > fid=open(filename,'r') > > lines = fid.readlines() > > fid.close() > > #how many variables > > ns=len(lines)/len(vList) > > #predefine the varibles > > for v in vList: > > exec( 'global %s ; %s = [0]*(ns+1)' % (v, v)) > > > > # Make it python friendly: put all values in 'single quotes' > > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in > > lines]) > > exec(cmd) > > for v in vList: > > exec( '%s=%s[1:]' % (v,v)) > > > > source('infile.py',['files','nfiles','nreleases']) > > > > print files > > print nreleases > > print nfiles > > > > > > > > But oddly, my output is: > > > > [0, 'ASP_200603', 'ASP_200604', 'ASP_200605'] > > [0, '248', '240', '248'] > > [0, '3', '3', '3'] > > > > > > > > So, I am not properly getting rid of the list[0], is it something with > > the 'global' nature of the vairables... it looks like it's only changing > > locallly in my source function. > > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Five 1.4.1, > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > 4.1.1-51)], > PIL 1.1.6 > I think you need to define the variable global again otherwise it will re-assign the object in local space. exec( "global %s ; %s = %s[1:]" % (v,v,v) ) -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/073fcfd9/attachment.htm From jeff at drinktomi.com Sat Oct 27 19:27:24 2007 From: jeff at drinktomi.com (Jeff Younker) Date: Sat, 27 Oct 2007 13:27:24 -0400 Subject: [Tutor] More type() puzzlement In-Reply-To: <20071027165329.A67D21E4015@bag.python.org> References: <20071027150614.6FE6B1E4027@bag.python.org> <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com> <20071027165329.A67D21E4015@bag.python.org> Message-ID: <AC661A13-6DA9-48C6-A602-2BC564A2949A@drinktomi.com> On Oct 27, 2007, at 12:52 PM, Dick Moores wrote: > At 08:39 AM 10/27/2007, Aditya Lal wrote: >> Hence if type(n) is already long it does not have to get converted >> to int to accommodate something small. > > And that's not a bug? There is no need for a type change to represent zero, so, no, that's not a bug. -jeff From rdm at rcblue.com Sat Oct 27 19:48:11 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 27 Oct 2007 10:48:11 -0700 Subject: [Tutor] More type() puzzlement In-Reply-To: <AC661A13-6DA9-48C6-A602-2BC564A2949A@drinktomi.com> References: <20071027150614.6FE6B1E4027@bag.python.org> <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com> <20071027165329.A67D21E4015@bag.python.org> <AC661A13-6DA9-48C6-A602-2BC564A2949A@drinktomi.com> Message-ID: <20071027174817.E84E31E4015@bag.python.org> At 10:27 AM 10/27/2007, Jeff Younker wrote: >On Oct 27, 2007, at 12:52 PM, Dick Moores wrote: >>At 08:39 AM 10/27/2007, Aditya Lal wrote: >>> Hence if type(n) is already long it does not have to get converted >>>to int to accommodate something small. >> >>And that's not a bug? > >There is no need for a type change to represent zero, so, no, that's >not a bug. I think I was referring to something like 1000000. And then there's 2**32-1. Dick From washakie at gmail.com Sat Oct 27 19:57:44 2007 From: washakie at gmail.com (John) Date: Sat, 27 Oct 2007 19:57:44 +0200 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <5df213700710271016i31627a76n16231d0300672065@mail.gmail.com> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <5df213700710270642n20794cbcj572d990922c51da9@mail.gmail.com> <aaf235960710270653q2d47bfafob106a3003d1e41bb@mail.gmail.com> <aaf235960710270713m23e3116gaeb5ba9944dd6e4a@mail.gmail.com> <5df213700710270751u78e3c8f7x4ffde427444e25a4@mail.gmail.com> <aaf235960710270823k5625f671ye00f2d206e53e75c@mail.gmail.com> <5df213700710270833s380df440h3dc6f939faa3631a@mail.gmail.com> <aaf235960710270912i1d677294j35f0f23059ac656f@mail.gmail.com> <aaf235960710270915g57543fddubf9ae909485b2ef1@mail.gmail.com> <5df213700710271016i31627a76n16231d0300672065@mail.gmail.com> Message-ID: <aaf235960710271057p2f9368cdx8e57fda41cac9a62@mail.gmail.com> Thanks, it's strange, it works within a script defined at the top, but if I try to import it from a module it fails: NameError: name 'files' is not defined On 10/27/07, Aditya Lal <aditya.n.lal at gmail.com> wrote: > > > > On 10/27/07, John <washakie at gmail.com> wrote: > > > > Note, i need the ns+1 because the 'source files are not zero indexed. > > > > On 10/27/07, John <washakie at gmail.com > wrote: > > > > > > Here's where I am: > > > > > > > > > def source(filename, vList): > > > """ takes a file object and a list of variables as input """ > > > import re > > > # Read the file > > > fid=open(filename,'r') > > > lines = fid.readlines() > > > fid.close() > > > #how many variables > > > ns=len(lines)/len(vList) > > > #predefine the varibles > > > for v in vList: > > > exec( 'global %s ; %s = [0]*(ns+1)' % (v, v)) > > > > > > # Make it python friendly: put all values in 'single quotes' > > > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in > > > lines]) > > > exec(cmd) > > > for v in vList: > > > exec( '%s=%s[1:]' % (v,v)) > > > > > > source('infile.py',['files','nfiles','nreleases']) > > > > > > print files > > > print nreleases > > > print nfiles > > > > > > > > > > > > But oddly, my output is: > > > > > > [0, 'ASP_200603', 'ASP_200604', 'ASP_200605'] > > > [0, '248', '240', '248'] > > > [0, '3', '3', '3'] > > > > > > > > > > > > So, I am not properly getting rid of the list[0], is it something with > > > the 'global' nature of the vairables... it looks like it's only changing > > > locallly in my source function. > > > > > > > > > > > -- > > Configuration > > `````````````````````````` > > Plone 2.5.3-final, > > CMF-1.6.4, > > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > > Five 1.4.1, > > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > > 4.1.1-51)], > > PIL 1.1.6 > > > > I think you need to define the variable global again otherwise it will > re-assign the object in local space. > > exec( "global %s ; %s = %s[1:]" % (v,v,v) ) > > -- > Aditya > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/0aa268d0/attachment.htm From sli1que at yahoo.com Sat Oct 27 20:34:25 2007 From: sli1que at yahoo.com (Eric Walker) Date: Sat, 27 Oct 2007 11:34:25 -0700 (PDT) Subject: [Tutor] system call Message-ID: <549364.38708.qm@web60123.mail.yahoo.com> disregard this one. I found the answer. I was using spawn instead of os.system. Thanks. ----- Original Message ---- From: Eric Walker <sli1que at yahoo.com> To: tutor at python.org Sent: Saturday, October 27, 2007 9:55:05 AM Subject: [Tutor] system call Hello, I am trying to run a timing script but I need the python program to stop and wait for the executable to finish. Does anyone have any examples of doing this? Thanks Python Newbie __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/dc35cca9/attachment-0001.htm From dkuhlman at rexx.com Sat Oct 27 20:34:56 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 27 Oct 2007 11:34:56 -0700 Subject: [Tutor] question re type() In-Reply-To: <ffv9ed$6m3$1@ger.gmane.org> References: <20071027112905.AFC3C1E4005@bag.python.org> <ffv9ed$6m3$1@ger.gmane.org> Message-ID: <20071027183456.GA7586@cutter.rexx.com> On Sat, Oct 27, 2007 at 01:03:18PM +0100, Alan Gauld wrote: > > "Dick Moores" <rdm at rcblue.com> wrote > > > if type(n) == 'int' or type(n) == 'long': > > do something > > don't use strings > > if type(n) == int > > Or just use an instance of the same type: > > if type(n) == type(42) Calling type(n) for any integer seems to return the same object. I checked with id(). So, should we be using: if type(n) is type(42) or, as suggested by Aditya Lal in another message in this thread: import types if type(n) is types.IntType Or, is this a frivolous question that makes no difference? Dave > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Dave Kuhlman http://www.rexx.com/~dkuhlman From samrobertsmith at gmail.com Sat Oct 27 21:47:14 2007 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 27 Oct 2007 12:47:14 -0700 Subject: [Tutor] about Tix In-Reply-To: <ffs77h$3e2$1@ger.gmane.org> References: <1d987df30710251948h2f2d4fbbtb94bafb0c2e01ec2@mail.gmail.com> <ffs77h$3e2$1@ger.gmane.org> Message-ID: <1d987df30710271247v2149c962g42774f9c68af635b@mail.gmail.com> On 10/26/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > Linda, > > >I run the following code in Python 2.5 and got the error (when I do > > "import Tix", no error). > > Congratulations I think this might just be the first Tix question > on the tutor list! :-) > > > Traceback (most recent call last): > > File "2.py", line 54, in <module> > > tkRoot = Tix.Tk( ) > > File > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", > > line 210, in __init__ > > self.tk.eval('package require Tix') > > _tkinter.TclError: can't find package Tix > > This looks to me like the Tix DLL hasn't been installed or it's > installed in a folder where it can''t be found. The Tix module > is just a wrapper round the Tix DLL so you need both. > I wonder where should I install Tix DLL (I just did the install on my desktop). Thanks, Linda From samrobertsmith at gmail.com Sat Oct 27 21:52:25 2007 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 27 Oct 2007 12:52:25 -0700 Subject: [Tutor] position Message-ID: <1d987df30710271252j4cf0239fhe7399c79ec11cfd4@mail.gmail.com> I have a string a= "qq,eee,rrr". >>> a.index(",") 2 It is the position of the first "," in a. Is that possible to find the Nth "," in a if a is a very long string and I need know the position of the Nth ","? Thanks, Linda From washakie at gmail.com Sat Oct 27 22:08:38 2007 From: washakie at gmail.com (John) Date: Sat, 27 Oct 2007 22:08:38 +0200 Subject: [Tutor] system call In-Reply-To: <549364.38708.qm@web60123.mail.yahoo.com> References: <549364.38708.qm@web60123.mail.yahoo.com> Message-ID: <aaf235960710271308l49765797p7d9915b734a4f33c@mail.gmail.com> I have the exact same situation, but system doesn't seem to wait. Here is my pseudo code: for i in attempts: #attempts holds strings of shellscripts cmd="%s which runs many different shell scripts and takes about an hour" % (i) os.system(cmd) #debugging print "Finished with %s" % (i) raw_input("More debugging, shouldn't see this until shell scripts are finished!") But it prints the print statement and waits for raw_input instantly... Any thoughts? On 10/27/07, Eric Walker <sli1que at yahoo.com> wrote: > > disregard this one. I found the answer. I was using spawn instead of > os.system. > > Thanks. > > ----- Original Message ---- > From: Eric Walker <sli1que at yahoo.com> > To: tutor at python.org > Sent: Saturday, October 27, 2007 9:55:05 AM > Subject: [Tutor] system call > > Hello, > I am trying to run a timing script but I need the python program to stop > and wait for the executable to finish. Does anyone have any examples of > doing this? > > Thanks > Python Newbie > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/a65b6a2c/attachment.htm From jtp at nc.rr.com Sat Oct 27 22:20:59 2007 From: jtp at nc.rr.com (James) Date: Sat, 27 Oct 2007 16:20:59 -0400 Subject: [Tutor] system call In-Reply-To: <aaf235960710271308l49765797p7d9915b734a4f33c@mail.gmail.com> References: <549364.38708.qm@web60123.mail.yahoo.com> <aaf235960710271308l49765797p7d9915b734a4f33c@mail.gmail.com> Message-ID: <FBC34CF6-2074-402F-84D5-60A1AA9B87E3@nc.rr.com> How about using subprocess.Popen( ... ).wait()? I believe subprocess.call() will wait until the process is finished, too. The subprocess module is meant to replace spawn, popen2, os.system() etc. if I'm not mistaken. Take a look at this excellent resource I've used numerous times: http://www.python.org/dev/peps/pep-0324/ Hope this helps. .james :) On Oct 27, 2007, at 4:08 PM, John wrote: > I have the exact same situation, but system doesn't seem to wait. > Here is my pseudo code: > > for i in attempts: #attempts holds strings of shellscripts > cmd="%s which runs many different shell scripts and takes > about an hour" % (i) > os.system(cmd) > #debugging > print "Finished with %s" % (i) > raw_input("More debugging, shouldn't see this until shell > scripts are finished!") > > > But it prints the print statement and waits for raw_input > instantly... Any thoughts? > > > > On 10/27/07, Eric Walker <sli1que at yahoo.com> wrote: > disregard this one. I found the answer. I was using spawn instead > of os.system. > > Thanks. > > > ----- Original Message ---- > From: Eric Walker < sli1que at yahoo.com> > To: tutor at python.org > Sent: Saturday, October 27, 2007 9:55:05 AM > Subject: [Tutor] system call > > Hello, > I am trying to run a timing script but I need the python program to > stop and wait for the executable to finish. Does anyone have any > examples of doing this? > > Thanks > Python Newbie > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Five 1.4.1, > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > 4.1.1-51)], > PIL 1.1.6 _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ricaraoz at gmail.com Sat Oct 27 23:16:33 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 27 Oct 2007 18:16:33 -0300 Subject: [Tutor] system call In-Reply-To: <aaf235960710271308l49765797p7d9915b734a4f33c@mail.gmail.com> References: <549364.38708.qm@web60123.mail.yahoo.com> <aaf235960710271308l49765797p7d9915b734a4f33c@mail.gmail.com> Message-ID: <4723AAB1.2000606@bigfoot.com> John wrote: > I have the exact same situation, but system doesn't seem to wait. Here > is my pseudo code: > > for i in attempts: #attempts holds strings of shellscripts > cmd="%s which runs many different shell scripts and takes about > an hour" % (i) > os.system(cmd) > #debugging > print "Finished with %s" % (i) > raw_input("More debugging, shouldn't see this until shell > scripts are finished!") > > > But it prints the print statement and waits for raw_input instantly... > Any thoughts? > Have you tried os.spawnl(...) with mode os.P_WAIT ? > > > On 10/27/07, *Eric Walker* <sli1que at yahoo.com > <mailto:sli1que at yahoo.com>> wrote: > > disregard this one. I found the answer. I was using spawn instead > of os.system. > > Thanks. > > > ----- Original Message ---- > From: Eric Walker < sli1que at yahoo.com <mailto:sli1que at yahoo.com>> > To: tutor at python.org <mailto:tutor at python.org> > Sent: Saturday, October 27, 2007 9:55:05 AM > Subject: [Tutor] system call > > Hello, > I am trying to run a timing script but I need the python program to > stop and wait for the executable to finish. Does anyone have any > examples of doing this? > From alan.gauld at btinternet.com Sun Oct 28 00:54:09 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Oct 2007 23:54:09 +0100 Subject: [Tutor] 'source' in python or preloading variables References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> Message-ID: <fg0fio$i8u$1@ger.gmane.org> "John" <washakie at gmail.com> wrote >I have a file sitelocations: > > STN_id[1]=AAA > STNlat[1]=58.800000 > STNlon[1]=17.400000 > STNelv[1]=20 > STN_id[2]=BBB > STNlat[2]=42.450000 > STNlon[2]=25.583333 > STNelv[2]=2925 > > which in shell scripts I can simple 'source'. > In Python I have to: > sitesFile=file('sitelocations','r') > sites=sitesFile.readlines() > i=0; > for l in sites: > if i==0: > STN_id.append(l.split('=')[1].strip('\n')); i+=1; > elif i==1: > STNlat.append(l.split('=')[1].strip('\n')); i+=1; > elif i==2: > STNlon.append(l.split('=')[1].strip('\n')); i+=1; > else: > STNelv.append(l.split('=')[1].strip('\n')); i=0; > > Is there a better way?? Yes, use the file as an iterator: sitesFile = open('sitelocations','r') for line in sitesFile: STN_id.append(line.split('=')[1]) line = sitesFile.next().strip() STNlat.append(line.split('=')[1]) line = sitesFile.next().strip() STNlon.append(line.split('=')[1]) line = sitesFile.next().strip() STNelv.append(line.split('=')[1]) No need for messy regex or unsafe exec. The dictionary solution is potentially safer still however since it eliminates the line order dependancy. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Oct 28 00:57:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Oct 2007 23:57:56 +0100 Subject: [Tutor] question re type() References: <20071027112905.AFC3C1E4005@bag.python.org><ffv9ed$6m3$1@ger.gmane.org> <20071027183456.GA7586@cutter.rexx.com> Message-ID: <fg0fpr$ird$1@ger.gmane.org> "Dave Kuhlman" <dkuhlman at rexx.com> wrote > Calling type(n) for any integer seems to return the same object. > I checked with id(). I would hope so since they are all of the same type. It thus makes sense that they all return a reference to the same type object. > So, should we be using: > > if type(n) is type(42) You could, it shouldn't make any difference in this context. > or, as suggested by Aditya Lal in another message in this thread: > > import types > > if type(n) is types.IntType > > Or, is this a frivolous question that makes no difference? 'is' or == can make a difference in some cases but I don't think this is one of them. Alan G From alan.gauld at btinternet.com Sun Oct 28 01:03:06 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 00:03:06 +0100 Subject: [Tutor] More type() puzzlement References: <20071027150614.6FE6B1E4027@bag.python.org> Message-ID: <fg0g3h$jkj$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > n = 10000000000 You start with n as a long. > print type(n) > while True: > if type(n) == long: > n -= 1000000 A long minus an int gives a long: >>> n = long(42) >>> n 42L >>> n - 3 39L So n never changes into an int even though it is within the range of an int. HTH, Alan G From alan.gauld at btinternet.com Sun Oct 28 01:09:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 00:09:35 +0100 Subject: [Tutor] system call References: <456243.62506.qm@web60122.mail.yahoo.com> Message-ID: <fg0gfm$kgd$1@ger.gmane.org> "Eric Walker" <sli1que at yahoo.com> wrote > I am trying to run a timing script but I need the python program > to stop and wait for the executable to finish. Does anyone have > any examples of doing this? There are several ways to do it depending on what exactly you are trying to do. We need a bit more detail. If the "timing script" is an externalo program then if you run it using os.system() your code will wait(ie block) until system() returms - which is when the program executed exits. However os.system() is a bit of a blunt tool and often not the best solution. If we know what the real problem is we might do better. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Oct 28 01:12:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 00:12:46 +0100 Subject: [Tutor] system call References: <549364.38708.qm@web60123.mail.yahoo.com> <aaf235960710271308l49765797p7d9915b734a4f33c@mail.gmail.com> Message-ID: <fg0gll$ksv$1@ger.gmane.org> "John" <washakie at gmail.com> wrote > for i in attempts: #attempts holds strings of shellscripts > cmd="%s which runs many different shell scripts and takes > about an > hour" % (i) > os.system(cmd) > #debugging > print "Finished with %s" % (i) > raw_input("More debugging, shouldn't see this until shell > scripts > are finished!") > > > But it prints the print statement and waits for raw_input > instantly... Any > thoughts? Have you checked the return code from system is zero - ie successfuil execution? If there is an error in your command string (or you have set the command to execute in the backgrouynd with &) the system call will return immediately with an error. Also I assume your cmd is not really like the one above which would always give an error! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Oct 28 01:06:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 00:06:11 +0100 Subject: [Tutor] More type() puzzlement References: <20071027150614.6FE6B1E4027@bag.python.org><5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com> <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com > <20071027165329.A67D21E4015@bag.python.org> Message-ID: <fg0g9b$k0a$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote >> Hence if type(n) is already long it does not have to get converted >> to int to accommodate something small. > > And that's not a bug? No its expected behaviour. If you start with a float and add an integer the result is a float. Why should long act any different? >>> n = 4.0 >>> n + 2 6.0 > So the largest int is 2147483647, or 2**31 - 1. > (I know this is all obvious to most, but I still get a kick out of > doing it.) Yep, exactly what sys.maxint tells you. ;-) >>> import sys >>> sys.maxint 2147483647 >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Oct 28 01:20:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 00:20:27 +0100 Subject: [Tutor] position References: <1d987df30710271252j4cf0239fhe7399c79ec11cfd4@mail.gmail.com> Message-ID: <fg0h42$ltt$1@ger.gmane.org> "linda.s" <samrobertsmith at gmail.com> wrote >I have a string a= "qq,eee,rrr". >>>> a.index(",") > 2 > It is the position of the first "," in a. > Is that possible to find the Nth "," in a if a is a very long string > and I need know the position of the Nth ","? Yes but not directly. index takes a couple of optional parameters S.index(sub [,start [,end]]) -> int So by repeating the index call in a loop using the previous index as youur start position you an get it untested pseudo code def nth_index(aString, aChar, N): n = 0 for i in range(N): n = aString.index(aChar, n) return n This should return the Nth index value or raise a ValueError if less than N occurences exist HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Oct 28 01:25:14 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 27 Oct 2007 23:25:14 +0000 (GMT) Subject: [Tutor] about Tix Message-ID: <587858.31005.qm@web86703.mail.ird.yahoo.com> > This looks to me like the Tix DLL hasn't been installed or it's > installed in a folder where it can''t be found. The Tix module > is just a wrapper round the Tix DLL so you need both. > > I wonder where should I install Tix DLL I'd look for the other DLLs in the Python tree or alternatively put it in Windows\System32 which is rthe default place Windows looks for DLLs... BTW If that doesn't work pull it out again or it will clutter up the system32 directory forever more! Alan G. From rdm at rcblue.com Sun Oct 28 01:47:19 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 27 Oct 2007 16:47:19 -0700 Subject: [Tutor] question re type() In-Reply-To: <20071027183456.GA7586@cutter.rexx.com> References: <20071027112905.AFC3C1E4005@bag.python.org> <ffv9ed$6m3$1@ger.gmane.org> <20071027183456.GA7586@cutter.rexx.com> Message-ID: <20071027234729.8B3311E4010@bag.python.org> At 11:34 AM 10/27/2007, Dave Kuhlman wrote: >On Sat, Oct 27, 2007 at 01:03:18PM +0100, Alan Gauld wrote: > > > if type(n) == int > > > > Or just use an instance of the same type: > > > > if type(n) == type(42) > >Calling type(n) for any integer seems to return the same object. >I checked with id(). > >So, should we be using: > > if type(n) is type(42) > >or, as suggested by Aditya Lal in another message in this thread: > > import types > > if type(n) is types.IntType > >Or, is this a frivolous question that makes no difference? I don't know. But lets see. We know this: >>> type(2147483648) <type 'long'> >>> type(2147483647) <type 'int'> >>> Let's try: ===================== #!/usr/bin/env python #coding=utf-8 n = 2147483650 print n, type(n) print while n > 2147483645: if type(n) == type(10000000000): n -= 1 print n, type(n) else: break print print n, type(n) =================== This outputs 2147483650 <type 'long'> 2147483649 <type 'long'> 2147483648 <type 'long'> 2147483647 <type 'long'> 2147483646 <type 'long'> 2147483645 <type 'long'> 2147483645 <type 'long'> And also try: ===================== #!/usr/bin/env python #coding=utf-8 import types n = 2147483650 print n, type(n) print while n > 2147483645: if type(n) is types.LongType: n -= 1 print n, type(n) else: break print print n, type(n) ========================== which outputs 2147483650 <type 'long'> 2147483649 <type 'long'> 2147483648 <type 'long'> 2147483647 <type 'long'> 2147483646 <type 'long'> 2147483645 <type 'long'> 2147483645 <type 'long'> Dick From david at boddie.org.uk Sun Oct 28 00:39:58 2007 From: david at boddie.org.uk (David Boddie) Date: Sun, 28 Oct 2007 00:39:58 +0200 Subject: [Tutor] underlying C/C++ object has been deleted Message-ID: <200710280039.59571.david@boddie.org.uk> On Thu Oct 25 06:45:38 CEST 2007, Lawrence Shafer wrote: > I am trying to convert a program with hand coded QT over to using UI > files from QT Designer. I am getting the error below and do not > understand what's going on. This error occurs when an object referred to by Python and Qt is deleted by Qt (i.e, on the C++ side), leaving a dangling reference on the Python side. There is another common error people make with this that occurs when a QObject subclass isn't initialized properly, but I don't think that this is the case here. > I have a feeling I need to add self. to > something in here, but I'm not sure what. Adding self may not help, but it depends on the exact problem. > Is this enough code for you to > see whats going on?? If not I can upload the project somewhere. Thanks, > Lawrence > > The error, > > Traceback (most recent call last): > File "atf.py", line 113, in on_actionOpen_triggered > self.open() > File "atf.py", line 56, in open > if self.isUntitled and self.textBrowser.document().isEmpty() and not > self.isWindowModified(): > RuntimeError: underlying C/C++ object has been deleted It's difficult to know what went wrong without being able to experiment with the code to determine exactly which object has been deleted, and the file you referred to in your later message doesn't contain the code that this traceback refers to, so it's a little difficult to diagnose the problem. However, as you suggest, it seems that you're doing some strange things with the .ui file. In your class's __init__() method, you first call the init() method, in which you create a QTextBrowser widget and set it as the central widget of your QMainWindow subclass: def init(self): self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.isUntitled = True self.textBrowser = QtGui.QTextBrowser() self.setCentralWidget(self.textBrowser) self.connect(self.textBrowser.document(), QtCore.SIGNAL("contentsChanged()"), self.documentWasModified) What implicitly happens here is that the QMainWindow takes ownership of the QTextBrowser on the C++ side. Then, after doing that, you instantiate the Ui_mainWindow class which was created using Qt Designer and set up its user interface within your QMainWindow subclass: self.ui = Ui_mainWindow() self.ui.setupUi(self) Since the user interface defined in this class will almost certainly contain a central widget of its own, your original central widget will be replaced and, since it is being maintained on the C++ side, it will be deleted. This means that you are left with a reference to a deleted object (self.textBrowser) and the signal-slot connection you made in init() will have been broken. The solution to this is to set up the QTextBrowser using Qt Designer. Just drag it into the central area of the main window and apply a layout. Hope this helps, David From rdm at rcblue.com Sun Oct 28 02:14:48 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 27 Oct 2007 17:14:48 -0700 Subject: [Tutor] More type() puzzlement In-Reply-To: <fg0g9b$k0a$1@ger.gmane.org> References: <20071027150614.6FE6B1E4027@bag.python.org> <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com> <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com > <20071027165329.A67D21E4015@bag.python.org> <fg0g9b$k0a$1@ger.gmane.org> Message-ID: <20071028001452.BF1D91E405A@bag.python.org> At 04:06 PM 10/27/2007, Alan Gauld wrote: >"Dick Moores" <rdm at rcblue.com> wrote > > >> Hence if type(n) is already long it does not have to get converted > >> to int to accommodate something small. > > > > And that's not a bug? > >No its expected behaviour. >If you start with a float and add an integer the result is a float. >Why should long act any different? > > >>> n = 4.0 > >>> n + 2 >6.0 So you're saying that it's to be expected that the analogy, "int is to long as int is to float" will hold. But why should it be expected to hold? float and long are completely different animals, no? Dick From samrobertsmith at gmail.com Sun Oct 28 02:08:06 2007 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 27 Oct 2007 18:08:06 -0700 Subject: [Tutor] position In-Reply-To: <fg0h42$ltt$1@ger.gmane.org> References: <1d987df30710271252j4cf0239fhe7399c79ec11cfd4@mail.gmail.com> <fg0h42$ltt$1@ger.gmane.org> Message-ID: <1d987df30710271808m11f48c2kae3dca8246c83aa6@mail.gmail.com> On 10/27/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > "linda.s" <samrobertsmith at gmail.com> wrote > > >I have a string a= "qq,eee,rrr". > >>>> a.index(",") > > 2 > > It is the position of the first "," in a. > > Is that possible to find the Nth "," in a if a is a very long string > > and I need know the position of the Nth ","? > > Yes but not directly. > index takes a couple of optional parameters > > S.index(sub [,start [,end]]) -> int > > So by repeating the index call in a loop using the previous > index as youur start position you an get it > > untested pseudo code > > def nth_index(aString, aChar, N): > n = 0 > for i in range(N): > n = aString.index(aChar, n) > return n > should be: def nth_index(aString, aChar, N): n = 0 for i in range(N): n = aString.index(aChar, n+1) return n From sli1que at yahoo.com Sun Oct 28 02:42:13 2007 From: sli1que at yahoo.com (Eric Walker) Date: Sat, 27 Oct 2007 18:42:13 -0700 (PDT) Subject: [Tutor] system call Message-ID: <355379.98932.qm@web60125.mail.yahoo.com> Alan, The problem is that I have another tool that has an initialization period when you start it up. I want to see how long it takes for it to start up or initialize. So, I set up the tool to startup and after it finishes the init stage, load up a file which has a custom procedure. Then run this custom procedure that executes an exit command. So, to time the entire init process, I want to use python. I first take a time stamp. Then execute the tool with os.system. Once it finishes, I take another time stamp. Subtract the two and get a general time of execution or init for the other program. What do you think? python newbie... ----- Original Message ---- From: Alan Gauld <alan.gauld at btinternet.com> To: tutor at python.org Sent: Saturday, October 27, 2007 4:09:35 PM Subject: Re: [Tutor] system call "Eric Walker" <sli1que at yahoo.com> wrote > I am trying to run a timing script but I need the python program > to stop and wait for the executable to finish. Does anyone have > any examples of doing this? There are several ways to do it depending on what exactly you are trying to do. We need a bit more detail. If the "timing script" is an externalo program then if you run it using os.system() your code will wait(ie block) until system() returms - which is when the program executed exits. However os.system() is a bit of a blunt tool and often not the best solution. If we know what the real problem is we might do better. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071027/1f0ab92d/attachment-0001.htm From alan.gauld at btinternet.com Sun Oct 28 09:53:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 08:53:53 -0000 Subject: [Tutor] More type() puzzlement References: <20071027150614.6FE6B1E4027@bag.python.org><5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com><5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com ><20071027165329.A67D21E4015@bag.python.org><fg0g9b$k0a$1@ger.gmane.org> <20071028001452.BF1D91E405A@bag.python.org> Message-ID: <fg1in9$orh$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > So you're saying that it's to be expected that the analogy, "int is > to long as int is to float" will hold. But why should it be expected > to hold? float and long are completely different animals, no? No, they are all types of numbers. The general rule is that Python (and most other languages) will convert a simpler type to a more "powerful" type but never the other way around - you may need to keep the power... Alan G From alan.gauld at btinternet.com Sun Oct 28 10:09:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 09:09:10 -0000 Subject: [Tutor] system call References: <355379.98932.qm@web60125.mail.yahoo.com> Message-ID: <fg1jju$qsc$1@ger.gmane.org> "Eric Walker" <sli1que at yahoo.com> wrote > The problem is that I have another tool that has an initialization > period when you start it up. I want to see how long it takes Have you considered just using the Unix time command? > So, to time the entire init process, I want to use python. As an exercise its fair enough, but the OS time command is probably just as effective for this kind of task. Reimplementing standard OS tools can be a great learning tool so if that is your aim, carry on with it. The os.system route (or subprocess.call) should be fine for what you need. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From vvinuv at gmail.com Sun Oct 28 10:57:07 2007 From: vvinuv at gmail.com (Vinu Vikram) Date: Sun, 28 Oct 2007 15:27:07 +0530 Subject: [Tutor] how to run function only for a pre-defined time In-Reply-To: <ffv9o1$7gd$1@ger.gmane.org> References: <637563b70710270456i58dad9ear8695d7f3aeb3afb2@mail.gmail.com> <ffv9o1$7gd$1@ger.gmane.org> Message-ID: <637563b70710280257j564a99aenf6c1a2c14a4498ef@mail.gmail.com> Hi alan Thanks. But if I write a code like the followiing, how I can stop the thread #!/usr/bin/env python import threading import time, os class Infi(threading.Thread): def __init__(self, a): self.a = a threading.Thread.__init__(self) def run(self): i = 1 while i==1: print self.a time.sleep(.5) self.a += 1 if __name__ == '__main__': t = Infi(1) t.start() time.sleep(2) if t.isAlive(): print 'Here I want to stop the thread (the while loop) and continue with the remaining part of the script' obj_file = open(clus_cata,'r') try: pnames = obj_file.readline().split() except: pass ...... ...... ...... and so on Thanks in Advance Vinu Vikram On 10/27/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > > "Vinu Vikram" <vvinuv at gmail.com> wrote > > > Could anybody try to tell me whether it is possible to run a > > function only > > for a particular time period. In my python script I call some third > > party > > function which some time won't give results. I would like to write > > the > > script in such a way that, it will wait for the result from this > > function > > for some time, say 10 seconds, and if it fails to get any results > > within > > that time (10 seconds), the script should skip that function and > > stop the > > program. > > > > I think you will need to use threading to launch your function in a > separate thread. If the thread dopesn't end in time you can proceed > in the main thread to kill the thread and exit the program. > > Read about Python threading here: > > http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- VINU VIKRAM http://iucaa.ernet.in/~vvinuv/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071028/e8548993/attachment.htm From washakie at gmail.com Sun Oct 28 11:30:43 2007 From: washakie at gmail.com (John) Date: Sun, 28 Oct 2007 12:30:43 +0200 Subject: [Tutor] system call In-Reply-To: <fg1jju$qsc$1@ger.gmane.org> References: <355379.98932.qm@web60125.mail.yahoo.com> <fg1jju$qsc$1@ger.gmane.org> Message-ID: <aaf235960710280330l502b7bd9g990c32bcd2cd7ec3@mail.gmail.com> Here is my actual code (a section of a long script): if os.path.isdir(ad) and aRun.split('_')[0]==STN_id[i] and in (aRun.split ('_')[1]): make_pages=os.path.join(BASEDIR,STN_id[i],SUBDIR[1],'make_pages') sedstr1="""cat %s | sed -e 's/ASYSmin=[0-9][0-9]*/ASYSmin=%s/g' > jnk""" % (make_webpages,nf+1) sedstr2="""cat jnk | sed -e 's/ASYSmax=[0-9][0-9]*/ASYSmax=%s/g' > %s""" % (nf+1,make_pages) cmd="""%s > %s """ % (make_pages,STN_id[i]+'.mw.out') print """ Now running make_pages for: %s """ % (files[nf]) os.system(sedstr1) os.system(sedstr2) fail= os.system(cmd) print(cmd) if fail: print """For %s there was an error""" % (files[i]) os.wait() print """Finished for %s """ % (files[i]) raw_input('Continue?') make_pages is a shell script which usually is run with nohup and takes anywhere from 1-24 hours to run, depending on ASYSmin, ASYSmax. If there the same (which they are here) then it should take around one hour. Perphaps I need to change the os.wait somehow? Or structure the os.systemcall for cmd a little differently??? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071028/379d6560/attachment.htm From washakie at gmail.com Sun Oct 28 11:37:12 2007 From: washakie at gmail.com (John) Date: Sun, 28 Oct 2007 12:37:12 +0200 Subject: [Tutor] 'source' in python or preloading variables In-Reply-To: <fg0fio$i8u$1@ger.gmane.org> References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com> <fg0fio$i8u$1@ger.gmane.org> Message-ID: <aaf235960710280337k182c2dd1m66da10fae0480e14@mail.gmail.com> But won't if fail since the variabls in the file are not quoted? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071028/720d4053/attachment.htm From rdm at rcblue.com Sun Oct 28 11:49:07 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 28 Oct 2007 03:49:07 -0700 Subject: [Tutor] More type() puzzlement In-Reply-To: <fg1in9$orh$1@ger.gmane.org> References: <20071027150614.6FE6B1E4027@bag.python.org> <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com> <5df213700710270839y671b2458w480b4534e5320c3@mail.gmail.com > <20071027165329.A67D21E4015@bag.python.org> <fg0g9b$k0a$1@ger.gmane.org> <20071028001452.BF1D91E405A@bag.python.org> <fg1in9$orh$1@ger.gmane.org> Message-ID: <20071028104915.87DF81E4014@bag.python.org> At 01:53 AM 10/28/2007, you wrote: >"Dick Moores" <rdm at rcblue.com> wrote > > > So you're saying that it's to be expected that the analogy, "int is > > to long as int is to float" will hold. But why should it be expected > > to hold? float and long are completely different animals, no? > >No, they are all types of numbers. >The general rule is that Python (and most other languages) >will convert a simpler type to a more "powerful" type but never >the other way around - you may need to keep the power... Ah, got it. Finally. Thanks very much, Alan. Dick From washakie at gmail.com Sun Oct 28 11:58:57 2007 From: washakie at gmail.com (John) Date: Sun, 28 Oct 2007 12:58:57 +0200 Subject: [Tutor] killing bash, sshd... dangerous? Message-ID: <aaf235960710280358h6b5de4b7oa1b539b4af8d747a@mail.gmail.com> Hello, I've written a little script with the intention of killing all of my bash, sshd sessions... is this dangerous? How could I make it work so that it didn't kill the session it was run from (as it is I suppose I have to run it with nohup): #!/usr/bin/env python import os cmd="ps -u myuser | grep 'bash' > .ps" os.system(cmd) pid=[] fid=open('.ps','r') for line in fid: pid.append(line.split(' ')[0]) for i in pid: cmd="""kill -9 %s""" % (i) os.system(cmd) cmd="ps -u myuser | grep 'sshd' > .ps" os.system(cmd) pid=[] fid=open('.ps','r') for line in fid: pid.append(line.split(' ')[0]) for i in pid: cmd="""kill -9 %s""" % (i) os.system(cmd) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071028/9164d9f2/attachment.htm From alan.gauld at btinternet.com Sun Oct 28 16:37:26 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 15:37:26 -0000 Subject: [Tutor] 'source' in python or preloading variables References: <aaf235960710270549l7b9d5b42o21e9fee603aab0f4@mail.gmail.com><fg0fio$i8u$1@ger.gmane.org> <aaf235960710280337k182c2dd1m66da10fae0480e14@mail.gmail.com> Message-ID: <fg2abt$nu4$1@ger.gmane.org> "John" <washakie at gmail.com> wrote > But won't if fail since the variabls in the file are not quoted? No the quoting is only necessary if you use eval/exec. The quotes prevent the interpreter from treating them as variable names. If you read the values from the file they are already strings, no need for quoting. Alan G From tktucker at gmail.com Sun Oct 28 17:23:33 2007 From: tktucker at gmail.com (Tom Tucker) Date: Sun, 28 Oct 2007 12:23:33 -0400 Subject: [Tutor] killing bash, sshd... dangerous? In-Reply-To: <aaf235960710280358h6b5de4b7oa1b539b4af8d747a@mail.gmail.com> References: <aaf235960710280358h6b5de4b7oa1b539b4af8d747a@mail.gmail.com> Message-ID: <2a278ffe0710280923y3a119b0vaa8e008121921386@mail.gmail.com> Instead of reading in an outputfile (.ps), try reading from command output. The correct terminology escapes me (for file in os.popen(cmd).readlines():). Are you looking for a auto logout method? For example if no activity after X minutes kill the shell. Bash and a few other shells have this functionality already. On 10/28/07, John <washakie at gmail.com> wrote: > Hello, I've written a little script with the intention of killing all of my > bash, sshd sessions... is this dangerous? How could I make it work so that > it didn't kill the session it was run from (as it is I suppose I have to run > it with nohup): > > > > #!/usr/bin/env python > import os > > cmd="ps -u myuser | grep 'bash' > .ps" > os.system(cmd) > > pid=[] > fid=open('.ps','r') > for line in fid: > pid.append(line.split(' ')[0]) > > for i in pid: > cmd="""kill -9 %s""" % (i) > os.system(cmd) > > > cmd="ps -u myuser | grep 'sshd' > .ps" > os.system(cmd) > > pid=[] > fid=open('.ps','r') > for line in fid: > pid.append(line.split(' ')[0]) > > for i in pid: > cmd="""kill -9 %s""" % (i) > os.system(cmd) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From detroit371 at gmail.com Sun Oct 28 17:44:13 2007 From: detroit371 at gmail.com (Lawrence Shafer) Date: Sun, 28 Oct 2007 10:44:13 -0600 Subject: [Tutor] os.sys Message-ID: <4724BC5D.7040302@gmail.com> Why doesn't this fill otp with the output of ls?? (I know python has it's own file tools, I'm just playing around ;) import os cmd="""ls""" otp=os.system(cmd) print otp From jtp at nc.rr.com Sun Oct 28 17:55:58 2007 From: jtp at nc.rr.com (James) Date: Sun, 28 Oct 2007 12:55:58 -0400 Subject: [Tutor] os.sys In-Reply-To: <4724BC5D.7040302@gmail.com> References: <4724BC5D.7040302@gmail.com> Message-ID: <F8F52837-C48D-4F61-8423-BAB134C5AE6D@nc.rr.com> Try using the commands, instead. import commands cmd = 'ls' opt = commands.getoutput( cmd ) print opt More information found here: http://docs.python.org/lib/module-commands.html :) .james On Oct 28, 2007, at 12:44 PM, Lawrence Shafer wrote: > Why doesn't this fill otp with the output of ls?? (I know python has > it's own file tools, I'm just playing around ;) > > import os > cmd="""ls""" > otp=os.system(cmd) > print otp > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From sxkorean at gmail.com Sun Oct 28 18:01:24 2007 From: sxkorean at gmail.com (Andrew Nelsen) Date: Sun, 28 Oct 2007 13:01:24 -0400 Subject: [Tutor] os.sys In-Reply-To: <4724BC5D.7040302@gmail.com> References: <4724BC5D.7040302@gmail.com> Message-ID: <a783f25a0710281001r6ce01961g19aedc028f2dea2e@mail.gmail.com> On 10/28/07, Lawrence Shafer <detroit371 at gmail.com> wrote: > > Why doesn't this fill otp with the output of ls?? (I know python has > it's own file tools, I'm just playing around ;) > > import os > cmd="""ls""" > otp=os.system(cmd) > print otp > _______________________________________________ > Tutor maillist - Tutor at python.org I actually had the same question a while back. I'm still a newbie, but the advice I was given was to use popen(). ls = os.popen("ls").read() worked for me. Also, for Unix style OSes, you can import commands, and then it has getoutput(). Just my two cents. - Drew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071028/5c8d3e21/attachment.htm From alan.gauld at btinternet.com Sun Oct 28 19:58:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Oct 2007 18:58:59 -0000 Subject: [Tutor] os.sys References: <4724BC5D.7040302@gmail.com> Message-ID: <fg2m5r$kch$1@ger.gmane.org> "Lawrence Shafer" <detroit371 at gmail.com> wrote > Why doesn't this fill otp with the output of ls?? (I know python has > it's own file tools, I'm just playing around ;) > > otp=os.system(cmd) Because os.system returnsd the exit status of the command. zero means the command executed OK anything else is an error code. To get the output you need to read stdout or stderr. To do that, the current preferred mechanism is via the subprocess module which replaces os.system/os.popen/commands os.spawn etc etc. The documentation has examples. Also my web -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld tutor at the end of the OS topic has examples of subprocess.Popen as well as the older methods. HTH, From washakie at gmail.com Mon Oct 29 00:12:11 2007 From: washakie at gmail.com (John) Date: Mon, 29 Oct 2007 00:12:11 +0100 Subject: [Tutor] killing bash, sshd... dangerous? In-Reply-To: <2a278ffe0710280923y3a119b0vaa8e008121921386@mail.gmail.com> References: <aaf235960710280358h6b5de4b7oa1b539b4af8d747a@mail.gmail.com> <2a278ffe0710280923y3a119b0vaa8e008121921386@mail.gmail.com> Message-ID: <aaf235960710281612t5dcbbd80x178051d9ad7c77eb@mail.gmail.com> No, mostly just playing around with scripting.... and I have a problem sometimes with cygwin where logging out from bash session, the xterm hangs, so this seems to fix it... but it's not really the best solution... needs some mods, I'm sure. On 10/28/07, Tom Tucker <tktucker at gmail.com> wrote: > > Instead of reading in an outputfile (.ps), try reading from command > output. The correct terminology escapes me (for file in > os.popen(cmd).readlines():). > > Are you looking for a auto logout method? For example if no activity > after X minutes kill the shell. Bash and a few other shells have this > functionality already. > > > > > > On 10/28/07, John <washakie at gmail.com> wrote: > > Hello, I've written a little script with the intention of killing all of > my > > bash, sshd sessions... is this dangerous? How could I make it work so > that > > it didn't kill the session it was run from (as it is I suppose I have to > run > > it with nohup): > > > > > > > > #!/usr/bin/env python > > import os > > > > cmd="ps -u myuser | grep 'bash' > .ps" > > os.system(cmd) > > > > pid=[] > > fid=open('.ps','r') > > for line in fid: > > pid.append(line.split(' ')[0]) > > > > for i in pid: > > cmd="""kill -9 %s""" % (i) > > os.system(cmd) > > > > > > cmd="ps -u myuser | grep 'sshd' > .ps" > > os.system(cmd) > > > > pid=[] > > fid=open('.ps','r') > > for line in fid: > > pid.append(line.split(' ')[0]) > > > > for i in pid: > > cmd="""kill -9 %s""" % (i) > > os.system(cmd) > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/29550ca5/attachment.htm From brunson at brunson.com Mon Oct 29 00:39:30 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 28 Oct 2007 17:39:30 -0600 Subject: [Tutor] Offtopic: Re: killing bash, sshd... dangerous? In-Reply-To: <aaf235960710281612t5dcbbd80x178051d9ad7c77eb@mail.gmail.com> References: <aaf235960710280358h6b5de4b7oa1b539b4af8d747a@mail.gmail.com> <2a278ffe0710280923y3a119b0vaa8e008121921386@mail.gmail.com> <aaf235960710281612t5dcbbd80x178051d9ad7c77eb@mail.gmail.com> Message-ID: <47251DB2.3010402@brunson.com> John wrote: > No, mostly just playing around with scripting.... and I have a problem > sometimes with cygwin where logging out from bash session Hi John, This is a known bug. The fix is to install a real operating system. For more info, please see one of the following: http://distrowatch.com http://www.opensolaris.org http://www.freebsd.org ;-) Sincerely, e. > the xterm hangs, so this seems to fix it... but it's not really the > best solution... needs some mods, I'm sure. > > > On 10/28/07, *Tom Tucker* <tktucker at gmail.com > <mailto:tktucker at gmail.com>> wrote: > > Instead of reading in an outputfile (.ps), try reading from command > output. The correct terminology escapes me (for file in > os.popen(cmd).readlines():). > > Are you looking for a auto logout method? For example if no activity > after X minutes kill the shell. Bash and a few other shells have this > functionality already. > > > > > > On 10/28/07, John <washakie at gmail.com <mailto:washakie at gmail.com>> > wrote: > > Hello, I've written a little script with the intention of > killing all of my > > bash, sshd sessions... is this dangerous? How could I make it > work so that > > it didn't kill the session it was run from (as it is I suppose I > have to run > > it with nohup): > > > > > > > > #!/usr/bin/env python > > import os > > > > cmd="ps -u myuser | grep 'bash' > .ps" > > os.system(cmd) > > > > pid=[] > > fid=open('.ps','r') > > for line in fid: > > pid.append(line.split(' ')[0]) > > > > for i in pid: > > cmd="""kill -9 %s""" % (i) > > os.system(cmd) > > > > > > cmd="ps -u myuser | grep 'sshd' > .ps" > > os.system(cmd) > > > > pid=[] > > fid=open('.ps','r') > > for line in fid: > > pid.append(line.split(' ')[0]) > > > > for i in pid: > > cmd="""kill -9 %s""" % (i) > > os.system(cmd) > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org <mailto:Tutor at python.org> > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Five 1.4.1, > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > 4.1.1-51)], > PIL 1.1.6 > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Oct 29 11:44:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Oct 2007 06:44:25 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071027013958.A91981E4002@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> Message-ID: <4725B989.4050302@tds.net> Dick Moores wrote: > OK, here's a short script, which runs fine on Windows. What do I add > to have it run on unix as well? > > #!/usr/bin/env python > #coding=utf-8 > > try: > # windows or dos > import msvcrt > while True: > if msvcrt.kbhit(): > key = msvcrt.getch() > if key == "h": > print "Hello, World!" > break > print "Bye, World!" > > except ImportError: > # assume unix > import tty, termios http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 Kent From rdm at rcblue.com Mon Oct 29 12:08:53 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 04:08:53 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <4725B989.4050302@tds.net> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> Message-ID: <20071029110859.33D311E4014@bag.python.org> At 03:44 AM 10/29/2007, Kent Johnson wrote: >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 Kent, I'm still too dumb to see how to use that. Could you show a script using it that, say, prints 1 if '1' is pressed and 2 if '2' is? Thanks, Dick From bhaaluu at gmail.com Mon Oct 29 12:17:10 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 29 Oct 2007 07:17:10 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071029110859.33D311E4014@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> <20071029110859.33D311E4014@bag.python.org> Message-ID: <ea979d70710290417o1fbcd747lb7830157fc675dde@mail.gmail.com> # tty-example-2.py # Tue Oct 19 09:07:14 CEST 1999 # Fredrik Lundh fredrik at pythonware.com # http://mail.python.org/pipermail/python-list/1999-October/014151.html import sys try: # windows or dos import msvcrt getkey = msvcrt.getch except ImportError: # assume unix import tty, termios print dir(termios) def getkey(): file = sys.stdin.fileno() mode = termios.tcgetattr(file) try: tty.setraw(file, termios.TCSANOW) ch = sys.stdin.read(1) finally: termios.tcsetattr(file, termios.TCSANOW, mode) return ch print "press 'q/p/r/s' to quit..." while 1: ch = getkey() if ch == "q": break print ch, print On 10/29/07, Dick Moores <rdm at rcblue.com> wrote: > At 03:44 AM 10/29/2007, Kent Johnson wrote: > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 > > Kent, I'm still too dumb to see how to use that. Could you show a > script using it that, say, prints 1 if '1' is pressed and 2 if '2' is? > > Thanks, > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From kent37 at tds.net Mon Oct 29 12:28:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Oct 2007 07:28:25 -0400 Subject: [Tutor] question re type() In-Reply-To: <5df213700710270652i1c38571bl4a85edcfa54af977@mail.gmail.com> References: <20071027112905.AFC3C1E4005@bag.python.org> <ffv9ed$6m3$1@ger.gmane.org> <5df213700710270652i1c38571bl4a85edcfa54af977@mail.gmail.com> Message-ID: <4725C3D9.8000506@tds.net> Aditya Lal wrote: > or use types module > > import types > > if type(n) == types.IntType or type(n) == types.LongType : > blah! A few notes: - If you look at types.py, you find IntType = int LongType = long and so on for all the built-in types, so there is no need or advantage to importing types vs if type(n) == int - Common Python practice is to prefer the least restrictive type check possible. For Dick's specific case it doesn't matter, but I generally use isinstance() instead of checking for a specific type. The difference is that isinstance() is true for subtypes as well as the named type. You can also pass a tuple of types to isinstance() so you can say if isinstance(n, (int, long)) Kent From rdm at rcblue.com Mon Oct 29 12:32:30 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 04:32:30 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071029110859.33D311E4014@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> <20071029110859.33D311E4014@bag.python.org> Message-ID: <20071029113242.F117A1E403A@bag.python.org> At 04:08 AM 10/29/2007, Dick Moores wrote: >At 03:44 AM 10/29/2007, Kent Johnson wrote: > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 > >Kent, I'm still too dumb to see how to use that. Could you show a >script using it that, say, prints 1 if '1' is pressed and 2 if '2' is? Seems I should clarify that. I'm not looking for a script that echoes the key pressed. So I'll change that last line to "Could you show a script using it that, say, prints "Hello" if '1' is pressed and "Bye" if '2' is, AND uses <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892> Dick From kent37 at tds.net Mon Oct 29 12:33:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Oct 2007 07:33:28 -0400 Subject: [Tutor] system call In-Reply-To: <FBC34CF6-2074-402F-84D5-60A1AA9B87E3@nc.rr.com> References: <549364.38708.qm@web60123.mail.yahoo.com> <aaf235960710271308l49765797p7d9915b734a4f33c@mail.gmail.com> <FBC34CF6-2074-402F-84D5-60A1AA9B87E3@nc.rr.com> Message-ID: <4725C508.7090005@tds.net> James wrote: > The subprocess module is meant to replace spawn, popen2, os.system() > etc. if I'm not mistaken. Yes. > Take a look at this excellent resource I've used numerous times: > > http://www.python.org/dev/peps/pep-0324/ The same information (with better format but split between multiple pages) is in the module docs at http://docs.python.org/lib/module-subprocess.html Kent From kent37 at tds.net Mon Oct 29 12:36:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Oct 2007 07:36:46 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071029110859.33D311E4014@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> <20071029110859.33D311E4014@bag.python.org> Message-ID: <4725C5CE.2020107@tds.net> Dick Moores wrote: > At 03:44 AM 10/29/2007, Kent Johnson wrote: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 > > Kent, I'm still too dumb to see how to use that. Could you show a > script using it that, say, prints 1 if '1' is pressed and 2 if '2' is? from getch_recipe import getch print getch() Kent From bhaaluu at gmail.com Mon Oct 29 13:03:58 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 29 Oct 2007 08:03:58 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071029113242.F117A1E403A@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> <20071029110859.33D311E4014@bag.python.org> <20071029113242.F117A1E403A@bag.python.org> Message-ID: <ea979d70710290503y27711656tabe469ecfd3dc761@mail.gmail.com> On 10/29/07, Dick Moores <rdm at rcblue.com> wrote: > Seems I should clarify that. I'm not looking for a script that echoes > the key pressed. So I'll change that last line to "Could you show a > script using it that, say, prints "Hello" if '1' is pressed and > "Bye" if '2' is, AND uses > <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892> > Dick # tty-example-2.py # Tue Oct 19 09:07:14 CEST 1999 # Fredrik Lundh fredrik at pythonware.com # http://mail.python.org/pipermail/python-list/1999-October/014151.html import sys try: # windows or dos import msvcrt getkey = msvcrt.getch except ImportError: # assume unix import tty, termios print dir(termios) def getkey(): file = sys.stdin.fileno() mode = termios.tcgetattr(file) try: tty.setraw(file, termios.TCSANOW) ch = sys.stdin.read(1) finally: termios.tcsetattr(file, termios.TCSANOW, mode) return ch print "press 'q/p/r/s' to quit..." while 1: ch = getkey() if ch == "q": break elif ch == "1": print "Hello", elif ch == "2": print "Bye", print ch, print Like that? -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html From rdm at rcblue.com Mon Oct 29 13:46:42 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 05:46:42 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <ea979d70710290503y27711656tabe469ecfd3dc761@mail.gmail.com > References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> <20071029110859.33D311E4014@bag.python.org> <20071029113242.F117A1E403A@bag.python.org> <ea979d70710290503y27711656tabe469ecfd3dc761@mail.gmail.com> Message-ID: <20071029124647.6FED91E4012@bag.python.org> At 05:03 AM 10/29/2007, bhaaluu wrote: >On 10/29/07, Dick Moores <rdm at rcblue.com> wrote: > > Seems I should clarify that. I'm not looking for a script that echoes > > the key pressed. So I'll change that last line to "Could you show a > > script using it that, say, prints "Hello" if '1' is pressed and > > "Bye" if '2' is, AND uses > > <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892> > > Dick > ># tty-example-2.py ># Tue Oct 19 09:07:14 CEST 1999 ># Fredrik Lundh fredrik at pythonware.com ># http://mail.python.org/pipermail/python-list/1999-October/014151.html >import sys > >try: > # windows or dos > import msvcrt > getkey = msvcrt.getch >except ImportError: > # assume unix > import tty, termios > > print dir(termios) > > def getkey(): > file = sys.stdin.fileno() > mode = termios.tcgetattr(file) > try: > tty.setraw(file, termios.TCSANOW) > ch = sys.stdin.read(1) > finally: > termios.tcsetattr(file, termios.TCSANOW, mode) > return ch > >print "press 'q/p/r/s' to quit..." > >while 1: > ch = getkey() > if ch == "q": > break > elif ch == "1": > print "Hello", > elif ch == "2": > print "Bye", > print ch, > >print > > >Like that? Thanks! I modified it slightly: <http://www.rcblue.com/Python/toTestOnUnix.py>. Could a unix/linux user see if it works? Dick From brunson at brunson.com Mon Oct 29 15:54:53 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 29 Oct 2007 08:54:53 -0600 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071029124647.6FED91E4012@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> <20071029110859.33D311E4014@bag.python.org> <20071029113242.F117A1E403A@bag.python.org> <ea979d70710290503y27711656tabe469ecfd3dc761@mail.gmail.com> <20071029124647.6FED91E4012@bag.python.org> Message-ID: <4725F43D.90104@brunson.com> Dick Moores wrote: > At 05:03 AM 10/29/2007, bhaaluu wrote: > >> On 10/29/07, Dick Moores <rdm at rcblue.com> wrote: >> >>> Seems I should clarify that. I'm not looking for a script that echoes >>> the key pressed. So I'll change that last line to "Could you show a >>> script using it that, say, prints "Hello" if '1' is pressed and >>> "Bye" if '2' is, AND uses >>> <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892> >>> Dick >>> > > Thanks! I modified it slightly: > <http://www.rcblue.com/Python/toTestOnUnix.py>. Could a unix/linux > user see if it works? > > Dick > Seems to work fine under my version of Linux and Solaris 10. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Mon Oct 29 16:13:14 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 08:13:14 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <4725F43D.90104@brunson.com> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> <20071029110859.33D311E4014@bag.python.org> <20071029113242.F117A1E403A@bag.python.org> <ea979d70710290503y27711656tabe469ecfd3dc761@mail.gmail.com> <20071029124647.6FED91E4012@bag.python.org> <4725F43D.90104@brunson.com> Message-ID: <20071029151318.AFB931E4012@bag.python.org> At 07:54 AM 10/29/2007, Eric Brunson wrote: >Dick Moores wrote: >>At 05:03 AM 10/29/2007, bhaaluu wrote: >> >>>On 10/29/07, Dick Moores <rdm at rcblue.com> wrote: >>> >>>>Seems I should clarify that. I'm not looking for a script that echoes >>>>the key pressed. So I'll change that last line to "Could you show a >>>>script using it that, say, prints "Hello" if '1' is pressed and >>>>"Bye" if '2' is, AND uses >>>><http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892> >>>>Dick >>>> >> >>Thanks! I modified it slightly: >><http://www.rcblue.com/Python/toTestOnUnix.py>. Could a unix/linux >>user see if it works? >> >>Dick >> > >Seems to work fine under my version of Linux and Solaris 10. Great! Thanks. Care to try another one?: <http://www.rcblue.com/Python/toTestOnUnix2.py>. It uses the Cookbook recipe Kent found for me (<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892>). Dick From washakie at gmail.com Mon Oct 29 16:22:29 2007 From: washakie at gmail.com (John) Date: Mon, 29 Oct 2007 16:22:29 +0100 Subject: [Tutor] calculation with arrays: shape mismatch Message-ID: <aaf235960710290822q60a6c18ap5db379f0d78595a6@mail.gmail.com> Does anyone have an idea why I can't do this? for k in range(nr): contribution=N.zeros(shape(H['area'])) contribution=[contribution+grid[:,:,z:,k,0]/A for z in range(len(H['outheight']))] zplot[:,:,k]=zplot[:,:,k]+contribution; And on the interactive line: >>> shape(contribution) (360, 180) >>> shape(grid[:,:,0,0,0]) (360, 180) >>> But I get the error: ValueError: shape mismatch: objects cannot be broadcast to a single shape for the highlighted line. Thanks!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/3bcffc76/attachment-0001.htm From mlangford.cs03 at gtalumni.org Mon Oct 29 15:59:34 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 29 Oct 2007 10:59:34 -0400 Subject: [Tutor] Build exe on Vista, have it run on XP? Message-ID: <82b4f5810710290759h33b5f8e3ja5a32cd1b668a74a@mail.gmail.com> I'm trying to build a exe on a vista system using py2exe. It will deploy to vista and XP systems. If it matters, the application uses pyserial, as well. I have VS Studio 2005 installed on this laptop as well. I've found this so far that seems to be identical to what I'm seeing (for non-python programs): http://www.thescripts.com/forum/thread611031.html When I attempt to run, I get "The procedure entry point _except_handler4_common could not be located in the dynamic link library mscvrt.dll." Apparently vista has one more _except_handler#_common function than XP does. I've used py2exe several times before (however not recenty, as it was before Vista came out). I'm using a very basic setup file right now: from distutils.core import setup import py2exe setup(console=['responderbot.py']) Are there any ways to either py2exe work or any other exe builder for my build environment and deployment scenario? I don't really want to dig around in py2exe/pyserial internals to force it to use the dll's that the MS support person said it should be using. Will any automated exe builder work where I am? I've heard IronPython can compile down to an exe....is it a valid alternative? Should my CPython utility be compatible with ipy? I only use the random,time,sys, and serial modules. I really know nothing about ipy. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/b9031d35/attachment.htm From rdm at rcblue.com Mon Oct 29 16:27:48 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 08:27:48 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <ffus00$3j6$1@ger.gmane.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <ffus00$3j6$1@ger.gmane.org> Message-ID: <20071029153324.DD2D61E4014@bag.python.org> At 01:13 AM 10/27/2007, Alan Gauld wrote: >Take a look at my Event Driven programming topic. It contains a >simple key echo program using msvcrt and instructions for Linux >users to convert it to use curses. > > From that you should be able to create a dual platform version. Alan, I'm afraid I wasn't able to, using <http://www.freenetpages.co.uk/hp/alan.gauld/>. Especially because I couldn't test what I was coming up with. Could you do it for me, for this tiny script? =============================== #!/usr/bin/env python #coding=utf-8 import msvcrt while True: if msvcrt.kbhit(): key = msvcrt.getch() if key == "q": break elif key == "h": print "Hello" elif key == "b": print "Bye" =============================== Dick From alan.gauld at btinternet.com Mon Oct 29 16:50:43 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Oct 2007 15:50:43 -0000 Subject: [Tutor] calculation with arrays: shape mismatch References: <aaf235960710290822q60a6c18ap5db379f0d78595a6@mail.gmail.com> Message-ID: <fg4vgs$trv$1@ger.gmane.org> "John" <washakie at gmail.com> wrote > > But I get the error: > ValueError: shape mismatch: objects cannot be broadcast to a single > shape > > for the highlighted line. When sending error messages send the entire error traceback not just the summary message. Error traces are full of useful information, it helps if we can see it all. For example which is the "highlighted line"? Alan G. From brunson at brunson.com Mon Oct 29 17:06:43 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 29 Oct 2007 10:06:43 -0600 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071029151318.AFB931E4012@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <ea979d70710260500obb4ed20q699669e1c648d030@mail.gmail.com> <20071027013958.A91981E4002@bag.python.org> <4725B989.4050302@tds.net> <20071029110859.33D311E4014@bag.python.org> <20071029113242.F117A1E403A@bag.python.org> <ea979d70710290503y27711656tabe469ecfd3dc761@mail.gmail.com> <20071029124647.6FED91E4012@bag.python.org> <4725F43D.90104@brunson.com> <20071029151318.AFB931E4012@bag.python.org> Message-ID: <47260513.9040307@brunson.com> Dick Moores wrote: > At 07:54 AM 10/29/2007, Eric Brunson wrote: > >> Dick Moores wrote: >> >>> At 05:03 AM 10/29/2007, bhaaluu wrote: >>> >>> >>>> On 10/29/07, Dick Moores <rdm at rcblue.com> wrote: >>>> >>>> >>>>> Seems I should clarify that. I'm not looking for a script that echoes >>>>> the key pressed. So I'll change that last line to "Could you show a >>>>> script using it that, say, prints "Hello" if '1' is pressed and >>>>> "Bye" if '2' is, AND uses >>>>> <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892> >>>>> Dick >>>>> >>>>> >>> Thanks! I modified it slightly: >>> <http://www.rcblue.com/Python/toTestOnUnix.py>. Could a unix/linux >>> user see if it works? >>> >>> Dick >>> >>> >> Seems to work fine under my version of Linux and Solaris 10. >> > > Great! Thanks. Care to try another one?: > <http://www.rcblue.com/Python/toTestOnUnix2.py>. It uses the Cookbook > recipe Kent found for me > (<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892>). > Works fine. > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From washakie at gmail.com Mon Oct 29 17:00:05 2007 From: washakie at gmail.com (John) Date: Mon, 29 Oct 2007 17:00:05 +0100 Subject: [Tutor] calculation with arrays: shape mismatch In-Reply-To: <fg4vgs$trv$1@ger.gmane.org> References: <aaf235960710290822q60a6c18ap5db379f0d78595a6@mail.gmail.com> <fg4vgs$trv$1@ger.gmane.org> Message-ID: <aaf235960710290900v592ffa9cge61226b23e55e4d6@mail.gmail.com> Sorry, here's the output from the command line >>>run Day_footprint.py trying... header has been opened succes! Reading grid 20060511000000 at: Mon Oct 29 16:57:57 2007 processing: 20060511000000 Traceback (most recent call last): File "Day_footprint.py", line 48, in ? contribution=[contribution+grid[:,:,z:,k,0]/A for z in range(len(H['outheigh t']))] ValueError: shape mismatch: objects cannot be broadcast to a single shape >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/dc0b2b93/attachment.htm From rdm at rcblue.com Mon Oct 29 23:14:28 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 15:14:28 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071026091813.BE7CC1E401F@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> Message-ID: <20071029221433.69B1A1E4007@bag.python.org> I've developed chessTimer a bit further: <http://www.rcblue.com/Python/chessTimerForWebV9.py> I'm still hoping for some constructive criticism. But I also thought I'd mention again the points I have doubts about: 1. Is wrapping the long lines where I have done so OK? 2. I've used 1 for White player, -1 for Black player, and (-1)*player to alternate players. Is there a better way? 3. I've used a lot of variables. Too Many? 4. Should more of the code be in functions? 5. Is there a way to collapse lines 130-137?: if player == 1: # player is White whiteMoveCounter += 1 print "Black to make move %d" % (blackMoveCounter) remainingWhiteTime -= timeUsedThisMove elif player == -1: # player is Black blackMoveCounter += 1 print "White to make move %d" % (whiteMoveCounter) remainingBlackTime -= timeUsedThisMove 6. I thought I had a way to make this script useable on unix as well as Windows. Thus the section with the 3 classes. But it won't run on unix, because it was necessary to import msvcrt outside of the classes--it wouldn't compile otherwise, and because of the need for the line 'if msvcrt.kbhit():' (line 116). I hope I'm wrong about this, and someone can show me how to fix it so that the unix people can give me some criticism/advice as well. Thanks, Dick Moores From danrfreeman at gmail.com Mon Oct 29 20:46:06 2007 From: danrfreeman at gmail.com (Dan Freeman) Date: Mon, 29 Oct 2007 15:46:06 -0400 Subject: [Tutor] script ? Message-ID: <ea8876fe0710291246v335c4a4j2ea6bfc320d25496@mail.gmail.com> How can I have this script exucute a .exe file instead of beeping the system speaker? __________________________________________ import os import time z = 2 while z ==2: connected = False while not connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("159.215.49.8.116:59999"): print "\a\a\a\a\aMatch!" connected = True else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) amount=0 while connected: o=os.popen("netstat -an") for l in o: try: if l.split()[1].endswith("159.215.49.8:59999"): print "Still There" connected = True amount +=1 print amount else: print "Nothing" except IndexError: print "Index Exception" time.sleep(1) if amount == 1: amount -=1 else: print "It's Gone" connected = False print "\a\a" raw_input("Press Enter to close") -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/fc5acf24/attachment.htm From alan.gauld at btinternet.com Tue Oct 30 00:15:33 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Oct 2007 23:15:33 -0000 Subject: [Tutor] script ? References: <ea8876fe0710291246v335c4a4j2ea6bfc320d25496@mail.gmail.com> Message-ID: <fg5pit$tka$1@ger.gmane.org> "Dan Freeman" <danrfreeman at gmail.com> wrote > How can I have this script exucute a .exe file instead of beeping > the system > speaker? The same way you ran netstat - which is an .exe... Of course, nowadays you probably should be using subprocess.Popen instead os os.popen, but thats a minor tik. Also if you don't need the output returned you could try subprocess.call() (or on older systems os.system()) You'll find more discussion of this with examples in the OS topic of my tutorial, near the end. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > __________________________________________ > > import os > import time > > z = 2 > > while z ==2: > > connected = False > while not connected: > o=os.popen("netstat -an") Here is an exe being run... > for l in o: > try: > if l.split()[1].endswith("159.215.49.8.116:59999"): > print "\a\a\a\a\aMatch!" > connected = True > else: > print "Nothing" > except IndexError: > print "Index Exception" > time.sleep(1) > > amount=0 > while connected: > o=os.popen("netstat -an") > for l in o: > try: > if l.split()[1].endswith("159.215.49.8:59999"): > print "Still There" > connected = True > amount +=1 > print amount > else: > print "Nothing" > except IndexError: > print "Index Exception" > time.sleep(1) > if amount == 1: > amount -=1 > else: > print "It's Gone" > connected = False > > print "\a\a" > > raw_input("Press Enter to close") > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Oct 30 00:24:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Oct 2007 23:24:28 -0000 Subject: [Tutor] calculation with arrays: shape mismatch References: <aaf235960710290822q60a6c18ap5db379f0d78595a6@mail.gmail.com><fg4vgs$trv$1@ger.gmane.org> <aaf235960710290900v592ffa9cge61226b23e55e4d6@mail.gmail.com> Message-ID: <fg5q3k$v12$1@ger.gmane.org> "John" <washakie at gmail.com> wrote > Sorry, here's the output from the command line > >>>>run Day_footprint.py Sorry for all the questions but I've never seen that "run" syntax before. What environment are you running? What IDE/OS/Python version etc? > trying... > header has been opened > succes! > Reading grid 20060511000000 at: Mon Oct 29 16:57:57 2007 > processing: 20060511000000 > > > Traceback (most recent call last): > File "Day_footprint.py", line 48, in ? > contribution=[contribution+grid[:,:,z:,k,0]/A for z in > range(len(H['outheigh > t']))] > ValueError: shape mismatch: objects cannot be broadcast to a single > shape Hmm, in this case the error isn't telli8ng us too much extra other than the line it doesn't like. But, putting this together with the code you posted earlier... --------------- for k in range(nr): contribution=N.zeros(shape(H['area'])) contribution=[contribution+grid[:,:,z:,k,0]/A for z in range(len(H['outheight']))] zplot[:,:,k]=zplot[:,:,k]+contribution; ------------- I will hazard a guess that N.zeros(...) is a different size to grid[:,:,z:,k,0]/A But since I have no idea what these look like - I assume its numPy or somesuch structure ? - I can only guess. Can you decompose the list comprehension and add some useful print statements to help debug it? HTH, Alan G. From washakie at gmail.com Tue Oct 30 00:39:47 2007 From: washakie at gmail.com (John) Date: Tue, 30 Oct 2007 00:39:47 +0100 Subject: [Tutor] calculation with arrays: shape mismatch In-Reply-To: <fg5q3k$v12$1@ger.gmane.org> References: <aaf235960710290822q60a6c18ap5db379f0d78595a6@mail.gmail.com> <fg4vgs$trv$1@ger.gmane.org> <aaf235960710290900v592ffa9cge61226b23e55e4d6@mail.gmail.com> <fg5q3k$v12$1@ger.gmane.org> Message-ID: <aaf235960710291639q4c12576fhffbf9e9cd5117e07@mail.gmail.com> Well, To be honest, part of the problem is that I work in about four different Python environments!! I've had a hard time getting the scipy suite to work fully on windows, and for number crunching it's just easier to run in linux. This here was just a cut from running a script I wrote at the DOS prompt... but that is not my usual flavor. Anyway, the problem was in fact a shape mismatch. Ha! Imagine that ;) Thanks for the feedback. The issue was in the dividing by A, I had to pull that out separately and things worked. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071030/f60ffad6/attachment.htm From hunter92383 at gmail.com Tue Oct 30 00:52:45 2007 From: hunter92383 at gmail.com (elis aeris) Date: Mon, 29 Oct 2007 20:52:45 -0300 Subject: [Tutor] python image libray Message-ID: <674d5ce60710291652n5add1d96o39b0ad01575334fa@mail.gmail.com> http://www.pythonware.com/products/pil/#pil116 how do I distribute standalone python executable with some contents of this library? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/9d8cc862/attachment.htm From hunter92383 at gmail.com Tue Oct 30 00:54:34 2007 From: hunter92383 at gmail.com (elis aeris) Date: Mon, 29 Oct 2007 20:54:34 -0300 Subject: [Tutor] python image libray - source to Mac OS X Message-ID: <674d5ce60710291654g22634f68se8ac964b0316b825@mail.gmail.com> http://www.pythonware.com/products/pil/#pil116 has anyone been able to compile this on Mac os x? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/f1fcfa03/attachment.htm From alan.gauld at btinternet.com Tue Oct 30 01:03:43 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Oct 2007 00:03:43 -0000 Subject: [Tutor] calculation with arrays: shape mismatch References: <aaf235960710290822q60a6c18ap5db379f0d78595a6@mail.gmail.com><fg4vgs$trv$1@ger.gmane.org><aaf235960710290900v592ffa9cge61226b23e55e4d6@mail.gmail.com><fg5q3k$v12$1@ger.gmane.org> <aaf235960710291639q4c12576fhffbf9e9cd5117e07@mail.gmail.com> Message-ID: <fg5sd7$5g7$1@ger.gmane.org> "John" <washakie at gmail.com> wrote > To be honest, part of the problem is that I work in about four > different > Python environments!! > This here was just a cut from running a script I wrote at the DOS > prompt... > but that is not my usual flavor. really? What Python version are you using? Is it a special ScviPy flavour? I don't know how the >>> run foo.py syntax works. It certainly gets a syntax error on all my Python prompts. I'm curious to know how it worked - run would need to be a new command (not a function: no parens) defined within the interpreter somehow... Glad you found your error though. Alan G. From alan.gauld at btinternet.com Tue Oct 30 01:04:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Oct 2007 00:04:55 -0000 Subject: [Tutor] python image libray References: <674d5ce60710291652n5add1d96o39b0ad01575334fa@mail.gmail.com> Message-ID: <fg5sfg$5lf$1@ger.gmane.org> "elis aeris" <hunter92383 at gmail.com> wrote > http://www.pythonware.com/products/pil/#pil116 > > > how do I distribute standalone python executable with some contents > of this > library? If you import pil then most (all?) of the exe builders will automatically drag it into the final executable file along with the interpreter. HTH, Alan G.. From kent37 at tds.net Tue Oct 30 01:36:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Oct 2007 20:36:54 -0400 Subject: [Tutor] calculation with arrays: shape mismatch In-Reply-To: <fg5q3k$v12$1@ger.gmane.org> References: <aaf235960710290822q60a6c18ap5db379f0d78595a6@mail.gmail.com><fg4vgs$trv$1@ger.gmane.org> <aaf235960710290900v592ffa9cge61226b23e55e4d6@mail.gmail.com> <fg5q3k$v12$1@ger.gmane.org> Message-ID: <47267CA6.4030506@tds.net> Alan Gauld wrote: > "John" <washakie at gmail.com> wrote > >> Sorry, here's the output from the command line >> >>>>> run Day_footprint.py > > Sorry for all the questions but I've never seen that "run" syntax > before. > What environment are you running? What IDE/OS/Python version etc? IPython has a run command. Details here if you scroll down far enough: http://ipython.scipy.org/doc/manual/node6.html#SECTION00062100000000000000 Kent From kent37 at tds.net Tue Oct 30 01:50:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Oct 2007 20:50:46 -0400 Subject: [Tutor] python image libray - source to Mac OS X In-Reply-To: <674d5ce60710291654g22634f68se8ac964b0316b825@mail.gmail.com> References: <674d5ce60710291654g22634f68se8ac964b0316b825@mail.gmail.com> Message-ID: <47267FE6.2020208@tds.net> elis aeris wrote: > http://www.pythonware.com/products/pil/#pil116 > > > has anyone been able to compile this on Mac os x? There is a compiled version here so I guess someone did ;-) http://www.pythonmac.org/packages/py25-fat/index.html The Python-mac list would probably be a good place for more details: http://mail.python.org/mailman/listinfo/pythonmac-sig Kent From samrobertsmith at gmail.com Tue Oct 30 02:24:53 2007 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 29 Oct 2007 18:24:53 -0700 Subject: [Tutor] repeated times Message-ID: <1d987df30710291824u3cc25ca6uf9a82d040255e0cf@mail.gmail.com> I want to run an .exe file and get the output many times. Can any one give me an example about how to use python to generate the automatic process? Thanks, Linda From reed at reedobrien.com Tue Oct 30 02:20:43 2007 From: reed at reedobrien.com (Reed O'Brien) Date: Mon, 29 Oct 2007 21:20:43 -0400 Subject: [Tutor] python image libray - source to Mac OS X In-Reply-To: <E833E458-452B-4172-82D1-C8EC61F1E61B@reedobrien.com> References: <674d5ce60710291654g22634f68se8ac964b0316b825@mail.gmail.com> <E833E458-452B-4172-82D1-C8EC61F1E61B@reedobrien.com> Message-ID: <A75E6805-5A53-44CD-85CC-4071F2430E10@reedobrien.com> On Oct 29, 2007, at 7:54 PM, elis aeris wrote: > >> http://www.pythonware.com/products/pil/#pil116 >> >> >> has anyone been able to compile this on Mac os x? > http://two.pairlist.net/pipermail/reportlab-users/2007-October/ 006262.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/c3f413e8/attachment.htm From kent37 at tds.net Tue Oct 30 02:38:06 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 29 Oct 2007 21:38:06 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071029221433.69B1A1E4007@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <20071029221433.69B1A1E4007@bag.python.org> Message-ID: <47268AFE.2060800@tds.net> Dick Moores wrote: > 1. Is wrapping the long lines where I have done so OK? I usually indent the second line of a wrapped line so it stands out more. > 2. I've used 1 for White player, -1 for Black player, and (-1)*player > to alternate players. Is there a better way? > 3. I've used a lot of variables. Too Many? I think it might work well to either put the player variables into lists or simple classes. > 4. Should more of the code be in functions? That might make it read more easily. Alternately some blank lines to break the code into sections would aid readability. > 5. Is there a way to collapse lines 130-137?: > if player == 1: # player is White > whiteMoveCounter += 1 > print "Black to make move %d" % (blackMoveCounter) > remainingWhiteTime -= timeUsedThisMove > elif player == -1: # player is Black > blackMoveCounter += 1 > print "White to make move %d" % (whiteMoveCounter) > remainingBlackTime -= timeUsedThisMove If the players were objects then this might look like currentPlayer.moveCounter += 1 otherPlayer.printNextMove() currentPlayer.remainingTime -= timeUsedThisMove Switching players would be done with currentPlayer, otherPlayer = otherPlayer, currentPlayer Kent From rabidpoobear at gmail.com Tue Oct 30 05:16:50 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 29 Oct 2007 23:16:50 -0500 Subject: [Tutor] repeated times In-Reply-To: <1d987df30710291824u3cc25ca6uf9a82d040255e0cf@mail.gmail.com> References: <1d987df30710291824u3cc25ca6uf9a82d040255e0cf@mail.gmail.com> Message-ID: <4726B032.4090307@gmail.com> linda.s wrote: > I want to run an .exe file and get the output many times. > Can any one give me an example about how to use python to generate the > automatic process? > Yes. -Luke From rdm at rcblue.com Tue Oct 30 05:18:15 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 29 Oct 2007 21:18:15 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <47268AFE.2060800@tds.net> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <20071029221433.69B1A1E4007@bag.python.org> <47268AFE.2060800@tds.net> Message-ID: <20071030041820.E34881E401C@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071029/c0b54ef2/attachment.htm From alan.gauld at btinternet.com Tue Oct 30 09:55:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Oct 2007 08:55:58 -0000 Subject: [Tutor] repeated times References: <1d987df30710291824u3cc25ca6uf9a82d040255e0cf@mail.gmail.com> Message-ID: <fg6rj7$8en$1@ger.gmane.org> "linda.s" <samrobertsmith at gmail.com> wrote >I want to run an .exe file and get the output many times. > Can any one give me an example about how to use python to generate > the > automatic process? Given that I know that you know about loops I have to ask what you see as the problem? Just run the process many times in a loop? Must be more to it I suspect? Alan G. From kent37 at tds.net Tue Oct 30 11:49:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 30 Oct 2007 06:49:07 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071030041820.E34881E401C@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <20071029221433.69B1A1E4007@bag.python.org> <47268AFE.2060800@tds.net> <20071030041820.E34881E401C@bag.python.org> Message-ID: <47270C23.2020101@tds.net> Dick Moores wrote: >>> 2. I've used 1 for White player, -1 for Black player, and (-1)*player >>> to alternate players. Is there a better way? >>> 3. I've used a lot of variables. Too Many? >> >> I think it might work well to either put the player variables into >> lists or simple classes. > > I have no confidence with classes, but how about this for lists: > > playerName = ['', 'White', 'Black'] > moveCounter = [0, whiteMoveCounter, blackMoveCounter} > remainingPlayerTime = [0, remainingWhiteTime, remainingBlackTime] > Is that something like what you were thinking? No. I was thinking more like this: whitePlayer = [ 'White', whiteMoveCounter, remainingWhiteTime] blackPlayer = [ 'Black', blackMoveCounter, remainingBlackTime] You could even define offsets: NAME = 0 MOVES = 1 TIME = 2 and refer to currentPlayer[NAME] From here to simple classes is not a big step: class player(object): def __init__(self, name, moveCounter, remainingTime): self.name = name self.moveCounter = moveCounter self.remainingTime = remainingTime whitePlayer = player('White', 1, timeLimit) blackPlayer = player('Black', 1, timeLimit) Then playerName(player) becomes player.name and remainingPlayerTime(player) becomes player.remainingTime. > Any thoughts about my number 6?: "I thought I had a way to make this > script useable on unix as well > as Windows. Thus the section with the 3 classes. But it won't run on > unix, because it was necessary to import msvcrt outside of the > classes--it wouldn't compile otherwise, and because of the need for > the line 'if msvcrt.kbhit():' Why do you need to call kbhit() at all? Why not just call getch() and wait for the next character? Kent From kent37 at tds.net Tue Oct 30 12:45:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 30 Oct 2007 07:45:24 -0400 Subject: [Tutor] [Fwd: ANN: Learning Python 3rd Edition] Message-ID: <47271954.90809@tds.net> There is a new edition of one of my recommended books. Kent -------- Original Message -------- Subject: ANN: Learning Python 3rd Edition Date: Mon, 29 Oct 2007 12:28:10 -0700 (GMT-07:00) From: lutz at rmi.net Reply-To: python-list at python.org, lutz at rmi.net To: python-announce-list at python.org I'm pleased to announce the release of the 3rd Edition of the book Learning Python. This new edition has been updated to cover Python 2.5, and includes numerous pointers for migrating to Python 3.0 in the future. Among other things, this edition has been augmented with material on function decorators, context managers, the new relative import syntax, generator expressions, and more. In addition, this edition has been enhanced to be even more of a self-paced learning resource, with new end-of-chapter quizzes, new introductory chapters on types and syntax, and new materials derived from recent Python training sessions. For more details, see O'Reilly's web page: http://www.oreilly.com/catalog/9780596513986/ O'Reilly also has a press release about the book here: http://press.oreilly.com/pub/pr/1843 Thanks, --Mark Lutz From bgailer at alum.rpi.edu Tue Oct 30 16:55:57 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 30 Oct 2007 11:55:57 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071029221433.69B1A1E4007@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <20071029221433.69B1A1E4007@bag.python.org> Message-ID: <4727540D.60804@alum.rpi.edu> I also encourage you to jump into classes. Yes there is a learning curve. It is IMHO worth it. Borrowing from Kent Johnson: class Player(object): def __init__(self, name, moveCounter, remainingTime): self.name = name self.moveCounter = moveCounter self.remainingTime = remainingTime Note I capitalized the class name. That's the Python "style". Also refer to the class-based code I wrote for you a week or 2 ago. That should help you. From orest.kozyar at gmail.com Tue Oct 30 17:53:27 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Tue, 30 Oct 2007 12:53:27 -0400 Subject: [Tutor] perplexing error with shelve Message-ID: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> I have a program which queries an online database (Medline) for XML data. It caches all data using shelve to avoid hitting the database too many times. For some reason, I keep getting a RuntimeError: maximum recursion depth exceeded when attempting to add a certain record. This program has successfully handled over 40,000 records from Medline, but for whatever reason, this particular record (PMID: 16842422) produces this error. If I set maximum recursion depth to a larger value such as 5,000, I get a segfault. Below is a script that should reproduce the problem I am having. Any guidance in solving this problem would greatly be appreciated. Thank you, Orest ####### START SCRIPT ####### import urllib, shelve from xml.dom import minidom baseurl = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' params = { 'db': 'pubmed', 'retmode': 'xml', 'rettype': 'medline' } badkey = '16842422' goodkey = '16842423' #or just about any other ID data = shelve.open('data.tmp', writeback=True) try: params['id'] = goodkey url = baseurl + urllib.urlencode(params) doc = minidom.parseString(urllib.urlopen(url).read()) print 'Successfully retrieved and parsed XML document with ID %s' % goodkey data[goodkey] = doc print 'Successfully shelved XML document with ID %s' % goodkey except RuntimeError: print 'Should not see this error message!' try: params['id'] = badkey url = baseurl + urllib.urlencode(params) doc = minidom.parseString(urllib.urlopen(url).read()) print 'Successfully retrieved and parsed XML document with ID %s' % badkey data[badkey] = doc #Should not get this message! print 'Successfully shelved XML document with ID %s' % badkey except RuntimeError, e: print 'Error shelving XML document with ID %s' % badkey print e ####### END SCRIPT ####### From gslindstrom at gmail.com Tue Oct 30 18:35:42 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Tue, 30 Oct 2007 12:35:42 -0500 Subject: [Tutor] Fwd: [pycon-tutorials] Request: Python Instruction Needed for GIS Symposium In-Reply-To: <OF3FD4F142.2EB8A898-ON86257384.00593A74-86257384.00598E96@modot.mo.gov> References: <OF3FD4F142.2EB8A898-ON86257384.00593A74-86257384.00598E96@modot.mo.gov> Message-ID: <a9f39a410710301035k5057ca36p9d55ee6c945d2535@mail.gmail.com> We received this on the PyCon tutorial list. Anyone interested?? Thanks, --greg ---------- Forwarded message ---------- From: Eric.Foster at modot.mo.gov <Eric.Foster at modot.mo.gov> Date: Oct 30, 2007 11:18 AM Subject: [pycon-tutorials] Request: Python Instruction Needed for GIS Symposium To: pycon-tutorials at python.org I sent out the following hoping to get a Python Instructor for an April 2008 GIS Symposium in Kansas City. If you would be so kind, please consider forwarding it to your list of folks who may be giving tutorials at your Chicago Conference. We would be glad to do a little advertising for you in return: I am involved with MAGIC http://www.magicgis.org/ an organization to encourage GIS development, sharing, cooperation, etc. and educate practitioners in GIS. We hold a symposium every two years in April (next is April 2008) and provide speakers and workshops in relevant GIS subjects. ESRI's ArcGIS software holds the market majority and has embrace Python language as a preferred scripting, customization language. One area we have trouble with for our symposium is getting instructors for Python workshops. The symposium is in Kansas City on April 20-24, 2008 and the hands on computer based Python course would be held for 4 hours on Sunday April 20th in the afternoon for about 30 beginner and intermediate programmers. We would like some application to ArcGIS, but just basic Python language instruction is also needed. The instructors and speakers as well as the planning committee are asked to volunteer to keep the cost down to symposium attendees. Would you be a good fit (or know anyone) as an instructor for this Introduction to Python language course? The Symposium Steering Committee would like to get a commitment by Nov. 2, 2008 in order to publish a preliminary program. Sorry for the short notice, we thought we had an instructor but do not. We need a short 1-2 paragraph summary or outline of the workshop by then. I am willing to help develop any materials needed. Contact me by phone or email if you have questions or would like to volunteer. Thanks. Eric Foster, Senior Transportation Planner MoDOT, 600 NE Colbern Rd. Lee's Summit, MO 64086 (816) 622-6330 _______________________________________________ pycon-tutorials mailing list pycon-tutorials at python.org http://mail.python.org/mailman/listinfo/pycon-tutorials -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071030/b6185b51/attachment.htm From bgailer at alum.rpi.edu Tue Oct 30 19:17:05 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 30 Oct 2007 14:17:05 -0400 Subject: [Tutor] perplexing error with shelve REVISED In-Reply-To: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> Message-ID: <47277521.2090802@alum.rpi.edu> Orest Kozyar wrote: > I have a program which queries an online database (Medline) for XML data. > It caches all data using shelve to avoid hitting the database too many > times. For some reason, I keep getting a RuntimeError: maximum recursion > depth exceeded when attempting to add a certain record. Please post the entire traceback (omitting duplicate lines). Else we can't (or won't try to) help. From bgailer at alum.rpi.edu Tue Oct 30 19:15:40 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 30 Oct 2007 14:15:40 -0400 Subject: [Tutor] perplexing error with shelve In-Reply-To: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> Message-ID: <472774CC.5000608@alum.rpi.edu> Orest Kozyar wrote: > I have a program which queries an online database (Medline) for XML data. > It caches all data using shelve to avoid hitting the database too many > times. For some reason, I keep getting a RuntimeError: maximum recursion > depth exceeded when attempting to add a certain record. Please post the entire traceback. Else we can't (or won't try to) help. From orest.kozyar at gmail.com Tue Oct 30 19:34:57 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Tue, 30 Oct 2007 14:34:57 -0400 Subject: [Tutor] perplexing error with shelve REVISED In-Reply-To: <47277521.2090802@alum.rpi.edu> References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> <47277521.2090802@alum.rpi.edu> Message-ID: <002101c81b23$936452d0$bd32000a@meei.harvard.edu> > Please post the entire traceback (omitting duplicate lines). Sorry, I should have included the traceback. I've revised the sample script so that it generates the traceback when run. The sample script is at the very bottom of this email. ####### SCRIPT OUTPUT ####### [kozyar]:~$ python example.py Successfully retrieved and parsed XML document with ID 16842423 Successfully shelved XML document with ID 16842423 Successfully retrieved and parsed XML document with ID 16842422 Traceback (most recent call last): File "example.py", line 30, in <module> data[badkey] = doc File "/usr/lib64/python2.5/shelve.py", line 123, in __setitem__ p.dump(value) RuntimeError: maximum recursion depth exceeded Exception exceptions.RuntimeError: 'maximum recursion depth exceeded' in <bound method DbfilenameShelf.__del__ of {'16842423': <xml.dom.minidom.Document instance at 0x96f290>}> ignored ####### START SCRIPT ####### import urllib, shelve from xml.dom import minidom baseurl = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' params = { 'db': 'pubmed', 'retmode': 'xml', 'rettype': 'medline' } badkey = '16842422' goodkey = '16842423' #or just about any other ID data = shelve.open('data.tmp', writeback=True) params['id'] = goodkey url = baseurl + urllib.urlencode(params) doc = minidom.parseString(urllib.urlopen(url).read()) print 'Successfully retrieved and parsed XML document with ID %s' % goodkey data[goodkey] = doc print 'Successfully shelved XML document with ID %s' % goodkey params['id'] = badkey url = baseurl + urllib.urlencode(params) doc = minidom.parseString(urllib.urlopen(url).read()) print 'Successfully retrieved and parsed XML document with ID %s' % badkey data[badkey] = doc #Will fail on the above line print 'Successfully shelved XML document with ID %s' % badkey From rdm at rcblue.com Wed Oct 31 06:25:45 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 30 Oct 2007 22:25:45 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <47270C23.2020101@tds.net> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <20071029221433.69B1A1E4007@bag.python.org> <47268AFE.2060800@tds.net> <20071030041820.E34881E401C@bag.python.org> <47270C23.2020101@tds.net> Message-ID: <20071031052556.BC23E1E4007@bag.python.org> At 03:49 AM 10/30/2007, Kent Johnson wrote: >Why do you need to call kbhit() at all? Why not just call getch() >and wait for the next character? Like this?: <http://www.rcblue.com/Python/chessTimerForWebV9atest.py>. The every-5-seconds time report doesn't report. Compare ============================ #!/usr/bin/env python #coding=utf-8 # 21aForTutor.py import time import msvcrt timeNow = time.time() oldTimeNow = timeNow while True: if msvcrt.kbhit(): key = msvcrt.getch() if key == 'h': print 'Hello' if key == 'b': print 'Bye' if key == '\r': # Enter key break else: time.sleep(0.001) timeNow = time.time() if timeNow - oldTimeNow > 2: print "2 seconds passed" oldTimeNow = timeNow ================================== with =================================== #!/usr/bin/env python #coding=utf-8 # 21bForTutor.py import time import msvcrt timeNow = time.time() oldTimeNow = timeNow while True: #if msvcrt.kbhit(): key = msvcrt.getch() if key == 'h': print 'Hello' if key == 'b': print 'Bye' if key == '\r': # Enter key break else: time.sleep(0.001) timeNow = time.time() if timeNow - oldTimeNow > 2: print "2 seconds passed" oldTimeNow = timeNow ===================================== In 21bForTutor.py the 2-second report is screwed up. Maybe you can fix it? Dick From aditya.n.lal at gmail.com Wed Oct 31 07:13:33 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Wed, 31 Oct 2007 11:43:33 +0530 Subject: [Tutor] question re type() In-Reply-To: <4725C3D9.8000506@tds.net> References: <20071027112905.AFC3C1E4005@bag.python.org> <ffv9ed$6m3$1@ger.gmane.org> <5df213700710270652i1c38571bl4a85edcfa54af977@mail.gmail.com> <4725C3D9.8000506@tds.net> Message-ID: <5df213700710302313g4e128ce6tbca45a624798a20b@mail.gmail.com> On 10/29/07, Kent Johnson <kent37 at tds.net> wrote: > > Aditya Lal wrote: > > or use types module > > > > import types > > > > if type(n) == types.IntType or type(n) == types.LongType : > > blah! > > A few notes: > - If you look at types.py, you find > IntType = int > LongType = long > > and so on for all the built-in types, so there is no need or advantage > to importing types vs > if type(n) == int > > - Common Python practice is to prefer the least restrictive type check > possible. For Dick's specific case it doesn't matter, but I generally > use isinstance() instead of checking for a specific type. The difference > is that isinstance() is true for subtypes as well as the named type. You > can also pass a tuple of types to isinstance() so you can say > if isinstance(n, (int, long)) > > Kent > > I completely agree that the check " type(n) == int " is very intuitive and simple. Its just that there are many more types that the basic ones and 'types' module provide a "consistent" way for checking for types. As an example - consider a function : def execMyFun( f ) : if type(f) == types.GeneratorType : return f.next() elif type(f) == types.FunctionType : return f() else : raise Exception("Invalid type for f : " + type(f) ) Here types module came to the rescue which otherwise I would have written using exception handling. *Well ! if you have a cleaner solution do let me know.* BTW, isinstance is cool :) as it checks for all subclasses as well - didn't think of that. -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071031/36c299fc/attachment-0001.htm From aditya.n.lal at gmail.com Wed Oct 31 08:43:12 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Wed, 31 Oct 2007 13:13:12 +0530 Subject: [Tutor] perplexing error with shelve REVISED In-Reply-To: <002101c81b23$936452d0$bd32000a@meei.harvard.edu> References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> <47277521.2090802@alum.rpi.edu> <002101c81b23$936452d0$bd32000a@meei.harvard.edu> Message-ID: <5df213700710310043j5da5f9e0u70e773767f25768@mail.gmail.com> On 10/31/07, Orest Kozyar <orest.kozyar at gmail.com> wrote: > > > Please post the entire traceback (omitting duplicate lines). > > Sorry, I should have included the traceback. I've revised the sample > script > so that it generates the traceback when run. The sample script is at the > very bottom of this email. > > ####### SCRIPT OUTPUT ####### > [kozyar]:~$ python example.py > > Successfully retrieved and parsed XML document with ID 16842423 > Successfully shelved XML document with ID 16842423 > Successfully retrieved and parsed XML document with ID 16842422 > > Traceback (most recent call last): > File "example.py", line 30, in <module> > data[badkey] = doc > File "/usr/lib64/python2.5/shelve.py", line 123, in __setitem__ > p.dump(value) > > RuntimeError: maximum recursion depth exceeded > > Exception exceptions.RuntimeError: 'maximum recursion depth exceeded' in > <bound method DbfilenameShelf.__del__ of {'16842423': > <xml.dom.minidom.Document instance at 0x96f290>}> ignored > > > ####### START SCRIPT ####### > import urllib, shelve > from xml.dom import minidom > > baseurl = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' > > params = { > 'db': 'pubmed', > 'retmode': 'xml', > 'rettype': 'medline' > } > > badkey = '16842422' > goodkey = '16842423' #or just about any other ID > > data = shelve.open('data.tmp', writeback=True) > > params['id'] = goodkey > url = baseurl + urllib.urlencode(params) > doc = minidom.parseString(urllib.urlopen(url).read()) > print 'Successfully retrieved and parsed XML document with ID %s' % > goodkey > data[goodkey] = doc > print 'Successfully shelved XML document with ID %s' % goodkey > > params['id'] = badkey > url = baseurl + urllib.urlencode(params) > doc = minidom.parseString(urllib.urlopen(url).read()) > print 'Successfully retrieved and parsed XML document with ID %s' % badkey > data[badkey] = doc > #Will fail on the above line > print 'Successfully shelved XML document with ID %s' % badkey > > The program worked fine for me (python 2.5.1 - stackless on Mac OSX). Can you provide details about your platform (python version, OS, etc.) ? -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071031/7abcd549/attachment.htm From kent37 at tds.net Wed Oct 31 12:48:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 31 Oct 2007 07:48:25 -0400 Subject: [Tutor] question re type() In-Reply-To: <5df213700710302313g4e128ce6tbca45a624798a20b@mail.gmail.com> References: <20071027112905.AFC3C1E4005@bag.python.org> <ffv9ed$6m3$1@ger.gmane.org> <5df213700710270652i1c38571bl4a85edcfa54af977@mail.gmail.com> <4725C3D9.8000506@tds.net> <5df213700710302313g4e128ce6tbca45a624798a20b@mail.gmail.com> Message-ID: <47286B89.1030405@tds.net> Aditya Lal wrote: > On 10/29/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote: > - Common Python practice is to prefer the least restrictive type check > possible. > I completely agree that the check " type(n) == int " is very intuitive > and simple. Its just that there are many more types that the basic ones > and 'types' module provide a "consistent" way for checking for types. Yes, for some types it is easiest to import types and use its definitions. Whether to use types.IntegerType or int is a matter of preference, I suppose. > As > an example - consider a function : > > def execMyFun( f ) : > if type(f) == types.GeneratorType : > return f.next() > elif type(f) == types.FunctionType : > return f() > else : > raise Exception("Invalid type for f : " + type(f) ) > > Here types module came to the rescue which otherwise I would have > written using exception handling. /Well ! if you have a cleaner solution > do let me know./ You probably should write this using exception handling. The least restrictive type check is to check for the specific operations you need, rather that checking for a type that supports the operation. This can be done with preflight checks - known as Look Before You Leap - or by trying an operation and catching exceptions in case of failure, known as Easier to Ask Forgiveness than Permission. In this case, it seems that if f implements the iterator protocol then you want the next item and if f is callable then you want to just call it. In both cases checking for specific operations or trying the operation and catching any exception will allow a wider range of parameters. For example, next() is meaningful for generators, iterators on built-in types, user-defined iterators (defined with classes). In [129]: import types In [130]: i=iter([1]) In [131]: type(i) Out[131]: <type 'listiterator'> In [132]: type(i)==types.GeneratorType Out[132]: False In [133]: isinstance(i, types.GeneratorType) Out[133]: False In [134]: i.next Out[134]: <method-wrapper 'next' of listiterator object at 0x20d0050> Function call is valid for functions, bound methods, and instances of any class that defines a __call__() method. Here is a less restrictive LBYL implementation of your function: def execMyFun( f ) : if hasattr(f, 'next') and callable(f.next): return f.next() elif callable(f): return f() else : raise Exception("Invalid type for f : " + type(f) ) Here in an EAFP implementation: def execMyFun( f ) : try: return f.next() except AttributeError: pass try: return f() except TypeError: pass raise Exception("Invalid type for f : " + type(f) ) I think I prefer the LBYL version here, it allows the same values for f and it won't hide AttributeErrors and TypeErrors raised by calling f.next() or f(). Finally you should probably raise TypeError which is "raised when an operation or function is applied to an object of inappropriate type." Kent From dineshbvadhia at hotmail.com Wed Oct 31 13:41:42 2007 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 31 Oct 2007 05:41:42 -0700 Subject: [Tutor] Inverted Index Message-ID: <BAY109-DAV125440F4D6FEE6150A059FA3930@phx.gbl> Hello! Anyone know of any example/cookbook code for implementing inverted indexes? Cheers Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071031/71b8e6e9/attachment.htm From kent37 at tds.net Wed Oct 31 15:48:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 31 Oct 2007 10:48:07 -0400 Subject: [Tutor] Inverted Index In-Reply-To: <BAY109-DAV125440F4D6FEE6150A059FA3930@phx.gbl> References: <BAY109-DAV125440F4D6FEE6150A059FA3930@phx.gbl> Message-ID: <472895A7.10904@tds.net> Dinesh B Vadhia wrote: > Hello! Anyone know of any example/cookbook code for implementing > inverted indexes? Can you say more about what you are trying to do? Maybe PyLucene is interesting: http://mail.python.org/pipermail/tutor/2006-April/046116.html http://pylucene.osafoundation.org/ Kent From dineshbvadhia at hotmail.com Wed Oct 31 16:04:20 2007 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 31 Oct 2007 08:04:20 -0700 Subject: [Tutor] Inverted Index References: <BAY109-DAV125440F4D6FEE6150A059FA3930@phx.gbl> <472895A7.10904@tds.net> Message-ID: <BAY109-DAV5BA708A2D8C6E451C483CA3930@phx.gbl> Sure! To create an inverted index of a very large matrix (M x N with M<>N and M>10m rows). Most times the matrix will be sparse but sometimes it won't be. Most times the matrix will consist of 0's and 1's but sometimes it won't. Hope that helps. Dinesh ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Wednesday, October 31, 2007 7:48 AM Subject: Re: [Tutor] Inverted Index Dinesh B Vadhia wrote: > Hello! Anyone know of any example/cookbook code for implementing > inverted indexes? Can you say more about what you are trying to do? Maybe PyLucene is interesting: http://mail.python.org/pipermail/tutor/2006-April/046116.html http://pylucene.osafoundation.org/ Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071031/5c10fed8/attachment.htm From kent37 at tds.net Wed Oct 31 16:16:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 31 Oct 2007 11:16:59 -0400 Subject: [Tutor] Inverted Index In-Reply-To: <BAY109-DAV5BA708A2D8C6E451C483CA3930@phx.gbl> References: <BAY109-DAV125440F4D6FEE6150A059FA3930@phx.gbl> <472895A7.10904@tds.net> <BAY109-DAV5BA708A2D8C6E451C483CA3930@phx.gbl> Message-ID: <47289C6B.9050305@tds.net> Dinesh B Vadhia wrote: > Sure! To create an inverted index of a very large matrix (M x N with > M<>N and M>10m rows). Most times the matrix will be sparse but > sometimes it won't be. Most times the matrix will consist of 0's and > 1's but sometimes it won't. How is the matrix represented? Is it in a numpy array? a dict? or... Kent > > Hope that helps. > > Dinesh > > > ----- Original Message ----- > *From:* Kent Johnson <mailto:kent37 at tds.net> > *To:* Dinesh B Vadhia <mailto:dineshbvadhia at hotmail.com> > *Cc:* tutor at python.org <mailto:tutor at python.org> > *Sent:* Wednesday, October 31, 2007 7:48 AM > *Subject:* Re: [Tutor] Inverted Index > > Dinesh B Vadhia wrote: > > Hello! Anyone know of any example/cookbook code for implementing > > inverted indexes? > > Can you say more about what you are trying to do? > > Maybe PyLucene is interesting: > http://mail.python.org/pipermail/tutor/2006-April/046116.html > http://pylucene.osafoundationorg/ <http://pylucene.osafoundation.org/> > > Kent From rdm at rcblue.com Wed Oct 31 18:54:24 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 31 Oct 2007 10:54:24 -0700 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <47270C23.2020101@tds.net> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <20071029221433.69B1A1E4007@bag.python.org> <47268AFE.2060800@tds.net> <20071030041820.E34881E401C@bag.python.org> <47270C23.2020101@tds.net> Message-ID: <20071031175437.9805F1E400A@bag.python.org> At 03:49 AM 10/30/2007, Kent Johnson wrote: >Dick Moores wrote: > >>>>2. I've used 1 for White player, -1 for Black player, and (-1)*player >>>>to alternate players. Is there a better way? >>>>3. I've used a lot of variables. Too Many? >>> >>>I think it might work well to either put the player variables into >>>lists or simple classes. >>I have no confidence with classes, but how about this for lists: >>playerName = ['', 'White', 'Black'] >>moveCounter = [0, whiteMoveCounter, blackMoveCounter} >>remainingPlayerTime = [0, remainingWhiteTime, remainingBlackTime] > >>Is that something like what you were thinking? > >No. I was thinking more like this: >whitePlayer = [ 'White', whiteMoveCounter, remainingWhiteTime] >blackPlayer = [ 'Black', blackMoveCounter, remainingBlackTime] > >You could even define offsets: >NAME = 0 >MOVES = 1 >TIME = 2 > >and refer to >currentPlayer[NAME] Done, I think. Seems to be a big improvement. <http://www.rcblue.com/Python/chessTimerForWebV12.py> You'll notice I've given up for the time being on trying to have it useable by unix-ers. This meant that I could use winsound again to get 3 short beeps when a player reaches his time limit and loses. > From here to simple classes is not a big step: > >class player(object): > def __init__(self, name, moveCounter, remainingTime): > self.name = name > self.moveCounter = moveCounter > self.remainingTime = remainingTime > >whitePlayer = player('White', 1, timeLimit) >blackPlayer = player('Black', 1, timeLimit) > >Then playerName(player) becomes player.name and >remainingPlayerTime(player) becomes player.remainingTime. Well, Kent (and Bob Gailer), thanks for trying to help with classes, but I still don't get them. I've just got to spend time with using classes in much simpler scripts. You guys may think my chessTimer is a piece of cake, but it stretched me a lot even without classes. >>Any thoughts about my number 6?: "I thought I had a way to make >>this script useable on unix as well >>as Windows. Thus the section with the 3 classes. But it won't run on >>unix, because it was necessary to import msvcrt outside of the >>classes--it wouldn't compile otherwise, and because of the need for >>the line 'if msvcrt.kbhit():' > >Why do you need to call kbhit() at all? Why not just call getch() >and wait for the next character? I answered this earlier, in my post of Tue, 30 Oct 2007 22:25:45 -0700 . Dick From dineshbvadhia at hotmail.com Wed Oct 31 19:02:16 2007 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 31 Oct 2007 11:02:16 -0700 Subject: [Tutor] Inverted Index References: <BAY109-DAV125440F4D6FEE6150A059FA3930@phx.gbl> <472895A7.10904@tds.net> <BAY109-DAV5BA708A2D8C6E451C483CA3930@phx.gbl> <47289C6B.9050305@tds.net> Message-ID: <BAY109-DAV131DD92FE07B398C175F68A3930@phx.gbl> A NumPy matrix (because we have to perform a dot matrix multiplication prior to creating an inverted index). Thank-you! ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Wednesday, October 31, 2007 8:16 AM Subject: Re: [Tutor] Inverted Index Dinesh B Vadhia wrote: > Sure! To create an inverted index of a very large matrix (M x N with > M<>N and M>10m rows). Most times the matrix will be sparse but > sometimes it won't be. Most times the matrix will consist of 0's and > 1's but sometimes it won't. How is the matrix represented? Is it in a numpy array? a dict? or... Kent > > Hope that helps. > > Dinesh > > > ----- Original Message ----- > *From:* Kent Johnson <mailto:kent37 at tds.net> > *To:* Dinesh B Vadhia <mailto:dineshbvadhia at hotmail.com> > *Cc:* tutor at python.org <mailto:tutor at python.org> > *Sent:* Wednesday, October 31, 2007 7:48 AM > *Subject:* Re: [Tutor] Inverted Index > > Dinesh B Vadhia wrote: > > Hello! Anyone know of any example/cookbook code for implementing > > inverted indexes? > > Can you say more about what you are trying to do? > > Maybe PyLucene is interesting: > http://mail.python.org/pipermail/tutor/2006-April/046116.html > http://pylucene.osafoundationorg/ <http://pylucene.osafoundation.org/> > > Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20071031/044fe3b0/attachment-0001.htm From kent37 at tds.net Wed Oct 31 19:40:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 31 Oct 2007 14:40:34 -0400 Subject: [Tutor] Looking for suggestions for improving chessTimer.py code In-Reply-To: <20071031175437.9805F1E400A@bag.python.org> References: <20071025163428.A2F241E400A@bag.python.org> <20071026091813.BE7CC1E401F@bag.python.org> <20071029221433.69B1A1E4007@bag.python.org> <47268AFE.2060800@tds.net> <20071030041820.E34881E401C@bag.python.org> <47270C23.2020101@tds.net> <20071031175437.9805F1E400A@bag.python.org> Message-ID: <4728CC22.30305@tds.net> Dick Moores wrote: > At 03:49 AM 10/30/2007, Kent Johnson wrote: >> From here to simple classes is not a big step: >> >> class player(object): >> def __init__(self, name, moveCounter, remainingTime): >> self.name = name >> self.moveCounter = moveCounter >> self.remainingTime = remainingTime >> >> whitePlayer = player('White', 1, timeLimit) >> blackPlayer = player('Black', 1, timeLimit) >> >> Then playerName(player) becomes player.name and >> remainingPlayerTime(player) becomes player.remainingTime. > > Well, Kent (and Bob Gailer), thanks for trying to help with classes, > but I still don't get them. I've just got to spend time with using > classes in much simpler scripts. You guys may think my chessTimer is > a piece of cake, but it stretched me a lot even without classes. You aren't going to find a simpler use of classes. Maybe a simpler script to use classes, but not a simpler class. All you need to do (I think) is add the class definition, change the two lines that create whitePlayer and blackPlayer, then change each list access, such as currentPlayer[NAME] to an attribute access like currentPlayer.name Once you do that I think you will have a working program, then you can think about possibly moving some code into methods. Kent From orsenthil at gmail.com Wed Oct 31 21:09:11 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Thu, 1 Nov 2007 01:39:11 +0530 Subject: [Tutor] Build exe on Vista, have it run on XP? In-Reply-To: <82b4f5810710290759h33b5f8e3ja5a32cd1b668a74a@mail.gmail.com> References: <82b4f5810710290759h33b5f8e3ja5a32cd1b668a74a@mail.gmail.com> Message-ID: <20071031200911.GA3578@gmail.com> * Michael Langford <mlangford.cs03 at gtalumni.org> [2007-10-29 10:59:34]: > I'm trying to build a exe on a vista system using py2exe. It will deploy to > vista and XP systems. If it matters, the application uses pyserial, as well. Before you proceed with lot of other experiments, my suggestion would be build exes on VISTA and XP separately, and trying running on the other system. I am assuming the either of the two. a) VISTA dlls should be backward compatible with XP, which your issue indicates that you faced problems. b) functionality which is provided by exe built on XP, should be provided by VISTA as well. I would also suggest to check the files and for any incompatible ones, ship both. I doubt, if renaming of msvcrt.dll to something like msvcrt1.dll will work if you have carry both. Just a little research on py2exe checking if we can ship two same named dlls in perhaps different folders can help. Thanks, Senthil -- O.R.Senthil Kumaran http://uthcode.sarovar.org From orest.kozyar at gmail.com Wed Oct 31 21:27:12 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Wed, 31 Oct 2007 16:27:12 -0400 Subject: [Tutor] perplexing error with shelve REVISED In-Reply-To: <5df213700710310043j5da5f9e0u70e773767f25768@mail.gmail.com> References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> <47277521.2090802@alum.rpi.edu> <002101c81b23$936452d0$bd32000a@meei.harvard.edu> <5df213700710310043j5da5f9e0u70e773767f25768@mail.gmail.com> Message-ID: <002601c81bfc$6c396b30$bd32000a@meei.harvard.edu> This is on: Python 2.5 (r25:51908, Oct 19 2007, 09:46:41) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Redhat Fedora release 7 (Moonshine) x86 64 bit processor (SMP) > The program worked fine for me (python 2.5.1 - stackless on > Mac OSX). Can you provide details about your platform (python > version, OS, etc.) ? From orest.kozyar at gmail.com Wed Oct 31 23:00:10 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Wed, 31 Oct 2007 18:00:10 -0400 Subject: [Tutor] perplexing error with shelve REVISED References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> <47277521.2090802@alum.rpi.edu> <002101c81b23$936452d0$bd32000a@meei.harvard.edu> <5df213700710310043j5da5f9e0u70e773767f25768@mail.gmail.com> Message-ID: <003301c81c09$69523de0$bd32000a@meei.harvard.edu> I should also add that when I run this script on my laptop (Windows XP, Python 2.5 r25:51908, 32 bit x84), it does not even print a stacktrace. The interpreter just dumps me back out to the command line. When I use the version of python that comes with cygwin (Python 2.5.1 r251:54863), I get the following error: 12 [main] python2.5 2700 _cygtls::handle_exceptions: Error while dumping state (probably corrupted stack) > -----Original Message----- > From: Orest Kozyar [mailto:orest.kozyar at gmail.com] > Sent: Wednesday, October 31, 2007 4:27 PM > To: 'Aditya Lal' > Cc: 'Bob Gailer'; 'tutor at python.org' > Subject: RE: [Tutor] perplexing error with shelve REVISED > > This is on: > > Python 2.5 (r25:51908, Oct 19 2007, 09:46:41) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Redhat Fedora release 7 (Moonshine) > x86 64 bit processor (SMP) > > > The program worked fine for me (python 2.5.1 - stackless on > > Mac OSX). Can you provide details about your platform (python > > version, OS, etc.) ? From brunson at brunson.com Wed Oct 31 23:39:03 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 31 Oct 2007 16:39:03 -0600 Subject: [Tutor] perplexing error with shelve REVISED In-Reply-To: <002101c81b23$936452d0$bd32000a@meei.harvard.edu> References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> <47277521.2090802@alum.rpi.edu> <002101c81b23$936452d0$bd32000a@meei.harvard.edu> Message-ID: <47290407.6090203@brunson.com> Orest Kozyar wrote: >> Please post the entire traceback (omitting duplicate lines). >> > > Sorry, I should have included the traceback. I've revised the sample script > so that it generates the traceback when run. The sample script is at the > very bottom of this email. > > ####### SCRIPT OUTPUT ####### > [kozyar]:~$ python example.py > > Successfully retrieved and parsed XML document with ID 16842423 > Successfully shelved XML document with ID 16842423 > Successfully retrieved and parsed XML document with ID 16842422 > > Traceback (most recent call last): > File "example.py", line 30, in <module> > data[badkey] = doc > File "/usr/lib64/python2.5/shelve.py", line 123, in __setitem__ > p.dump(value) > RuntimeError: maximum recursion depth exceeded > > Exception exceptions.RuntimeError: 'maximum recursion depth exceeded' in > <bound method DbfilenameShelf.__del__ of {'16842423': > <xml.dom.minidom.Document instance at 0x96f290>}> ignored > > > ####### START SCRIPT ####### > import urllib, shelve > from xml.dom import minidom > > baseurl = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' > > params = { > 'db': 'pubmed', > 'retmode': 'xml', > 'rettype': 'medline' > } > > badkey = '16842422' > goodkey = '16842423' #or just about any other ID > > data = shelve.open('data.tmp', writeback=True) > > params['id'] = goodkey > url = baseurl + urllib.urlencode(params) > doc = minidom.parseString(urllib.urlopen(url).read()) > print 'Successfully retrieved and parsed XML document with ID %s' % goodkey > data[goodkey] = doc > print 'Successfully shelved XML document with ID %s' % goodkey > > params['id'] = badkey > url = baseurl + urllib.urlencode(params) > doc = minidom.parseString(urllib.urlopen(url).read()) > print 'Successfully retrieved and parsed XML document with ID %s' % badkey > The problem seems to be with pickling the doc object. try adding: import pickle print pickle.dumps(doc) right here in your code. Are you sure the XML is well formed? If nothing else, you could try shelving the XML rather than the doc. > data[badkey] = doc > #Will fail on the above line > print 'Successfully shelved XML document with ID %s' % badkey > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Wed Oct 31 23:46:09 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 31 Oct 2007 16:46:09 -0600 Subject: [Tutor] perplexing error with shelve REVISED In-Reply-To: <002101c81b23$936452d0$bd32000a@meei.harvard.edu> References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> <47277521.2090802@alum.rpi.edu> <002101c81b23$936452d0$bd32000a@meei.harvard.edu> Message-ID: <472905B1.8070508@brunson.com> Orest Kozyar wrote: >> Please post the entire traceback (omitting duplicate lines). >> > > Sorry, I should have included the traceback. I've revised the sample script > so that it generates the traceback when run. The sample script is at the > very bottom of this email. > It appears you have a cyclic reference in your doc object. Try adding "doc.unlink()" before you add it to your shelf. > ####### SCRIPT OUTPUT ####### > [kozyar]:~$ python example.py > > Successfully retrieved and parsed XML document with ID 16842423 > Successfully shelved XML document with ID 16842423 > Successfully retrieved and parsed XML document with ID 16842422 > > Traceback (most recent call last): > File "example.py", line 30, in <module> > data[badkey] = doc > File "/usr/lib64/python2.5/shelve.py", line 123, in __setitem__ > p.dump(value) > RuntimeError: maximum recursion depth exceeded > > Exception exceptions.RuntimeError: 'maximum recursion depth exceeded' in > <bound method DbfilenameShelf.__del__ of {'16842423': > <xml.dom.minidom.Document instance at 0x96f290>}> ignored > > > ####### START SCRIPT ####### > import urllib, shelve > from xml.dom import minidom > > baseurl = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' > > params = { > 'db': 'pubmed', > 'retmode': 'xml', > 'rettype': 'medline' > } > > badkey = '16842422' > goodkey = '16842423' #or just about any other ID > > data = shelve.open('data.tmp', writeback=True) > > params['id'] = goodkey > url = baseurl + urllib.urlencode(params) > doc = minidom.parseString(urllib.urlopen(url).read()) > print 'Successfully retrieved and parsed XML document with ID %s' % goodkey > data[goodkey] = doc > print 'Successfully shelved XML document with ID %s' % goodkey > > params['id'] = badkey > url = baseurl + urllib.urlencode(params) > doc = minidom.parseString(urllib.urlopen(url).read()) > print 'Successfully retrieved and parsed XML document with ID %s' % badkey > data[badkey] = doc > #Will fail on the above line > print 'Successfully shelved XML document with ID %s' % badkey > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Oct 31 23:51:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 31 Oct 2007 18:51:00 -0400 Subject: [Tutor] perplexing error with shelve REVISED In-Reply-To: <002101c81b23$936452d0$bd32000a@meei.harvard.edu> References: <001401c81b15$663ff5b0$bd32000a@meei.harvard.edu> <47277521.2090802@alum.rpi.edu> <002101c81b23$936452d0$bd32000a@meei.harvard.edu> Message-ID: <472906D4.8010602@tds.net> Orest Kozyar wrote: >> Please post the entire traceback (omitting duplicate lines). > > Sorry, I should have included the traceback. I've revised the sample script > so that it generates the traceback when run. The sample script is at the > very bottom of this email. I've poked at this a little. The problem is in the pickling of the minidom object. It fails for me using Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin If you use pickle instead of cPickle the stack trace at least shows the recursive calls. Here is a slightly shorter program that demonstrates the problem a little better: import urllib from pickle import Pickler from cStringIO import StringIO from xml.dom import minidom baseurl = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' params = { 'db': 'pubmed', 'retmode': 'xml', 'rettype': 'medline', } badkey = '16842422' params['id'] = badkey url = baseurl + urllib.urlencode(params) doc = minidom.parseString(urllib.urlopen(url).read()) print 'Successfully retrieved and parsed XML document with ID %s' % badkey f = StringIO() p = Pickler(f, 0) p.dump(doc) #Will fail on the above line print 'Successfully shelved XML document with ID %s' % badkey Here is the top of the stack trace: File "BadShelve.py", line 35, in <module> p.dump(doc) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 224, in dump self.save(obj) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 725, in save_inst save(stuff) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 663, in _batch_setitems save(v) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 725, in save_inst save(stuff) You might want to take this to comp.lang.python or perhaps xml-sig. Kent From ricaraoz at gmail.com Wed Oct 31 14:21:53 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 31 Oct 2007 10:21:53 -0300 Subject: [Tutor] Problem with msvcrt Message-ID: <47288171.7050106@bigfoot.com> Hi, was just checking msvcrt module, tried a sample script : >>> import time >>> import msvcrt >>> while True : if msvcrt.kbhit() : key = msvcrt.getch() if key == 'h' : print 'Hello' if key == 'b' : print 'Bye' if key == '\r' : # <Enter> break else : time.sleep(0.1) < Now I keyboard 'h'..... nothing happens (an 'h' appears in idle) > < keyboard 'b'...... nothing still (a 'b' appears) > < keyboard <Enter>...... nothing > < keyboard <Ctrl>+<c> and then : Traceback (most recent call last): File "<pyshell#16>", line 11, in <module> time.sleep(0.1) KeyboardInterrupt hb >>> This is XP with 2.5 in Idle. Any ideas? Thx