Re: [Tutor] Encoding
Denis, That was a great explanation!! I'm not the OP, but your explanation really clicked with me. Regards, Malcolm For sure, but it's true for any kind of data, not only text :-) Think at music or images *formats*. The issue is a bit obscured for text but the use of the mysterious, _cryptic_ (!), word "encoding". When editing an image using a software tool, there is a live representation of the image in memory (say, a plain pixel 2D array), which is probably what the developper found most practicle for image processing. [text processing in python: unicode string type] When the job is finished, you can choose between various formats (png, gif, jpeg..) to save and or transfer it. [text: utf-8/16/32, iso-8859-*, ascii...]. Conversely, if you to edit an existing image, the software needs to convert back from the file format into its internal representation; the format need to be indicated in file, or by the user, or guessed. The only difference with text is that there is no builtin image or sound representation _type_ in python -- only because text and sound are domain specific data while text is needed everywhere. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bowing out
Hi Kent, Your posts and web pages really helped me during my early days with python. Wishing you great success in your new endeavors!!! Cheers, Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Encoding
> Or, maybe even better, the format could be given as third parameter of file > open(); then any read or write operation would directly convert from/to the > said format. What do you all think? See the codecs.open() command as an alternative to open(). With all the hassles of encoding, I'm puzzled why anyone would use the regular open() for anything but binary operations. Malcolm - Original message - From: "spir" To: "Python tutor" Date: Sun, 7 Mar 2010 14:29:11 +0100 Subject: Re: [Tutor] Encoding On Sun, 7 Mar 2010 13:23:12 +0100 Giorgio wrote: > One more question: Amazon SimpleDB only accepts UTF8. [...] > filestream = file.read() > filetoput = filestream.encode('utf-8') No! What is the content of the file? Do you think it can be a pure python representation of a unicode text? uContent = inFile.read().decode(***format***) outFile.write(uContent.encode('utf-8')) input -->decode--> process -->encode--> output This gives me an idea: when working with unicode, it would be cool to have an optional format parameter for file.read() and write. So, the above would be: uContent = inFile.read(***format***) outFile.write(uContent, 'utf-8') Or, maybe even better, the format could be given as third parameter of file open(); then any read or write operation would directly convert from/to the said format. What do you all think? denis -- la vita e estrany spir.wikidot.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating through a list of strings
> Agreed that > > line = line[:line.index('%')] > > is slightly more readable than > >line = line.split('%', 1)[0] How about: line = line.partition('%')[0] partition() works even if '%' isn't present. The index() and split() techniques raise exceptions if '%' isn't present. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] portability of pickle and shelve across platforms and different python versions?
Garry, I asked a similar question on Stackoverflow.com and got some great responses including at least one from a member of the Python development team. Best way to save complex Python data structures across program sessions (pickle, json, xml, database, other) http://stackoverflow.com/questions/2003693/best-way-to-save-compl ex-python-data-structures-across-program-sessions-pickle To cut-to-the-chase: I believe pickle files are portable across platforms and versions. I do not know how portable shelve files are. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
Not the OP, but I was surprised to see class Name() work (in Python 2.6.5 at least). Is this equivalent to class Name( object ) or does this create an old style class? Going forward into the 2.7/3.x world, is there a preferred style? Thanks, Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
Hi Mark, >> I was surprised to see class Name() work (in Python 2.6.5 at least). Is this >> equivalent to class Name( object ) or does this create an old style class? >> Going forward into the 2.7/3.x world, is there a preferred style? > RTFM? :) I am reading TFM :) Here's why I'm confused. The following paragraph from TFM seems to indicate that old style classes are the default: Quote: For compatibility reasons, classes are still old-style by default. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the “top-level type” object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type() returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are “fixes” that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance. http://docs.python.org/reference/datamodel.html#newstyle Yet TFM for 2.6.5 shows all class examples without specifying a parent class. http://docs.python.org/tutorial/classes.html I've been taught that the proper way to create new style classes has been to always specify an explicit "object" parent class when creating a new class not based on other classes. Somewhere along the line I seemed to have missed the fact that it is no longer necessary to define classes with 'object' as a parent in order to get a new style class. In other words, it seems that the following are now equivalent: class Name: -AND- class Name( object ): My impression was the "class Name:" style created an old style class. Thanks for your help! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
> In Python 2.x, all classes are old-style unless you directly or indirectly > inherit from object. If you inherit from nothing, it is an old-style class > regardless of whether you say class Name: pass or class Name(): pass. In > Python 3.x, there are no old-style classes. Thanks Steven! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
Steven, Thanks again for your explanations. I thought I had missed a major change in Python class behavior - relieved to find that I'm up-to-date. Cheers, Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
Hi Mark, > I see that Stephen D'Aprano has already replied twice so I won't bother. > Apart from that no offence meant, I hope none taken. Your RTFM reply actually gave me a good laugh. No (zero) offence taken. And I appreciate your many helpful posts in these forums. Cheers, Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives?
Can someone confirm that Python 2.6 ftplib does *NOT* support Unicode file names? Or must Unicode file names be specially encoded in order to be used with the ftplib module? The following email exchange seems to support my conclusion that the ftplib module only supports ASCII file names. Should ftplib use UTF-8 instead of latin-1 encoding? http://mail.python.org/pipermail/python-dev/2009-January/085408.html Any recommendations on a 3rd party Python module that supports Unicode file names? I've googled this question without success[1], [2]. The official Python documentation does not mention Unicode file names[3]. Thank you, Malcolm [1] ftputil wraps ftplib and inherits ftplib's apparent ASCII only support. [2] Paramiko's SFTP library does support Unicode file names, however I'm looking specifically for ftp (vs. sftp) support relative to our current project. [3] http://docs.python.org/library/ftplib.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives?
Updating this thread for users searching the archives. Additional commentary can be found in this thread I started on Stackoverflow.com. http://stackoverflow.com/questions/3120295/confirm-that-python-2-6-ftplib-does-not-support-unicode-file-names-alternatives Gabriel Genellina added the following comment on Python-list: According to RFC 2640, you should use UTF-8 instead. http://www.faqs.org/rfcs/rfc2640.html The server software must be able to convert from file system encoding to utf-8 and viceversa; check its configuration. The stackoverflow thread mentioned above also contains a workaround/ugly-hack if you need to use Unicode path/file names with ftplib and/or a file server that does not support Unicode path/file names. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where to start with Unit Testing
Mac, > My answer falls in the category "feedback" ... I'm not the OP, but I wanted to let you know that I really enjoyed your feedback - excellent writeup! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] web-based python?
Alex, > I have an IPowerWeb.com server, which claims to support Python Many hosting providers claim to support Python. The best hosting service I've found for Python is webfaction.com. Originally this hosting provider specialized in just Python hosting and this enthusiasm for Python and hands-on Python skills are still part of their culture. Highly recommended. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to get script to detect whether a file exists?
Richard, Look at the os.path.isfile function. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem with python
> I just wanted to note that Steven is a great teacher! +1 Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Too different 2.6 vs 2.7?
Jorge, Python 2.7 supports an updated version of the Tkinter GUI framework with support for native themes (ttk). This makes it possible to create professional looking user interfaces without having to install a separate GUI framework like wxPython or pyQt. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple counter to determine frequencies of words in a document
> it is difficult for me not to be profuse in my thanks because you guys really > go beyond the call of duty. I love this list. The responses in this list most > of the times don't just address the problem at hand but are also useful in a > more general sense and help people become better programmers. So, thanks for all the good advice as well as helping me solve the particular problem I had. Not the OP, but a big +1 from me! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
Kent, > Except they are not equivalent when you want to print more than one thing. > ... > Python 2.6: > In [1]: print(3, 4) > (3, 4) I'm running Python 2.6.1 (32-bit) on Windows XP. I don't get the tuple-like output that you get. Here's what I get: >>> print( 3, 4 ) 3 4 Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
Lie, >> Here's what I get: >> >> >>> print( 3, 4 ) >> 3 4 > Are you sure it isn't python 3.x you're playing with? The reason why simple > print function "works" in python 2.x is because of a syntactical coincidence, it is still a 100% statement. Yes, I'm sure :) I restarted IDLE and pasted my session output below: Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. IDLE 2.6.1 >>> from __future__ import print_function >>> print( 3, 4 ) 3 4 >>> Malcolm - Original message - From: "Lie Ryan" To: tutor@python.org Date: Tue, 10 Feb 2009 15:15:01 + (UTC) Subject: Re: [Tutor] Simple PassGen On Tue, 10 Feb 2009 09:43:18 -0500, python wrote: > Kent, > >> Except they are not equivalent when you want to print more than one >> thing. ... >> Python 2.6: >> In [1]: print(3, 4) >> (3, 4) > > I'm running Python 2.6.1 (32-bit) on Windows XP. > > I don't get the tuple-like output that you get. > > Here's what I get: > >>>> print( 3, 4 ) > 3 4 Are you sure it isn't python 3.x you're playing with? The reason why simple print function "works" in python 2.x is because of a syntactical coincidence, it is still a 100% statement. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
DOH! I just realized why we're getting different results. Sorry for the confusion - I wasn't trying to be a smart-ass! We've been trying to future proof our new code for Python 3.x so we automatically have 3.0 print() functionality enabled in our Python 2.6 dev environments. Malcolm - Original message - From: "spir" To: tutor@python.org Date: Tue, 10 Feb 2009 16:35:26 +0100 Subject: Re: [Tutor] Simple PassGen Le Tue, 10 Feb 2009 10:26:54 -0500, pyt...@bdurham.com a écrit : > IDLE 2.6.1 > >>> from __future__ import print_function > >>> print( 3, 4 ) > 3 4 lol! -- la vida e estranya ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
Lie, The import from __future__ print_function happens automatically in our environment and I took this for granted. Sorry about the confusion :) Regards, Malcolm - Original message - From: "Lie Ryan" To: pyt...@bdurham.com Cc: tutor@python.org Date: Wed, 11 Feb 2009 23:16:11 +1100 Subject: Re: [Tutor] Simple PassGen On Wed, Feb 11, 2009 at 2:26 AM, <[1]pyt...@bdurham.com> wrote: > Are you sure it isn't python 3.x you're playing with? The reason why simple print function "works" in python 2.x is because of a syntactical coincidence, it is still a 100% statement. Yes, I'm sure :) I restarted IDLE and pasted my session output below: You didn't tell that you imported __future__'s print_function! I thought I was having a hallucination or something... seeing that behavior in python2.6 References 1. mailto:pyt...@bdurham.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Possible to change values of scalar function parameters?
Is there a way to change values of scalar function parameters? I know you can change the values of parameters if the parameter is a mutable type like a list, but is there a way to update the value of scalar parameters of type integer or string? Simple example: Is there a way to have the following function update its changeme parameter in a 'call by reference' manner? >>> def test1( changeme ): changeme = 'Changed!' >>> ref_value = 'blah' >>> test1( ref_value ) >>> ref_value 'blah' Thanks! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Possible to change values of scalar function parameters?
Kent, > No, not a simple way at least. Possibly you can do it with hackery involving stack frames but I wouldn't recommend that. Either pass the values in some kind of container (list, dict, class instance) or return the new value and assign it in the caller. That's what I thought. Thank you! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Possible to change values of scalar function parameters?
Alan, > But don't forget that in python you can return multiple values from a > function. Yes. Thank you! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Yet another Python book
Dave, Great stuff!!! Thanks for sharing your hard work with the community! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] importance of Docstring
Albert, That was a great writeup on docstrings. I'm going to share that with my dev team. Thank you! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Pythonic way to normalize vertical whitespace
Note: Following cross-posted to python-list where it got queued due to suspicious subject line. I'm looking for suggestions on technique (not necessarily code) about the most pythonic way to normalize vertical whitespace in blocks of text so that there is never more than 1 blank line between paragraphs. Our source text has newlines normalized to single newlines (\n vs. combinations of \r and \n), but there may be leading and trailing whitespace around each newline. Approaches: 1. split text to list of lines that get stripped then: a. walk this list building a new list of lines that track and ignore extra blank lines -OR- b. re-join lines and replace '\n\n\n' wth' \n\n' until no more '\n\n\n' matches exist 2. use regular expressions to match and replace whitespace pattern of 3 or more adjacent \n's with surrounding whitespace 3. a 3rd party text processing library designed for efficiently cleaning up text Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] clean text
Denis, Untested idea: 1. Fill a dict with pre-calculated repr() values for chars you want to replace (replaceDict) 2. Create a set() of chars that you want to replace (replaceSet). 3. Replace if (n < 32) ... test with if char in replaceSet 4. Lookup the replacement via replaceDict[ char ] vs. calculating via repr() 5. Have result = list(), then replace result += char with result.append( char ) 6. Return ''.join( result ) Does this help? Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] clean text
Denis, Thank you for sharing your detailed analysis with the list. I'm glad on didn't bet money on the winner :) ... I'm just as surprised as you that the regex solution was the fastest. Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best Python Editor
Alan, > I spoke a wee bit too soon. The editor is nice but the debugger and some of > the other tools windows (eg variables) are broken. Pity, lots of potential > here. The current release of Pyscripter is not stable. Drop back one release and you'll find a very solid product. Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best Python Editor
>> The current release of Pyscripter is not stable. Drop back one release and >> you'll find a very solid product. > Sounds interesting. What is the stable version and where can it be found? Ken, Here's the version we use: Version 1.7.2, Oct 2006 http://mmm-experts.com/Downloads.aspx?ProductId=4 The most current release (w/2.6.x and 3.x support) can be found here: http://code.google.com/p/pyscripter/ We tried running newer releases earlier this year and had lots of problems. The very latest versions on code.google may be better, but we haven't looked at them. I am interested in hearing feedback on anyone running the most recent release of Pyscripter. Malcolm . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mac os x executable
Alan, > After all with Python 2.3 pre installed on MacOS X Is Python 2.3 really the most recent version of Python distributed with new Macs? So if I wanted to distribute a Python 2.6 script to a Mac user, I would need to instruct the Mac user how to download and install a separate version of Python (2.6), being careful not to overwrite the system default version of Python (2.3). Or I could use py2app to build in single standalone distributable (with an embedded Python 2.6 interpreter and library files) and distribute that. Does that sound right? Thank you, Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Tutorials: How to create useful programs after learning the syntax?
> but if you ever come across a copy of "Core Python Programming," i've put > lots of exercises at the end of every chapter. +1 from a reader/customer (vs. the author) "Core Python Programming" is an excellent resource for learning Python. I enjoyed the exercises - they force you to master the content vs. thinking you know what's going on via a fast skim of the content. Highly recommended! Regards, Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Tutorials: How to create useful programs after learning the syntax?
Wesley, You mean my check is not in the mail? Damn! Well, no more positive reviews for you :) Since you've stepped off your soapbox, I'll also mention your free hour long video hosted by Safari Books (you may have to signup for a free account to see the video). What is Python by CPP (Core Python Programming) by author Wesley Chun http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcasts.php QUOTE: This one-hour webcast is ideal for technical professionals, programmers, engineers or students already literate in another high-level language that want to pick up Python as quickly as possible. No computer science background is necessary. In this webcast, leading Python developer and trainer, Wesley Chun, will help you learn Python quickly and comprehensively so you can immediately succeed with any Python project. Instead of focusing on creating applications, he will address the fundamentals of the language itself. I'm happy to hear about the errata - do you have a link? Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Basic terminology
Hi, I'm reading a Python book right now (Learning Python, a great book!), and there are few terms that come are brought up a few times but without any explanation. So what are: - "remainders" (in the context of remainders-of-division modulus for numbers) - "modulus" (in the same context; I have also seen it in different context, like 3D graphics programs to perform certain types of calculations). Thanks Bernard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] MySQL Connection Function
As a newbie developer, the easiest way for me to connect to MySQL is to > just copy & paste the connection commands into each funtion I write. > However, I know that's far from ideal, and consumes more time than its > worth. I would like to create a MySQL connection function that I can just > call up whenever I need it from within an other function. I like to use the following style of code. Since there will be passwords, the connection strings should be somewhat protected. Put them in a separate file that can be controlled. Here's my sample code. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #! /usr/bin/python # sqlconnect.py import MySQLdb as SQLdb db_parms = { 'regular': { 'host': 'localhost', 'user':'regular_user', 'passwd':'password', 'db':'some_database', }, 'premium': { 'host':'localhost', 'user':'premium_user', 'passwd':'password', 'db': 'SGSG02', }, "super": { 'host': 'localhost', 'unix_socket': '/var/lib/superdb/mysql.sock', 'user':'super_user', 'passwd':'password', 'db':'some_database', }, } def connect( parm_name): parms = db_parms[parm_name] return SQLdb.connect( **parms) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Use a dictionary to save the connect parameters. Different users and circumstances can require different parameters. To use this code import sqlconnect as sql conn = sql.connect('regular') # then get a cursor so that you can do something to the database curs = conn.Cursor() curs.execute(Some_SQL_Command) results = curs.fetchall() curs.close() Your example code seems to view getting a connection and a cursor as closely related. Typically, a connection is kept for the life of the application process and cursors are created, used, and closed as needed. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] First Project - Ping Sweeper!
ping uses icmp. icmp does not have port numbers. icmp is a host-to- host protocol for managing the flow of packets and reporting errors. http://en.wikipedia.org/wiki/ICMP_Echo_Request describes the outgoing "ping packet", but is probably too low-level to be useful. Port numbers are used in UDP and TCP. The port scanning program will not help you with ping. UDP and TCP have port numbers because they are application-to-application protocols and use the port number to identify the target application. I checked the index of "Foundations of Python Network Programming" and did not see entries for icmp or ping. I have not noticed icmp support in the Python libraries. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Closing BaseHTTPServer...
This sidesteps the issue of how to fix your threading code. SocketServer has a ThreadingMixIn class. You can create a threading HTTPServer without coding the threading yourself. (watch for typos - this is NOT from working code) class ThreadingHTTPD(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass srvr = ThreadingHTTPD( , ) srvr.serve_forever() Credit for this goes to John Goerzen and his fine book "Foundations of Python Network Programming" -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sys.argv?
I've been reading the python tutorial trying to get used to the style tryna understand it. So I come across this: "sys.argv[0]" in the tutorial on python.org. What is "sys.argv"? How does it work? Can someone give me a simple example on how to use it? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] range() help
Alright I'm a bit confused when looking at how range works. I'm reading lesson 4.3 in the python tutorial. http://docs.python.org/tut/node6.html I came across this: >>> range(-10, -100, -30) [-10, -40, -70] How come it prints on -40 or -70. Does -70 come from -70 -> -100? This is really confusing me. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Browser based?
How can I used python online. I'm getting my hoster to install python and I'm wondering how Do I use python online? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] celcius to farenheit converter.
I found this site and I'm practicing coding and I write this script, but I'm unsure why its not working. Everything goes well until it gets to the part where it tries to calculate the formula. Inputs work fine anyone know what I did wrong? ### #Temperature Converter #Coding Practice for lamonte(uni-code.com) ### temp = raw_input("Insert a temperature to convert.\n") type = raw_input("Now choose a convertion: Celcius(c) or Farenheit(f)") if type == "c": cel = (5/9)*(temp-32) print "Farhrenheit" +temp+" is equal to "+cel+" celcius.\n" elif type == "f": far = (9/5)*(temp+32) print "Farhrenheit" +far+" is equal to "+temp+" celcius.\n" else: print "Unknown Syntax!\n"; raw_input("\nPress enter to close program") ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python 2.4 or Python 2.5?
Im confused When i had python 2.4 all my scripts work correctly should i reinstall python 2.4? Or should I keep 2.5? Where can I find information on coding for python 2.5? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Counting help
listofnames = nameofsender[0], listofnames does not add a name to a list. Rather it creates a tuple of the new name and the list and then binds the tuple to the list name. That's why you wind up with the lisp style list. To add a name to the head of the list use listofnames.insert(0, nameofsender[0]) If you are using a version of Python that supports sets, using sets would be much simpler since the duplicates get discarded automatically. import sets # python2.3 setofnames = sets.Set() while. setofnames.add(nameofsender[0]) len(setofnames) # count of distinct names -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] MySQLdb error - PLEASE SAVE ME!
You should avoid sending the connection info to the list. Google will be making this widely available. Pranksters *will* delete your tables. Change your password! Including the error info would help, but chances the following changes will fix things: stmt = """CREATE TABLE links ( ID INT NOT NULL auto_increment, ^^ Name TEXT, URL LONGTEXT, Category LONGTEXT, primary key (ID) )""" for line in inp.readlines(): #links = map(str, line.split(",")) # values are already strings links = line.split(",",2) # limit to two splits i.e. only use first 2 commas arr.append(links) # arr is not used ??? cursor.execute (""" INSERT INTO links (Name, URL, category) VALUES (%s, %s, %s)""", links ) You are not supplying an ID value. I assume that you want MySQL to fill it in for you. So you need to make ID an auto_increment field. The cursor.execute is now getting *two* arguments, the sql and the values for the insert. Do not interpolate your values into the SQL string. Leave that to the MySQLdb module. The %s in the VALUES serves as a placeholder for the module and should not be used by you with the Python string format (%) operator. This should work so long as the name and URL never contain commas. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] MySQLdb error - PLEASE SAVE ME
> I dont see why your new code shouldn't work, it makes sense to me ... Danny nailed this one. He warned that your data could be short commas. You have lines with fewer than two commas. The INSERT is failing with: not enough arguments Simple fix is to skip insert if len(links) != 3. Note that we can't test without your data. Generally, it is better to keep the responsibility for testing in your hands and simply provide the error info and the background context. (Didn't mean to panic about the password, BUT I know folks who've learned the hard way that Google sees a lot more than you might expect, and pranksters really will drop your tables.) -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] subclass problem: __names and type-checking
I think that a sub-class *needs* to support the same programming interface as the parent class. Bertrand Meyer has written about programming by contract and the implications for object oriented design. http://archive.eiffel.com/doc/oosc/ http://se.ethz.ch/~meyer/ If B inherits from A then every context where A or an A instance appears should work correctly with B or a B instance. Since the B constructor *requires* more arguments, it violates that ideal. In other words, it would be OK to allow additional arguments. It is not OK to require them. In other words sub-class should really be a different class that adapts or possibly acts as a proxy for the _BaseClass. Obviously you have picked names that presuppose inheritance. I've abused inheritance in the past in an attempt to reuse code and have usually regretted it. An alternative is to create a new class that "fronts" for the class with the code we want to reuse. The __getattr__ method provides a real simple way to redirect references from our new class to the original class. class Base: def __init__(self, arg1,arg2): ... class Adapt: def __init__(self,arg1,arg2,arg3,arg4): self._base = Base(arg1,arg2) ... # this provides reuse of those Base methods that can be reused directly def __getattr__(self,attrname): return getattr(self._base, attrname) Without knowing more about what you are doing, I could be sending you off in the wrong direction, but hopefully this is relevant. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] subclass problem: __names and type-checking
Traceback (most recent call last): File "C:/Python24/foofoofoo.py", line 26, in -toplevel- s2 = Sub2() File "C:/Python24/foofoofoo.py", line 22, in __init__ super(Sub2, self).__init__() File "C:/Python24/foofoofoo.py", line 10, in __init__ if type(self) == __TwoUnderBase: # What to write here NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined Within a class, __ prefixes mangle the name to include the class name as part of the name. However, it appears that within a class statement, the __ prefix is not mangled. This is good for you because otherwise the inheritance would not work. However, it appears to make it impossible to directly reference the class name from within the class. You may want to rethink the idea of using __ prefixes in the class name. Normally __ is used to "privatize" attributes within a class. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Listing all of an instances variables
def report(self): for i in dir(self): # use the getattr function print getattr(self, i) -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using CGIHTTPServer on Windows to run Perl & Python scripts - POST to Perl fails
The perl scripts use cgi.pm. The Python scripts use the cgi module. Everything runs OK on Linux, where fork is available. On Windows the run_cgi method uses os.popen3 to run the script and writes the post data to the script's input file. The Python scripts are OK. The Perl scripts do not receive the POST parameters so they execute as though no parameters were supplied. I've added logic to display the environment and that appears (to my Python oriented eye) to be correct. In particular, the CONTENT_LENGTH and CONTENT_TYPE are correct. GET requests work correctly. In googling around, I found references to old POST problems under Windows. Those have clearly been fixed. The Python scripts work and the comments in the source code explain what was done (reading extra characters beyond the specified content-length that IE pushes up to the server). My guesses are that the Perl CGI module in Windows needs some other environment cue to get it to read the input file or it expects a different mechanism for receiving POST data than reading it from a file. Any suggestions would be greatly appreciated. (My fall back will be to change the run_cgi method for the Perl scripts to mimic a GET and put the parameters into the environment QUERY_STRING and hope that I do not exceed any limits on the string size.) -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using CGIHTTPServer on Windows to run Perl & Python scripts - POST to Perl fails
I should have included the REQUEST_METHOD before. Yes it is correct. This is a useful test perl script I downloaded from a Perl oriented site: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #!/usr/bin/perl use CGI; $cgi = new CGI; for $key ( $cgi->param() ) { $input{$key} = $cgi->param($key); } print qq{Content-type: text/html }; #print every key in the environment foreach $key (sort (keys %ENV)) { print $key, ' = ', $ENV{$key}, "\n"; } for $key ( keys %input ) { print $key, ' = ', $input{$key}, "\n"; } #print a couple of simple forms: a POST form and a GET form print qq{ }; print qq{ }; print qq{}; <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< I think I am pushing the limits of being on topic here, though having the Python CGI server work with Perl under Windows would be nice. I suppose it is possibly an issue with my Perl setup in Windows. It's Perl 5.8.7 from ActiveState binary build 813. The Windows version is (from sys.getwindowsversion): (5, 1, 2600, 2, 'Service Pack 2') Here is the webserver code: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #! /usr/bin/env python # cgiserver.py import sets, posixpath, sys, os, urllib, select from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler from SocketServer import ThreadingMixIn class ThreadingServer(ThreadingMixIn, HTTPServer): pass class MyRequestHandler(CGIHTTPRequestHandler): '''I could not figure out how to convince the Python os.stat module that the perl scripts are executable so that the server would actually run them. The simple solution is to override is_executable to always return true. (The perl scripts are indeed executable and do run.) ''' def is_executable(self, path): return True serveraddr = ('',8000) srvr = ThreadingServer(serveraddr, MyRequestHandler) srvr.serve_forever() <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< I assume anyone with access to a Windows computer could try this. The server expects to be in a directory with a subdirectory of cgi-bin cgi-env.pl should be in the cgi-bin directory The URL to use cgi-env.pl is http://localhost:8000/cgi-bin/cgi-env.pl I'd be curious if this issue is peculiar to the version of Windows that I am dealing with here. I have no other Windows web server environment to check against. The CGIRequestHandler can't be doing anything terribly wrong, or the Python scripts would fail. I will see if I can use the cgi.pm source to figure something out. Python schrieb: > The Python scripts are OK. The Perl scripts do not receive the POST > parameters so they execute as though no parameters were supplied. I've > added logic to display the environment and that appears (to my Python > oriented eye) to be correct. In particular, the CONTENT_LENGTH and > CONTENT_TYPE are correct. GET requests work correctly. Could you post some code examples, i.e. the HTML form which does the POST request and the Perl code to handle it? Have you checked, that the REQUEST_METHOD is really POST? Chris -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about serial coms
The device at the far end of the serial connection is echoing what you write back to you. This is a convenience for someone typing at a terminal, but a nuisance when you are programming. The easier way out is to turn echoing off at the far device. Failing that, you will want to provide a copy of your output to the read routine so that it can filter your output out of the data stream coming back to you. Unfortunately there is no reliable error detection on a serial line, so line errors can complicate the task of matching the echoes to your output. On Mon, 2005-11-14 at 17:04 -0800, Bennett, Joe wrote: > I have been working with pyserial. One question I have > is this. I have a loop that writes to the serial port > and then waits about 500ms and then reads from the > serial port. The first thing read from the serial port > is ALWAYS the data written to the serial port... I > must be missing something obvious, but I thuoght the > two buffers were separate... (snipped) > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [Fwd: Re: question about serial coms]
(Forwarding to the list.) -- Lloyd Kvam Venix Corp --- Begin Message --- Ya know, you're right!... Wow, I feel good about myself now..:) What I'll do is have the fist command be ECHO OFF and see what happens... Sorry about the waisted bandwidth, but thank you for bringing me back to reality... It's the simple stuff that will get ya! :) -Joe --- Python <[EMAIL PROTECTED]> wrote: > The device at the far end of the serial connection > is echoing what you > write back to you. This is a convenience for > someone typing at a > terminal, but a nuisance when you are programming. > > The easier way out is to turn echoing off at the far > device. Failing > that, you will want to provide a copy of your output > to the read routine > so that it can filter your output out of the data > stream coming back to > you. > > Unfortunately there is no reliable error detection > on a serial line, so > line errors can complicate the task of matching the > echoes to your > output. > > On Mon, 2005-11-14 at 17:04 -0800, Bennett, Joe > wrote: > > I have been working with pyserial. One question I > have > > is this. I have a loop that writes to the serial > port > > and then waits about 500ms and then reads from the > > serial port. The first thing read from the serial > port > > is ALWAYS the data written to the serial port... I > > must be missing something obvious, but I thuoght > the > > two buffers were separate... > (snipped) > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > > --- End Message --- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about ord
chr(value) >>> chr(ord('a')) == 'a' True On Tue, 2005-11-15 at 14:46 -0600, nephish wrote: > Hey there, > i am using a script to change a byte into an integer > like this: > a = the byte > value = ord(a) > > but i cant find the operation that can change it back to a byte. > i am sure its easy, but i am missing how to do it. > > thanks for any tips > > sk > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax:320-210-3409 -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dynamic inheritance?
On Sat, 2005-11-19 at 16:45 +0100, Jan Eden wrote: > > Is there a way to dynamically determine the value of Super at runtime? > Background: Depending on certain object attributes which are set during the > object initialization, I need to use a different set of templates for the > respective object. > If you use new style classes, then there is a super function that can be used to automatically resolve a superclass reference. You can force new style classes by: inherit from object easy to see, but repetitive __metaclass__ = typeput before the class statements super(Myclass,self).__init__(...) will search through the inheritance tree and (in this case) invoke __init__. Use __bases__ to run up the inheritance yourself. >>> class A: ... pass ... >>> class B(A): ... pass ... >>> b.__class__.__bases__ (,) >>> B.__bases__ (,) The "magic" class attributes don't get listed by the dir command so you need to search the documentation to find this. http://docs.python.org/lib/specialattrs.html >>> dir(B) ['__doc__', '__module__'] >>> b = B() >>> dir(b) ['__doc__', '__module__'] -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dynamic inheritance?
On Sat, 2005-11-19 at 15:23 -0800, Danny Yoo wrote: > Here's a small example that shows how classes can be treated just like any > other value in Python: > > # > def makeYa(superclass): > class Ya(superclass): > def sayHi(self): > superclass.sayHi(self) > print "ya" > return Ya > Sorry I totally misunderstood. Essentially, you want the super class(es) in the class statement to be variables. It's a good thing Danny and Kent were around. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] smtplib alternative???
On Sun, 2005-11-20 at 09:26 -0500, Adisegna wrote: > Hi Danny, > > Yes, when sending an email your mail client will always send the email > to the mail server specified by the MX record in the authoritive > domain. Usually the domain specificed after the @ symbol. The problem > with smtplib is that I have to specify the mail server I'm sending > email too. No. It is asking you to specify the server that the email will be coming from. Your email to the list went through the gmail server. If you look at the email headers, you will see entries from the mail servers that handled the message. Your local smtp server will handle the MX lookups. Simply specify the mail server provided by the ISP that provides your Internet connection, if you do not run a mail server yourself. > What if I wanted to send an email to 3 different people on three > different domains hosted by 3 different mail servers? Smtlib prohibits > this functionality. Do you see what I mean now...? > > Thanks for replying... If you have a conventional email program (e.g. Thunderbird, Evolution, Outlook Express) then the smtp server listed in that config should work with your Python script. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] smtplib problems ?
On Mon, 2005-11-21 at 19:59 +, dave wrote: > Traceback (most recent call last): > File "/home/dave/my files/andrew_torture/email_remind.py", line 49, in ? > email_remind() > File "/home/dave/my files/andrew_torture/email_remind.py", line 43, in > email_remind > raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) > Mail Failure > smtplib.SMTPRecipientsRefused > {'[EMAIL PROTECTED]': (553, "sorry, that domain isn't in my list of allowed > rcpthosts (#5.7.1)")} http://www.greenend.org.uk/rjk/2000/05/21/smtp-replies.html It is a standard SMTP error message. Essentially the mail server is trying to prevent relaying. Your script is working correctly. This SMTP server, since it works some of the time, probably uses POP before SMTP to authenticate your request. So if you login to the POP server using your mailbox name and password, it will authenticate your IP address as permitted to relay. This authentication will time out after a few minutes. Test this by checking your email on that server and then see if your script runs successfully. If you can use an SMTP server from your ISP that uses IP addresses to control relaying, you can avoid the need to login to the POP server. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lowercase, uppercase
On Sat, 2005-12-10 at 16:56 -0600, david wrote: > i am thinking that string.upper and string.lower may be what you are > looking for. >>> x = 'This is Some Mixed CaSe TExt' >>> x.lower() 'this is some mixed case text' >>> x.upper() 'THIS IS SOME MIXED CASE TEXT' Unless you are using a very old version of Python, there is no need to use the string module. the upper and lower methods now built into str and unicode objects. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Multi-Dimensional Dictionary that contains a 12 element list.
On Sat, 2005-12-31 at 09:33 -0500, Kent Johnson wrote: > Could be >self.results[key] = [0*24] [0]*24 Excellent points and advice, just noting a typo. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Design suggestion - is a cookie the answer?
On Mon, 2006-01-16 at 01:12 +, Alan Gauld wrote: > > I'm sure this is implied in Alan's post, but I'm going to point it > out > ... > > To avoid further cheating you might want to sure there is no way to > > submit the form without javascript turned on. E.g. Don't have a > submit > > button and a form with an 'onSubmit' validation. Which some examples > > do use. Otherwise, they can just turn off Javascript support in > their > > browser and bypass your validation. > Javascript might be the appropriate level of paranoia for your situation, however, remember that people do not have to use your form to submit data to your web script. An enterprising student could save the form and edit it him(her)self to bypass any javascript checks or even synthesize their own submit data (e.g. use urllib to supply answers). There is no check to make sure that the answers fed back to the script fit the problems that were written out in the form. Of course any kid who could figure out how to maximize points cheating your script can probably handle simple multiplication. I liked the variable name insertpupilsnick. If Dr Seuss had written a book on programming, I'm sure it would have had variable names like that. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
On Tue, 2006-01-17 at 09:11 -0800, andy senoaji wrote: > I am starting to pull my hair here. There were some postings in the > past, similar to my problem, but the response was not clear enough. > Sorry if you thingk I am reposting this. > > I am trying to run (on an XP box) a simple open file using this: > f = open(r'C:\Test.txt', 'r') This looks correct! > > but it keeps give me nagging error of: > Traceback (most recent call last): > File "", line 1, in -toplevel- > f = open('Test.txt', 'r') This is not the same is the line above! > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' And this does not match *either* of the lines above. If you really use that first line, I would expect it to work. If you get an error, from that line, the file will be identified as: 'C:\\Test.txt' > > I know for sure that the file is there, I even put copies of the files > here and there, just to guess how python does the file search, but it > keeps giving me 'No such file or directory'. i also tried variation of > the file location string, but gave me a variation of errors :). Any > suggestions? > > Furthermore, how does Python assumes the search path? Will it look > at /LIB first? How does it knows drive lettering, network mapping etc? > Is there a configuration settings that I can tweak in my Python? FYI I > am using Activestate's. > > > Thx, > > Andy > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
(replying back to the list also) On Tue, 2006-01-17 at 10:03 -0800, andy senoaji wrote: > Sorry for the inconsistent error message. I think I may pasted > incorretcly. I am now in a different machine, and have tested Paul's > suggestion, and it worked. But would the 'r' tackles the escape > sequence? I may misunderstood the intent of the r' switcher here. > > Thanks, > > Andy > f = open(r'C:\Test.txt', 'r') > This looks correct! r'C:\Test.txt' is a raw string. The r'strings' ignore the special use of the backslash character except that a raw string must not end with a backslash. This is strictly a convenience when entering a string. Since Windows uses backslash as the path separator, it helps ease the pain when constructing file paths in Windows. Raw strings are also very helpful when writing regular expression strings which often need to have backspace characters. Internally, a raw string is the same as any other Python string. When Python displays a raw string, Python will show the backslashes as \\ (doubled) because that is usually how you need to enter a backslash. Python does not track (as far as I know) that the string originated as a raw string. In regular strings, the backslash is used to mark characters that need special handling. '\t' is a tab character. '\n' is a newline (linefeed). '\r' is a carriage-return (Enter Key). http://docs.python.org/ref/strings.html provides the detailed documentation about how strings work and the definitive list of backspace usages. > > On 1/17/06, Python <[EMAIL PROTECTED]> wrote: > On Tue, 2006-01-17 at 09:11 -0800, andy senoaji wrote: > > I am starting to pull my hair here. There were some postings > in the > > past, similar to my problem, but the response was not clear > enough. > > Sorry if you thingk I am reposting this. > > > > I am trying to run (on an XP box) a simple open file using > this: > > f = open(r'C:\Test.txt', 'r') > This looks correct! > > > > > but it keeps give me nagging error of: > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > f = open('Test.txt', 'r') > This is not the same is the line above! > > > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' > And this does not match *either* of the lines above. > > If you really use that first line, I would expect it to > work. If you > get an error, from that line, the file will be identified as: > 'C:\\Test.txt' > > > > > I know for sure that the file is there, I even put copies of > the files > > here and there, just to guess how python does the file > search, but it > > keeps giving me 'No such file or directory'. i also tried > variation of > > the file location string, but gave me a variation of > errors :). Any > > suggestions? > > > > Furthermore, how does Python assumes the search path? Will > it look > > at /LIB first? How does it knows drive lettering, network > mapping etc? > > Is there a configuration settings that I can tweak in my > Python? FYI I > > am using Activestate's. > > > > > > Thx, > > > > Andy > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Quoting trouble
On Fri, 2006-01-20 at 13:50 -0800, Marilyn Davis wrote: > for each in significant_headers.keys(): > this = '''self.h_%s = "%s"''' % \ >(each[:-2].lower().replace('-','_'), > repr(significant_headers[each])) > exec(this) So you are using exec to process an assignment statement. The setattr builtin function will do what you want. http://docs.python.org/lib/built-in-funcs.html#l2h-64 so your code could wind up looking something like: setattr( self, 'h_' + each[:-2].lower().replace('-','_'), significant_headers[each] ) Looking at that code, you can pull the key and value from significant_headers in the for statement. That is: for key,val in significant_headers.items(): setattr( self, 'h_' + key[:-2].lower().replace('-','_'), val ) Now the line that actually determines the attribute name looks pretty ugly. I would recommend writing a function to replace that operation with an understandable function name (perhaps key2name). That would result in: setattr(self, key2name(key), val) Hope this helps. The ease with which Python allows you to attach names to values is one of the great features of the language. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is this overkill?
On Sat, 2006-01-21 at 10:09 -0500, Bradly McConnell wrote: > On 1/21/06, Alan Gauld <[EMAIL PROTECTED]> wrote: > > number = input("Please enter a number: ") > > while number != 100: > > additional_number = input("Please enter an additional number: ") > > if additional_number + number > 100: > > lower_number = input("please enter a lower number: ") > > > > you can just 'continue' here since the while loop asks for a new > > number anyhow. It xchanges the behaviour salightly in that it never > > allows a number that sums to more than 100 whereas you allow > > only two attempts. > > Not sure where I went wrong, but at this point, I cannot get the count > to reach 100 unless I use something like 60 and 40 for the number a > additional_number inputs. It seems that my variables are being > overwritten, but the "previous" additional number doesn't get added to > number before it happens. This appears in both my original, and with > the modifications that you (Alan) suggested. One approach that might help simplify things would be to use a variable for the input prompt. Changing as little as possible: prompt = "Please enter an additional number: " while number != 100: additional_number = input(prompt) This helps remove the need for additional input requests and should let you keep the while loop logic reasonably simple. Do this in conjunction with Alan's advice. I think we are both trying to push you in the same direction. > > I think I worked on it a bit too much last night, and lost track of > what I tried and didn't try so I think I'll take a look through the > areas on loops and conditional statements again this evening and start > over "fresh". > > Thanks for the help. > > Brad > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Searching for email id in MySQL giving wrong results
On Sun, 2006-01-22 at 21:23 +0300, ZIYAD A. M. AL-BATLY wrote: > wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) The string is being used in a call to cursor.execute. The email_id is a second parameter getting passed to execute. That is the *correct* approach to use. That is no help in explaining why the SELECT command is failing to return the expected results. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Linux Python install?
On Mon, 2006-01-23 at 09:28 -0500, CPIM Ronin wrote: > Sorry to bother the list with so simple a question but on moving to Linux > from Windows XP, it's not clear to me how to accomplish a Python install on > Linux. On XP it was mostly point and click on a ".msi" file (with msi > standing for Microsoft install). I've loaded the latest Fedora/Redhat > release on an old AMD machine. How do I install Python such that it shows up > as a selection under the Programming task bar with EMACS? I assume you are using yum for package management. It should have been installed by default. As root, you can issue the command yum install python python-docs python-devel python-tools The package yumex provides a GUI interface to the yum package manager. You can think of yumex as the Windows "Add/Remove Programs" application on steroids. yum install yumex The yumex install view with a filter of python will provide an extensive list of additional python packages. Finally, I do not know if this includes the best python integration with EMACS. > I assume I have to do this under root, right? > > Step by step please. > > Thanks. > > _ > Dont just search. Find. Check out the new MSN Search! > http://search.msn.click-url.com/go/onm00200636ave/direct/01/ > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Searching for email id in MySQL giving wrong results
On Mon, 2006-01-23 at 18:17 +, Alan Gauld wrote: > > On Sun, 2006-01-22 at 21:23 +0300, ZIYAD A. M. AL-BATLY wrote: > >> wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) > > > > The string is being used in a call to cursor.execute. The email_id is a > > second parameter getting passed to execute. That is the *correct* > > approach to use. > > Nope, sorry. > This sends the string > > SELECT . id=%s [EMAIL PROTECTED] > > ie the %s is kept in the string, not what is wanted. > > The OP must replace the comma with a % character for the string > substitution to take place. > > > That is no help in explaining why the SELECT command is failing to > > return the expected results. > > The rogue %s in the select string will mess things up. > > Alan G. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Searching for email id in MySQL giving wrong results
On Mon, 2006-01-23 at 18:17 +, Alan Gauld wrote: > > On Sun, 2006-01-22 at 21:23 +0300, ZIYAD A. M. AL-BATLY wrote: > >> wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) > > > > The string is being used in a call to cursor.execute. The email_id is a > > second parameter getting passed to execute. That is the *correct* > > approach to use. > > Nope, sorry. > This sends the string > > SELECT . id=%s [EMAIL PROTECTED] > > ie the %s is kept in the string, not what is wanted. > > The OP must replace the comma with a % character for the string > substitution to take place. The wrong_string line was lifted from the following code in the OP. entry = db.cursor() entry.execute("""SELECT * FROM contact WHERE email_id = %s""", (s_email,)) The execute method will handle the string substitution. This is better than doing it yourself, because execute will deal with any quoting issues for feeding the data to the database. I should have included the original code as I did here. Sorry if I created any confusion as related to regular Python string substitution. It is a very common mistake for people to do the SQL string interpolation themselves as opposed to leaving it for the execute method. > > > That is no help in explaining why the SELECT command is failing to > > return the expected results. > > The rogue %s in the select string will mess things up. > > Alan G. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Searching for email id in MySQL giving wrong results
On Mon, 2006-01-23 at 19:46 +, Alan Gauld wrote: > >> >> wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id) > >> > > >> The OP must replace the comma with a % character for the string > >> substitution to take place. > > > > The wrong_string line was lifted from the following code in the OP. > > > >entry = db.cursor() > >entry.execute("""SELECT * FROM contact WHERE email_id = %s""", > > (s_email,)) > > > > Ah I see. Yes that's a different proposition entirely! > I really should read the whole thread before jumping in... :-( > > Alan G. > Well I created the trap by not pasting in the execute call and posting what was on its face an invalid piece of Python coding. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] email-sending.. (fwd)
On Sun, 2006-01-29 at 10:09 -0800, Danny Yoo wrote (forwarding a direct reply to the list): > Hi Danny, > > i have crossed that point where it complains of socket error.., but > now i am stuck with another issue, where it says that it has sent the > mail, but i dont recive any in my yahoo mail.,i have even unbloked my > spam filter in my yahoo.. You will find testing this kind of script much easier if you have access to the mail server logs. If you do not have a friend with a mail server and do not know how to run a mail server yourself, a local Linux user group may be able to provide some assistance. Your ISP, especially a smaller locally focused operation, would be another possibility. The big ISP's will now discard email without any notification. This is largely due to the overwhelming spam load they have to deal with. Your email could be getting discarded for any number of reasons. Chances are your script is working. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] smtplib with yahoo smtp server
On Wed, 2006-02-01 at 18:51 +0530, Intercodes wrote: > Received: by wproxy.gmail.com with SMTP id i23so141320wra for > ; Wed, 01 Feb 2006 05:21:36 -0800 (PST) > Received: by 10.65.228.15 with SMTP id f15mr63752qbr; Wed, 01 Feb 2006 > 05:21:36 -0800 (PST) > Received: by 10.65.100.11 with HTTP; Wed, 1 Feb 2006 05:21:36 -0800 > (PST) > Message-ID: > <[EMAIL PROTECTED]> Intercodes, you are using a web interface to send your email. Can you get a "normal" (Evolution, Thunderbird, pine, etc.) email client to work on your system. If those do not work, your Python program probably won't work either. The errors you're getting appear to come from system config issues rather than programming errors. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
On Sat, 2006-02-11 at 16:19 +1000, Joal Heagney wrote: > > 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. A friend described MySQL as the RDBMS for people who do not really need an RDBMS. This is a little unfair, but has just enough truth to bear repeating. MyISAM tables offer good performance at the cost of transactions, views, row locking, etc. The MySQL documentation suggests some work-arounds. I use MySQL for these benefits: replication - (off-site near real time backups; simple distributed processing) enum and set datatypes - easy to use integer to text mapping fields. enums == radio buttons (single-select), sets == check boxes (multi- select) very easy administration good performance Obviously, the lack of transactions is a nuisance. If you are converting software from another RDBMS, the MySQL limitations will be especially painful. When replication and/or easy administration trump other concerns, MySQL can be a good choice. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems with the shebang line and linux
On Thu, 2006-02-16 at 07:36 -0600, Brian van den Broek wrote: > Hi all, > > I've switched to Linux fairly recently and am still at the fumbling > about stage :-) I'm having a devil of a time with the shebang line > and running a py file from a command line. > The file has dos/windows format with CR/LF markers to separate lines. A normal posix file should only use LF. dos2unix is a handy utility for converting text files. Depending on your distribution, you should be able to install it using apt or yum e.g. yum install dos2unix or use the GUI interface to your package manager (yumex is the yum GUI, I do not remember the name of the apt GUI). On a shared partition, keeping .py files in a posix format (LF only) has never caused any problems for me. The Python compiler/interpreter on Windows will happily process either format. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Telnet to cisco device
On Tue, 2006-02-28 at 16:36 +1000, STREET Gideon (SPARQ) wrote: > tn.read_until('Username: ') #expected prompt after telnetting to the > router > tn.write(user + '\r\n') #hopefully write username and pass character > return > Sending both \r and \n may be confusing things. I'd recommend using tcpwatch.py http://hathawaymix.org/Software/TCPWatch to monitor a telnet session that works. That way you will have a collection of exact prompts available to build your script. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] URGENT doubt!!!!
On Wed, 2006-03-01 at 17:13 +0100, Joaquin Sanchez Sanchez wrote: > I have a doubt > > I have some modules in python, and in one of them, i have to > dictionarys. In them, i have some vars yhat I want to save before > clossing my session, ande then, in a new session, i want to load them. > > I have heard about "pickle" > How does it work?I dont understand the help page example > How have I to used it? > Another suggestion? I think the shelve module better fits what you are trying to do. It will store the pickle into a file for later retrieval and possible modification. http://docs.python.org/lib/module-shelve.html Note that you should be using strings for the shelve keys. > > THANKS A LOT > > > __ > > LLama Gratis a cualquier PC del Mundo. > Llamadas a fijos y móviles desde 1 céntimo por minuto. > http://es.voice.yahoo.com > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print list vs telnetlib.telnet.write differences
On Fri, 2006-03-03 at 15:41 +1000, STREET Gideon (SPARQ) wrote: > The problem I'm stumbling over is that when I print x, the output is > what I want. If I delete the print x and #, leaving only tn.write(x) > on > the last line everything looks good except it writes the 1st item in > "lines" (the banner exec command) twice, once at the beginning where > it's supposed to, but then once again at the end. See except below for > example. > > Anyone able to explain why that is happening or is it me just not > understanding what I'm doing? Hope my explanation is clear I'm still > unfamiliar with the exact phrasology. > Could that be your data being echoed back to you? Is the router configured correctly after the script runs? I normally feed commands to Cisco devices using tftp. It is relatively easy to edit a file to get the commands correct. Then you could limit your "conversational script" to logging in and running tftp to transfer the command file. It looks like you are pretty close to having this working. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax:320-210-3409 -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] One shared object. class attribute or global variable?
On Sat, 2006-03-04 at 00:42 +, Adam wrote: > On 04/03/06, Adam <[EMAIL PROTECTED]> wrote: > > I've got a module that needs to share a pack of cards > > > > pack = ["14s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", "11s", > > "12s", "13s", "14d", "2d", "3d", "4d", "5d", "6d", "7d", "8d", "9d", > > "10d", > > "11d", "12d", "13d", "14c", "2c", "3c", "4c", "5c", "6c", "7c", "8c", > > "9c", > > "10c", "11c", "12c", "13c", "14h", "2h", "3h", "4h", "5h", "6h", "7h", > > "8h", > > "9h", "10h", "11h", "12h", "13h"] > > random.shuffle(pack) > > > > do you think it is worth making a class with just this attribute or > > would this be a good place to use a global variable? > > > > I just realised this probably isn't as clear as it should be, sorry > it's late. It needs to share the variable with the functions (or > methods) in the module not with anything outside of it. It looks like this will be shared and modified. In general, I think read-only variables (initialized at start-up when not constants) can work OK as globals. A container that will be changed and shared should almost certainly go in a class. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print list vs telnetlib.telnet.write differences
On Tue, 2006-03-07 at 11:31 +1000, STREET Gideon (SPARQ) wrote: > Enter configuration commands, one per line. End with CNTL/Z. > switch01(config)#banner exec ^ > > ## > > switch01 > > Level XX, XX Some Street, Somewhere >Site contact: John Citizen 555 > System Contact: Helpdesk 555 5556 > > ## > > ^ > banner exec ^ < this is the second time this command is sent to the > device > Enter TEXT message. End with the character '^'. > > ###exit > My tcpwatch.py display shows different colors for each side of the conversation. Do you get two colors? are both in the same color? Isn't the second banner exec simply the echo back from the cisco device? It is giving you your entry instructions. 1. Is the banner exec command working? If it works, then the funny duplication is almost certainly just an artifact of characters getting echoed from the cisco device. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print list vs telnetlib.telnet.write differences
On Tue, 2006-03-07 at 13:39 +1000, STREET Gideon (SPARQ) wrote: > The second banner exec is red, the previous commands I send are in > green. So I take it to mean that it is an echo produced by the router. > MMmm strange as the echo is overwriting what I'm sending initially. Well the device is designed for interactive use by a human who does not spew characters nearly has quickly as your script. In this case you probably need to read the response to the exec banner command before sending the banner. Most commands are done in a single line, but banner is an exception. This kind of scripting is often done with expect and I believe that there is some expect-like module for Python. As I suggested earlier, getting tftp to send command files will make a much better long term solution. This script would only have to manage logging in and starting tftp. Once that works all other commands would be in the file that tftp transfers. Linux/Unix systems already have tftp built in. Cisco provides a tftp implementation for Windows. It is easy to put comments into the command files and also use subversion or some other version control package to track changes. > > The banner appears to work but is then overwritten, maybe I need to come > up with another way of sending the commands so I get around the echo. > > Thanks > > Gideon > > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On > Behalf Of Python > Sent: Tuesday, 7 March 2006 12:52 PM > To: Tutor Python > Subject: Re: [Tutor] Print list vs telnetlib.telnet.write differences > > On Tue, 2006-03-07 at 11:31 +1000, STREET Gideon (SPARQ) wrote: > > Enter configuration commands, one per line. End with CNTL/Z. > > switch01(config)#banner exec ^ > > > > ## > > > > switch01 > > > > Level XX, XX Some Street, Somewhere > >Site contact: John Citizen 555 > > System Contact: Helpdesk 555 5556 > > > > ## > > > > ^ > > banner exec ^ < this is the second time this command is sent to > > the device Enter TEXT message. End with the character '^'. > > > > ###exit > > > > My tcpwatch.py display shows different colors for each side of the > conversation. Do you get two colors? are both in the same color? > > Isn't the second banner exec simply the echo back from the cisco device? > It is giving you your entry instructions. > > 1. Is the banner exec command working? > If it works, then the funny duplication is almost certainly just an > artifact of characters getting echoed from the cisco device. > > -- > Lloyd Kvam > Venix Corp > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > > This e-mail (including any attachments) may contain confidential or > privileged information and is intended for the sole use of the person(s) to > whom it is addressed. If you are not the intended recipient, or the person > responsible for delivering this message to the intended recipient, please > notify the sender of the message or send an e-mail to > mailto:[EMAIL PROTECTED] immediately, and delete all copies. Any > unauthorised review, use, alteration, disclosure or distribution of this > e-mail by an unintended recipient is prohibited. Ergon Energy accepts no > responsibility for the content of any e-mail sent by an employee which is of > a personal nature. > > Ergon Energy Corporation Limited ABN 50 087 646 062 > Ergon Energy Pty Ltd ABN 66 078 875 902 -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need help tracing a syntax error
On Sat, 2006-03-11 at 10:42 -0500, Kermit Rose wrote: > I get the message > > syntax error > > > and it highlightsr2 > > in the line > > .If r2 == 1: if should be lower case (all of the python syntax words are lower case) You will also need to change Else and Elif Int should probably be int unless you are providing an Int class. special python objects get capitalized (None, True, False) -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python & MP3
On Tue, 2006-03-21 at 10:50 +0100, Johanna wrote: > Hallo > > > > This is my first post, so hallo to everyone. Im just a newbee with > python so I hope my msg will make some sense. J > > > > Is it possible to work with MP3 in python? yumex lists python-eyed3 python-mad as python packages that deal with mp3 files. eyed3 is geared towards tags (id3). mad appears to be closer to what you are looking for. I have no first hand experience with either. > > I’m looking for a library to modify MP3s (like fade in, fade out, > etc..). I know there are actually some libraries for doing this work > with .wav but I didn’t find one for working with MP3. I’m not sure but > should be something like -> http://effbot.org/librarybook/wave.htm . > Anyone? > > > > Thanks. > > > > Jo > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about large numbers of arguments
On Wed, 2006-04-05 at 12:34 +0100, Alan Gauld wrote: > > Suppose you have a situation where you have a large number of command-line > > options that you will parse with getopt. You want to keep track of these > > as you move around in the code and do various things. > > > > Is it more Pythonic to: > > > > Have the functions take large numbers of parameters. > > > > Create an options class to pass the options around. > > Neither, the most Pythonic way IMHO is to use a dictionary and > possibly combine with Pythons variable arguments syntax as > described in section 4.7.3/4 of the official tutor. > > > I personally think the latter would look a lot cleaner once the number of > > options got up to around a half dozen, but I usually see the "large number > > of parameters" style in other people's code. > > Classes without behaviour are really just glorified dictionaries so > I prefer to use a dictionary. The **args mechanism provides a > good way to pass these to functions. Just to expand on that a little bit, one useful coding trick where you use only a few of the parameters is to define the function as: def myfunc(param6, param11, param17, **extra): # The parameters you care about are unpacked for you # The rest are in extra # use the ** syntax to pass the dictionary in to your function myfunc( **param_dict) Coming up with better names is left as an exercise for the reader. I mostly use this when dealing with HTML forms with many variables. > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] date conversion
On Wed, 2006-04-05 at 10:50 -0400, Kent Johnson wrote: > Ray Allen wrote: > > I would like Python to convert a date returned by MySQL (2006-04-05) Kent's advice below is of course correct, but I'd bet your variable is already a datetime.date (or mx.DateTime.Date with older Python releases). In that case you'd already be at step 7. When executing your update statement use the args field. cursor.execute("UPDATE table SET mydate=%s WHERE id=%s", (date_variable, recordID)) You should not have to worry about getting your date into the proper string format for the database SQL syntax. Here's the help from MySQLdb: help(curs.execute) execute(self, query, args=None) method of MySQLdb.cursors.Cursor instance Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any > to a > > user readable format such as 05-Apr-2006 for display and then to convert it > > back to ISO format for update. > > Here's one way: > > In [1]: from datetime import date > > In [2]: data = '2006-04-05' > > Use split() and int() to convert to a list of year, month, day > In [4]: ymd = map(int, data.split('-')) > > In [5]: ymd > Out[5]: [2006, 4, 5] > > Turn it into a date. The * makes the list act like individual parameters. > In [6]: d=date(*ymd) > > In [7]: d > Out[7]: datetime.date(2006, 4, 5) > > See the docs for the time module for info about strftime() format codes > In [8]: d.strftime('%d-%b-%Y') > Out[8]: '05-Apr-2006' > > ISO format is built-in. > In [9]: d.isoformat() > Out[9]: '2006-04-05' > > > For other input formats you might have to use time.strptime() to convert > to a time tuple, then pass the first three elements do date(): > > In [10]: import time > > In [15]: t=time.strptime(data, '%Y-%m-%d') > > In [16]: t > Out[16]: (2006, 4, 5, 0, 0, 0, 2, 95, -1) > > In [17]: date(*t[:3]) > Out[17]: datetime.date(2006, 4, 5) > > > Kent > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax:320-210-3409 -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] failing to learn python
On Tue, 2006-04-11 at 12:06 -0400, Payal Rathod wrote: > The reason I am disgrunted with Python is because lack of good > documentation. http://www.python.org/doc/ The Python Docs - possibly you missed this because of the plethora of links. The Library Reference used to have the tag line: (keep this under your pillow) The Module Index is the other key starting point. http://rgruet.free.fr/PQR24/PQR2.4.html A very handy quick reference. I think Python has incredibly good documentation. Fred Drake and the other folks who write, edit and maintain the documentation do a wonderful job of keeping it fresh and current as the language changes. There are very few rough spots within the thousands of pages of text. It's been a while since I looked at the Tutorial. Is that where you felt let down? I felt compelled to respond to your post. I think the quality and quantity of Python documentation is hard to beat. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] checking diagonals on a chessboard
On Thu, 2006-04-13 at 15:16 -0400, Matthew Singletary wrote: > I'm building a genetic algorithm to solve the queen placement problem, > the complicated stuff I can do on my own, but I'm not getting one > part. > suppose the queen is on a square, I can check that it is in the same > row or same col but the diagonals, are less straight-forward. > I know I could solve this by just smashing away at it, but I was > wondering if anyone could suggest some tips on directions to work > > I'm NOT looking for any answers, just some tips to an _elegant_ method > to solve this. > This problem is discussed in "The ICON Programming Language" by Ralph and Madge Griswold around page 150. The basic approach they take is to number diagonals, just like you number rows and columns. So every queen's position involves a row #, col #, and diag #. Scratching your head over how to number the diagonals I'll leave to you. They counted 30 diagonals, so if you come up with a different count, you either have an original approach or have blundered somewhere. (Hopefully that was the kind of pointer you were looking for. Tim Peters (I think) has written about this problem in a Python context, but citing Icon.) -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] encode
On Wed, 2006-04-19 at 10:10 +0700, kakada wrote: > Hi again folks, > > I wonder if we can check the encoding of text in one text file. > user is free to encode the file whether Latin1, utf-8, ANSI... > Any ideas? def decode_file(filepath): '''Order of codecs is important. ASCII is most restrictive to decode - no byte values > 127. UTF8 is next most restrictive. There are illegal byte values and illegal sequences. LATIN will accept anything since all 256 byte values are OK. The final decision still depends on human inspection. ''' buff = open(filepath,'rb').read() for charset in (ASCII,UTF8,LATIN,): try: unistr = buff.decode(charset,'strict') except UnicodeDecodeError: pass else: break else: unistr,charset = u'',None return unistr, charset Also note that the unicode character u'\ufffd' represents an error placeholder. It can be decoded from UTF8 inputs and reflects earlier processing problems. DO NOT USE THIS CODE BLINDLY. It simply offers a reasonable, first cut where those are the likely encodings. It is impossible to distinguish the various LATINx encodings by simply looking at bits. All 8 bit bytes are valid, but their meanings change based on the encoding used. > > Thx > > da > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting a number into even- and odd- numbered digits
On Wed, 2006-04-19 at 17:17 -0700, Carroll, Barry wrote: > Greetings: > > I am writing a function that accepts a string of decimal digits, > calculates a checksum and returns it as a single character string. > The first step in the calculation is to split the input into two > strings: the even- and odd- numbered digits, respectively. The least > significant digit is defined as odd. > This sounds like credit card checksum processing. This is my code for that: def isbad(cardnumber): factors = ([2,1] * 8)[-len(cardnumber):]# alternating factors of 2 and 1 ending with 1 chkprods = [int(d)*f for (d,f) in zip(cardnumber,factors)] return sum(chkprods) % 10 This deviates quite a bit from your description and the description of the algorithm that I was working from. It was only after I had coded up separate even/odd character lists and looked at what was going on that I realized there was a much simpler way to describe the rules. Hopefully, I am not off in left field here. > The following code fragment does the job but seems sort of brutish and > inelegant to me: > > >>> > >>> s = '987654321' > >>> odd = '' > >>> for c in s[::-2]: > ... odd = c + odd > ... > >>> s = s[:-1] > >>> even = '' > >>> for c in s[::-2]: > ... even = c + even > ... > >>> odd > '97531' > >>> even > '8642' > >>> > > Is there a better (i.e. more Pythonic) way to do this? > > Thanks in advance for all your help. > > Regards, > > Barry > [EMAIL PROTECTED] > 541-302-1107 > > We who cut mere stones must always be envisioning cathedrals. > -Quarry worker's creed > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] looking to hire a tutor
On Fri, 2006-04-21 at 19:44 -0700, [EMAIL PROTECTED] wrote: > How would I go about hiring a python tutor who: > > Spends time critiquing my code and providing detailed feedback. > Cares about good programming practices and is able to provide cogent > explanations of programming principles. > Can instruct me in the finer points of breaking a programming problem > down > into constituent parts. > Is well versed in Python. It would be great (but not necessary) if > he/she > were also familiar with data mining practices. > > I would be willing to pay 20-30$ an hour (or more depending on > instructor > qualifications). > >How do I go about doing this? Any suggestions? Sometimes having someone sitting at your side helping you get acclimated can be a big help. I would expect your school would have some computer oriented clubs or groups where you could find the expertise you're looking for. A Linux User Group could be a good source of help, even if you are using Windows since the percentage of Python users is generally higher among Linux folks than in the Windows population. For remote help, this list is hard to beat. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] counting number of inputs
On Tue, 2006-05-02 at 19:25 -0400, MICHELLE EVANS wrote: > I am trying to count the number of times a positive number is entered > from the user. But, the program must stop after 5 user inputs or a > negative number. > > Can anyone help. Yes, but you need to help yourself also. Do you know how to get input from the user? Do you know how to count things in Python? Do you know how to test a number to see if it is positive or negative? Why don't you post your code for any part of this problem and explain how it is supposed to work and where you are having difficulty. If necessary, review some of the tutorials to get some pointers on writing Python programs. We're happy to help you learn, but do not want to simply write your program for you. > Rick > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] counting number of inputs
(Tip: Best to use reply-to-all when responding to an email on the list) On Tue, 2006-05-02 at 21:34 -0400, MICHELLE EVANS wrote: > number1 = int(raw_input("Run number 1 (-1 to end) : ")) > number2 = int(raw_input("Run number 2 (-1 to end) : ")) > number3 = int(raw_input("Run number 3 (-1 to end) : ")) > number4 = int(raw_input("Run number 4 (-1 to end) : ")) > number5 = int(raw_input("Run number 5 (-1 to end) : ")) Good. You collect the string from raw_input and convert it to an integer. This will prompt for 5 inputs, but it is missing any logic to actually break if -1 is entered. With a language like BASIC, you could stick in tests sort of like: if number1 == -1 goto done: BUT Python does not have a goto. So we actually need some "flow control" around the block of code where you collect inputs. while blocks process an indefinite number of times while a test condition is True. for blocks iterate through a sequence until they reach the end. By providing a sequence with the correct count, you can repeat the block the correct number of times. The range (and xrange for big sequences) functions provide a sequence of integers that can be used conveniently with for. The easiest way to fix your code above would be something like: ask_for_number = True while ask_for_number: > > > # The following will sum the numbers and then print the answer > sum = number1 + number2 + number3 + number4 + number5 > print > print "The total number of parts produced was:", sum,"." > > I need this to ask the user to enter their number per each run. That is why > I have 5 different input numbers. I need this break if a -1 is entered. > Would I use "if-else" to break this if -1 is entered? I need to be able to > count the number of lines entered. > > Thanks > Rick > > > - Original Message - > From: "Python" <[EMAIL PROTECTED]> > To: "MICHELLE EVANS" <[EMAIL PROTECTED]> > Cc: "Tutor Python" > Sent: Tuesday, May 02, 2006 7:56 PM > Subject: Re: [Tutor] counting number of inputs > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE EVANS wrote: > > > I am trying to count the number of times a positive number is entered > > > from the user. But, the program must stop after 5 user inputs or a > > > negative number. > > > > > > Can anyone help. > > Yes, but you need to help yourself also. > > > > Do you know how to get input from the user? > > Do you know how to count things in Python? > > Do you know how to test a number to see if it is positive or negative? > > > > Why don't you post your code for any part of this problem and explain > > how it is supposed to work and where you are having difficulty. If > > necessary, review some of the tutorials to get some pointers on writing > > Python programs. > > > > We're happy to help you learn, but do not want to simply write your > > program for you. > > > > > Rick > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > -- > > Lloyd Kvam > > Venix Corp > > > > > -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY)
(Tip: Best to use reply-to-all when responding to an email on the list) On Tue, 2006-05-02 at 21:34 -0400, MICHELLE EVANS wrote: > number1 = int(raw_input("Run number 1 (-1 to end) : ")) > number2 = int(raw_input("Run number 2 (-1 to end) : ")) > number3 = int(raw_input("Run number 3 (-1 to end) : ")) > number4 = int(raw_input("Run number 4 (-1 to end) : ")) > number5 = int(raw_input("Run number 5 (-1 to end) : ")) Good. You collect the string from raw_input and convert it to an integer. This will prompt for 5 inputs, but it is missing any logic to actually break if -1 is entered. With a language like BASIC, you could stick in tests sort of like: if number1 == -1 goto done: BUT Python does not have a goto. So we actually need some "flow control" around the block of code where you collect inputs. while blocks process an indefinite number of times while a test condition is True. for blocks iterate through a sequence until they reach the end. By providing a sequence with the correct count, you can repeat the block the correct number of times. The range (and xrange for big sequences) functions provide a sequence of integers that can be used conveniently with for. The easiest way to fix your code above would be something like: ask_for_number = True while ask_for_number: number1 = if number1 == -1: break ... number5 = ... ask_for_number = False HOWEVER, that is not a good approach in the long run. A better approach is to have a single container to hold all of the inputs. For this, Python provides lists. Rather than have 5 separate variables, use a single list variable to hold all of the inputs. Then use a "for block" to ask for the input and put the result into the list. You already know how to convert the input from a string to a number. If you have trouble figuring out lists and for blocks, ask for help. (Sorry about the extra email. I forgot and used ad editor hot-key combo in my email program which sent the email.) > > > # The following will sum the numbers and then print the answer > sum = number1 + number2 + number3 + number4 + number5 > print > print "The total number of parts produced was:", sum,"." > > I need this to ask the user to enter their number per each run. That is why > I have 5 different input numbers. I need this break if a -1 is entered. > Would I use "if-else" to break this if -1 is entered? I need to be able to > count the number of lines entered. > > Thanks > Rick > > > - Original Message - > From: "Python" <[EMAIL PROTECTED]> > To: "MICHELLE EVANS" <[EMAIL PROTECTED]> > Cc: "Tutor Python" > Sent: Tuesday, May 02, 2006 7:56 PM > Subject: Re: [Tutor] counting number of inputs > > > > On Tue, 2006-05-02 at 19:25 -0400, MICHELLE EVANS wrote: > > > I am trying to count the number of times a positive number is entered > > > from the user. But, the program must stop after 5 user inputs or a > > > negative number. > > > > > > Can anyone help. > > Yes, but you need to help yourself also. > > > > Do you know how to get input from the user? > > Do you know how to count things in Python? > > Do you know how to test a number to see if it is positive or negative? > > > > Why don't you post your code for any part of this problem and explain > > how it is supposed to work and where you are having difficulty. If > > necessary, review some of the tutorials to get some pointers on writing > > Python programs. > > > > We're happy to help you learn, but do not want to simply write your > > program for you. > > > > > Rick > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > -- > > Lloyd Kvam > > Venix Corp > > > > > -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bitten by lexical closures
On Wed, 2006-05-03 at 14:00 +0200, Igor wrote: > Hi. > > And I thought I understood python pretty well. Until I got hit by this: > > >>> def f(x): > ... print x > > >>> cb = [lambda :f(what) for what in "1234"] > >>> for c in cb:c() > 4 > 4 > 4 > 4 >>> cb = [(lambda x=what:f(x)) for what in "1234"] >>> cb[0]() 1 A variable from the enclosing scope is normally only evaluated when used, that is when the closure is called. To capture a "transient" value, you need to explicitly pass it into the closure. I've gotten burned on this more than once. (snipped) > Regards, > Igor > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax:320-210-3409 -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] counting number of inputs (EARLIER VERSION SENT ACCIDENTLY)
On Wed, 2006-05-03 at 15:33 -0400, MICHELLE EVANS wrote: > OK, I've tried a different approach to this. > How do I get this to stop by using -1? > I do not want this to print until either 5 inputs have been entered or -1 > has been entered. See below: > use a "for block" rather than a "while block" to have a normal limit of 5 repetitions: for x in range(5): will repeat 5 times with x running from 0 to 4. x is ignored - unless some use for it does turn up. the break statement allows you to terminate a block, so if number == -1: break will end the for block. Now, one of the cute features in Python is the else clause that goes with the for and while blocks. The else block is executed when there is no break. So the skeleton for your program can look something like for x in range(5): # get inputs and break on -1 else: # no break so just process the inputs Good luck. > # Add number of per hour > numbers = [] > stop = None > while stop != "-1": > number = int(raw_input("Run number(-1 to end) : ")) > numbers.append(number) > print > for number in numbers: > print number > > > > > - Original Message - > From: "Python" <[EMAIL PROTECTED]> > To: "MICHELLE EVANS" <[EMAIL PROTECTED]> > Cc: "Tutor Python" > Sent: Wednesday, May 03, 2006 12:18 PM > Subject: Re: [Tutor] counting number of inputs (EARLIER VERSION SENT > ACCIDENTLY) > > > > (Tip: Best to use reply-to-all when responding to an email on the list) > > On Tue, 2006-05-02 at 21:34 -0400, MICHELLE EVANS wrote: > > > number1 = int(raw_input("Run number 1 (-1 to end) : ")) > > > number2 = int(raw_input("Run number 2 (-1 to end) : ")) > > > number3 = int(raw_input("Run number 3 (-1 to end) : ")) > > > number4 = int(raw_input("Run number 4 (-1 to end) : ")) > > > number5 = int(raw_input("Run number 5 (-1 to end) : ")) > > Good. You collect the string from raw_input and convert it to an > > integer. > > > > This will prompt for 5 inputs, but it is missing any logic to actually > > break if -1 is entered. With a language like BASIC, you could stick in > > tests sort of like: > > if number1 == -1 goto done: > > BUT Python does not have a goto. So we actually need some "flow > > control" around the block of code where you collect inputs. > > > > while blocks process an indefinite number of times while a test > > condition is True. > > > > for blocks iterate through a sequence until they reach the end. By > > providing a sequence with the correct count, you can repeat the block > > the correct number of times. The range (and xrange for big sequences) > > functions provide a sequence of integers that can be used conveniently > > with for. > > > > The easiest way to fix your code above would be something like: > > ask_for_number = True > > while ask_for_number: > > number1 = > > if number1 == -1: break > > ... > > number5 = ... > > ask_for_number = False > > > > HOWEVER, that is not a good approach in the long run. > > > > A better approach is to have a single container to hold all of the > > inputs. For this, Python provides lists. Rather than have 5 separate > > variables, use a single list variable to hold all of the inputs. Then > > use a "for block" to ask for the input and put the result into the list. > > You already know how to convert the input from a string to a number. > > > > If you have trouble figuring out lists and for blocks, ask for help. > > > > (Sorry about the extra email. I forgot and used ad editor hot-key combo > > in my email program which sent the email.) > > > > > > > > > > > > > # The following will sum the numbers and then print the answer > > > sum = number1 + number2 + number3 + number4 + number5 > > > print > > > print "The total number of parts produced was:", sum,"." > > > > > > I need this to ask the user to enter their number per each run. That is > why > > > I have 5 different input numbers. I need this break if a -1 is entered. > > > Would I use "if-else" to break this if -1 is entered? I need to be able > to > > > count the number of lines entered. > > > > > > Thanks > > > Rick > > > > > > > > > - Original Message - > > > From: "Python" <[EMAIL PROTECTED]> > > > To: "
Re: [Tutor] web intefaces?
On Mon, 2006-05-08 at 18:29 -0400, Chad Crabtree wrote: > While everything that Alan Guald said is true, there are a couple of > options for you. Provided you know HTML (you must), you could > generate html pragmatically but, knowledge of html is still mandatory. > Your options are, basically > > http://www.cherrypy.org > Which is an app server that should be fairly easy to package up with, > say py2exe. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442481 This is an example of configuring a cherrypy application so that it runs and starts the browser. It's a convenient way to make sure that the web application is running before the browser tries to access it. It also shows how a cherrypy application can stop itself. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sending e-mail msg
On Wed, 2006-05-17 at 10:03 -0500, URBAN LANDREMAN wrote: > I'm trying to set up a routine to send customized e-mail messages from > records in a database. > My first step is trying to send one simple e-mail message. After I get that > figured out, I can move on to step 2. > > Unfortunately, when I try the example code in the tutorials for sending > e-mail, I get error messages which I am unsure how to interpret. > > The code I use is: > import smtplib > > fromaddr = "[EMAIL PROTECTED]" > toaddrs = "[EMAIL PROTECTED]" > # Add the From: and To: headers at the start! > msg = ("From: %s\r\nTo: %s\r\n\r\n" >% (fromaddr, toaddrs)) > msg = msg + "This is a test message" > > print "Message = " + msg > print "Message length is " + repr(len(msg)) > > server = smtplib.SMTP('mail.hennepinPublicHealth.org') > server.set_debuglevel(1) > server.sendmail(fromaddr, toaddrs, msg) > server.quit() > *** > > The output I get is: > > Message = From: [EMAIL PROTECTED] > > To: [EMAIL PROTECTED] > > > > This is a test message > Message length is 89 > > Traceback (most recent call last): > File "J:/SPSS/Python/EMailExample.py", line 14, in -toplevel- > server = smtplib.SMTP('mail.hennepinPublicHealth.org') > File "C:\Program Files\Python\lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Program Files\Python\lib\smtplib.py", line 307, in connect > (code, msg) = self.getreply() > File "C:\Program Files\Python\lib\smtplib.py", line 348, in getreply > line = self.file.readline() > File "C:\Program Files\Python\lib\socket.py", line 340, in readline > data = self._sock.recv(self._rbufsize) > error: (10054, 'Connection reset by peer') 'Connection reset by peer' This occurs when a connection is terminated without going through the normal TCP close procedure. If localhost is giving you the same behavior, you should be able to learn why from your logs. Your code looks OK. I would expect that the issue lies with your network config or firewall(s). That mail server was happy to accept a connection from me, so I doubt if the problem is at the server. >>> import smtplib >>> c = smtplib.SMTP('mail.hennepinPublicHealth.org') >>> dir(c) ['__doc__', '__init__', '__module__', 'close', 'connect', 'data', 'debuglevel', 'docmd', 'does_esmtp', 'ehlo', 'ehlo_resp', 'esmtp_features', 'expn', 'file', 'getreply', 'has_extn', 'helo', 'helo_resp', 'help', 'local_hostname', 'login', 'mail', 'noop', 'putcmd', 'quit', 'rcpt', 'rset', 'send', 'sendmail', 'set_debuglevel', 'sock', 'starttls', 'verify', 'vrfy'] >>> c.close() > > *** > I also tried: > server = smtplib.SMTP('localhost') > > with the same result. > > I have checked several of the tutorials and FAQ sites and the impression > that's given is that this functionality is quite simple, so I assume that > I'm just missing one small step. > > Any suggestion would be much appreciated. > > Thank you. > Urban Landreman > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with class - get message that self is not defined
On Mon, 2006-05-22 at 14:28 -0400, Andrew Robert wrote: > When I try to use the class listed below, I get the statement that > self > is not defined. > > test=TriggerMessage(data) > var = test.decode(self.qname) Perhaps var = test.decode() would do what you want. It is not clear why you are trying to use a "qname" argument when decode's only argument is self. test.decode will bind self to the test object. Alan Gauld's web site has a useful discussion of OOP programming. http://www.freenetpages.co.uk/hp/alan.gauld -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with class - get message that self is not defined
(usually best to click reply-All so that the reply goes to the list) On Mon, 2006-05-22 at 15:08 -0400, Andrew Robert wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > Well.. inside the class is the decode function. The decode method depends on "data" which is referenced as a global. Perhaps data should be passed into decode as a second argument. My edited version: def decode(self, data): ^^ import struct format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' size=struct.calcsize(format) #self.data=data # not needed ^ ^^ self.structid, self.version, self.qname, self.processname, \ self.triggerdata, self.appltype, self.applid, \ self.envdata, self.userdata, self.qmgr \ = struct.unpack(format,data) ^ (removed self.) > > In that function, several variables are defined from a struct unpack. I am suggesting that the data to be unpacked gets passed into the decode method as an argument: test.decode(data) I changed the struct.unpack call to use the data argument. Some additional suggestions: size is never used. perhaps you want: assert size = import struct could be moved to the top of the script and imported once Hopefully this helps. > > What I need is to get those values out. > > How to do that, I am not exactly clear. > > > Andy > > > Python wrote: > > On Mon, 2006-05-22 at 14:28 -0400, Andrew Robert wrote: > >> When I try to use the class listed below, I get the statement that > >> self > >> is not defined. > >> > >> test=TriggerMessage(data) > >> var = test.decode(self.qname) > > > > Perhaps > > var = test.decode() > > > > would do what you want. > > > > It is not clear why you are trying to use a "qname" argument when > > decode's only argument is self. test.decode will bind self to the test > > object. > > > > Alan Gauld's web site has a useful discussion of OOP programming. > > http://www.freenetpages.co.uk/hp/alan.gauld > > > > - -- > Thank you, > Andrew Robert > Systems Architect > Information Technologies > MFS Investment Management > Phone: 617-954-5882 > > E-mail: [EMAIL PROTECTED] > Linux User Number: #201204 > -BEGIN PGP SIGNATURE- > Version: GnuPG v1.4.3 (MingW32) > > iD8DBQFEcgwoDvn/4H0LjDwRAsUuAJ94rHJbBQVxgHyLYlmi1pAhJzkE1QCfR1xK > sZlx+dHtvaZOOwRpC8tuN6o= > =2Nsp > -END PGP SIGNATURE- -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cisco router + telnetlib
On Wed, 2006-05-24 at 18:18 -0400, Daniel McQuay wrote: > Hello List, > > I am rather new to programming and I was wondering y'all think the > best way to configure a cisco router using python would be. currently > I am using telnetlib. my problem is, I get an error after connecting > to the router. here is the error I get when I use IDLE: > http://mail.python.org/pipermail/tutor/2006-March/045547.html This is part of an earlier thread about configuring routers using a script. I'd recommend using tcpwatch to debug the connection. The router may have sent an error message before closing the connection. Remember that the router software was designed for human interaction. tcpwatch will allow you to see both sides of the conversation. You'll see in the earlier thread that I'd also recommend using tftp to send most of the commands and limit the interactive telnet script to: logging on running tftp logging off > Enter IP: 205.180.0.3 > Warning: Problem with getpass. Passwords may be echoed. > Router Password: cisco > Warning: Problem with getpass. Passwords may be echoed. > Router Secret: class > Enter Router hostname: RouterBob > Traceback (most recent call last): > File "C:\Documents and Settings\bob\My Documents\Administration > \Scripts\cisco_config.py", line 20, in ? > tn.write("hostname " + hostName + "\n") > File "C:\Python24\lib\telnetlib.py", line 292, in write > self.sock.sendall(buffer) > File "", line 1, in sendall > error: (10053, 'Software caused connection abort') > >>> > > I have also attached the script that I use. could you please point me > in the right direction. > > thank you in advance, > > > -- > Daniel McQuay > boxster.homelinux.org > Dead Possum Productions > 814.825.0847 > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor