Re: Why NOT only one class per file?
John Nagle [EMAIL PROTECTED] wrote: systems that didn't work that way, in which the program source was manipulated within the language environment, in a more structured fashion. Smalltalk, LISP, and (wierdly) Forth environments have been built that way. But it never really caught on. APL was that way, too. And now the ACM wants to dissolve the APL SIG -- there just isn't anything much happening there any more:-( Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping issues
Larry Bates wrote: If the files aren't terribly large (not tested): correct_lines=open(rC:\Python25\Scripts\Output \ \correct_settings.txt, r).readlines() current_lines=open(rC:\Python25\Scripts\Output\output.txt, r).readlines() for line in current_settings: if line in correct_lines: print line + found You only have to read the inner file into memory, and a set is more efficient than a list here: current_settings = open(...) correct_settings = set(open(...)) for line in current_settings: if line in correct_settings: print line.rstrip(), found Of course your suggestion of difflib is spot-on. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re:
James Stroud jstroud at mbi.ucla.edu writes: C.L. wrote: I was looking for a function or method that would return the index to the first matching element in a list. ... ... __please don't be overly defensive__ ... The amount of typing wasted to defend design decisions such as this can boggle one's mind. Just use lists unless you have on overwhelming reason to do otherwise. James Read the quote. I *am* using a list. That doesn't change the fact that this is unfriendly design. It's an ugly inconsistent chunk of a Python's past in which built-in types didn't behave like objects. It sticks out like a sore thumb, maybe just not very often. Oh, and thanks for the insulting tone of your anticipated response. Have you anything better to do with your time than wasting bytes writing empty responses to what you already deem a waste of typing? *sighs* just what I expected: another idle troll defending something just for the sake of defending it. On the other hand, thanks 7stud, for the truly helpful response. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why NOT only one class per file?
Now we're at the '_/How many Angels can dance on the head of a pin/_' question (like anything with wings would waste time dancing. Ever seen eagles mate (not the football players)? Dance it's not, but it looks like /sex on a roller coaster only better/! Get me a pair of wings!). Religious war over please! They get me long winded (as you'll note if you keep reading). So, back to the original questions, now long forgotten. The questions (there were three) were: (1) Why does Java require each class be in a separate file? (2) Why Python has no such rule? And (3) Is there a reason I should do one or the other (I assume that means either, (3)(a) one class per file, regardless of language and/or (3)(b) Java or Python). -- evangelist flag off -- Answers: Question (1): There appear to be four answers to this question. (a) Don't know (most answers, but with some religious dogma attached. JAVA bad; PYTHON good and I worship PHP. Move the adj. around to suit your tastes). (b) KISS principle. /Keep It Simple, Stupid/. This is probably the right answer. Back then SUN, or as some of us remember '/Stanford University Network/' employed some sharp people (I must admit, my main reason for disliking SUN and CISCO was where they started. I was from UC Berkeley. It should have been UCBUN, or Uncle Buns; but that's just wouldn't sell. See how well BSD or 'bastard' sells). (c) Early Java development technology not up to n+1 classes in a single file. Reasonable from an old programmer's point of view. Those old IPC workstation didn't have that much memory. Small compiling jobs and executable loads would have been preferred if not required. I remember my first IPC had 4 Megabytes of RAM (boy did I have to beg for that box!) My Compaq 386/20 MHz computer, running MSDOS 3.1 only had 1 Meg and a Hercules graphics card (16 colors. I must have been good that year). I must have been a star, as most other's new hires were using '*/Bleeding Edge/*' computers (and if you don't know the reference, your just too young; think Gateway or Dell's cheap, hobbled products). File and more importantly, virus transfers where by /SneakerNet/. You young people have it too good; just one message via Exchange and you can infect a million computers in a thousand countries in moments. We had to work at it before we could take a day off as IT reloaded our computers. Thank God or Bill Gates, that companies keep buying a broken product. (d) Last. It was developed for vending machines (as someone pointed out, it started life as 'OAK'). Small memory foot print and a limited feature set were no brainers. '/We Taka the coins in, We dropa the Twinky out'. /The net's early domination by Unix variants and the Macintosh made Java's '/jack of all trades'/ a good solution. It was the main reason Microsoft tried (and failed) to '/Embrace and Extend'/ Java (Novell watch your ass; Microsoft wants to embrace and extend up your backside. SUN, just like a good Catholic girl said NO! (Or not in public! as the IBM/SCO trial seems to show)). So, pick an answers. It's God's fault/feature (sorry, I forget SUN != Microsoft), a programming dogma, hardware related or just old fashion growing pains. Probably some of each is the truth. Question (2): Python is a later generation language then Java. Without a SUN, Digital or Microsoft to push it, it had to serve it's users better. Design limitations, due to hardware (see HP and Korn shell) weren't a consideration. The main issue I could see, when I was first introduced to the Python language, was the reduction of overhead and limited ways of doing the same task (1/ Perl ^ n in my experience). The need to prettify code so other could read it, or more importantly, so other's couldn't read it (for job security), wasn't there. Python really is easy to learn, like Pascal was suppose to be. Python, like Java was OO from the word go (ok gcc for you purists), but was not syntactically a descendant of C++, so non-C++ programmers didn't need to pay homage to ATT (and God's only son, Bell Labs, from whence the Holy Ghost, Unix was created, destroyed and reborn as BSD. Is there a movie with Mell Gibson there? Remember, I said it first!). Freedom of vendors often means best of breed wins (i.e. most useful feature are includes). Freedom of vendors also means it hard to get into your shop (no one ever got fired for buying IBM after all). That takes care of why, I hope. _No doubt_ there's a few opinions left to be expressed. Who knows, they might stay on topic as well or better them I. Question (3): (3)(a) Is there a reason I should practice the 'One Class per File' rule? Answer is *yes,* when it makes your programming task easier and *no,* when
Re: Objects, lists and assigning values
Hello Gabriel, hello William, thanks to both of you for your answers. I seem to need a better book about python. Regards, Manuel Gabriel Genellina [EMAIL PROTECTED] writes: class new_class(object): def __init__(self, internal_list=None): if internal_list is None: internal_list = [] self.internal_list= internal_list See http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm -- Gabriel Genellina -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 -- http://mail.python.org/mailman/listinfo/python-list
Freeze vs cx_Freeze
Hello, I am currently investigating how to distribute a python based application on a targeted linux system (debian) and so far I only found two options: - Freeze (shipped with python dist) - cx_Freeze (*) As far as I understand those two options are very close. According to the cx_Freeze README cx_Freeze is simply easier to use (no dependencie of gcc, faster to create binaries) and it is cross-platform (no interest for me in this case). Anything else ? thanks, -MM (*) http://python.net/crew/atuining/cx_Freeze/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why NOT only one class per file?
John Nagle [EMAIL PROTECTED] writes: Interestingly, PHP breaks this model; PHP programs are web pages. They may be on to something. See also literate programming, including the version built into Haskell. -- http://mail.python.org/mailman/listinfo/python-list
Re: Freeze vs cx_Freeze
On Friday 06 April 2007 9:08 am, mathieu wrote: Hello, I am currently investigating how to distribute a python based application on a targeted linux system (debian) and so far I only found two options: - Freeze (shipped with python dist) - cx_Freeze (*) As far as I understand those two options are very close. According to the cx_Freeze README cx_Freeze is simply easier to use (no dependencie of gcc, faster to create binaries) and it is cross-platform (no interest for me in this case). Anything else ? http://pyinstaller.python-hosting.com/ Phil -- http://mail.python.org/mailman/listinfo/python-list
ANN: PyPE 2.8.5
=== What is PyPE? === PyPE (Python Programmers' Editor) was written in order to offer a lightweight but powerful editor for those who think emacs is too much and idle is too little. Syntax highlighting is included out of the box, as is multiple open documents via tabs. Beyond the basic functionality, PyPE offers an expandable source tree, filesystem browser, draggable document list, todo list, filterable function list, find and replace bars (no dialog to find or replace simple strings), recordable and programmable macros, spell checker, reconfigurable menu hotkeys, triggers, find in files, external process shells, and much more. === More Information === If you would like more information about PyPE, including screenshots, where to download the source or windows binaries, bug tracker, contact information, or a somewhat complete listing of PyPE's features, visit PyPE's home on the web: http://pype.sf.net/index.shtml If you have any questions about PyPE, please contact me, Josiah Carlson, aka the author of PyPE, at jcarlson at uci.edu (remember to include PyPE in the subject). PyPE 2.8.5 includes the following changes and bugfixes since release 2.8: (fixed) issue where double-clicking on a result while search was still going wouldn't actually go to the line of the result. (fixed) macros that use the line-based abstraction will now cause the parse timers to restart (just like hitting a keyboard key). (added) 'GotoLineS' utility method on stc instances for easy navigation to and selection of an entire line. (added) and disabled tagging tool. (fixed) commented/uncommented line discovery for latex documents. (fixed) vim option discovery when opening up latex documents. (added) the ability to disable individual tools if desired (disabling a tool prevents it from being updated, and may reduce tool refresh times). (fixed) calltips. (fixed) removed debug printouts for autocomplete. (fixed) View - Go To Line Number, now goes to the proper line (not the one after), and now will always show the content of the line. (changed) stopped using combined file/text drop targets, drags could cause extra copies of text to be pasted at the end of the document. (added) ability to have a read-only view of a document in the wide or tall tools. See View - Split Wide and Split Tall. Note that you can have two different documents displayed in either split. See View - Unsplit for hiding removing the view to the documents (the split views persist even if you close the open documents, but will not update if you close and re-open the closed document). (changed) moved search code (for the Search tab) use a separate thread in order to increase interactivity, and to prevent lockups due to bad regular expressions. (fixed) checkbox updating for showing or hiding wide or tall tools when using the keyboard to toggle them on some platforms. (known issue) sometimes when attempting to use keyboard shortcuts, PyPE will not recognize the keyboard shortcuts. Click on an open document to allow the keyboard shortcuts to work again. (fixed) the 'Ignore .subdirs' option in the 'Search' tab; if you add a path of foo/, and there was a foo/bar/.subdir, PyPE will now ignore foo/bar/.subdir . PyPE mistakenly only previously ignored foo/.subdir . (fixed) Option Document - Save Position will now properly go to the right position when there are document folds present. (changed) the way tree controls update their content during refresh. Should prevent unnecessary horizontal scrolling as was the case in PyPE 2.8, and be noticably faster. (fixed) classes or functions with the same names will no longer all be expanded in the browsable source trees when one is expanded. (fixed) icon update issues in the browsable source trees when classes, functions, or methods lose child nodes. (fixed) filter tool to not list #-- stuff -- style labels as having negative lengths, instead will have lengths of zero, and won't affect line counts otherwise. (changed) the included stc-styles.rc.cfg to make // comments the standard font size. (changed) adjusted the layout of the Find/Replace bar to use less horizontal space (really only noticable in the Replace bar). (fixed) pasting in a shell when non-editable data is selected will no longer change the non-editable data or result in an error dialog. -- http://mail.python.org/mailman/listinfo/python-list
Re: Objects, lists and assigning values
On Apr 6, 1:23 am, Manuel Graune [EMAIL PROTECTED] wrote: Hello Gabriel, hello William, thanks to both of you for your answers. I seem to need a better book about python. What book are you reading? -- http://mail.python.org/mailman/listinfo/python-list
Python on MIPS
Hi everybody, I bought a very small embedded card, with a MIPS processor, running Linux. So, I would to use Python on that; I checked on python.org, but I did'nt find any release for this architecture. Could you help me? -- http://mail.python.org/mailman/listinfo/python-list
Re: RFC: Assignment as expression (pre-PEP)
Gabriel Genellina [EMAIL PROTECTED] wrote: You have to build the handlers list, containing (regex, handler) items; the unknown case might be a match-all expression at the end. Well, after playing a bit with decorators I got this: snip That's a nice class, and more maintainable with the separate handler methods than a long function. Here's a completely untested variation. I hope the intent is clear: def handle_this(regex, handlers=handlers): # A decorator; associates the function to the regex # (Not intended to be used as a normal method! # not even a static method!) def register(function, regex=regex): handlers.append((function.__name__, regex)) return function return register ... insert handlers here ... def parse(self): regex = '|'.join(['(?P%s%s)' % pair for pair in self.handlers]) fields = str.split(self.name) for field in fields: match = regex.match(field) if match: handler = getattr(self, match.lastgroup, self.handle_unknown) handler(self, field, match) The handler functions themselves would have to be constrained to also use only named groups, but you gain by only having a single regex.match call on each field which could (if there are a lot of handlers) be significant. The calculation of regex could also of course be pulled out of parse to somewhere it only happens once for the class instead of once per instance. -- http://mail.python.org/mailman/listinfo/python-list
How to fix this? Sybase module and character set!!!!
C:\python msMdbPro2.py Traceback (most recent call last): File msMdbPro2.py, line 152, in ? main() File msMdbPro2.py, line 132, in main testSyb = SybaseProc(199477,'10.130.58.154','sa','','zxdb_ecity',173624) File msMdbPro2.py, line 44, in __init__ self.sybdata = Sybase.connect(hostip,user,pwd,databasename) File C:\Python24\lib\site-packages\Sybase.py, line 1087, in connect strip, auto_commit, delay_connect, locking, datetime) File C:\Python24\lib\site-packages\Sybase.py, line 866, in __init__ self.connect() File C:\Python24\lib\site-packages\Sybase.py, line 960, in connect status = conn.ct_connect(self.dsn) File C:\Python24\lib\site-packages\Sybase.py, line 200, in _servermsg_cb raise DatabaseError(_fmt_server(msg)) Sybase.DatabaseError: Msg 2401, Level 11, State 2 Character set conversion is not available between client character set 'iso_1' and server character set 'eucgb'. Msg 2411, Level 10, State 1 No conversions will be done. Msg 2415, Level 10, State 1 Due to previous errors, the language for this session is being forced to 'us_english'. How to change the client(My python program)'s character set from iso_1 to eucgb(Chinese gb2312)? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyPE 2.8.5
Josiah Carlson wrote: === What is PyPE? === PyPE (Python Programmers' Editor) was written in order to offer a lightweight but powerful editor for those who think emacs is too much and idle is too little. Syntax highlighting is included out of the box, as is multiple open documents via tabs. Very beautiful, Josiah ! Not only very nice as an IDE, but also to show the possibilities (and some of the limitations) of wxPython, wxWidgets. A few remarks, - example macros are placed one level to deep, so you won't see them - you didn't include the run current Python script macro - why not (also) place this announcement in the python-announce-list@python.org -- cheers, Stef Mientki http://pic.flappie.nl -- http://mail.python.org/mailman/listinfo/python-list
BaseHTTPRequestHandler reading .html with python code
H! I was wondering how I can do something like this. file.html - bhello world/b special pythoncodetag print 'hello world' #or display str(time.localtime()[7]) /special pythoncodetag webserver.py - def do_GET(self): try: if self.path.endswith(.html): f = open(curdir + sep + self.path) #self.path has / test.html self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # now display the bhello world/b and run the python code. self.wfile.write(f.read()) f.close() return I saw the mod python for apache and some PSP but I really want to know how they do this. Is there are special module for doing this ? Or is there something like this: --- 1. a running python program 2. include with write(f.read()) a extra python code inside the already running python program. How they handle this ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping issues
On Apr 5, 8:01 pm, [EMAIL PROTECTED] wrote: What I am trying to do is compare two files to each other. If the 2nd file contains the same line the first file contains, I want to print it. I wrote up the following code: correct_settings = open(C:\Python25\Scripts\Output \correct_settings.txt,r) current_settings = open(C:\Python25\Scripts\Output\output.txt,r) for line in correct_settings: for val in current_settings: if val == line: print line + found. correct_settings.close() current_settings.close() For some reason this only looks at the first line of the correct_settings.txt file. Any ideas as to how i can loop through each line of the correct_settings file instead of just looking at the first? I'm not entirely sure I understand what you're trying to do, but in case you're trying to walk through the two files in lockstep printing the lines that correspond, here's a way to do that: # note the r'..' syntax correct = open(r'c:\python25\scripts\output\correct_settings.txt') current = open(r'c:\python25\scripts\output\output.txt') for correct_line, current_line in zip(correct, current): if correct_line == current_line: print correct_line, 'found.' correct.close() current.close() hth, -- bjorn -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing of folder structure in SQL DB
Amit Khemka: On 5 Apr 2007 04:58:22 -0700, Sergei Minayev [EMAIL PROTECTED] wrote: Hi All! Can you please help me with the following problem: I need to store a copy of local folders structure in MySQL database. I have chosen the following table structure for that: | id | id_uplink | folder_name | id - unique property of each folder. id_uplink - id of upper level folder is stored here (for example: if id of c:\test is 1, than id_uplink of c:\test\python equals 1). folder_name - name of folder. You see, i dont want to store the path list, but the structure. The question is how to implement that in Python. I easily made it in C+ + using recursion. But, unfortunately, I can't figure it out how to make it in python using os.walk function (or can you recommend smth. else???). :( Though it looks quite simple, but anyway. Best Regards, os.walk should be more than sufficient in your case. You can navigate the directory structure and at each 'new' directory find its parents id and assign a new-id to this 'new' directory. An Example: import os root='/my/root/directory' id =0 tree={root:(-1, id)} id+=1 for path, dirs, files in os.walk(root): for dir in dirs: if not tree.has_key(path+'/'+dir): tree[path+'/'+dir]=(tree[path][1], id) id+=1 It stores ids as a tuple (parent_id, id) in a dictionary(tree). Should be straight forward to modify to your requirements. Also you can make the following code more efficient by saving/caching some lookups ! Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. Thanks! Your code example was really helpful! -- http://mail.python.org/mailman/listinfo/python-list
[optparse] Problem with getting an option value
Hello all. I'm trying to do a little script. Simply I want to make a list of all options with them default values. If the option is not specified in the command line, the script must try to read it in a config.ini file. If it's not present also there, it must set the default value. The problem is I maked a simple list for this: optname = [ [ delete, False ], [ file, file ], [ dir, ], But I must check that the option was specified in command line: (options, args) = parser.parse_args() for opt in optname : if not options.opt[0] : # read the options from config.ini The problem is options is an instance, so options.delete, for example, is wrong; I should pass options.delete . How can I do? -- Protect yourself from spam, use http://sneakemail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on MIPS
Lorenzo Mainardi schrieb: I bought a very small embedded card, with a MIPS processor, running Linux. So, I would to use Python on that; I checked on python.org, but I did'nt find any release for this architecture. Could you help me? How about compiling it from source? Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter canvas mvc
Gigs_ wrote: Hi all! I have just finished my tkinter text editor, learning tkinter purpose. Now I want to learn canvas so I want to make my paint program, I think that this will be the best to do over model-view-controler pattern which I need to learn also. Is there any good tutorial for mvc in python or can someone explain me little bit about mvc? or maybe some code snippet in mvc, that will be nice. Thanks in advance! MVC in a nutshell. 1. You need a model. 2. You need a view. 3. You need a controller. Lets see how they work together, using dictionary-like interfaces: class Model(dict): pass class View(object): def __init__(self, controller, keys): self.controller = controller self.widgets = {} for k in keys: w = make_a_widget(k) def _callback(w=w): v = w.get_value() self.controller[k] = v w.bind(SomeEvent, _callback) self.widgets[k] = w self.controller.register_view(self) def __setitem__(self, k, v): self.widgets[k].set_value(v) def __contains__(self, k): return k in self.widgets class Controller(object): def __init__(self, model): self.views = [] self.data = model def register_view(self, aview): self.views.append(aview) def __setitem__(self, k, v): self.data[k] = v for aview in self.views: if k in aview: aview[k] = v def __getitem__(self, k): return self.data[k] def update(self, adict): self.data.update(adict) for k,v in adict.items(): for aview in self.views: if k in aview: aview[k] = v James -- http://mail.python.org/mailman/listinfo/python-list
Using os.popen3() to get binary data
Hello everybody, I need to get the different frames from a GIF image in my python script and want to use the giftopnm program from netpbm to get the frames and directly convert them to pnm files. I tried to use the following code: for image in images: if (image[0:3] == 'GIF'): (si, so, se) = os.popen3('giftopnm -image=all', 'b') si.write(image) frame = so.readlines() But with this code the script just hangs. When I interrupt the script, I get the following error message: Traceback (most recent call last): File /home/tiger/stock-spam/scripts/all_in_one.py, line 46, in ? frames = so.readlines() KeyboardInterrupt close failed: [Errno 32] Broken pipe Can somebody tell me, which command I have to use that the pipe will be closed when the giftopnm returns? This program just prints the converted images to stdout and terminates. Thanks in advance, Christoph -- http://mail.python.org/mailman/listinfo/python-list
Comments in ConfigParser module
Hi list: I have run across a situation with ConfigParser Module. It refers to the comments in the configuration filed. According to the http://docs.python.org/dev/lib/module-ConfigParser.html it states that lines starting with # and ; are ignored. So lines like: ; comment # comment are considered comments. So far so good. The module also allows the comments to appear in the same line as the name = value constructs. The only difference being that this is only possible with ; and not with # character. I did not see this in the documentation but this is how it is behaving. So while the following line takes the comment as a comment. *name = value ; comment* the next line does not result in the same behavior. *name = value # comment* the name element would have value # comment as its value, when what I really want is for comment to be taken as a comment. QUESTION...So the question is: Can you use # and ; as comment characters? and if so why does the # not apply for the same situations as the ;? I'm working with fc7 (I synced it sometime last week) and python 2.5 (r25:51908, Feb 13 2007, 09:13:20) Any comment greatly appreciated Just for reference: On the RFC 822 http://www.faqs.org/rfcs/rfc822.html (a document referenced in the documentation) there is a mention of ; being used as comment character but not necessarily at the beginning of the line. So anything that comes after the ; is ignored. name = value ; comment (;comment would be ignored) -- http://mail.python.org/mailman/listinfo/python-list
Re: [optparse] Problem with getting an option value
Lucas Malor wrote: Hello all. I'm trying to do a little script. Simply I want to make a list of all options with them default values. If the option is not specified in the command line, the script must try to read it in a config.ini file. If it's not present also there, it must set the default value. The problem is I maked a simple list for this: optname = [ [ delete, False ], [ file, file ], [ dir, ], But I must check that the option was specified in command line: (options, args) = parser.parse_args() for opt in optname : if not options.opt[0] : # read the options from config.ini The problem is options is an instance, so options.delete, for example, is wrong; I should pass options.delete . How can I do? Use getattr(): for name, default_value in optname: if getattr(options, name) == default_value: value = ... # read value from config file setattr(options, name, value) Personally, I would always read the config file, use the values found there to set up the parser and avoid such post-processing. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re:
C.L. wrote: James Stroud jstroud at mbi.ucla.edu writes: C.L. wrote: I was looking for a function or method that would return the index to the first matching element in a list. ... ... __please don't be overly defensive__ ... The amount of typing wasted to defend design decisions such as this can boggle one's mind. Just use lists unless you have on overwhelming reason to do otherwise. James Read the quote. I *am* using a list. That doesn't change the fact that this is unfriendly design. It's an ugly inconsistent chunk of a Python's past in which built-in types didn't behave like objects. It sticks out like a sore thumb, maybe just not very often. OK, if you want a *reason*, the *reason* is that tuples were originally intended to be used in the same way that tuples are used in mathematics: as an ordered collection of dissimilar objects. Given that the sequence held by a tuple wasn't intended to be homogeneous it didn't originally make sense to be able to find something (which would of necessity be of a particular type) in it. Of course much has changed since then, and nowadays the world goes in for tuple-abuse. Consequently the majority don't appear to understand why tuple doesn't become simply an immutable list. But you have clearly found the preferred solution on your own, so this is basically just a history lesson. Glad you asked? Is your thumb any less sore. Oh, and thanks for the insulting tone of your anticipated response. Have you anything better to do with your time than wasting bytes writing empty responses to what you already deem a waste of typing? I'd have thought you would have saved time simply by refusing to rise to what you clearly see as bait. *sighs* just what I expected: another idle troll defending something just for the sake of defending it. On the other hand, thanks 7stud, for the truly helpful response. Get over it. This is Usenet, abuse is next door. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: About python Sybase module and the database manipulation!
boyeestudio wrote: I write a python program which can insert one record into the Sybase databae at a time using the function fetchone(),But I find it runs slowly. So I want speed it up,But I don't know how to manipulate the database more efficiently! Thread or any other methods can do it?? Since fetchone() is for *retrieval* of data from a database and since you don't show us your code it's difficult to know what to suggest. If you let us have an example it will be easier to tell you why your code doesn't run fast enough. You may wish to look at executemany() if you have lots of insertions to make. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Using os.popen3() to get binary data
Christoph Krammer schrieb: for image in images: if (image[0:3] == 'GIF'): (si, so, se) = os.popen3('giftopnm -image=all', 'b') si.write(image) frame = so.readlines() But with this code the script just hangs. When I interrupt the script, I get the following error message: Traceback (most recent call last): File /home/tiger/stock-spam/scripts/all_in_one.py, line 46, in ? frames = so.readlines() KeyboardInterrupt close failed: [Errno 32] Broken pipe Just a try: use read() instead of readlines()! Thomas -- http://mail.python.org/mailman/listinfo/python-list
Getting Stack Trace on segfault
Hello All, The built-in mac osx vecLib is segfaulting in some cases--A very fun fact to find out the hard way over two nights of work. I also spent an embarrassing amount of time figuring out just where. Although I'm in quite a self-congratulatory mood right now, in the future, I feel like I could save a lot of time by coercing the interpreter to spew forth method calls to stderr. Is this possible? I would hope to produce something hauntingly reminiscent of [] my_function [my_function] another_function [my_function - another_function] yet_a_deeper_function Presentation, of course, is irrelevant. I read the docs on pdb, but it did not seem to do what I want--unless, of course, I missed something. James -- http://mail.python.org/mailman/listinfo/python-list
Simple mx.ODBC prob seeks simple answer
Hello all, I'm having trouble inserting an SQL selection into a new MS Access table. I get a parameter error on my insert statement when I try this (see below for code and error msg). I'm not sure if 'insert' or 'update' is the route I should be taking. CODE: #Import Pythond Standard Library Modules import win32com.client, sys, os, string, copy, glob import mx.ODBC.Windows as odbc # Create the Geoprocessor Object gp = win32com.client.Dispatch(esriGeoprocessing.GpDispatch.1) gp.overwriteoutput = 1 # Variables tempspace = C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs Shapefiles\TEST.mdb workspace = string.replace(tempspace,\\,/) worksheet1 = Mower_I worksheet2 = Mower_II #Conection to Access driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace conn = odbc.DriverConnect(driv) curse = conn.cursor() #Drop Tables if they already exist try: curse.execute('Drop table Table_I') curse.execute('Drop table Table_II') curse.execute('Drop table Checker') except: pass #Create a New Tables curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN TEXT(4))') curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') conn.commit() #Upload DBF 1 as a List of Tuples: Returns tuple as ('102150','BMP') sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 curse.execute(sql) x = curse.fetchall() #Put the fetched Data into Table_II for i in x: curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) conn.commit() conn.close() TRACEBACK ERROR MSG: Traceback (most recent call last): File C:/Documents and Settings/corr1gre/Desktop/Workspace/Python/ArcGIS Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py, line 40, in ? curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.', 4612) -- View this message in context: http://www.nabble.com/Simple-mx.ODBC-prob-seeks-simple-answer-tf3536661.html#a9871804 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: elementary tuple question. (sorry)
On Apr 6, 5:31 am, 7stud [EMAIL PROTECTED] wrote: On Apr 5, 3:08 pm, Steven W. Orr [EMAIL PROTECTED] wrote: I have a tuple that I got from struct.unpack. Now I want to pass the data from the returned tuple to struct.pack fmt 'l 10l 11i h 4h c 47c 0l'struct.pack(fmt, tup) Traceback (most recent call last): File stdin, line 1, in ? struct.error: required argument is not an integer What's the idiom to pass the data in tup? TIA import struct fmt = l l result = struct.pack(fmt, 12, 4) t = (12, 4) result = struct.pack(fmt, *t) - The * unpacks the tuple. there's an unpack(). struct.unpack(fmt,result) -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple mx.ODBC prob seeks simple answer
Greg Corradini wrote: Hello all, I'm having trouble inserting an SQL selection into a new MS Access table. I get a parameter error on my insert statement when I try this (see below for code and error msg). I'm not sure if 'insert' or 'update' is the route I should be taking. CODE: #Import Pythond Standard Library Modules import win32com.client, sys, os, string, copy, glob import mx.ODBC.Windows as odbc # Create the Geoprocessor Object gp = win32com.client.Dispatch(esriGeoprocessing.GpDispatch.1) gp.overwriteoutput = 1 # Variables tempspace = C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs Shapefiles\TEST.mdb workspace = string.replace(tempspace,\\,/) worksheet1 = Mower_I worksheet2 = Mower_II #Conection to Access driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace conn = odbc.DriverConnect(driv) curse = conn.cursor() #Drop Tables if they already exist try: curse.execute('Drop table Table_I') curse.execute('Drop table Table_II') curse.execute('Drop table Checker') except: pass #Create a New Tables curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN TEXT(4))') curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') conn.commit() #Upload DBF 1 as a List of Tuples: Returns tuple as ('102150','BMP') sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 curse.execute(sql) x = curse.fetchall() #Put the fetched Data into Table_II for i in x: curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) conn.commit() conn.close() TRACEBACK ERROR MSG: Traceback (most recent call last): File C:/Documents and Settings/corr1gre/Desktop/Workspace/Python/ArcGIS Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py, line 40, in ? curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.', 4612) That error usually occurs when you use a name that isn't defined int he database (typically I mistype a column name) - the JET engine then thinks it's missing a value for some parameter. In your case it's because you aren't surrounding the string literal value for TISCODE in your statement with the appropriate '' single quotes. The engine thus parses it as a name, hence the assumption that a parameter is missing. It's actually good that you have made this error, because it allows me to expound yet again on the dangers of constructing your own SQL statements instead of using parameterised statements. In the case of mxODBC the correct parameter mark to use is a question mark. You should then supply the data to be substituted for the parameter marks as a tuple argument to the cursor's execute() method. So what you really need is: #Put the fetched Data into Table_II for i in x: curse.execute(Insert into Table_II (TISCODE,EXISTSIN) values (?, ?), i) conn.commit() conn.close() A couple of other points: 1. It would actually be better to put the commit() call outside the loop. This is not only more efficient but it defines the whole set of changes as a transaction. 2. It would be even more efficient not to use a loop at all but to use the cursor's executemany() method to perform all inserts with a single call as follows: #Put the fetched Data into Table_II curse.executemany(Insert into Table_II (TISCODE,EXISTSIN) values (?, ?), x) conn.commit() conn.close() For more on using the DBI API, including something about the risks of SQL injection vulnerabilities, take a look at the notes from my PyCon tutorial at http://www.holdenweb.com/PyConTX2007/dbapi.tgz regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove multiple occurrences of a string within a list?
On Wed, 04 Apr 2007 15:56:34 +0200, Hendrik van Rooyen wrote: Now how would one do it and preserve the original order? This apparently simple problem is surprisingly FOS... But list comprehension to the rescue : [x for x in duplist if duplist.count(x) == 1] ['haha', 5, 6] *shakes head* duh... why does it take so long? Because you are using Shlemiel the painter's algorithm: http://www.joelonsoftware.com/articles/fog000319.html Each time you call duplist.count(), you go back to the beginning of the list and walk the entire list. You end up walking the list over and over and over again. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
C.L. wrote: That doesn't change the fact that this is unfriendly design. It's an ugly inconsistent chunk of a Python's past in which built-in types didn't behave like objects. It sticks out like a sore thumb, maybe just not very often. When this topic last appeared on my radar, I ended up writing a long message about it: http://groups.google.com/group/comp.lang.python/msg/30e89128bdeb59c0 [...] *sighs* just what I expected: another idle troll defending something just for the sake of defending it. On the other hand, thanks 7stud, for the truly helpful response. The problem with 7stud's quote from GvR is that it's out of date: tuples do have methods now, as you've noticed, but just not the index method. Previously, I've missed that method, and it wouldn't be hard to add it to the tuple class (in CPython's own source code), but one has to wonder whether it's really necessary, or at least as necessary as for other classes. Certainly, there's a trade-off between essential functionality and having, say, 100 methods which are all useful to someone but which make interactive introspection a rather tedious and confusing business. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Plugin architecture - how to do?
On Apr 5, 10:57 am, [EMAIL PROTECTED] wrote: I'm making a program that consists of a main engine + plugins. Both are in Python. My question is, how do I go about importing arbitrary code and have it be able to use the engine's functions, classes, etc? For a true plugin architecture, you don't have the main engine calling methods on the plugin. What you do is have an API on your engine with methods the plugin can call and events it can hook into. The events are how the engine communicates state to any plugins, without having to know who they are or what they do. Your engine has a configuration that tells it what plugins to load (which the plugins presumably modified when they installed themselves) or otherwise has some standard way that the engine can figure out what plugins need to be loaded. Now granted, I don't specifically know how to do this via python.. but, maybe what I've said will send you in the right direction. -Nate -- http://mail.python.org/mailman/listinfo/python-list
Re: Why NOT only one class per file?
On Wed, 04 Apr 2007 14:23:19 -0700, Chris Lasher wrote: A friend of mine with a programming background in Java and Perl places each class in its own separate file in . I informed him that keeping all related classes together in a single file is more in the Python idiom than one file per class. He asked why, and frankly, his valid question has me flummoxed. Hah! Writing one class per file is for wimps! When I program, I write one *method* per file, then import them and build the class at runtime. I have a friend who writes one *line* per file, then pulls them all together with exec(), but that's just being stupid. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using os.popen3() to get binary data
Just got the solution... After sending the image data with si.write(image), I have to close the pipe to tell the program to convert the image with si.close(). Now everything works fine. Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: low level networking in python
On 4/4/07, Irmen de Jong [EMAIL PROTECTED] wrote: Maxim Veksler wrote: I'm trying to bind a non-blocking socket, here is my code: #!/usr/bin/env python import socket, select from time import sleep s_nb1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s_nb1.setblocking(0) s_nb1.bind(('192.168.2.106', 10002)) s_nb1.listen(5) while 1: conn, addr = s_nb1.accept() ready_to_read, ready_to_write, in_error = select.select([conn], [], [], 0) print (ready_to_read, ready_to_write, in_error) sleep(100) s_nb1.close() And this is the exception I'm getting: python non_blocking_socket.py Traceback (most recent call last): File non_blocking_socket.py, line 13, in ? conn, addr = s_nb1.accept() File /usr/lib/python2.4/socket.py, line 161, in accept sock, addr = self._sock.accept() socket.error: (11, 'Resource temporarily unavailable') What am I doing wrong here? Nothing. Any operation on a non-blocking socket that is usually blocking (this includes accept(), bind(), connect(), recv with MSG_WAITALL) can possibly return a socket.error with errno set to EAGAIN. ('resource temporarily unavailable'). If this happens you should use a select() on the socket to wait until it's done with the requested operation. Hello everyone, I would like to thank you all for the helping tips so far, with your help I managed to improve the previous code to not give the error, I believe it's now working. The non blocking echo socket code: #!/usr/bin/env python import socket, select s_nb1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s_nb1.setblocking(0) s_nb1.bind(('0.0.0.0', 10002)) s_nb1.listen(5) while 1: ready_to_read, ready_to_write, in_error = select.select([s_nb1], [], [], 0) if s_nb1 in ready_to_read: conn, addr = s_nb1.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() s_nb1.close() --Irmen Maxim. -- Cheers, Maxim Veksler Free as in Freedom - Do u GNU ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract zip file from email attachment
On Apr 6, 12:51 am, Gabriel Genellina [EMAIL PROTECTED] wrote: erikcw wrote: resp = p.retr(msg_num) if resp[0].startswith('+OK'): You don't have to check this; errors are transformed into exceptions. fileObj = StringIO.StringIO() cStringIO is faster fileObj.write( part.get_payload() ) You have to reset the file pointer to the beginning: fileObj.seek(0), else ZipFile will not be able to read the contents. -- Gabriel Genellina Hi Gabriel, I added fileObj.seek(0) on the line directly after fileObj.write( part.get_payload() ) and I'm still getting the following error. Traceback (most recent call last): File wa.py, line 209, in module attachment = zipfile.ZipFile(fileObj) File /usr/lib/python2.5/zipfile.py, line 346, in __init__ self._GetContents() File /usr/lib/python2.5/zipfile.py, line 366, in _GetContents self._RealGetContents() File /usr/lib/python2.5/zipfile.py, line 378, in _RealGetContents raise BadZipfile, File is not a zip file zipfile.BadZipfile: File is not a zip file Could the file like object still be encoded in MIME or something? Thanks! Erik -- http://mail.python.org/mailman/listinfo/python-list
How to access multiple group matches?
Hello, I want to use the re module to split a data stream that consists of several blocks of data. I use the following code: iter = re.finditer('^(HEADER\n.*)+$', data) The data variable contains binary data that has the word HEADER in it in some places and binary data after this word till the next appearance of header or the end of the file. But if I iterate over iter, I only get one match and this match only contains one group. How to access the other matches? Data may contain tens of them. Thanks in advance, Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple mx.ODBC prob seeks simple answer
Thanks Steve, Once again your advice solved the problem Greg Steve Holden wrote: Greg Corradini wrote: Hello all, I'm having trouble inserting an SQL selection into a new MS Access table. I get a parameter error on my insert statement when I try this (see below for code and error msg). I'm not sure if 'insert' or 'update' is the route I should be taking. CODE: #Import Pythond Standard Library Modules import win32com.client, sys, os, string, copy, glob import mx.ODBC.Windows as odbc # Create the Geoprocessor Object gp = win32com.client.Dispatch(esriGeoprocessing.GpDispatch.1) gp.overwriteoutput = 1 # Variables tempspace = C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs Shapefiles\TEST.mdb workspace = string.replace(tempspace,\\,/) worksheet1 = Mower_I worksheet2 = Mower_II #Conection to Access driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace conn = odbc.DriverConnect(driv) curse = conn.cursor() #Drop Tables if they already exist try: curse.execute('Drop table Table_I') curse.execute('Drop table Table_II') curse.execute('Drop table Checker') except: pass #Create a New Tables curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN TEXT(4))') curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') conn.commit() #Upload DBF 1 as a List of Tuples: Returns tuple as ('102150','BMP') sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 curse.execute(sql) x = curse.fetchall() #Put the fetched Data into Table_II for i in x: curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) conn.commit() conn.close() TRACEBACK ERROR MSG: Traceback (most recent call last): File C:/Documents and Settings/corr1gre/Desktop/Workspace/Python/ArcGIS Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py, line 40, in ? curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.', 4612) That error usually occurs when you use a name that isn't defined int he database (typically I mistype a column name) - the JET engine then thinks it's missing a value for some parameter. In your case it's because you aren't surrounding the string literal value for TISCODE in your statement with the appropriate '' single quotes. The engine thus parses it as a name, hence the assumption that a parameter is missing. It's actually good that you have made this error, because it allows me to expound yet again on the dangers of constructing your own SQL statements instead of using parameterised statements. In the case of mxODBC the correct parameter mark to use is a question mark. You should then supply the data to be substituted for the parameter marks as a tuple argument to the cursor's execute() method. So what you really need is: #Put the fetched Data into Table_II for i in x: curse.execute(Insert into Table_II (TISCODE,EXISTSIN) values (?, ?), i) conn.commit() conn.close() A couple of other points: 1. It would actually be better to put the commit() call outside the loop. This is not only more efficient but it defines the whole set of changes as a transaction. 2. It would be even more efficient not to use a loop at all but to use the cursor's executemany() method to perform all inserts with a single call as follows: #Put the fetched Data into Table_II curse.executemany(Insert into Table_II (TISCODE,EXISTSIN) values (?, ?), x) conn.commit() conn.close() For more on using the DBI API, including something about the risks of SQL injection vulnerabilities, take a look at the notes from my PyCon tutorial at http://www.holdenweb.com/PyConTX2007/dbapi.tgz regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list -- View this message in context: http://www.nabble.com/Simple-mx.ODBC-prob-seeks-simple-answer-tf3536661.html#a9873176 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting Stack Trace on segfault
On Apr 6, 7:13 am, James Stroud [EMAIL PROTECTED] wrote: Hello All, The built-in mac osx vecLib is segfaulting in some cases--A very fun fact to find out the hard way over two nights of work. I also spent an embarrassing amount of time figuring out just where. Although I'm in quite a self-congratulatory mood right now, in the future, I feel like I could save a lot of time by coercing the interpreter to spew forth method calls to stderr. Is this possible? I would hope to produce something hauntingly reminiscent of [] my_function [my_function] another_function [my_function - another_function] yet_a_deeper_function Presentation, of course, is irrelevant. I read the docs on pdb, but it did not seem to do what I want--unless, of course, I missed something. James Hi, I've never done that before, but I found a recipe that claims to do it with meta-classes. Check it out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078 I hope this gives you some ideas. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Why NOT only one class per file?
Steven D'Aprano wrote: On Wed, 04 Apr 2007 14:23:19 -0700, Chris Lasher wrote: A friend of mine with a programming background in Java and Perl places each class in its own separate file in . I informed him that keeping all related classes together in a single file is more in the Python idiom than one file per class. He asked why, and frankly, his valid question has me flummoxed. Hah! Writing one class per file is for wimps! When I program, I write one *method* per file, then import them and build the class at runtime. I have a friend who writes one *line* per file, then pulls them all together with exec(), but that's just being stupid. I guess you're one of those sissies who uses EDLIN as an editor. REAL programmers use COPY CON: ... :) -- http://mail.python.org/mailman/listinfo/python-list
Re: SNMP agent
In article [EMAIL PROTECTED], alain [EMAIL PROTECTED] wrote: . . . I still find it strange that, in all these years of existence, no one felt the need for a SNMP agent in Python. Do Pythoneers only write test tools and not real apps? . . . No, but I understand the question. Python has had considerable success with test tools, by the way. On the other hand, SNMP has become such a minor niche that its technologic implementations depend heavily on historical accident. The right combination of expertise-resources-need-... simply hasn't occurred for Python- based SNMP. I'll repeat: Tcl is the basis of Scotty, which, while largely unsupported now, remains quite usable. Perl is in a somewhat more primitive condition. I don't know of any other high-level language which can effectively boast of the ability to write SNMP agents. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Java
Steve Holden [EMAIL PROTECTED] wrote: Ed Jensen wrote: Steve Holden [EMAIL PROTECTED] wrote: Jython is an implementation of Python that compiles to Java bytecode, but at the moment there's some version lag so it won't handle the mos recent language enhancements. Probably worth a look, though. http://www.jython.org/ Does Jython compile to Java bytecode, or is Jython a Java implementation of a Python interpreter? Please read what I wrote again. I read it and understood it just fine. My question was meant more along the lines of, Are you SURE it compiles to Java bytecode, and isn't a Python interpreter written in Java? I guess I didn't make that clear. Anyway, I checked the Jython home page, and sure enough, Jython compiles Python code to Java bytecode, as stated in the FAQ which can be found at the following URL (in case anyone else reading this message is following along and is interested): http://www.jython.com/Project/userfaq.html#what-is-jython In particular: 1.1 What is Jython? Jython implements the Python programming language on the Java(tm) Platform. It consists of a compiler to compile Python source code down to Java bytecodes which can run directly on a JVM, a set of support libraries which are used by the compiled Java bytecodes, and extra support to make it trivial to use Java packages from within Jython. Sorry if I bothered/annoyed you, Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: [optparse] Problem with getting an option value
Peter Otten wrote: Lucas Malor wrote: Hello all. I'm trying to do a little script. Simply I want to make a list of all options with them default values. If the option is not specified in the command line, the script must try to read it in a config.ini file. If it's not present also there, it must set the default value. The problem is I maked a simple list for this: optname = [ [ delete, False ], [ file, file ], [ dir, ], But I must check that the option was specified in command line: (options, args) = parser.parse_args() for opt in optname : if not options.opt[0] : # read the options from config.ini The problem is options is an instance, so options.delete, for example, is wrong; I should pass options.delete . How can I do? Use getattr(): for name, default_value in optname: if getattr(options, name) == default_value: value = ... # read value from config file setattr(options, name, value) Personally, I would always read the config file, use the values found there to set up the parser and avoid such post-proc But then, if the command-line value == the default_value the program will try to get a value from the config file. If the config file overrides the defaults, then the command line can't re-override. Stuck with this, I usually initialize with None, then after all the option sources have been done, set anything that's still None to the default. It's not tidy. If even None could be a valid value, then a new None: class LikeNothingElse: '''Not a reasonable option value for anything''' # ... various code option_a = LikeNothingElse option_b = LikeNothingElse # ... process all the option sources if option_a == LikeNothingElse: option_a = None Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to access multiple group matches?
Christoph Krammer wrote: Hello, I want to use the re module to split a data stream that consists of several blocks of data. I use the following code: iter = re.finditer('^(HEADER\n.*)+$', data) The data variable contains binary data that has the word HEADER in it in some places and binary data after this word till the next appearance of header or the end of the file. But if I iterate over iter, I only get one match and this match only contains one group. How to access the other matches? Data may contain tens of them. Thanks in advance, Christoph Use .*? instead of .* in your regular expression. From the manual page: *|*?|, |+?|, |??|* The *, +, and ? qualifiers are all /greedy/; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE .* is matched against |'H1title/H1'|, it will match the entire string, and not just |'H1'|. Adding ? after the qualifier makes it perform the match in /non-greedy/ or /minimal/ fashion; as /few/ characters as possible will be matched. Using .*? in the previous expression will match only |'H1'|. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
block scope?
One thing I sometimes miss, which is common in some other languages (c++), is idea of block scope. It would be useful to have variables that did not outlive their block, primarily to avoid name clashes. This also leads to more readable code. I wonder if this has been discussed? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Java
Ed Jensen wrote: Steve Holden [EMAIL PROTECTED] wrote: Ed Jensen wrote: Steve Holden [EMAIL PROTECTED] wrote: Jython is an implementation of Python that compiles to Java bytecode, but at the moment there's some version lag so it won't handle the mos recent language enhancements. Probably worth a look, though. http://www.jython.org/ Does Jython compile to Java bytecode, or is Jython a Java implementation of a Python interpreter? Please read what I wrote again. I read it and understood it just fine. My question was meant more along the lines of, Are you SURE it compiles to Java bytecode, and isn't a Python interpreter written in Java? I guess I didn't make that clear. Anyway, I checked the Jython home page, and sure enough, Jython compiles Python code to Java bytecode, as stated in the FAQ which can be found at the following URL (in case anyone else reading this message is following along and is interested): http://www.jython.com/Project/userfaq.html#what-is-jython In particular: 1.1 What is Jython? Jython implements the Python programming language on the Java(tm) Platform. It consists of a compiler to compile Python source code down to Java bytecodes which can run directly on a JVM, a set of support libraries which are used by the compiled Java bytecodes, and extra support to make it trivial to use Java packages from within Jython. Sorry if I bothered/annoyed you, Steve. No real problem, I just thought I had already answered the question you asked. Of course the web reference was, as you'd expect, definitive, and your quoting it in this group will probably help those weho follow along. Glad it sounds like Jython might suit you - it's a great integration job! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
Neal Becker wrote: One thing I sometimes miss, which is common in some other languages (c++), is idea of block scope. It would be useful to have variables that did not outlive their block, primarily to avoid name clashes. This also leads to more readable code. I wonder if this has been discussed? Nested scopes were put into the language for function definitions, at least. Back in around 2.0, I believe, though that's lost in the mists of time for me as it's not a feature I use. I suspect, in fact, that those nested scopes have caused more trouble that they're worth, and continue to do so. Be that as it may, I don't think there's ever been any attempt to introduce scoping blocks into the language. Any ideas how you'd like it done? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Over a billion people believe Allah will provide 72 virgins to some Muslims.
On Apr 4, 6:31 pm, Dr. V I Plankenstein [EMAIL PROTECTED] wrote: The anthrax attack was almost certainly carried out by someone who had access to Gov labs or other secure facilities, but the attack on WTC was an act of Islamic fanaticism, and you're an ass to suggest otherwise without having some very solid proof to back your ridiculous claims - which you lack. You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. If the ODIOUS George W Bush did not inform the American Public (Who pays his salary) that Anthrax Attack was by a YANK BASTARD, then it must not be so. On the other hand if the Anthrax Attack was produced on such short notice and such coordination with the whole 911, then 911 was ALL done by yank bastards themselves and George W Bush is a prime suspect with all his underlings. ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank bastards themselves. -- http://mail.python.org/mailman/listinfo/python-list
Basic Serialization - a design decision question
Hello I am a relative newcomer to Python, and I am studying it to understand its design. It intrigues me. I recently studied Serialization of classes via the pickle/cPickle library, and I have a question. Why is Serialization handled by a separate library (ie, pickle). Is it possible, by design, to have serialization internally implemented via an implicit ___serialize___ method? Ofcourse, you have to make this method not overrideable (sp?). For example, the __repr__ method gives us the string representation of a class... similarly, the __serialize__ method would give us the serial norm representation of the class. This would allow me to do something like this, conn.send(serial(myClass)); // or something like that? Thoughts? -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
On 4/6/07, Neal Becker [EMAIL PROTECTED] wrote: One thing I sometimes miss, which is common in some other languages (c++), is idea of block scope. It would be useful to have variables that did not outlive their block, primarily to avoid name clashes. This also leads to more readable code. I wonder if this has been discussed? Block scope as a way to prevent name clashes is usually solved by refactoring (in C++, too) - if you can't disambiguate locals in a function it's usually a sign that your function does to much and needs to be broken up. Block scope as a way to control object lifetimes (automatic variables, or RAII) is addressed (in 2.5) by context managers or (pre-2.5) try/finally blocks. -- http://mail.python.org/mailman/listinfo/python-list
Dr Jeff King, A Jewish MIT Engineer is the LEAD SPEAKER on 911 truth, no Islamics involved http://video.google.com/videoplay?docid=1822764959599063248
See the video with your own EYEBALLS, that is if you have some courage and shame left: http://video.google.com/videoplay?docid=1822764959599063248 On Apr 6, 9:39 am, [EMAIL PROTECTED] wrote: On Apr 4, 6:31 pm, Dr. V I Plankenstein [EMAIL PROTECTED] wrote: The anthrax attack was almost certainly carried out by someone who had access to Gov labs or other secure facilities, but the attack on WTC was an act of Islamic fanaticism, and you're an ass to suggest otherwise without having some very solid proof to back your ridiculous claims - which you lack. You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. If the ODIOUS George W Bush did not inform the American Public (Who pays his salary) that Anthrax Attack was by a YANK BASTARD, then it must not be so. On the other hand if the Anthrax Attack was produced on such short notice and such coordination with the whole 911, then 911 was ALL done by yank bastards themselves and George W Bush is a prime suspect with all his underlings. ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank bastards themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question about sequence multiplication
Thanks to everyone that respondedI would never have figured that out. 7stud, Your suggestion is being considered lol, as there are a lot more bits of code in that book that I can't get running correctly. Any other books you'd, or anyone for that matter, would recommend as required reading? Free would be very very (read very) good, as you've already said the one I have isn't very viable and it cost me $50. Basically, what I'm saying is that if I go and spend another $50+ my wife is going to make it very hard to learn Python; after all, how much can I learn with a size 5 down my throat? lol Now when suggesting books, keep in mind that, that while I'm new to Python (and programming in general) I'm able to grasp difficult concepts as long as I have enough detail as to why it is the way it is. For instance I'm, by experience and nature, a computer technician and communications specialist. I've studied, everything from childrens walkie talkie to deep space satalittes back to how computers talk (which is why I'm here now trying to learn the language of computers). And all that just because I have a unquenchable desire to know. SO, with that all said, the more details the better. If you have a book with 4 chapters on functions..I want to read it. Any help would be greatly appreciated. As I've said, this is something that I feel I have to know. 7stud [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Apr 4, 4:48 pm, John Machin I suggest you get another book. I am currently reading that book, and unless you are an experienced programmer that can detect all the mistakes, and you have another book like Python in a Nutshell to fill in all the gaps, I don't think you can learn python from that book. I recently looked at Learning Python in the bookstore, and it seems a lot better. Unfortunately, it doesn't reflect the major changes in python over the last couple of years, but I would still recommend it over Beginning Python: From Novice to Professional. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on MIPS
Thomas Krüger ha scritto: Lorenzo Mainardi schrieb: I bought a very small embedded card, with a MIPS processor, running Linux. So, I would to use Python on that; I checked on python.org, but I did'nt find any release for this architecture. Could you help me? How about compiling it from source? Thomas I did'nt try...I will do that :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why NOT only one class per file?
On 4/6/07, Dennis Lee Bieber [EMAIL PROTECTED] wrote: For one liners, wouldn't ECHO the text line the.file be more appropriate? G # dd if=/dev/tty of=/dev/hda1 -- Greg Donald http://destiney.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter canvas
gigs wrote: I have made drawing area and few butons. How can I make when i click my fill button that later when i click on oval oval gets filled with chousen color? when later click on my oval that is drawn in to change oval color, or to fill color in oval if click in oval with mouse -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
Neal Becker [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | One thing I sometimes miss, which is common in some other languages (c++), | is idea of block scope. It would be useful to have variables that did not | outlive their block, primarily to avoid name clashes. This also leads to | more readable code. I wonder if this has been discussed? Yes, but Guido (and others) prefer to keep things simple. There is also the question of how to indicate a limited scope. In C++, you put the declaration in the scope. But Python has no such declarations. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Welch essential for learning Tkinter well?
In article [EMAIL PROTECTED], Kevin Walzer [EMAIL PROTECTED] wrote: James Stroud wrote: This begs the question, is anyone truly an expert in Tkinter? Frederick Lundh is, if anyone is. http://www.pythonware.com/library/tkinter/introduction/index.htm (outdated) http://effbot.org/tkinterbook/ (new but incomplete) I agree that this is an excellent resource. I find Welch's book and the on-line tcl/tk help very helpful for Tkinter programming--especially some of the more obscure details. But to use either of these resources comfortably you must learn the basics of Tkinter first (including understanding the simple mapping between Tkinter and Tcl/Tk). For learning the basics of Tkinter I suggest the links that Kevin listed above and/or Alex Martelli's Python in a Nutshell (an excellent reference in any case). Grayson's book is another reasonable alternative (and includes enough reference material to keep you from having to refer to the tcl/tk documentation very often). -- Russell -- http://mail.python.org/mailman/listinfo/python-list
Re: BaseHTTPRequestHandler reading .html with python code
On 6 avr, 11:52, [EMAIL PROTECTED] wrote: H! I was wondering how I can do something like this. Use a template engine like : Genshi Django/Jinja Cheetah Kid template For more engine look at http://www.turbogears.org/cogbin/ And maybe what you are looking fore is a complete framework like : turbogears pylon django Hope this help file.html - bhello world/b special pythoncodetag print 'hello world' #or display str(time.localtime()[7]) /special pythoncodetag webserver.py - def do_GET(self): try: if self.path.endswith(.html): f = open(curdir + sep + self.path) #self.path has / test.html self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # now display the bhello world/b and run the python code. self.wfile.write(f.read()) f.close() return I saw the mod python for apache and some PSP but I really want to know how they do this. Is there are special module for doing this ? Or is there something like this: --- 1. a running python program 2. include with write(f.read()) a extra python code inside the already running python program. How they handle this ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Prevent Modification of Script?
On Wednesday, Apr 4th 2007 at 18:04 -0700, quoth ts-dev: =Is it possible to prevent modification of a python file once its been =deployed? File permissions of the OS could be used..but that doesn't =seem very secure. = =The root of my question is verifying the integrity of the application =and the scripts being run. Is this possible, if so, how? I'm going to take a stab at this one even though I'm a really junior pythonian. I know others have already responded, but I'd like to offer a couple of suggestions that have nothing to do with python. (BTW, I do applaud the previous answers that suggest that this is really a non-problem in the first place.) 1. *IF* you are on a linux target platform then it's likely that you have a package management system in use, either rpm or deb. In either case, you have the ability to verify by checksum, every file of any package. In the case of rpm, just use the -V option. 2. You also have the ability to set the immutable flag on ext2/ext3 filesystems. See lsattr/chattr commands. Of course, if you can get root access then you can shut off immutability, but you can also replace your package management tools as well. AAAUUUGGGHHH!!! -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -- http://mail.python.org/mailman/listinfo/python-list
HTML Parser in python
Hi, Is there a HTML parser (not xml) in python? I need a html parser which has the ability to handle mal-format html pages. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Parser in python
On Apr 6, 1:05 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, Is there a HTML parser (not xml) in python? I need a html parser which has the ability to handle mal-format html pages. Thank you. Yeah...it's called Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ Mike -- http://mail.python.org/mailman/listinfo/python-list
Picture resolution and PIL
Is it possible to find out a picture resolution by using PIL package? Thanks for help L. -- http://mail.python.org/mailman/listinfo/python-list
Re: Picture resolution and PIL
On Apr 6, 1:16 pm, Johny [EMAIL PROTECTED] wrote: Is it possible to find out a picture resolution by using PIL package? Thanks for help L. Dunno. But I found some ways to read metadata that should give you the info in most cases: http://snippets.dzone.com/posts/show/768 http://hachoir.org/wiki/hachoir-metadata Hope that helps, Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Apr 6, 7:56 am, Paul Boddie [EMAIL PROTECTED] wrote: The problem with 7stud's quote from GvR is that it's out of date: I would argue that it shows the very guy who invented the language stated publicly there was no good reason for tuples not to have an index method---except for consistency; tuples had no other methods. Now that tuples have other methods, the only justification he stated no longer exists. -- http://mail.python.org/mailman/listinfo/python-list
real time updating of popen, bufsize=0 problems
hey all, I'm trying to get real time updates of batch file output. Here is my batch file: @echo off echo 1 @ping 127.0.0.1 -n 2 -w 1500 nul echo 2 @ping 127.0.0.1 -n 2 -w 1500 nul echo 3 If I run it in cmd.exe it will print 1, wait 15sec, print 2, wait 15sec, print 3. I tried doing it like this: r, w, e = popen2.popen3('C:/path/to/test.bat',bufsize=0) for line in r: self.display.WriteText(line) ... but get: ValueError: popen3() arg 3 must be -1 If I use -1, then it waits for the batch file to complete, and prints out all 3 lines at once. So I tried subprocess: proc = subprocess.Popen('C:/path/to/test.bat', bufsize=0, stdout=subprocess.PIPE) for line in proc.stdout: self.display.WriteText(line) No error message, but no real time printing either. info: self.display is a wx.TextCtrl - not that it should matter,as 'WriteText()' behaves basically like 'print' winXP pro SP2, python 2.5, wxPython 2.6.3.3 You help is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: zip files as nested modules?
Importing modules from zip files was proposed in PEP-273 [1] Here is how the spec of PEP-273 begins: ''' Currently, sys.path is a list of directory names as strings. If this PEP is implemented, an item of sys.path can be a string naming a zip file archive. ''' My interpretation of the above is that, to be importable, a zip file must be explicitly named in sys.path. So the mere fact that a zip file lies somewhere in a directory which is part of the sys.path does not make it importable. Cheers, Luciano [1] http://www.python.org/dev/peps/pep-0273/ -- http://mail.python.org/mailman/listinfo/python-list
Re:
C.L. wrote: James Stroud jstroud at mbi.ucla.edu writes: C.L. wrote: I was looking for a function or method that would return the index to the first matching element in a list. ... ... __please don't be overly defensive__ ... The amount of typing wasted to defend design decisions such as this can boggle one's mind. Just use lists unless you have on overwhelming reason to do otherwise. James Read the quote. I *am* using a list. That doesn't change the fact that this is unfriendly design. It's an ugly inconsistent chunk of a Python's past in which built-in types didn't behave like objects. It sticks out like a sore thumb, maybe just not very often. Oh, and thanks for the insulting tone of your anticipated response. Have you anything better to do with your time than wasting bytes writing empty responses to what you already deem a waste of typing? *sighs* just what I expected: another idle troll defending something just for the sake of defending it. On the other hand, thanks 7stud, for the truly helpful response. I think you misinterpreted my post, I agree with you. Please read it again. You have touched on a very old topic. Many people have fought tooth and nail to defend arbitrary design decisions such as a tuple not having an index. It boils down to the fact that tuples are useless as a result unless you know you really need them--and you never really NEED them. James -- http://mail.python.org/mailman/listinfo/python-list
SWIG, Python, C++, and Coca-Cola
Hi Everyone, Recently I have been working on building a module for Python from C++ code, with SWIG, and towards the end of compiling the various sets of code I'm getting an error. [comp:~/swig_project] user% swig -c++ -python example.i [comp:~/swig_project] user% g++ -c example.cpp [comp:~/swig_project] user% g++ -c example_wrap.cxx -I/scisoft/i386/ Packages/Python-2.4.3/Python.framework/Versions/2.4/include/python2.4/ example_wrap.cxx: In function 'PyObject* _wrap_main(PyObject*, PyObject*)': example_wrap.cxx:735: error: 'main' was not declared in this scope The beginning of example.i looks like the following: %module filename %{ #define file_plugin plugins/file.h #if foo_OS!=2 #include pthread.h #endif #include ../Foo.h using namespace foo_library; %} The error that is being picked up in reference to 'main' is contained in the following excerpt, generated by SWIG (example_wrap.cxx): /*--- @(target):= _filename.so */ #define SWIG_initinit_filename #define SWIG_name_filename #define cimg_plugin plugins/file.h #if foo_OS!=2 #include pthread.h #endif #include ../Foo.h using namespace foo_library; #ifdef __cplusplus extern C { #endif static PyObject *_wrap_main(PyObject *self, PyObject *args) { PyObject *resultobj; int arg1 ; char **arg2 = (char **) 0 ; int result; PyObject * obj1 = 0 ; if(!PyArg_ParseTuple(args,(char *)iO:main,arg1,obj1)) goto fail; if ((SWIG_ConvertPtr(obj1,(void **) arg2, SWIGTYPE_p_p_char,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail; result = (int)main(arg1,arg2); resultobj = PyInt_FromLong((long)result); return resultobj; fail: return NULL; } Any clues as to what is happening here or what to do next? If you know, your help would greatly help. Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: Picture resolution and PIL
Johny: Is it possible to find out a picture resolution by using PIL package By Gian Mario Tagliaretti: import PIL.Image a = PIL.Image.open(foo.jpg) a.info[dpi] (72, 72) (It may raise an exception if that information isn't available) I don't know if that can be used to read the DPI tag inside a TIFF image. You can also read the pixel size of any image. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Serialization - a design decision question
Gizmo wrote: Hello I am a relative newcomer to Python, and I am studying it to understand its design. It intrigues me. I recently studied Serialization of classes via the pickle/cPickle library, and I have a question. Why is Serialization handled by a separate library (ie, pickle). Is it possible, by design, to have serialization internally implemented via an implicit ___serialize___ method? Ofcourse, you have to make this method not overrideable (sp?). For example, the __repr__ method gives us the string representation of a class... similarly, the __serialize__ method would give us the serial norm representation of the class. This would allow me to do something like this, conn.send(serial(myClass)); // or something like that? Serialization is a complicated task. It needs at least a full module devoted to it just in terms of being able to implement it. Trying to stuff all of it into a builtin is asking for trouble. Of course, you can always do this: from cPickle import dumps ... conn.send(dumps(myClass)) -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Fri, 2007-04-06 at 11:33 -0700, 7stud wrote: On Apr 6, 7:56 am, Paul Boddie [EMAIL PROTECTED] wrote: The problem with 7stud's quote from GvR is that it's out of date: I would argue that it shows the very guy who invented the language stated publicly there was no good reason for tuples not to have an index method---except for consistency; tuples had no other methods. Now that tuples have other methods, the only justification he stated no longer exists. Except that that wasn't the only justification. GvR also said: For tuples, I suspect such a function would rarely be used; I think that is most cases where x.index() would be useful, x is generally a list, whose contents varies in time, rather than a tuple (which cannot change easily). The lack of convincing use cases is still a pertinent reason today. Note that the original poster on this thread did not present a use case for tuple.index, they were only asking out of curiosity. If you have a use case for tuple.index, please show it to me, and I'll show you what you should be using instead of a tuple. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
On Apr 6, 1:44 pm, ianaré [EMAIL PROTECTED] wrote: hey all, I'm trying to get real time updates of batch file output. Here is my batch file: @echo off echo 1 @ping 127.0.0.1 -n 2 -w 1500 nul echo 2 @ping 127.0.0.1 -n 2 -w 1500 nul echo 3 If I run it in cmd.exe it will print 1, wait 15sec, print 2, wait 15sec, print 3. I tried doing it like this: r, w, e = popen2.popen3('C:/path/to/test.bat',bufsize=0) for line in r: self.display.WriteText(line) ... but get: ValueError: popen3() arg 3 must be -1 If I use -1, then it waits for the batch file to complete, and prints out all 3 lines at once. So I tried subprocess: proc = subprocess.Popen('C:/path/to/test.bat', bufsize=0, stdout=subprocess.PIPE) for line in proc.stdout: self.display.WriteText(line) No error message, but no real time printing either. info: self.display is a wx.TextCtrl - not that it should matter,as 'WriteText()' behaves basically like 'print' winXP pro SP2, python 2.5, wxPython 2.6.3.3 You help is appreciated. Hi, I think this script on another post will help: http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en; The 4 line code example (from Daniel) in one of the posts at this link worked with your batch file: http://www.velocityreviews.com/forums/t350573-redirect-ossystem-output.html Mike -- http://mail.python.org/mailman/listinfo/python-list
Debugging multithreaded program using Eclipse/Pydev
I am back against the wall trying to migrate my multithreaded application from Python 2.3 to 2.5. The part of the code that's failing has to do with queues (2.3 queues and 2.5 queues are not the same). Since WingIDE doesn't support multithread debugging (they've been saying that one day they might support that - and that was 2003), I am starting to look for alternatives. From what I can gather, it appears the only *real* option I have is to debug under Eclipse/Pydev. I did a google search of this newsgroup and didn't turn up too many hits. Before I invest the time to learn Eclipse/Pydev, I like to hear from somebody that have gone this path. Have you been successful in using Eclipse/Pydev to debug multi- threaded Python applications? Is so, what was the learning curve like to you? Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
On Apr 6, 3:22 pm, [EMAIL PROTECTED] wrote: On Apr 6, 1:44 pm, ianaré [EMAIL PROTECTED] wrote: hey all, I'm trying to get real time updates of batch file output. Here is my batch file: @echo off echo 1 @ping 127.0.0.1 -n 2 -w 1500 nul echo 2 @ping 127.0.0.1 -n 2 -w 1500 nul echo 3 If I run it in cmd.exe it will print 1, wait 15sec, print 2, wait 15sec, print 3. I tried doing it like this: r, w, e = popen2.popen3('C:/path/to/test.bat',bufsize=0) for line in r: self.display.WriteText(line) ... but get: ValueError: popen3() arg 3 must be -1 If I use -1, then it waits for the batch file to complete, and prints out all 3 lines at once. So I tried subprocess: proc = subprocess.Popen('C:/path/to/test.bat', bufsize=0, stdout=subprocess.PIPE) for line in proc.stdout: self.display.WriteText(line) No error message, but no real time printing either. info: self.display is a wx.TextCtrl - not that it should matter,as 'WriteText()' behaves basically like 'print' winXP pro SP2, python 2.5, wxPython 2.6.3.3 You help is appreciated. Hi, I think this script on another post will help: http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?... The 4 line code example (from Daniel) in one of the posts at this link worked with your batch file:http://www.velocityreviews.com/forums/t350573-redirect-ossystem-outpu... Mike Thanks but it doesn't work. Still prints it out all at once. It is supposed to print, then wait 15sec for the next line to print. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question about sequence multiplication
Scott wrote: [...] Now when suggesting books, keep in mind that, that while I'm new to Python (and programming in general) I'm able to grasp difficult concepts as long as I have enough detail as to why it is the way it is. For instance I'm, by experience and nature, a computer technician and communications specialist. I've studied, everything from childrens walkie talkie to deep space satalittes back to how computers talk (which is why I'm here now trying to learn the language of computers). And all that just because I have a unquenchable desire to know. SO, with that all said, the more details the better. If you have a book with 4 chapters on functions..I want to read it. Any help would be greatly appreciated. As I've said, this is something that I feel I have to know. Dive into Python is probably the best free read about Python for programmers. It takes you in deep much more quickly that the tutorial, but if you can understand it you develop quite a sophisticated understanding of the language in a fairly short time. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Serialization - a design decision question
Gizmo wrote: Hello I am a relative newcomer to Python, and I am studying it to understand its design. It intrigues me. I recently studied Serialization of classes via the pickle/cPickle library, and I have a question. Why is Serialization handled by a separate library (ie, pickle). Is it possible, by design, to have serialization internally implemented via an implicit ___serialize___ method? Ofcourse, you have to make this method not overrideable (sp?). For example, the __repr__ method gives us the string representation of a class... similarly, the __serialize__ method would give us the serial norm representation of the class. This would allow me to do something like this, conn.send(serial(myClass)); // or something like that? Thoughts? It would be quite possible to do this - it just hasn't been done, is all. I'm not quite sure what advantage you see for serial(myClass) over pickle.dumps(myClass) though. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
ianaré [EMAIL PROTECTED] writes: hey all, I'm trying to get real time updates of batch file output. [...] So I tried subprocess: proc = subprocess.Popen('C:/path/to/test.bat', bufsize=0, stdout=subprocess.PIPE) Instead of that: for line in proc.stdout: self.display.WriteText(line) try that: while True: line = proc.stdout.readline() if not line: break self.display.WriteText(line) When a file is used in a for loop it works like an iterator. You can read details here (description of method ``next``): http://docs.python.org/lib/bltin-file-objects.html -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Parser in python
Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ Works, well...beautifully. -- http://mail.python.org/mailman/listinfo/python-list
British Marines Were tortured In Iran According to the Washington Conventions Re: Dr Jeff King, A Jewish MIT Engineer is the LEAD SPEAKER on 911 truth, no Islamics involved http://video.google.com/vid
We have just heard the news that the British Marines are ashamed to admit that they were tortured with Electric Wires to their Genitalia and two of them have had their penises bitten while a third ones testicles were eaten by an Iranian dog for the meal. People are now preferring the AbuGharib and Guantanamo style Washington Conventions over the Geneva Conventions. On Apr 6, 9:43 am, [EMAIL PROTECTED] wrote: See the video with your own EYEBALLS, that is if you have some courage and shame left: http://video.google.com/videoplay?docid=1822764959599063248 On Apr 6, 9:39 am, [EMAIL PROTECTED] wrote: On Apr 4, 6:31 pm, Dr. V I Plankenstein [EMAIL PROTECTED] wrote: The anthrax attack was almost certainly carried out by someone who had access to Gov labs or other secure facilities, but the attack on WTC was an act of Islamic fanaticism, and you're an ass to suggest otherwise without having some very solid proof to back your ridiculous claims - which you lack. You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. If the ODIOUS George W Bush did not inform the American Public (Who pays his salary) that Anthrax Attack was by a YANK BASTARD, then it must not be so. On the other hand if the Anthrax Attack was produced on such short notice and such coordination with the whole 911, then 911 was ALL done by yank bastards themselves and George W Bush is a prime suspect with all his underlings. ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank bastards themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
On Apr 6, 3:59 pm, Rob Wolfe [EMAIL PROTECTED] wrote: ianaré [EMAIL PROTECTED] writes: hey all, I'm trying to get real time updates of batch file output. [...] So I tried subprocess: proc = subprocess.Popen('C:/path/to/test.bat', bufsize=0, stdout=subprocess.PIPE) Instead of that: for line in proc.stdout: self.display.WriteText(line) try that: while True: line = proc.stdout.readline() if not line: break self.display.WriteText(line) When a file is used in a for loop it works like an iterator. You can read details here (description of method ``next``):http://docs.python.org/lib/bltin-file-objects.html -- HTH, Rob Rob, you are the man =) thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging multithreaded program using Eclipse/Pydev
On Apr 6, 2007, at 2:32 PM, John Henry wrote: I am back against the wall trying to migrate my multithreaded application from Python 2.3 to 2.5. The part of the code that's failing has to do with queues (2.3 queues and 2.5 queues are not the same). Since WingIDE doesn't support multithread debugging (they've been saying that one day they might support that - and that was 2003), I am starting to look for alternatives. The alpha release of Wing IDE (3.0.0-a1) does in fact, support multithread debugging. It is an alpha release but so far, I'm quite satisfied with it. hth, Michael -- http://mail.python.org/mailman/listinfo/python-list
Database Timestamp conversion error
Hi, I am populating a mySQL database with data from the MS Access database. I have successfully figured out how to extract the data from Access, and I can insert the data successfully into mySQL with Python. My problem is that I keep hitting screwy records with what appears to be a malformed dbiDate object when I insert certain records. I get the following traceback: Traceback (most recent call last): File \\someServer\Development\collectiveFleet.py, line 68, in - toplevel- mycursor.execute(sql) TypeError: argument 1 must be string without null bytes, not str When I print the timestamp variable, I get this output: (I31 (S'OK' p1 Nttp2 . If I look in the MS Access database, I see the timestamp as 5/6/112. Obviously some user didn't enter the correct date and the programmer before me didn't give Access strict enough rules to block bad dates. How do I test for a malformed date object so I can avoid this? There are thousands of records to transfer. I am using the odbc module for connection purposes with Python 2.4 on Windows XP SP2. Thanks a lot! Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Serialization - a design decision question
Gizmo [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Hello | I am a relative newcomer to Python, and I am studying it to understand its | design. It intrigues me. | I recently studied Serialization of classes via the pickle/cPickle library, | and I have a question. | | Why is Serialization handled by a separate library (ie, pickle). Is it | possible, by design, to have serialization internally implemented via an | implicit ___serialize___ method? Ofcourse, you have to make this method not | overrideable (sp?). For example, the __repr__ method gives us the string | representation of a class... similarly, the __serialize__ method would give | us the serial norm representation of the class. Pickle has the factored-out code common to all classes. It uses .__reduce__() for each, which has the class-specific code. | This would allow me to do something like this, | conn.send(serial(myClass)); // or something like that? I believe pickle does more than just that. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: British Marines Were tortured In Iran According to the Washington Conventions Re: Dr Jeff King, A Jewish MIT Engineer is the LEAD SPEAKER on 911 truth, no Islamics involved http://video.google.com
On Apr 6, 1:06 pm, [EMAIL PROTECTED] wrote: We have just heard the news that the British Marines are ashamed to admit that they were tortured with Electric Wires to their Genitalia and two of them have had their penises bitten while a third ones testicles were eaten by an Iranian dog for the meal. People are now preferring the AbuGharib and Guantanamo style Washington Conventions over the Geneva Conventions. stj911: That was indeed a good pun at the BASTARDS of the tribal bastards. Such CONTEMPTIBLE liars. There is no comparison between the bening Iranian treatment and the Bastards give in ABU-GHRAIB, and GUANTANAMO and the SECRET DETENTION CENTERS of the CRIMINAL INTERNATIONAL AGENCY whose chief at one time was the PEDOPHILE Herbert Walter Bush the most even man alive after his son. Even Newt Gingrich, who cheated on both his wives has not that much blood on his both hands. They were injected with LSD, carcinogens, poisons, mind altering drugs by the yank bastards. The zionist press has published these openly with relish and when it became an issue, the pawns were given contemptibly token punishment. On Apr 6, 9:43 am, [EMAIL PROTECTED] wrote: See the video with your own EYEBALLS, that is if you have some courage and shame left: http://video.google.com/videoplay?docid=1822764959599063248 On Apr 6, 9:39 am, [EMAIL PROTECTED] wrote: On Apr 4, 6:31 pm, Dr. V I Plankenstein [EMAIL PROTECTED] wrote: The anthrax attack was almost certainly carried out by someone who had access to Gov labs or other secure facilities, but the attack on WTC was an act of Islamic fanaticism, and you're an ass to suggest otherwise without having some very solid proof to back your ridiculous claims - which you lack. You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. If the ODIOUS George W Bush did not inform the American Public (Who pays his salary) that Anthrax Attack was by a YANK BASTARD, then it must not be so. On the other hand if the Anthrax Attack was produced on such short notice and such coordination with the whole 911, then 911 was ALL done by yank bastards themselves and George W Bush is a prime suspect with all his underlings. ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank bastards themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging multithreaded program using Eclipse/Pydev
On Apr 6, 1:33 pm, Michael Bentley [EMAIL PROTECTED] wrote: On Apr 6, 2007, at 2:32 PM, John Henry wrote: I am back against the wall trying to migrate my multithreaded application from Python 2.3 to 2.5. The part of the code that's failing has to do with queues (2.3 queues and 2.5 queues are not the same). Since WingIDE doesn't support multithread debugging (they've been saying that one day they might support that - and that was 2003), I am starting to look for alternatives. The alpha release of Wing IDE (3.0.0-a1) does in fact, support multithread debugging. It is an alpha release but so far, I'm quite satisfied with it. hth, Michael That's nice to know. May be I can get on their alpha list. Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: Database Timestamp conversion error
On Apr 6, 1:48 pm, [EMAIL PROTECTED] wrote: (snipped) If I look in the MS Access database, I see the timestamp as 5/6/112. Obviously some user didn't enter the correct date and the programmer before me didn't give Access strict enough rules to block bad dates. How do I test for a malformed date object so I can avoid this? There are thousands of records to transfer. time.strptime ? import time for date in (5/6/2008, 5/6/118): try: struct_tm = time.strptime(date, %m/%d/%Y) print Good date: + date print struct_tm except ValueError: print Bad date: + date -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list
printing longs
Python 2.3.4 (#1, Oct 26 2004, 16:42:40) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 x = int(8000, 16) x = x | 0x8000 stdin:1: FutureWarning: hex/oct constants sys.maxint will return positive values in Python 2.4 and up print %x % ( x ) -8000 How do I get python to print the usual answer: 800, not -8000 Thanks, Gary -- http://mail.python.org/mailman/listinfo/python-list
Hide the python-script from user
Hi, recently there was a thread about hiding the python-script from the user. The OP could use http://freshmeat.net/projects/pyobfuscate/ H. -- http://mail.python.org/mailman/listinfo/python-list
Re: printing longs
On Apr 7, 7:54 am, garyp [EMAIL PROTECTED] wrote: Python 2.3.4 (#1, Oct 26 2004, 16:42:40) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 x = int(8000, 16) x = x | 0x8000 stdin:1: FutureWarning: hex/oct constants sys.maxint will return positive values in Python 2.4 and up As your subject says, you are working with longs, so don't mix in an int (0x800, which is negative in Python 2.3 and earlier) -- use 0x800L instead. print %x % ( x ) -8000 %x % x is enough. How do I get python to print the usual answer: 800, not -8000 usual in what context? Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Hide the python-script from user
On Apr 6, 3:19 pm, hlubenow [EMAIL PROTECTED] wrote: recently there was a thread about hiding the python-script from the user. The OP could use Interesting - thanks -- http://mail.python.org/mailman/listinfo/python-list
Convert xml symbol notation
Hi, I'm working on a script to download and parse a web page, and it includes xml symbol notation, such as #39; for the ' character. Does anyone know of a pre-existing python script/lib to convert the xml notation back to the actual symbol it represents? -- http://mail.python.org/mailman/listinfo/python-list
Re: Hide the python-script from user
ts-dev wrote: On Apr 6, 3:19 pm, hlubenow [EMAIL PROTECTED] wrote: recently there was a thread about hiding the python-script from the user. The OP could use Interesting - thanks Well, testing it, it doesn't seem to work very well ... It seems, Python-code is rather difficult to obfuscate, probably because of its clear syntax and indentations. Here's yet another approach: http://pythonhacker.is-a-geek.net/my_programs/pyfuscate/pyfuscate-0.1.zip/view H. -- http://mail.python.org/mailman/listinfo/python-list
08 and 09 in sequence create invalid token error?!
Hello all, I am confused as to why including 08 or 09 in a sequence (list or tuple) causes this error. All other numbers with a leading zero work. [01,02,03,04,05,06,07] is fine [01,02,03,04,05,06,07,10] is fine [01,02,03,04,05,06,08] produces SyntaxError: invalid token, as does: [01,02,03,04,05,06,09] I have tried this both in a script and in the interactive interpreter. Using Python 2.3.4 Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: 08 and 09 in sequence create invalid token error?!
IamIan wrote: I am confused as to why including 08 or 09 in a sequence (list or tuple) causes this error. All other numbers with a leading zero work. All literals that start with 0 digit are considered as octal numbers, i.e. only digits 0..7 are allowed. See octinteger lexical definition: http://docs.python.org/ref/integers.html w. -- http://mail.python.org/mailman/listinfo/python-list
Re: 08 and 09 in sequence create invalid token error?!
Thank you! Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Database Timestamp conversion error
On Apr 7, 6:48 am, [EMAIL PROTECTED] wrote: Hi, I am populating a mySQL database with data from the MS Access database. I have successfully figured out how to extract the data from Access, and I can insert the data successfully into mySQL with Python. My problem is that I keep hitting screwy records with what appears to be a malformed dbiDate object when I insert certain records. I get the following traceback: Ummm ... I didn't start using Python on databases till after DB API 2.0 came out (1999) so please pardon my ignorance, but isn't dbiDate something that was in API 1.0 but vanished in API 2.0 [e.g. its mentioned only briefly in the history section of the current mxODBC docs]? If that's what you are still using: (a) I can't imagine how printing a dbiDate object would give such a garbled result -- try: print type(obj) print repr(obj) for both a bad obj and a good obj. (b) The API 1.0 docs give a clue: dbiDate(value) This function constructs a 'dbiDate' instance that holds a date value. The value should be specified as an integer number of seconds since the epoch (e.g. time.time()). and googling brought up a few hits mentioning that not handling dates earlier that the epoch (1970-01-01T00:00:00) was a limitation. So: if you are calling dbiDate yourself, you can inspect its input argument; presumably a date in the year 112 will show up as negative. Traceback (most recent call last): File \\someServer\Development\collectiveFleet.py, line 68, in - toplevel- mycursor.execute(sql) TypeError: argument 1 must be string without null bytes, not str When I print the timestamp variable, I get this output: (I31 (S'OK' p1 Nttp2 . If I look in the MS Access database, I see the timestamp as 5/6/112. Obviously some user didn't enter the correct date and the programmer before me didn't give Access strict enough rules to block bad dates. How do I test for a malformed date object so I can avoid this? There are thousands of records to transfer. I am using the odbc module for connection purposes with Python 2.4 on Windows XP SP2. If this is the odbc module that comes in the win32all package: 1. There are much better options available on Windows e.g. mxODBC. 2. Doesn't document dbiDate objects AFAICT. If your SELECT from the Access db is returning you seconds since the epoch values, proceed as I suggested earlier. If it is returning you dbiDate objects directly, find out if the dbiDate obj has any useful attributes or methods e.g. obj.date_as_tuple() - (2007, 4, 7, ...) or obj.year - 2007 obj.month - 4 etc How to find out: insert code like print dir(obj) in your script and inspect the output for likely attribute/method names. And if that doesn't help, abandon the odbc module and use e.g. mxODBC or Python adodb. Hope some of this helps, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentifying the LAST occurrence of an item in a list
On Apr 5, 6:37 pm, John Machin [EMAIL PROTECTED] wrote: help(list.index) Help on method_descriptor: index(...) L.index(value, [start, [stop]]) - integer -- return first index of value I look forward to your next version. Great point! I was assuming the temp variable space was static but the pointer to the start of the list was moving- shame on me (what language is this now ;)! Couldn't resist the temptation to just collect all of the locations as I traversed m = [2,9,1,5,6,3,1,1,9,2] f = 1#What we're looking for location = 0 #Start at beginning of list fIndexs = [] while 1: try: location = m.index(f,location) + 1 fIndexs.append(location-1) except ValueError: break print(Last location = %d % fIndexs[-1]) print(All Items = %s % fIndexs) -- http://mail.python.org/mailman/listinfo/python-list
Re: Comments in ConfigParser module
Joel Andres Granados wrote: Hi list: Any comment greatly appreciated Very clever. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hide the python-script from user
hlubenow wrote: ts-dev wrote: On Apr 6, 3:19 pm, hlubenow [EMAIL PROTECTED] wrote: recently there was a thread about hiding the python-script from the user. The OP could use Interesting - thanks Well, testing it, it doesn't seem to work very well ... It seems, Python-code is rather difficult to obfuscate, probably because of its clear syntax and indentations. Here's yet another approach: http://pythonhacker.is-a-geek.net/my_programs/pyfuscate/pyfuscate-0.1.zip/view H. That didn't work very well either :(. Ok, but now I can offer a real secure solution: You can have real encryption in Python using this modules: http://www.amk.ca/files/python/crypto/pycrypto-2.0.1.tar.gz and http://sourceforge.net/projects/yawpycrypto Below I post a code-example that I've written some time ago. With it, encrypting text is rather easy. Then you have to program a start-script, that reads in your script and the decryption-key. The decryption-key must be encrypted too. Such a encrypted key can be generated by the modules if you don't pass a password to my function doEncrypt(). The decryption-key must then be hidden somewhere within the encrypted program-script. That's because, if the user knows where to find the key, he can decrypt the program-script. If your start-script is written, everything should work automatically, one shouldn't nearly notice the decryption-process. Ok, here's my example code, how to encrypt and decrypt some text with the modules: #!/usr/bin/env python import os import sys import base64 from yawPyCrypto.Cipher import DecryptCipher, EncryptCipher from yawPyCrypto.Cipher import ZipDecryptCipher, ZipEncryptCipher from yawPyCrypto.Constants import CIPHER_BLOWFISH, MODE_CBC def doEncrypt(text, passw = None): e = EncryptCipher(passw, CIPHER_BLOWFISH, MODE_CBC) e.feed(text) e.finish() encryptedtext = e.data if passw != None: passwr = passw else: passwr = e.password a = (encryptedtext, passwr) return a def doDecrypt(encryptedtext, passw): d = DecryptCipher(passw) d.feed(encryptedtext) d.finish() decoded = (d.data) return decoded # Calling the encryption routine. # If you just pass the text to encrypt, a password is generated: a = doEncrypt(For your eyes only !, Melina) # Just trying to clean the screen: if sys.platform == win32: os.system(cls) else: os.system(clear) print print Hello ! print print I just encrypted some text. It looks like this now: print print base64.b64encode(a[0]) print print 'Please notice, that I just encoded the text once more using base64.b64encode() to make it printable.' print print The password for decryption is: print print base64.b64encode(a[1]) print print Let's decrypt again (the original password must be passed without b64encoding): print print doDecrypt(a[0], a[1]) print See you H. -- http://mail.python.org/mailman/listinfo/python-list