Re: [Tutor] Unable to get the gateway IP of wlan interface using python code
On Tue, Nov 13, 2018, srinivasan wrote: >Dear Python Experts, > >*First method:* > >I need to get the IP address basically the gateway IP in my setup I get it >as "192.168.178.1" when I run the below standalone python code. > > >*def get_gateway_ip(self):* >*"""* >*Get the IP address to the WIFI module from the AP* >*"""* > >*cmd = 'ip route show 0.0.0.0/0 <http://0.0.0.0/0> dev wlp1s0 | cut >-d\ -f3'* >*f = os.popen(cmd)* >*return str(f.read().strip())* This command should get the gateway IP. Linux: cmd = "ip route list | awk '/^default/{print $3}'" or perhaps Linux: cmd = "netstat -rn | awk '/^0.0.0.0/{print $2}'" OSX: cmd = "netstat -rn | awk '/^default/{print $2}'" I don't have a freebsd system available to test this, but I think this pattern should work: re.compile(r'^(default|0\.0\.0\.0)\s+(\S+)') Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www2.celestial.com/ PO Box 820; 6641 E. Mercer Way Mobile: (206) 947-5591 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc On the free market, everyone earns according to his productive value in satisfying consumer desires. Under statist distribution, everyone earns in proportion to the amount he can plunder from the producers. -- Murray N. Rothbard ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python smtplib 'Message denied - From address spoofing attempt detected via SMTP
On Sat, Mar 26, 2016, nitin chandra wrote: >Hi All, > >I am trying to script a confirmation mail on submission of a form. > >Till now the form submission and summery page is working. > >BUT the following 'section' is not working. >-- This is a python(CGI) script >-- hosted on a shared server on hostgator.in > >-- This is giving "250 Spoofing error ", below copy/pasted error >log of apache with respect to my website The problem isn't with the python usage, but basic SMTP checking to prevent spamming and such. It's indicating that it thinks the 'From:' address, <no-re...@jss.hs.org> is bogus. There's no MX record for jss.hs.org, and no IP address for jss.hs.org either. The From: address should be legitimate and deliverable. It might also accept a legitimate 'Reply-To:' address. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 A Democracy cannot exist as a permanent form of government. It can only exist until the voters discover they can vote themselves largesse out of the public treasury. From the moment on the majority always votes for the candidate promising the most benefits from the public treasury with the result that Democracy always collapses over a loose fiscal policy, always to be followed by a Dictatorship. Professor Alexander Fraser Tytler. 1801 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] imaplib and mutt flags
On Thu, Jan 30, 2014, Alan Gauld wrote: On 30/01/14 02:45, Bill Campbell wrote: I'm writing a python script which uses imaplib We don't get many messages about imaplib so I'm not sure how many folks here know about it. I've used it off and on for years, but still don't know much about it :-). After some trial and error, I've figured out how to remove the \Seen flag from messages I want to look at manually, Then it's probably a good idea to post at least a code extract showing us how you are going about that. We work better when we have code to look at... have a bit of a problem in that when I open the folder with mutt using direct access to the Maildir folder in the file system, mutt flags these parsed but unseen messages with the 'O' instead of 'N' which is uses for new messages. We have some mutt users so they may be able to p[itch in here. The mail server is using courier-imap with Maildir stores on CentOS Linux. Mutt access is direct on the file system, not via IMAP. OK, Final missing piece is which Python version? On this machine, Python 2.4.6. It seems my main problem is more related to the way that courier-imap and mutt handle the Maildir stores. Mutt distinguishes unread messages as 'N' where the messages are in the $folder/new directory and 'O' in $folder/cur, and moves them from cur to new when one manually changes the flag to 'N'. The IMAP protocol hides the mail store so one cannot manage the message files as this depends on the physical storage format, Maildir, UW IMAP, etc. The bottom line is that this isn't an imaplib/python problem. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 The problems we face today are there because the people who work for a living are now outnumbered by those who vote for a living. -- Anonymous ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] imaplib and mutt flags
I'm writing a python script which uses imaplib to select all unseen messages from a mail folder to process some messages flagging them as seen, and leaving others as unseen so they can be manually processed using the 'mutt' mail client. After some trial and error, I've figured out how to remove the \Seen flag from messages I want to look at manually, but I still have a bit of a problem in that when I open the folder with mutt using direct access to the Maildir folder in the file system, mutt flags these parsed but unseen messages with the 'O' instead of 'N' which is uses for new messages. I would like to have the script restore the 'N' status flag that mutt uses instead of 'O'. The mail server is using courier-imap with Maildir stores on CentOS Linux. Mutt access is direct on the file system, not via IMAP. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Political language... is designed to make lies sound truthful and murder respectable, and to give an appearance of solidity to pure wind. -- George Orwell ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Processing Linux command line output
On Thu, Apr 25, 2013, Gareth Allen wrote: Hi all, I'm trying to get the output of a command and split it into a list that I can process. What is the best way to go about doing this? In bash I would use tools like grep, sed awk etc. The old way to do this uses os.popen import os fh = os.popen('ifconfig') for line in fh: # scan line here The more modern way to handle this is using the subprocess module with something like: from subprocess import PIPE, Popen fh = Popen('ifconfig', stdout=PIPE).stdout ... Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 When the customer has beaten upon you long enough, give him what he asks for, instead of what he needs. This is very strong medicine, and is normally only required once. -- The Consultant's Curse: ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] distutils site.cfg variable expansion
I'm learning my way around package building using setuptools, and would like to have scripts for a system administration package installed under $(prefix)/sbin instead of under the default $(prefix)/bin directory without requiring the installer to use the manual 'python setup.py install --install-scripts=...'. I would like to have something in the setup.cfg file like this which would be handled by the normal ConfigParser expansion. Either I have the syntax wrong, or the setuptools/distutils configuration parsing is different. [global] prefix=/path/to/prefix [install] install-scripts=%(prefix)s/sbin Better yet would be for the prefix to be available from the command line or taken from sys.prefix if not specified. Is there a way to do this other than fiddling the site.cfg file? Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 In a nation ruled by swine, all pigs are upwardly mobile. -- Hunter S. Thompson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting a List
On Wed, Jan 12, 2011, Corey Richardson wrote: Hello Tutors, I am generating XML definitions for animations to be used in a FIFE-based game. I need to sort the frames of the animations, and I am currently using: sorted([image for image in os.listdir(path) if image.endswith('.png')]) The final output in the XML is: frame source=walk_0.png/ frame source=walk_1.png/ frame source=walk_10.png/ frame source=walk_11.png/ frame source=walk_2.png/ frame source=walk_3.png/ frame source=walk_4.png/ frame source=walk_5.png/ frame source=walk_6.png/ frame source=walk_7.png/ frame source=walk_8.png/ frame source=walk_9.png/ Having frame 10 and 11 between frame 1 and 2 is not desired behavior; how can I sort all of these with walk_10.png and company (this isn't the only animation like this) being after walk_9.png? A google search doesn't return anything I could use. I tried just using [image for image in os.listdir(path) if image.endswith('.png')], but that doesn't appear to have any order. This is discussed in the Python Cookbook from O'Reilly. If I remember correctly, it deals exactly with the problem of sorting file names containing numbers as you have above. Here's a bit of code I use in a module I wrote for dealing with RPM versions. import re _digits = re.compile(r'(\d+)') def ver(s): r = _digits.split(s) r[1::2] = map(lambda x: int(x), r[1::2]) return(tuple(r)) class FileInfo(object): def __init__(self, fname) self.fname = fname self.cmp = ver(fname) def __cmp__(self, othr): return cmp(self.cmp, othr.cmp) Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Government is the great fiction, through which everbody endeavors to live at the expense of everybody else. -- Frederic Bastiat ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to pass a python variable to subprocess.call?
On Mon, Oct 25, 2010, Sean Carolan wrote: I'm rewriting a bunch of my bash scripts to get some python practice. There are some instances where python doesn't have the built-in text processing that I need, so I'm using subprocess.call. How can I pass a python variable to these subprocesses? For example: mydir = /usr/local/bin subprocess.call(ls -l /usr/local/bin, shell=True) How do I replace /usr/local/bin in the subprocess call with the mydir variable? subprocess.call(ls -l '%s' % mydir, shell=True) Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Whatever the State saith is a lie; whatever it hath is a theft. -- Nietzsche ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension, efficiency?
On Tue, Sep 28, 2010, Lie Ryan wrote: On 09/28/10 13:57, Bill Allen wrote: I can now see that quite a bit of the code I write dealing with lists can be done with list comprehensions. My question is this, is the list comprehension styled code generally more efficient at runtime? If so, why? Yes, because the looping in list comprehension is done in C instead of a python construct. However, they are the type of efficiency that you shouldn't bother yourself with unless you're microoptimizing. True enough, but dealing with large lists can be expensive, particularly when appending. Before I discovered sets, I found significant time savings by creating a dictionary, adding as necessary, then use d.keys() to get the keys back. This became a significant factor when I was selecting unique lines from about 1.3 million samples. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Independent self-reliant people would be a counterproductive anachronism in the collective society of the future where people will be defined by their associations. 1896 John Dewey, educational philosopher, proponent of modern public schools. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Plea for Sensible Quoting
On Tue, Sep 14, 2010, Michael Powe wrote: Hello, I read this list in a linux console using mutt. I dunno, maybe I'm the only idiot left still using a console mail client. I write my emails and email replies in emacs, too, which may make me even weirder. Mutt in xterms here with vi (I've never been able to get my fingers retrained for emacs after almost 30 years of vi :-). Agreed on the quoting. Interspersing new information between quoted sections is great, but quoting an entire message only to add ``ditto'' at the end is idiotic. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Democracy extends the sphere of individual freedom, Democracy attaches all possible value to each man, while socialism makes each man a mere agent, a mere number. Democracy and socialism have nothing in common but one word: equality. But notice the difference: while democracy seeks equality in liberty, socialism seeks equality in restraint and servitude. Alexis de Tocqueville == 1848 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FTP from mainframe
On Thu, Jul 29, 2010, bob gailer wrote: On 7/29/2010 12:34 PM, Steve Bricker wrote: This is my first attempt to FTP a file from a mainframe. The code: import ftplib The easiest way I've found to get a file via ftp in python is to user urllib, not ftplib. Something like this (add error checking). import urllib, os fname='something.pdf' url = 'ftp://%...@%s:%s/%s' % ('john', 'secret', 'example.com', fname) # f will have a temporary file name, and h the headers (f, h) = urllib.urlretrieve(url) os.rename(f, fname) Of course this works for http by simply changing the url. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 If you want government to intervene domestically, you're a liberal. If you want government to intervene overseas, you're a conservative. If you want government to intervene everywhere, you're a moderate. If you don't want government to intervene anywhere, you're an extremist -- Joseph Sobran ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why is the max size so low in this mail list?
On Mon, Mar 01, 2010, Sander Sweers wrote: On 1 March 2010 18:13, Wayne Watson sierra_mtnv...@sbcglobal.net wrote: See Subject. 40K here, but other Python lists allow for larger (total) sizes. Don't know but if it is that long use pastebin [1]. 40K is the default on Mailman mailing lists, and for good reason. I don't know how many subscribers there are, but multiplying message size by number of recipients can generate huge volumes (don't forget that encoding binary attachments increases their size by about 1/3). Not everybody has broadband connections, and getting large attachments can cost them Real Money(tm) (as if there is any of that in the world's monetary systems these days :-), and take a long time to download. One of the best features of the horde/imp webmail program is that it makes it easy for one to upload attachments to the web server with a link to the attachment in the body of the message. That's a feature I would like to see an all webmail servers. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 I have no reason to suppose that he, who would take away my Liberty, would not when he had me in his Power, take away everything else. John Locke ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] imaplib command to delete messages
I've written a script to go through varions Sent folders on IMAP servers to archive the messages on a central server using imaplib to do the heavy lifting. Perhaps I'm a bit thick, but I have not been able to figure out how to delete messages in the folders after processing them. The imaplib documentation as lots of ways to delete mailboxes (folders) and expunge messages from folders, but I don't see anything about marking individual messages as deleted. What am I missing? Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Our Foreign dealings are an Open Book, generally a Check Book. Will Rogers ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] email module, convert non multipart to multipart message
Is there a simple way to convert a MIMENonMultipart message parsed into a MIMEMultipart message? My goal is to take a message from the TouchTerm iPhone App with an openssh public key that has been mangled by intervening mailers, and convert it into a multipart message with the original text in one part and the cleaned up key as an application/base64 part that can be easily saved by a non- technical user. I have written a routine that does this by creating a new multipart container, copying all (well almost all) the headers into the new container then attaching the original body and the clean key, but I think there ought to be a neater way. Thanks. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 There is no worse tyranny than to force a man to pay for what he does not want merely because you think it would be good for him. -- Robert Heinlein ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Faster list searching?
On Wed, Nov 18, 2009, GoodPotatoes wrote: I'm dealing with bigger lists than I have been, and noticed this is getting really slow. Is there a faster way to do this? for x in list1: if x not in list2: list3.append(x) My search is taking up to 5 minutes to complete. When I have had to deal with large lists, I have found that using an intermediate dictionary can save huge amounts of time. Something like: dict2 = {}.fromkeys(list2) for x in list1: if x not in dist2: dict2[x] = True list2 = dict2.keys() Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Intaxication: Euphoria at getting a refund from the IRS, which lasts until you realize it was your money to start with. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is Curses and why do they call it that.
On Tue, Oct 13, 2009, Alan Gauld wrote: Katt the_only_kat...@verizon.net wrote Some documentation indicate it as a module that will translate commands to control screen output. Is this right? Also, why do they call it curses? Thats right, it provides a way to draw GUI like windows on the screen using graphics characters if they are available or plain ASCII if not, thus it offers a degree of terminal independance. It was popular in the period before GUIs became normal but after they became desirable - ie around 1985-1995. And should be more desirable today for applications that require efficient, heads-down data entry where one does not want to take fingers off of home keys or numeric keypads. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 What this country needs are more unemployed politicians. -- Edward L angley, Artist (1928 - 1995) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issues with regex escaping on \{
On Wed, Jul 29, 2009, vince spicer wrote: On Wed, Jul 29, 2009 at 11:35 AM, gpo goodpotat...@yahoo.com wrote: My regex is being run in both Python v2.6 and v3.1 For this example, I'll give one line. This lines will be read out of log files. I'm trying to get the GUID for the User ID to query a database with it, so I'd like a sub match. Here is the code - import re line = 'Checking Privilege for UserId: {88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId: {71AD2527-8494-4654-968D-FE61E9A6A9DF}. Returned hr = 0' pUserID=re.compile('UserID: \{(.+)\}',re.I) #Sub match is one or more characters between the first set of squigglies immediately following 'UserID: ' #the output is: (re.search(pUserID,line)).group(1) '88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId: {71AD2527-8494-4654-968D-FE61E9A6A9DF' --- Why isn't the match terminating after it finds the first \} ? ... your grouping (.+) appears to be greedy, you can make it non-greedy with a question mark As a general rule, it's a Good Idea(tm) to write regular expressions using the raw quote syntax. Instead of: re.compile('UserID: \{(.+)\}',...) Use: re.compile(r'UserID: \{(.+)\}',...) The alternative is to backwhack any special characters with an appropriate number if ``\'' characters, whatever that may be. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Government is a broker in pillage, and every election is a sort of advance auction in stolen goods. -- H.L. Mencken ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] != -1: versus == 1
On Fri, Jul 17, 2009, pedro wrote: Hi I have been trying to understand a python script and I keep coming across this kind of structure that says If it is not equal to negative one for line in theLines: if line.find(Source Height) != -1: #etc... ### Is there some special reason for this. Why not just write If it is equal to one The string find method returns -1 if the string is not found, otherwise it returns the 0-based index into the string matching the argument to find. The test above will return -1 if ``Source Heigtht'' is not in line, and one generally wants to have the test return True if there is something to do. The alternative would be to say ``if not line.find('Source Height') == -1: ...'' Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Windows is a computer virus with a user interface!! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.system and/or subprocess.call problem...
On Fri, Jul 10, 2009, daychi...@gmail.com wrote: I'm working on a program that calls another program recursively - this other program reads in ini file and processes it; my program creates a number of slightly different ini files and calls the other program for each one. I can successfully generate the ini file. The problem is that the other program doesn't seem to execute it correctly; or is unable to read its contents. I'm not sure what's going on from the error it's giving me - basically, it says there's nothing to do in the ini, so that's why I think it's either not reading the ini, or perhaps it's being executed as the wrong user or something. (Linux environment) Are you closing or flushing the output file before starting the subprocess? Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 Thou shalt not steal, except by majority vote. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mac os x executable
On Tue, Jul 07, 2009, Pete Froslie wrote: Hi, I'm having trouble finding good tutorials on creating standalone executable files for mac os x.. I've been looking at 'py2app', but can't seem get a solid grasp. Any help would be greatly appreciated! For a python script, say mypython.py, it should start with something like this: #!/usr/bin/env python # do stuff here Then ``chmod +x mypython.py'' and it's ready to go. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 There has been no greater threat to life, liberty, and property throughout the ages than government. Even the most violent and brutal private individuals have been able to inflict only a mere fraction of the harm and destruction that have been caused by the use of power by political authorities. -- Richard Ebeling ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mac os x executable
On Tue, Jul 07, 2009, Pete Froslie wrote: Wesley, What I meant is that I would like a file that can be double clicked in order to run the python script.. so that I can drop it on another mac where someone can execute it without worrying about Terminal. Essentially, I need everything to be clean in the end.. My projects are artworks and function better without the tech confusion when viewers interact with them.. I hope this helps clarify my trouble Thanks for the explanation -- it is helpful.. You might want to look at XDroplets, a program that generates wrappers for X11 applications that one can click on or drop files on to execute them. For instance, I have one I call Gvim.app that executes the vim editor in an xterm (I don't like the GUI versions of vim, but prefer working in a simple xterm). Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 It's time to feed the hogs -- Unintended Consequences ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quick question to open(filename, 'r') vs. file(filename, 'r')
On Tue, May 05, 2009, David wrote: Dear list, in different books I come across different syntax for dealing with files. It seems that open(filename, 'r') and file(filename, 'r') are used interchangeably, and I wonder what this is all about. Is there a reason why Python allows such ambiguity here? Cheers for a quick shot of enlightenment ;-) ``pydoc file'' is your friend. It says open is an alias for file. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 A petty thief is put in jail. A great brigand becomes ruler of a State. -- Chuang Tzu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sorting file paths made up of of strings and numbers
On Tue, Apr 14, 2009, Emad Nawfal ( ) wrote: Hi tutors, How can I sort the following list in a way that takes care of the right order of numbers? The sorted function compares strings here as far as I can see, but I want to have filepath2 follow filepath1. Your help is appreciated. There is at least one example of a method of dealing with this in the O'Reilly ``Python cookbook''. myList ['filepath54', 'filepath25', 'filepath49', 'filepath0', 'filepath89', 'filepath52', 'filepath37', 'filepath32', 'filepath2', 'filepath15', 'filepath88', 'filepath70', 'filepath33', 'filepath58', 'filepath28', 'filepath61', 'filepath23', 'filepath64', 'filepath72', 'filepath11', 'filepath63', 'filepath76', 'filepath87', 'filepath45', 'filepath41', 'filepath68', 'filepath81', 'filepath75', 'filepath62', 'filepath46', 'filepath36', 'filepath39', 'filepath5', 'filepath34', 'filepath8', 'filepath67', 'filepath14', 'filepath82', 'filepath29', 'filepath47', 'filepath79', 'filepath13', 'filepath16', 'filepath71', 'filepath27', 'filepath100', 'filepath20', 'filepath92', 'filepath57', 'filepath73', 'filepath40', 'filepath44', 'filepath83', 'filepath50', 'filepath66', 'filepath94', 'filepath86', 'filepath22', 'filepath17', 'filepath84', 'filepath38', 'filepath12', 'filepath53', 'filepath6', 'filepath48', 'filepath60', 'filepath51', 'filepath90', 'filepath4', 'filepath78', 'filepath69', 'filepath35', 'filepath97', 'filepath93', 'filepath24', 'filepath26', 'filepath1', 'filepath3', 'filepath96', 'filepath77', 'filepath98', 'filepath18', 'filepath43', 'filepath19', 'filepath56', 'filepath65', 'filepath95', 'filepath55', 'filepath7', 'filepath99', 'filepath91', 'filepath85', 'filepath9', 'filepath59', 'filepath10', 'filepath30', 'filepath31', 'filepath80', 'filepath42', 'filepath74', 'filepath21'] sorted(myList) ['filepath0', 'filepath1', 'filepath10', 'filepath100', 'filepath11', 'filepath12', 'filepath13', 'filepath14', 'filepath15', 'filepath16', 'filepath17', 'filepath18', 'filepath19', 'filepath2', 'filepath20', 'filepath21', 'filepath22', 'filepath23', 'filepath24', 'filepath25', 'filepath26', 'filepath27', 'filepath28', 'filepath29', 'filepath3', 'filepath30', 'filepath31', 'filepath32', 'filepath33', 'filepath34', 'filepath35', 'filepath36', 'filepath37', 'filepath38', 'filepath39', 'filepath4', 'filepath40', 'filepath41', 'filepath42', 'filepath43', 'filepath44', 'filepath45', 'filepath46', 'filepath47', 'filepath48', 'filepath49', 'filepath5', 'filepath50', 'filepath51', 'filepath52', 'filepath53', 'filepath54', 'filepath55', 'filepath56', 'filepath57', 'filepath58', 'filepath59', 'filepath6', 'filepath60', 'filepath61', 'filepath62', 'filepath63', 'filepath64', 'filepath65', 'filepath66', 'filepath67', 'filepath68', 'filepath69', 'filepath7', 'filepath70', 'filepath71', 'filepath72', 'filepath73', 'filepath74', 'filepath75', 'filepath76', 'filepath77', 'filepath78', 'filepath79', 'filepath8', 'filepath80', 'filepath81', 'filepath82', 'filepath83', 'filepath84', 'filepath85', 'filepath86', 'filepath87', 'filepath88', 'filepath89', 'filepath9', 'filepath90', 'filepath91', 'filepath92', 'filepath93', 'filepath94', 'filepath95', 'filepath96', 'filepath97', 'filepath98', 'filepath99'] ``` -- áÇ ÃÚÑÝ ãÙáæãÇ ÊæÇØà ÇáäÇÓ Úáí åÖãå æáÇ ÒåÏæÇ Ýí ÅäÕÇÝå ßÇáÍÞíÞÉ.ãÍãÏ ÇáÛÒÇáí No victim has ever been more repressed and alienated than the truth Emad Soliman Nawfal Indiana University, Bloomington ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 An almost hysterical antagonism toward the gold standard is one issue which unites statists of all persuasions. They seem to sense that gold and economic freedom are inseparable. -- Alan Greenspan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] glob in order of the file numbers
On Fri, Mar 06, 2009, Emad Nawfal ( ) wrote: Hi Tutors, suppose I have four files in the current directory: 1.temp, 2.temp, 3.temp, and 4.temp. I want to use glob, or anything else, to print the contents of the files in their respective orders, where the content of 1.temp gets printed, then 2.temp, then 3.temp, then 4.temp. I write the following, but it does not get me what I want: import glob for path in glob.iglob(*.temp): infile = open(path) for line in infile: print line.strip() # This prints e...@emad-laptop:~/Desktop/TEMP$ python globbing.py This is four This is one This is two This is three Could somebody please tell me how to get the output in the right order? files = glob.glob('*.temp') files.sort() for file in files: ... Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 The pinnacle of open systems is: when moving from vendor to vendor, the design flaws stay the same. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] *nix tail -f multiple log files with Thread
On Mon, Feb 16, 2009, David wrote: Bill Campbell wrote: The ``swatch'' program, written in perl, does this by using the gnu-tail program via a pipe using. gtail --follow=name --lines=1 file1 file2 ... Use the source Luke. ... That looks like the right tool for the job at hand. Looking at setting up the configuration file, a stumbling block in my learning to program is my lack of a good understanding of regular expressions. I have started studying grep, sed and awk. It is a lot more fun to just write little python programs and watch in amazement when they work as expected. I have been avoiding this phase of learning. Looking at other people's scripts can be very enlightening. When I started learning Xenix in 1982, there were about 2 books on the subjects, Jean Thompson's blue one, and I forget the other. I learned a lot by reading system administration scripts, once I figured out that these were working programs. One of the best books I've ever seen for general *nix text processing and use of tools is ``Unix Text Processing'' by Dougherty and O'Reilly. It has been out of print for years, but can probably be found through bookfinder.com It has lots on regular expressions, using ``vi'', etc. There is information on regular expressions in any book on python, perl, and other scripting languages. O'Reilly has a book ``Mastering Regular Expressions'' which is probably pretty good, but I have never read it. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 About all I can say for the United States Senate is that it opens with prayer and closes with an investigation. -- Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] *nix tail -f multiple log files with Thread
On Sun, Feb 15, 2009, bob gailer wrote: David wrote: Hi everyone, I copied a program from C to track multiple log files. I would like to be able to print a label when a log file is updated. Did the C program accomplish that? If so, it might help to see that code. If not why mention it? The ``swatch'' program, written in perl, does this by using the gnu-tail program via a pipe using. gtail --follow=name --lines=1 file1 file2 ... Use the source Luke. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 The day-to-day travails of the IBM programmer are so amusing to most of us who are fortunate enough never to have been one -- like watching Charlie Chaplin trying to cook a shoe. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] eval and floating point
On Wed, Jan 14, 2009, jadrifter wrote: On Thu, 2009-01-15 at 12:19 +1000, Mr Gerard Kelly wrote: Thanks very much I've noticed that the eval() function gives an integer, so eval(3/2) gives back 1. float(eval(3/2)) doesn't seem to work, any way to get a floating point number back with eval()? I know you can just do (3./2.), but is there any way to do it with just (3/2)? That's not the eval function returning that integer so much as it is Python itself. You might try: eval (1.0 * 3/2) Make either the numerator or denominator floating point. eval ('3.0/2') Python does the Right Thing(tm) when dividing two integers, returning an integer result. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 The essence of all slavery consists in taking the produce of another's labor by force. It is immaterial whether this force be founded on ownership of the slave or ownership of the money that he must get to live on. Leo Tolstoy 1891 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] beginsWith multiple prefixes
On Wed, Dec 24, 2008, bob gailer wrote: Emad Nawfal ( ) wrote: Hi Tutors, I want a function that acts like the startswith method, but can take multiple prefixes. As an amateur programmer, I came up with this one, and it works fine, but my experience tells me that my solutions are not always the best ones around. Can you please tell me what a better option might be: ... Above does a lot more work than necessary. Try: def beginsWith(word, listname): for prefix in listname: if word.startswith(prefix): return True It might be more useful to return the prefix that matched as the caller already knows what ``word'' is. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Basic Definitions of Science: If it's green or wiggles, it's biology. If it stinks, it's chemistry. If it doesn't work, it's physics. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading output from a c executable.
On Sat, Dec 20, 2008, Ravi Kondamuru wrote: I am trying to use xstruct module to unpack a varaible size record with the following structure. struct nameid { u32bits len /* total length */ u32bits id; char name; /* name variable length */ } As can be seen the length of the name = len - (sizeof(len) + sizeof(id)). How do I use xstruct or struct to unpack such a structure? n = xstruct.structdef(xstruct.little_endian, [ ('len', (xstruct. unsigned_long, 1)), ('id', (xstruct.unsigned_long, 1)), ('name', (xstruct.string, ?)), ]) xstruct seems to expect the exact len to be specified in structdef. Is there a way to tell it to go till the end of the buffer passed? I haven't done this in python yet, but when handling things like this in C and perl, I have done it with two reads, the first to get the length, the second to read the data with that length. Bill -- INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Independent self-reliant people would be a counterproductive anachronism in the collective society of the future where people will be defined by their associations. 1896 John Dewey, educational philosopher, proponent of modern public schools. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Decimal fixed point representation
On Fri, Nov 21, 2008, Dinesh B Vadhia wrote: That's right, it is the Decimal module I'm trying to understand. And, it is how to represent a decimal floating point number as a common/vulgar fraction eg 1.234 = 1234/1000. How do you do this using the Decimal module? The motivation is to avoid floating point calculations and use integers only (don't ask why!). Cheers! I can understand why if one is writing accounting applications that have to be accurate to the penny (or whatever in the local currency). Accountants and auditors don't like rounding errors. The accounting system I wrote in the mid-80s, and still use today, is written mostly in C, and handles all monitary calculations in cents in long integers with appropriate input and output routines to make them look to the world as it would expect. There was (is?) a FixedPoint package in python that I use for handling dollar amounts. It came out before the Decimal type, and I am not fixing something that works. The only machines I worked on extensively that handled decimal arithmatic very well were the Burroughs Medium Systems B-2500 through B-4800 which did everything in decimal which made a lot of sense since they were designed primarily to run COBOL accounting applications. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Scientists are explorers. Philosophers are tourists. -- Richard Feynman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python based blogging software/cms?
On Mon, Nov 03, 2008, [EMAIL PROTECTED] wrote: Not sure if this is appropriate for the tutor mailing list, but it is a beginner question for python. It seems most of the popular cms/blogging software is php/mysql based Anything of substancial popularity/support based on python? I was looking for something along the lines of wordpress popular, but not sure if there exists something for python. I'm aware of Zine (http://dev.pocoo.org/projects/zine/ ) that is trying to become wordpress like, any others? We have been using Zope and Plone for about 4 years now. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 If taxation without consent is not robbery, then any band of robbers have only to declare themselves a government, and all their robberies are legalized. -- Lysander Spooner, Letter to Grover Cleveland 1886 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dealing with user input whose value I don't know
On Thu, Oct 02, 2008, Steve Willoughby wrote: On Fri, Oct 03, 2008 at 01:38:48AM +0800, David wrote: Does that mean input() is obsolete (after all, Zelle's book is not the freshest on the shelf)? Or do they have different uses? Depends on how you look at it. input() automatically evaluates whatever the user types as a Python expression and returns the result. So if they type 5, the integer 5 is returned. For your program, that's probably what you want, and has the advantage of letting you type something like 2+3 so your user can let Python evaluate math expressions. On the other hand, you'd think that you could ask a user for a text response using input(): name = input(What is your name? ) print Hello, , name But if they just type the answer, Python will crash with an error because it's expecting a legal Python expression there (so a string value would have to be typed in quotes). Remember the cardinal rule NEVER TRUST USER INPUT! Always check for validity, and use methods that prevent malicious strings from allowing the user to get unauthorized access or change things they shouldn't. Many of the common exploits of web pages are the result of poor checking of input resulting in sql injection attacks, and other breaches. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 There are three kinds of men. The ones that learn by reading. The few who learn by observation. The rest of them have to pee on the electric fence for themselves. -- Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting Dictionary of Dictionary by certain Value
On Wed, Sep 24, 2008, John Fouhy wrote: 2008/9/24 Joe Python [EMAIL PROTECTED]: Hi Pythonistas, I have a large dictionary of dictionary (50,000+ keys) which has a structure as follows: [snip] I want to sort the dictionary by 'income' Is there an efficient way to do the same. Note that you cannot sort a dictionary. The best you can do is build a list containing the dictionary keys in the appropriate order and use the dictionary in combination with that list. What you can do is create a class for the objects in the top level dictionary, and create a __cmp__ method in that class using cmp to compare the objects in the dictionary, finally sorting the values. class MyStuff(object): def __init__(self, name, income): self.name = name self.income = int(income) def cmp(self, other): return(cmp((-self.income, self.name), -other.income, other.name)) d = dict( key1 = MyStuff('john', 1), key2 = MyStuff('bill', 2), ) vals = d.values() vals.sort() # vals should be sorted by income in descending order and name. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 People who relieve others of their money with guns are called robbers. It does not alter the immorality of the act when the income transfer is carried out by government. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting Dictionary of Dictionary by certain Value
On Tue, Sep 23, 2008, Bill Campbell wrote: On Wed, Sep 24, 2008, John Fouhy wrote: 2008/9/24 Joe Python [EMAIL PROTECTED]: Hi Pythonistas, I have a large dictionary of dictionary (50,000+ keys) which has a structure as follows: [snip] I want to sort the dictionary by 'income' Is there an efficient way to do the same. Note that you cannot sort a dictionary. The best you can do is build a list containing the dictionary keys in the appropriate order and use the dictionary in combination with that list. What you can do is create a class for the objects in the top level dictionary, and create a __cmp__ method in that class using cmp to compare the objects in the dictionary, finally sorting the values. class MyStuff(object): def __init__(self, name, income): self.name = name self.income = int(income) Whoops The method below should be def __cmp__ def cmp(self, other): return(cmp((-self.income, self.name), -other.income, other.name)) d = dict( key1 = MyStuff('john', 1), key2 = MyStuff('bill', 2), ) vals = d.values() vals.sort() # vals should be sorted by income in descending order and name. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 People who relieve others of their money with guns are called robbers. It does not alter the immorality of the act when the income transfer is carried out by government. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax:(206) 232-9186 Microsoft is to computers what Phillip Morris is to lungs. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Truncate First Line of File
On Wed, Feb 27, 2008, Alex Ezell wrote: I must be missing some simple method on a file object or something. What I need to do is to truncate the first line of a file which has an unknown number of lines and an unknown size. The only thing I can think to do is to readlines() and then slice off the first line in the resulting list, then writelines(). pseduo-code: my_file = open('file.txt', 'wb') lines = my_file.readlines() del lines[0] my_file.writelines() my_file.close() Is there a better way? Defensive programming avoids slurping entire files of unknown size into memory. I would just open the file, use readline() to get rid of the first line, the loop writing the rest. If you're going to slurp the whole thing: infile = open('inputfile') lines = infile.readlines() outfile = open('outfile', 'wb') outfile.writelines(lines[1:]) outfile.close() Another way on *nix systems that might be better wouldn't use python at all. Edit the file in place with ed or ex: #!/bin/sh ex - filename DONE 1d w q DONE Bill -- INTERNET: [EMAIL PROTECTED] 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 Government is actually the worst failure of civilized man. There has never been a really good one, and even those that are most tolerable are arbitrary, cruel, grasping and unintelligent. -- H. L. Mencken ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] appending to a list
On Wed, Jan 30, 2008, David Bear wrote: I want to return a tuple from a function. I want to append the second element of that tupple to a list. For example mylist = [] def somefunc(): return(3.14, 'some string') somenum, mylist.append(??) somefunc() obviously, the syntax doesn't work. This should be easy, but I've never seen example code. any pointers? mylist.append(somefunc()[1]) Bill -- INTERNET: [EMAIL PROTECTED] 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 If ye love wealth greater than liberty, the tranquillity of servitude greater than the animating contest for freedom, go home from us in peace. We seek not your consul, nor your arms. Crouch down and lick the hand that feeds you. May your chains set lightly upon you; and may posterity forget ye were our countrymen. -- Samuel Adams (American Patriot) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Spaces and tabs messing up code
On Tue, Jan 08, 2008, [EMAIL PROTECTED] wrote: my friend uses vim and i use xemacs so our shared python code is a mix of tabs and spaces and it is hard for him to edit it in vim any idea on how to make it clean convert it all to 4 spaces? Do that, and in his ~/.vimrc file, add a line ``set expandtab'' (Friends don't let friends use emacs :-). Bill -- INTERNET: [EMAIL PROTECTED] 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 Giving money and power to government is like giving whiskey and car keys to teenage boys -- P.J. O'Rourke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Windows - Linux based open() file handle mode
On Mon, Nov 19, 2007, Srinivas Iyyer wrote: Dear group, I want to parse an file generated for windows. My code works beautifully when I try to parse the same file generated in Linux. I uses the following options with no success: blast_out = open('C:\human\prb_blast.out','r') blast_out = open('C:\human\prb_blast.out','rU') blast_out = open('C:\human\prb_blast.out','U') Are there any other ways to solve this problem. Try blast_out = open('C:/human/prb_blast.out', 'U') instead of the $DEITY/Awful DOSish backwacks. If you're really enamoured of backslashes, add an r before the single quotes to get what you want. blast_out = open(r'C:\human\prb_blast.out','U') Bill -- INTERNET: [EMAIL PROTECTED] 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 There is nothing as stupid as an educated man if you get him off the thing he was educated in. Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re-Naming an existent file
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: [EMAIL PROTECTED] 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function for removing all white spaces from a string
On Mon, Oct 01, 2007, Alan Gauld wrote: Tim [EMAIL PROTECTED] 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: [EMAIL PROTECTED] 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Image Analysis
On Wed, Sep 12, 2007, Kent Johnson wrote: Bill Campbell wrote: Most mailing lists limit the size of messages to 40k or less. On this list large messages go to moderation. I think I was so captivated with the images that I forgot about the size. A better way to present this would be to put the images on a web site and reference them from email. Sorry about that... I've done the same thing on occassion on lists I manage :-). One of the things I really like about the IMP webmail package is that it makes it easy for people to provide links to attachments rather than sending the files. It automatically copies the files to the web server, adding the links to the bottom of the message. I don't generally like web e-mail interfaces, but do use IMP when dealing with large attachment. Bill -- INTERNET: [EMAIL PROTECTED] 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 I don't make jokes, I just watch the Government and report the facts... Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Image Analysis
On Tue, Sep 11, 2007, Eric Brunson wrote: Just my opinion, but I didn't mind the attachments, I felt they added quite a bit to the discussion and I certainly appreciated the input on the application of the libraries. My opinion on your tone, I'll keep to myself. Figure out the total size sending a megabyte+ mail message to hundreds of list recipients. Most mailing lists limit the size of messages to 40k or less. While large messages aren't much of an issue on broadband connections, they can be a problem for those on dialup or with tight disk quotas. Bill -- INTERNET: [EMAIL PROTECTED] 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 We'll show the world we are prosperous, even if we have to go broke to do it. Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bookpool sale on Addison Wesley
On Wed, Aug 08, 2007, Kent Johnson wrote: Bookpool is having a sale on all books from Addison-Wesley and Prentice Hall. In my opinion these are two of the best publishers for top-notch computer titles. I've found bookpool.com to generally have better prices on technical books than Amazon or Powells. They're generally the first place I look. (my only assocation with any of them is as a customer). ... Bill -- INTERNET: [EMAIL PROTECTED] 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 Government is actually the worst failure of civilized man. There has never been a really good one, and even those that are most tolerable are arbitrary, cruel, grasping and unintelligent. -- H. L. Mencken ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex Ordering
On Mon, Jul 23, 2007, James Hartley wrote: On 7/23/07, Shidan [EMAIL PROTECTED] wrote: I'm looking for a Python module that provides methods for ordering regexes based on how general they are ( how much they match). Do I have to write it Your question is relative. Classifying which regular expression is more general depends upon the other regular expressions used in comparison along with the specific input. As you change input regular expressions, the ordering will change. As a first cut, one might sort the regular expression strings in reverse order such that the longer strings are tested first. Bill -- INTERNET: [EMAIL PROTECTED] 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 Virtually everything is under federal control nowadays except the federal budget. -- Herman E. Talmadge, 1975 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] #!/usr/bin/env python vs #!/usr/local/bin/python
On Thu, Jun 14, 2007, Rolando Pereira wrote: [EMAIL PROTECTED] escreveu: Okay, I guess, people are missing points here. When do you #!/usr/local/bin/python You are specifying the location to the python executable in your machine, that rest of the script needs to be interpreted with. You are pointing to python is located at /usr/local/bin/python Consider the possiblities that in a different machine, python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail. For those cases, we get to call the env executable with argument which will determine the arguments path by searching in the $PATH and use it correctly. Thus, #/usr/bin/env python Will figure out the correct location of python ( /usr/bin/python or /bin/python from $PATH) and make that as the interpreter for rest of the script. - ( env is almost always located in /usr/bin/ so one need not worry what is env is not present at /usr/bin) ... I've always used #!/usr/bin/python... Perhaps I should use the #!/usr/bin/env python one. The case where ``#!/usr/bin/env python'' won't work is where there are multiple versions of python on the system, and one wants to run a version that's not first in the PATH. In that case one needs to put the full path to the proper executable. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``The trouble with fighting for human freedom is that one spends most of one's time defending scoundrels. For it is against scoundrels that oppressive laws are first aimed, and oppression must be stopped at the beginning if it is to be stopped at all.'' -- H. L. Mencken ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Behaviour of dictionaries and others when deleting?
On Mon, May 21, 2007, Kent Johnson wrote: Bill Campbell wrote: Is the behaviour defined if one is processing a dictionary using iteritems, and delete items? for k, v in d.iteritems(): if somecondition(k, v): del d[k] Would this process all the original members of the dictionary? This is not well-defined. You can use for k, v in d.items(): which creates a new list to hold the items and iterates that. Thanks for the feeback Kent. It confirms my thoughts. Using the 2nd method, d.items(), can be an issue with very large dictionaries (although I tend use the Berkeley databases for these when dealing with very large data sets). I've always been leary of deleting items while processing things like this, keeping a list of keys to be deleted, then processing that list upon completion of the mail loop to delete the items from the original dictionary or database file. I don't know about bsddb but for lists and dicts that is the right approach. You can also use a list comprehension to filter a list or dict. The places where I'm really concerned with this is dealing with large databases, say a few million records with info on all data storage on a server. Bill -- INTERNET: [EMAIL PROTECTED] 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 If you think health care is expensive now, wait until you see what it coses when it's free -- P.J. O'Rourke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Behaviour of dictionaries and others when deleting?
Is the behaviour defined if one is processing a dictionary using iteritems, and delete items? for k, v in d.iteritems(): if somecondition(k, v): del d[k] Would this process all the original members of the dictionary? How about doing something similar with bsddb files? I've always been leary of deleting items while processing things like this, keeping a list of keys to be deleted, then processing that list upon completion of the mail loop to delete the items from the original dictionary or database file. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``there is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things. Because the innovator has for enemies all those who have done well under the old conditions, and lukewarm defenders in those who may do well under the new.'' -- Machiavelli ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to test for a remainder from division
On Mon, May 14, 2007, Luke Paireepinart wrote: Matt Smith wrote: Hi there, I'm trying to write a short function to test whether a year is a leap year or not. To do this I need to check whether the year divides exactly by 4, 100 and 400. I can't think of an easy way to test whether there is a remainder or not. The best I can come up with so far is: if (year / 4.0) - (year // 4.0) 0: This doesn't seem to work, it is always True, is there a problem with the comparison? The arithmetic seems to be the correct way to isolate the remainder of the division. Can anyone suggest a better way of performing this test or alternately, how can I get the line above to work. Matt Matt: I'm not sure about your pseudocode, but have you tried to accomplish this with the modulus operator? It provides the remainder of integer division (i.e. a remainder of 0 indicates a perfect divisor.) so you could do: if year % 4 or year % 100 or year % 400: #then it's divisible perfectly by any of [4,100,400] While the modulus operator is generally useful for things like this, one might want to use the calendar module for this if it's smarter about some of the subtle quirks of leapyear: import calendar if calendar.isleap(year): ... Bill -- INTERNET: [EMAIL PROTECTED] 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 We contend that for a nation to try to tax itself into prosperity is like a man standing in a bucket and trying to lift himself up by the handle. -- Winston Churchill ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.path.join question
On Wed, May 02, 2007, Jason Coggins wrote: Is it possible to use os.path.join to link to a file located in the directory above where you are currently located? os.path.join('..', filename) os.path.realpath(os.path.join('..', filename)) Bill -- INTERNET: [EMAIL PROTECTED] 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 ``Democracy extends the sphere of individual freedom, Democracy attaches all possible value to each man, while socialism makes each man a mere agent, a mere number. Democracy and socialism have nothing in common but one word: equality. But notice the difference: while democracy seeks equality in liberty, socialism seeks equality in restraint and servitude.'' de Tocqueville == 1848 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about exception
On Thu, Apr 05, 2007, Mike Hansen wrote: When doing a try/except block, is it possible to return a list as part of the exception? try: check_someting() except CheckSomethingError, e: for each_error in e: # do something Can 'e' be a list of errors? If so, how do you construct your exception class? If the Exception is defined as a class, e will be an instance of that class so you can have pretty much anything available: class MyException(Exception): def __init__(self, msg, mylist) self.msg = msg self.mylist = mylist Exception.__init__(self, msg) try: check_something() except MyException, e: for entry in e.mylist: ... Bill -- INTERNET: [EMAIL PROTECTED] 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 ``I don't make jokes, I just watch the Government and report the facts...'' Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing a list, dict or tuple to MySQLdb?
On Wed, Mar 07, 2007, Alan Wardroper wrote: I'm parsing some data to feed to a MySQL database, and would like to be able to pass in a list (a dictionary or a series of tuples) in the cursor.execute() or cursor.executemany() statement, but everything I've tried raises errors. I'm sure it's a matter of correct formatting the list as a sequence... CODE: import sys, MySQLdb conn = MySQLdb.connect (host = localhost, user = user, psswd = db = testdb) cursor = conn.cursor() infile = open(sys.argv[2], 'r') list_of_tuples = [] for line in infile: tuple = (line.split()[0], line.split()[1]) list_of_tuples.append(tuple) cursor.executemany(UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE field2 = %s, (list_of_tuples) I think what you want is ...(*list_of_tuples) similar to the syntax used when calling functions with position arguments from a list. Bill -- INTERNET: [EMAIL PROTECTED] 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 Few skills are so well rewarded as the ability to convince parasites that they are victims. -- Thomas Sowell ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionaries and memory handling
On Fri, Feb 23, 2007, =?ISO-8859-1?Q? Arild_B._N=E6ss ?= wrote: Hi, I'm working on a python script for a task in statistical language processing. Briefly put it all boils down to counting different things in very large text files, doing simple computations on these counts and storing the results. I have been using python's dictionary type as my basic data structure of storing the counts. This has been a nice and simple solution, but turns out to be a bad idea in the long run, since the dictionaries become _very_ large, and create MemoryErrors when I try to run my script on texts of a certain size. It seems that an SQL database would probably be the way to go, but I am a bit concerned about speed issues (even though running time is not all that crucial here). In any case it would probably take me a while to get a database up and running and I need to hand in some preliminary results pretty soon, so for now I think I'll postpone the SQL and try to tweak my current script to be able to run it on slightly longer texts than it can handle now. You would probably be better off using one of the hash databases, Berkeley, gdbm, etc. (see the anydbm documentation). These can be treated exactly like dictionaries in python, and are probably orders of magnitude faster than using an SQL database. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``Rightful liberty is unobstructed action according to our will within limits drawn around us by the equal rights of others. I do not add 'within the limits of the law' because law is often but the tyrant's will, and always so when it violates the rights of the individual.'' -Thomas Jefferson ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionaries and memory handling
On Fri, Feb 23, 2007, Alan Gauld wrote: Bill Campbell [EMAIL PROTECTED] wrote It seems that an SQL database would probably be the way to go, but I am a bit concerned about speed issues (even though running time is ... You would probably be better off using one of the hash databases, Berkeley, gdbm, etc. (see the anydbm documentation). These can be treated exactly like dictionaries in python, and are probably orders of magnitude faster than using an SQL database. I'm glad Bill suggested this because I'd forgotten about them entirely! But while they wont literally be orders of magnitude faster - the disk I/O subsystem is usually the main limiter here - they will be several factors faster, in fact many SQL databases use the dbm database under the hood. While the disk subsystem is going to be a factor, the overhead communicating with the SQL server, parsing the queries, etc. will be far greater than calculating location of the record using the hashed key. FWIW: I've found that the size of Berkeley DB btree files can be significantly less than the Berkeley hash files. I would really like to see somebody come up with a good alternative to the Berkeley DB stuff from sleepcat. The source code is the most godawfull mess if #ifn*defs I've ever seen, with frequent API even in minor release levels. Take a look at the bdb source in python or perl if you want to see what I'm talking about. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``the purpose of government is to reign in the rights of the people'' -Bill Clinton during an interview on MTV in 1993 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Replying to the tutor-list
The major reason for not setting Reply-To: thelist is that it makes it *SLIGHTLY* more difficult to post something to the list and replys should go to the sender. IHMO, one should have to go to a little bit of effort before posting a message that may go to thousands of recipients. Using the ``mutt'' mailer, this effort is simply pressing ``L'' instead of ``r'' when posting to the list and adding the listname to the subscribe section of ~/.muttrc, hardly a major inconvenience. http://www.unicom.com/pw/reply-to-harmful.html ... Bill -- INTERNET: [EMAIL PROTECTED] 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 ``We believe...that a mugger will kill you in the half-second it takes to draw from the holster, but won't harm you while you dial the police on your cell phone, talk to the dispatcher and wait half an hour for officers to arrive.'' -- Gun-Control Net-work Credo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Replying to the tutor-list
On Thu, Feb 15, 2007, Luke Paireepinart wrote: Bill Campbell wrote: The major reason for not setting Reply-To: thelist is that it makes it *SLIGHTLY* more difficult to post something to the list and replys should go to the sender. IHMO, one should have to go to a little bit of effort before posting a message that may go to thousands of recipients. Using the ``mutt'' mailer, this effort is simply pressing ``L'' instead of ``r'' when posting to the list and adding the listname to the subscribe section of ~/.muttrc, hardly a major inconvenience. It's not the inconvenience but the fact that it's nonstandard, as far as every mailing list i've been on except this. Hardly non-standrd. The option for this in the Mailman MLM is: Where are replies to list messages directed? Poster is strongly recommended for most mailing lists. I've been maintaining various technical mailing lists for over twenty years now, and see this same thread come up many times. Having the Reply-To: to the original poster minimizes the probability of somebody sending mail to a list that was intended for the original poster (which may be private). The only advantage of having it set to the list is it makes it easier for lazy people to send nonsense to hundreds of people. As I said in my original message, it should require a little bit of effort to send messages to hundreds or thousands of recipients. Bill -- INTERNET: [EMAIL PROTECTED] 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 It is necessary for the welfare of society that genius should be privileged to utter sedition, to blaspheme, to outrage good taste, to corrupt the youthful mind, and generally to scandalize one's uncles. -- George Bernard Shaw ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file open error
On Thu, Feb 08, 2007, Jalil wrote: Hey guys, I have this simple code and i cant seem to get it to run. here is the code. from os import * import re hostname =raw_input(Host name : ) or 'unknown' mac_addr =input(Mac address : ) filename='/etc/dhcpd.conf' fh=open(filename) m = re.match(hostname,fh.readlines()) if m!=None: m.group() Here is the error I get when i try to run the code monkeysee% python sys_wireless.py Host name : Mac address : 1234567 Traceback (most recent call last): File sys_wireless.py, line 8, in ? fh=open(/etc/dhcpd.conf,r) TypeError: an integer is required I dont know what the issue is? any hints ? It appears to me that your ``from os import *'' is biting you in the butt as the os.open command is being executed instead of the normal open. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``Liberty don't work as good in practice as it does in speeches.'' Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ***SPAM*** List to dictionary
On Wed, Dec 06, 2006, Morpheus wrote: I'm new to programming, and trying to learn the Python language. The following code does what I want it to do, but I have not idea how it works. def scanList(names,temp): for i in names: temp[i] = 0 print temp Names = [] temp = {} I have a list of names (Names[]) and want to remove duplicate names in the list. Here is what I think is happening (please correct me if I'm wrong, or using the wrong technical terminology): I'm passing the variables Names and temp as arguments to the scanList function. The statement (for i in names:) is an iteration going through each item in the list. The next statement (temp[i] = 0) is where I get confused. Can someone please explain what is happening here. The way I usually do this is something like: outDict = dict(map(lambda x: (x, 1), inList)) names = outDict.keys() names.sort() Bill -- INTERNET: [EMAIL PROTECTED] 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 ``Find out just what people will submit to, and you have found out the exact amount of injustice and wrong which will be imposed upon them; and these will continue until they are resisted with either words or blows, or both. The limits of tyrants are prescribed by the endurance of those whom they oppress.'' -- Frederick Douglass. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Has anyone tried matplotlib...??
On Sun, Oct 22, 2006, Matt Richardson wrote: I just used it a couple of weeks ago to produce a histogram of randomly generated numbers. Read the documentation, it's well written and has good examples. You might also want to look at gnuplot. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``If guns are outlawed, only the government will have guns. Only the police, the secret police, the military, the hired servants of our rulers. Only the government -- and a few outlaws. I intend to be among the outlaws.'' EDWARD ABBEY (1927-1989) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can i pass a list to a function and get one back ?
On Sat, Oct 21, 2006, shawn bright wrote: hey there, i was just wondering if i could get a list back from a function. something like def return_a_list(some_var): some_list = [] for i in range(5): var = some_var + i some_list.append(var) return some_list is this cool ? Ayup! The best way to find answers to questions like this is to just do it, and see what python does. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``It will be of little avail to the people that the laws are made by men of their own choice if the laws be so voluminous that they cannot be read, or so incoherent that they cannot be understood.'' -James Madison, Federalist Paper #62 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python equivalent of perl readlink()?
On Mon, Oct 16, 2006, Alan Gauld wrote: Bill Campbell [EMAIL PROTECTED] wrote in messageThe function is in the os module ([2] http://docs.python.org/lib/os-file-dir.html). Silly me. I was looking in the os.path module :-). Yes, its confusing/. One thing that should be rationalised IMHO is the various os modules.There are os, os.path, shutil, and now subprocess too. Alll doing things vaguely related to os type things. A re-org to make them more consistent would be good, but unfortunately would probably break lots of code! It would probably be possible to do much, if not all, to make these consistent by judicious programming for backwards compatibility (e.g. having the old call work while creating the new, rational call for use by newer programs). I certainly wouldn't like to see python breaking backwards compatibility, which is probably my primary gripe about open source software (although Bell Labs was equally guilty when they did things like change the ``grep -y'' option to ``grep -i''). Bill -- INTERNET: [EMAIL PROTECTED] 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 Instead of giving money to found colleges to promote learning, why don't they pass a constitutional amendment prohibiting anybody from learning anything? If it works as good as the Prohibition one did, why, in five years we would have the smartest race of people on earth. -- The Best of Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Capture telnet output to a file?
On Mon, Oct 16, 2006, [EMAIL PROTECTED] wrote: Hello, I am trying to capture telnet output to a file. For example I want to telnet into a router and run the command ?show arp? and be able to capture all the arp information that normally would show up on the screen to a file on my system.I am using python and pexpect to backup my router configurations on a daily basis, but for this the router has the option to send the configuration via tftp to a server, there is no option to send normal screen data to a file. Any ideas? One could use the ``script'' program in *NIX systems which captures your entire session. I haven't used pexpect with python yet, but the perl expect module can also be used to capture things like this, and I would expect that one could do this with pexpect as well. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``If the personal freedoms guaranteed by the Constitution inhibit the government's ability to govern the people, we should look to limit those guarantees.'' -President Bill Clinton, August 12, 1993 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Capture telnet output to a file?
On Mon, Oct 16, 2006, [EMAIL PROTECTED] wrote: I was not aware of script. Thanks! Don't feel bad. I've been using *NIX systems since 1982, and still find new commands from time to time (and we won't talk of the continual ``stupid vi tricks'' I find :-). Bill -- INTERNET: [EMAIL PROTECTED] 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 To say that UNIX is doomed is pretty rabid, OS/2 will certainly play a role, but you don't build a hundred million instructions per second multiprocessor micro and then try to run it on OS/2. I mean, get serious. -- William Zachmann, International Data Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] python equivalent of perl readlink()?
Is there a python equivalent of the perl readlink() function (e.g. one that returns the relative path in cases where a command such as ``ln -s ls /usr/local/bin/gls'' created the link? Reading the documentation on the various os.path functions, the only thing I see returns the fully resolved path rather than the relative one (/usr/local/bin/ls in the case above). Bill -- INTERNET: [EMAIL PROTECTED] 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 ``It's time to feed the hogs'' -- Unintended Consequences ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python equivalent of perl readlink()?
On Sun, Oct 15, 2006, Michael P. Reilly wrote: On 10/15/06, Bill Campbell [EMAIL PROTECTED] wrote: Is there a python equivalent of the perl readlink() function (e.g. one that returns the relative path in cases where a command such as ``ln -s ls /usr/local/bin/gls'' created the link? Reading the documentation on the various os.path functions, the only thing I see returns the fully resolved path rather than the relative one (/usr/local/bin/ls in the case above). Bill The function is in the os module ([2] http://docs.python.org/lib/os-file-dir.html). Silly me. I was looking in the os.path module :-). Thanks. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``Unix is simple. It just takes a genius to understand its simplicity'' -- Dennis Ritchie ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a tutorial on ez_install.py
On Fri, Sep 08, 2006, Kent Johnson wrote: johnf wrote: Hi, Is there a location (web link) that explains the inner workings of setuptools, etc http://peak.telecommunity.com/DevCenter/EasyInstall Is it possible to use EasyInstall to install relative to a directory other than the site-packages directory in the manner that the standard distutils does with the ``--root'' option? I build a lot of packages under the OpenPKG portable packaging system which is an RPM based system, and find EasyInstall fits Doug Gwynn's description of GUIs ``GUIs make simple things simple and complex things impossible''. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``People who relieve others of their money with guns are called robbers. It does not alter the immorality of the act when the income transfer is carried out by government.'' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a tutorial on ez_install.py
On Fri, Sep 08, 2006, Kent Johnson wrote: Bill Campbell wrote: On Fri, Sep 08, 2006, Kent Johnson wrote: http://peak.telecommunity.com/DevCenter/EasyInstall Is it possible to use EasyInstall to install relative to a directory other than the site-packages directory in the manner that the standard distutils does with the ``--root'' option? Did you see the section Custom Installation Locations in the above-referenced guide? Does that do what you want? http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations No. That would have the installation looking for it in some location like /opkg/RPM/TMP/package-name-root/lib/python... instead of the proper location under the site-packages on the installed system. It seems to me that EasyInstall is aimed at people installing on individual systems, not ones building packages that will be installed on multiple machines using a package manager. We build many packages under the OpenPKG.org portable package manager which allows us to use standard source packages on a wide variety of Linux and UNIX systems. The main package we build that uses EasyInstall is sqlobject, and I'm currently kludging this by doing the build under the control of EasyInstall (being careful that all the supporting packages are current so it doesn't go grabbing things across the network that aren't in the package). Once the build is done, my SPEC file then copies from the build directory to the temporary destination directory, skipping the EasyInstall install routine. Personally I haven't found any good reasons not to use the standard distutils, particularly since all the dependencies are handled already by the OpenPKG package manager. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``there is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things. Because the innovator has for enemies all those who have done well under the old conditions, and lukewarm defenders in those who may do well under the new.'' -- Machiavelli ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Library for rtf to text?
I'm looking for a python library to convert rtf to plain text (parsing Delicious Library XML files for other use), but haven't found anything python-specific in the python Library Reference or in a google search. I have found a C program that will convert rtf2html, and I could use that if necessary, but would prefer a pure python solution. Any hints on this? Bill -- INTERNET: [EMAIL PROTECTED] 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 ``I have no reason to suppose that he, who would take away my Liberty, would not when he had me in his Power, take away everything else.'' John Locke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python + PostGreSQL
On Fri, Mar 31, 2006, Srinivas Iyyer wrote: Dear group, I want to connect python to postgresql. My python dist. is 2.4.2 My postgres: 8.1.2 My system: Linux Enterprise Linux, Intel Xeon, 4GB RAM. I tried to install pygresql: version: 3.8, it failed throwing exception : Exception: pg_config tool is not available. I gave another try on google and Postgres site and found Pypgsql, PoPy and psycopg1. I think that psycopg is generally considered the preferred package. I have been using it with several systems including Zope, and sqlobject. So far I haven't tried psycopg2. Bill -- INTERNET: [EMAIL PROTECTED] 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 A child can go only so far in life without potty training. It is not mere coincidence that six of the last seven presidents were potty trained, not to mention nearly half of the nation's state legislators. -- Dave Barry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Test If File System is mounted in Linux
On Fri, Mar 17, 2006, Michael Lange wrote: On Fri, 17 Mar 2006 00:36:35 -0700 fortezza-pyt [EMAIL PROTECTED] wrote: If there a semi-standard way to test if a file system has been mounted or not using Python? In the Linux command line, I can type mount and see all mounted file system, and then see if the one I am looking for is in the list. While I could replicate this with Python, I am curious if there is an easier way. Hi Fortezza, try os.path.ismount() . That's fine if one knows what the mount points are. The more general problem is to get a list of mounted file systems. The most standard way I've found to get a list of mounted systems is to parse the output of the gdf program from the gnu fileutils compiled with the program prefix `g' so it's called gdf. The gdf program handles a lot of the dirty work, and its output is standard regardless of the underlying system, which you can't say about the system's mount or df commands. The routine below is one I've used for years (actually I used a perl version for a long time before switching primarily to python :-). # This aren't real file systems. pseudofilesys = \ dict(map((lambda x: (x, 1)), ('none', 'shmfs', 'procfs', 'tmpfs'))) gdf_cols = ('filesys', 'blocks', 'used', 'avail', 'use', 'dir') def mounted(): '''Get Mounted File Systems''' df = os.popen('gdf 2/dev/null', 'r') df.readline() # skip first line mounted = [] for line in df.readlines(): line = line.strip() rec = dict(zip(gdf_cols, line.split(None, 5))) filesys = rec['filesys'] dir = rec.get('dir') if ( dir and not (filesys.find(':') = 0 or pseudofilesys.get(filesys)) ): mounted.append(dir) df.close() return mounted Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Systems, Inc. URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``I presume you all know who I am. I am humble Abraham Lincoln. I have been solicited by many friends to become a candidate for the legistlature. My politics are short and sweet, like the old woman's dance. I am in favor of a national bank ... in favor of the internal improvements system, and a high protective tariff.'' -- Abraham Lincoln, 1832 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Test If File System is mounted in Linux
On Fri, Mar 17, 2006, Adam wrote: On 17/03/06, Bill Campbell [EMAIL PROTECTED] wrote: On Fri, Mar 17, 2006, Michael Lange wrote: On Fri, 17 Mar 2006 00:36:35 -0700 fortezza-pyt [EMAIL PROTECTED] wrote: If there a semi-standard way to test if a file system has been mounted or not using Python? In the Linux command line, I can type mount and see all mounted file system, and then see if the one I am looking for is in the list. While I could replicate this with Python, I am curious if there is an easier way. Hi Fortezza, try os.path.ismount() . That's fine if one knows what the mount points are. The more general problem is to get a list of mounted file systems. How about just reading the mtab? That's usually /etc/mtab it should be readable as a user and it means you don't have to rely on any other programs. The words usually, and should are the kickers. In the 24 years I've been making my living on various versions of Unix type systems, I've seen a lot of cases where this type of assumption either fails totally or gets me in trouble because the vendor didn't do it the way they should. This is the reason I started building standard open source tools for all the systems we support (Richard Stallman would probably have said I was creating GNU/Xenix and GNU/OpenServer systems back when we supported many SCO systems :-). My fingers automatically type gfind, gdu, etc., even on Linux systems where I make symbolic links as necessary so I don't have to remember what type of system I'm typing on. One of the basic tenets of the *nix philosophy is ``build on the work of others'', and it's a lot easier to leave figuring out the guts of various systems to the authors of the gnu fileutils than it is to reinvent their work every time I want to do something. Bill -- INTERNET: [EMAIL PROTECTED] 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 A fake fortuneteller can be tolerated. But an authentic soothsayer should be shot on sight. Cassandra did not get half the kicking around she deserved. -- R.A. Heinlein ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Test If File System is mounted in Linux
On Fri, Mar 17, 2006, Pawel Kraszewski wrote: Dnia piÄ tek, 17 marca 2006 18:41, Adam napisaÅ: The more general problem is to get a list of mounted file systems. How about just reading the mtab? That's usually /etc/mtab it should be readable as a user and it means you don't have to rely on any other programs. Or always-up-to-date user readable '/proc/mounts' ? If you're sure it's a Linux system, fine. Like /etc/mtab, this isn't portable. Looking at some of the systems we have here: Linux -- systems from Caldera OpenLinux 2.3 through SuSE 10.0, have /proc/mounts and /etc/mtab. FreeBSD 4.8 Stable -- has /proc file system, but no /proc/mounts, and no /etc/mtab (yeah 4.8 is out of date, but it's been up 632 days and I want to see how long it will stay up :-). OS X 10.4.5 (Tiger) -- no /proc/mounts or /etc/fstab SCO OpenServer 5.0.6a -- no /proc/mounts or /etc/fstab All of these systems have the gnu gdf which returns information in the same format. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Systems, Inc. URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``Fix reason firmly in her seat and call to her tribunal every fact, every opinion. Question with boldness even the existence of a God; because, if there is one, he must more approve of the homage of reason, than that of blindfolded fear.'' --Thomas Jefferson ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
On Sat, Feb 11, 2006, Joal Heagney wrote: Alan G wrote: I've been using MySQL up this day, but would like to convert my program to use Postgresql. I'm curious. Why? Is there some advantage to Postgres over MySql? Yes and no. Postgresql offers more features and is IMO more flexible than most SQL servers out there. ... However, MySQL is used a lot in web pages because it can return queries much faster than any other database - the catch is that it can only do this with transaction-less tables. ... (MySQL can use transactions, however, you immediately lose the speed advantage.) Postgresql is a far more mature product than mysql when it comes to the critical ACID features, transactions, stored procedures, and triggers. Postgresql is also far more compliant with SQL standards. As I understand it, mysql's transaction capabilities are only available when it's built with the innodb back end storage. Mysql and innodb licensing isn't GPL, and the company that provides innodb has recently been purchased by a commercial databae vendor (I don't remeber which one offhand). The licensing issues with mysql make me very leary of doing anything commercial with it. There is also the python sqlobject system which provides a very object oriented wrapper on top of relational databases. Using sqlobject can make many database functions very easy, and largely independent of the underlying database. Bill -- INTERNET: [EMAIL PROTECTED] 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 ``I don't make jokes, I just watch the Government and report the facts...'' Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Who called me?
On Tue, Nov 08, 2005, Kent Johnson wrote: Kent Johnson wrote: Bill Campbell wrote: Is there a way in python for a method to determine its parent? In particular, I'm working with SimpleXMLRPCServer, and would like to be able to find the client_address in the routine that has been dispatched. I know that client_address is an attribute of the handler class instance, but don't know how to get to that. ... good stuff deleted... HOWEVER, I don't think this is a good solution to your problem - it's quite a fragile hack. Better would be to find a way to pass the information you need to your function. For example, from a quick look at the code for SimpleXMLRPCServer, it looks like you could subclass SimpleXMLRPCServer and make your own _dispatch() method that adds client_address to the parameter list, then all your functions would be passed the client_address. Or even specialize it so that just one special function gets this treatment. That's one solution that I had considered, but in this particular case, I will probably use the CGI version of the XMLRPCServer since I can get the information from the REMOTE_ADDR environment variable that apache will set for me. The problem I'm working on now is to have our client's machines connect to our XML-RPC server in cron jobs which will do at least two things, check to see if their dynamic IP address has changed so we can update DNS for them, and/or let our system know they're still alive and functioning. This part of the job is probably best handled behind apache using the CGIXMLRPCRequestHandler as it makes some things simpler and can be done via https. Being fairly new to python, I wanted to know if there was a clean way to get parent information if the author of a package hadn't provided this. I generally have attributes in children that point back to the parent making it easy to get back to the parent from the child. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``The children who know how to think for themselves spoil the harmony of the collective society that is coming, where everyone would be interdependent.'' 1899 John Dewey, educational philosopher, proponent of modern public schools. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Who called me?
On Thu, Nov 10, 2005, Kent Johnson wrote: Bill Campbell wrote: The problem I'm working on now is to have our client's machines connect to our XML-RPC server in cron jobs which will do at least two things, check to see if their dynamic IP address has changed so we can update DNS for them, and/or let our system know they're still alive and functioning. If you have control of the code on the client machines you could just have them add their IP address to the parameters they send the server... The problem is that the clients are often on dynamic IP addresses behind a router/firewall that's doing NAT (Network Address Translation) so they don't know their IP address. One of the primary reasons for doing this is to be able to easily and automatically detect when a dynamic IP address has changed so we can update the DNS, postfix rules, etc. so we know where the client is. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ The Constitution is a written instrument. As such, its meaning does not alter. That which it meant when it was adopted, it means now. -- SOUTH CAROLINA v. US, 199 U.S. 437, 448 (1905) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Who called me?
Is there a way in python for a method to determine its parent? In particular, I'm working with SimpleXMLRPCServer, and would like to be able to find the client_address in the routine that has been dispatched. I know that client_address is an attribute of the handler class instance, but don't know how to get to that. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ My brother sent me a postcard the other day with this big satellite photo of the entire earth on it. On the back it said: ``Wish you were here''. -- Steven Wright ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python ncurses vs OS X Tiger's xterms.
On Fri, Oct 14, 2005, Alan Gauld wrote: Bill this is a guess but try setting the terminal type to vt220 or vt330 or similar rather than xterm. Does that make any difference? I haven't tried fiddling the terminal type, and would prefer not to unless it's the last resort. curses uses the termcap database to determine how int interacts with the keyboard so changing the terminal type to somethingwell defined might make a difference? The ncurses libraries support termcap, but I think that all current versions of curses use terminfo which has many more options under ncurses than the original ATT versions had. I suspect that the problem is more related to keyboard mappings in the Apple X11 implementation than it does with the terminfo and terminal type settings as the same applications work fine from Linux desktops. I've looked into xmodmap, and the X Resources that xterms support, but it would be much nicer if there is something I can handle in my python ncurses routines than if I have to dig into the keyboard mapping stuff. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``It's not what you pay a man but what he costs you that counts.'' Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Importing Modules Within Classes
On Fri, Oct 07, 2005, Kent Johnson wrote: Pierre Barbier de Reuille wrote: (never import a module in a small function likely to be called in an inner-loop !) That's good advice, but I would say in a *time-critical* inner-loop. After the first import, importing a module is fast, it is just a few dictionary lookups (looking up the module in sys.modules) and a dictionary write (to the local namespace). It's only the first import that is potentially expensive. Another way that I use this is to handle parts of a module that may not always be used (e.g. curses routines for interactive use). In this case we have a module that provides our curses interactive screen routines, and it has something like this: import os os.environ['cursesstuff'] = True Then in the more general purpose routines: # stuff goes here that's not interactive if os.environ.get('cursestuff']: import ... class ... # other things that don't need the extra functions. All that's necessary to activate the interactive classes and other related stuff is to include the curses routines before importing the modules that may or may not use them. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``It wasn't raining when Noah built the ark.'' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Stupid newbie question
On Fri, Sep 23, 2005, Valone, Toren W. wrote: I am trying to noodle thru classes with python and I built the following class import time class startremail: def __init__(self): remailfile = open('U:\Bounce20.txt', 'r') #future address/file from outlook resendfile = open('resend.txt', 'w') #currently these files are in Python24 EmailReport = open('erprt.txt', 'w') #Report of bad emails etc fromaddr='[EMAIL PROTECTED]' #set fromadd to a constant null_recepient_count = 0 date_received = date_email_generated = Error_050 = Error_501 = Current_Date = time.ctime(time.time()) month = Current_Date[4:8] day = Current_Date[8:10] print month def getday(self): return self.day def Read(self,line): line = remailfile.readline() #primer read return line I fire up IDLE and then do this from startremail import * x = startremail() print x.getday() I get the following return NameError: name 'getday' is not defined It appears that you're being bitten by my least-favorite ``feature'' of python, indentation errors. The getday routine appears to be a subroutine of __init__, not a method of the class. BTW: Not to start a religious war, I hated BEGIN/END blocks on ALGOL too, but in those days my editor was an 026 keypunch or worse, making paper tapes on a teletype for time sharing services. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``You know the one thing that's wrong with this country? Everyone gets a chance to have their fair say.'' -Bill Clinton, May 29, 1993, The White House ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Performance difference, ``in'' vs ``has_key()''
On Sun, Jul 17, 2005, Danny Yoo wrote: A related question is where's the trade-off between using ``in'' with a list, and a dictionary? I presume that using it with small hashes will be faster than dictionries since it doesn't have to calculate the hashes. Hi Bill, Scanning for an elements in a list is a linear operation, in the sense that the time it takes to search is proportional to the size of the list. (Big list == big search time.) I just noticed that I said it backwards in my first post, ``using it with small hashes'' should have been ``using it with small lists'' (and my perl background leaks out referring to dictionaries as hashes :-). ... This doesn't mean that dictionaries are always faster than lists: as you know, calculating hash values can take time. But the cost of hashing is usually negligible, since many of Python primitive data types (like strings) automatically cache their hash values too! This would say that it's better to create the dictionary with string keys rather than tuples, but that seems pretty obvious in any case. The problem I'm working on involves going through a large list of invoices that are now zero balance, to purge those before a certain date that have no payment applications after that date. I have a dictionary of zero- balance invoices containing invoice objects, and each invoice object contains a list of invoice keys applied to it. This internal list may well contain keys that refer to invoices that are either non-zero or have a date after the cutoff date. # begin code snippet global invoices # dictionary of all zero balance invoices with date = cutoff deleted = True while deleted: deleted = False keys = invoices.keys() for key in keys: # use try/except since the instance may be deleted try: invoice = invoices[keys] except KeyError: continue for appKey in invoice.appKeys: if not appKey in invoices: deleted = True del invoices[key] # this invoice can't be purged for appKey in invice.appKeys: try: del invoices[appKey] except KeyError: pass # finish processing invoices ... A good book in algorithms will almost always cover the performance characteristics of those two strategies; there are also a lot of good resources on the web about them. NIST has two articles on those two: http://www.nist.gov/dads/HTML/linearSearch.html http://www.nist.gov/dads/HTML/hashtab.html Thanks for the references (occassionaly there's something that government does that's actually useful :-). Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ When the customer has beaten upon you long enough, give him what he asks for, instead of what he needs. This is very strong medicine, and is normally only required once. -- The Consultant's Curse: ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Performance difference, ``in'' vs ``has_key()''
I'm going to be doing some work where I'll be doing existence testings on keys on about a million records where it may require multiple passes so I'm a bit concerned about the timing of these tests. Is there any significant performance difference between the tests, ``key in dictionary'' and ``dictionary.has_key(key)''? I would prefer using the ``key in'' because it's a bit easier to type, and can also be used with lists in addition to dictionaries. A related question is where's the trade-off between using ``in'' with a list, and a dictionary? I presume that using it with small hashes will be faster than dictionries since it doesn't have to calculate the hashes. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ Government is the great fiction, through which everbody endeavors to live at the expense of everybody else. -- Frederic Bastiat ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] strip an email
On Fri, Jun 24, 2005, Hugo González Monteverde wrote: Hi nephish, I clearly remember it is very very simple and it is defined in the RFC. As far as I remember, the end of the headers are signalled by an empty line. Try looking for '\n\n', this should do the trick. I've saved a couple of emails and it looks like this should work. See http://docs.python.org/lib/module-email.html for easy ways to handle e-mail. The email module has utilities that make it easy to handle headers and body. something like: #full_text holds the full text of the message bodypos = full_text.find('\n\n') + 2 body = full_text[bodypos:] #body now holds the message body Please let us know if this works, hope it helps. Hugo nephish wrote: Does anyone know how to strip everything off of an email? i have a little app that i am working on to read an email message and write the body of a message to a log file. each email this address gets is only about three to five lines long. but i cannot seem to get just the body filtered through. i get all the headers, the path, what spam-wall it went through, etc... any suggestions would be greatly appreciated . thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``Good luck to all you optimists out there who think Microsoft can deliver 35 million lines of quality code on which you can operate your business.'' -- John C. Dvorak ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] CPAN for python
On Mon, Jun 06, 2005, Danny Yoo wrote: On Mon, 6 Jun 2005, Ron Nixon wrote: Is there a site like Perl's CPAN for Python? I've seen the stuff at ActiveState. Anything else? Hi Ron, Yes, there is a system called 'PyPI': http://www.python.org/pypi There's also the vaults of parnassus http://www.vex.net/parnassus/ Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ There are three kinds of men. The ones that learn by reading. The few who learn by observation. The rest of them have to pee on the electric fence for themselves. -- Will Rogers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Detecting my own IP address?
On Sun, Jun 05, 2005, Lee Harr wrote: At present, the only thing I can think of is to redirect the output of 'ifconfig' into a temporary file, then read it back in and use Python and regular expressions to try and extract the IP info from that. Why go to a temporary file when you can open a pipe? import os fh = os.popen('ifconfig') #... The advantage of parsing ifconfig output instead of using socket calls is that it allows you to discriminate between multiple interfaces (e.g. most of our dual hosted machines have the primary interface on the private address which probably isn't what is required). One disadvantage of parsing ifconfig is that output varies depending on the operating system. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Systems, Inc. UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``The fact is that the Constitution was intended to protect us from the government, and we cannot expect the government to enforce it willingly'' -- Dave E. Hoffmann, Reason Magazine March 2002 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Detecting my own IP address?
On Mon, Jun 06, 2005, Simon Gerber wrote: Thank you for your suggestions everyone. I do wish to parse ifconfig, as I'm specifically after the address of ppp0. At this stage, I'm only writing the script for my own machine, so the downside to parsing ifconfig does not yet apply. I'm a little curious, however. When you say 'varies depending on the operarating system', are you talking about Windows vs. Linux, or, say, Debian vs. Gentoo? The output format of ifconfig varies slightly on several Linux machines we have running here ranging from SuSE 9.3 Professional as far back as Caldera OpenLinux 1.2 or so. It's different on the FreeBSD box I'm using for e- mail now, and on an OS X box. SCO OpenServer doesn't return anything useful from ifconfig with now arguments, and one has to parse the output of ``netstat -in'' to get the interface names, then run ifconfig on each name to get full info. The differences aren't great, and it's easy to write regular expressions to extract things like IP address (ipv4 and ipv6), netmask, MAC address, etc. One could probably build a dictionary of regular expressions, keyed on the first and third entries in os.uname() output. I don't do Windows so can't say what it does (knowing Microsoft, it may vary between Windows versions, patch levels, and the phase of the moon :-). Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``... because most politicians and bureaucrats are technological idiots, it's going to be crucial for the rank and file members of the IT community to find its collective voice soon.'' --Michael Vizard, InfoWorld Editor in Chief. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TKinter and things over Linux
On Wed, Apr 20, 2005, Alberto Troiano wrote: You're so right and I apologize for my mistake Do you or anybody knows where the error.log for this kind o things is? or how can I capture the output in a file???Cause is so damn long that I barely see the 10% of all the things its print out The following command will keep a copy of the output in the file make.output (this doesn't work with csh). The ``21'' modem noise joins standard error and standard output, and the ``tee'' program is a pipe fitting that puts its standard input into a file, and to its own standard output. make 21 | tee make.output Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``If the personal freedoms guaranteed by the Constitution inhibit the government's ability to govern the people, we should look to limit those guarantees.'' -President Bill Clinton, August 12, 1993 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Of fish and foul...(aka the Perl require command)
On Mon, Apr 18, 2005, Smith, Jeff wrote: Is there a Python equivalent to the Perl require 5.6.0 Which enforces a minimum interpreter version? Is there a good Python for Perl Programmers book? It thought O'Reilly had one but I couldn't find it. Was this particular question in the book you recommend? Good? That depends on what your standards are. I found ``Perl to Python Migration'' by Martin C. Brown useful. I think I found this on bookpool.com, but you can always try bookfinder.com which can find pretty much anything. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``Are we at last brought to such a humiliating and debasing degradation, that we cannot be trusted with arms for our own defense? Where is the difference between having our arms in our own possession and under our own direction, and having them under the management of Congress? If our defense be the real object of having those arms, in whose hands can they be trusted with more propriety, or equal safety to us, as in our own hands?'' -- Patrick Henry June 9, 1788, in the Virginia Convention on the ratification of the Constitution. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TKinter and things over Linux
On Sat, Apr 16, 2005, joe_schmoe wrote: Alberto Troiano wrote: Hi everyone Sorry to bother you again but I don't know where else to go I recently switch to Linux Red Hat AS 3.0 because I have to make a daemon to run in this OS and I'm having a few problems I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but could) Now I want to program a GUI with Tkinter but when I put the sentence from TKinter import *, it tells me that it doesn't find the module Tkinter. I have downloaded Python 2.3.4 from python.org and follow the steps. The build process for python will pick up installed libraries for various components (e.g. Berkeley database, Tk, etc.), so if you don't have Tkinter on your system, and you built python yourself, it probably means that you don't have the necessary Tk/TCL development libraries installed on the system. Careful perusal of the output of the build is necessary to see what libraries have been built, and which were skipped. I normally build using ``make 21 | tee makelist'' which puts all the output in the file makelist which I can then examine when the make is complete. Secondly I want to know how to run the .py programs and which is the extension of a GUI in Linux (I know that for Windows is .pyw but it doesn't know what are these in Linux) Python scripts should Just Run(tm) whether they have a .py extension or not on a Linux box. Linux, and most *nix flavours don't depend on the file suffix to determine what type of file it is, but generally look at the first few bytes of the file (if a text file starts with ``#!'' the rest of the line is taken to be the command to run the script. ... Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ When you have an efficient government, you have a dictatorship. -- Harry Truman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) How to run a script file
On Wed, Jan 05, 2005, Alan Gauld wrote: Sorry if I missed something obvious, but how do I execute a python script file in the interpreter? I have Using the Python Interpreter in the Python tutorial but not much is said... You can import a script at the prompt as you would under Pythonwin. Or you can run IDLE much as you did Pythonwin. Or you can learn emacs and run python mode in that. Personally I just open a gvim window and a terminal and edit the code in gvim and run the program in the terminal... If I need to experiment I open a third window and run the prompt there. Linux is the IDE... Alan G. PS I just got my own Linux box running again 4 months after moving house! I thought I'd try a Suse distro I got with Borlands Kylix and calamity - no python! Back to Mandrake I think. I have yet to see a SuSE distribution without python although you may have to install it from using yast2. FWIW, I would strongly recommend the SuSE Professional rather than the Personal if you're going to be doing any serious development work. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ Manual, n.: A unit of documentation. There are always three or more on a given item. One is on the shelf; someone has the others. The information you need is in the others. -- Ray Simard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] eval and exec
On Sat, Dec 04, 2004, Alan Gauld wrote: I'm having trouble understanding the difference between eval and exec. eval evaluates an *expression* - that is something that returns a value. ... Both are extremely dangerous functions from a security and maintenance/reliability pouint of view and should be used very rarely. True enough, but useful upon occassion. In particular I've had a question on the back burner for a while. Suppose I have a dictionary of database instances, dbtables, keyed on table name, and I want a general way of creating variables with the name of the table so I'm not accessing the dictionary. Would something like this work: # dbtables is already built for table in dbtables.keys(): exec(%s = dbtables['%s'] % (table, table)) Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ My brother sent me a postcard the other day with this big satellite photo of the entire earth on it. On the back it said: ``Wish you were here''. -- Steven Wright ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor