Re: Generating .pyc/.pyo from a make file
Roland Heiber wrote: Tim Daneliuk wrote: under the impression that compiled meant optimized byte code that You where right, i was totally mislead by optimized ... ;) Greetings, Roland -- http://mail.python.org/mailman/listinfo/python-list
SysV IPC message queues
Hello everyone. I'm trying to control a program from a Python program using IPC. Although using a socket is a common choice for such applications, I would like to use SysV message queues because I don't need to parse the stream. I thought Python had a support of SysV message queues (I have found almost anything I need in Python library modules so far). But Python library seems not supporting SysV message queues yet. I'm thinking of calling a C function from Python but it seems not so easy. Is there any easy work around for this? Any suggestions, any comments are highly appreciated. Thanks in adavance. Aki Niimura -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding user's home dir
Hello Nemesis, Hi all, I'm trying to write a multiplatform function that tries to return the actual user home directory. ... What's wrong with: from user import home which does about what your code does. Bye. -- Miki Tebeka [EMAIL PROTECTED] http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -- http://mail.python.org/mailman/listinfo/python-list
Re: python-2.4.msi installation issue
[EMAIL PROTECTED] wrote: O/S: Windows XP Home (with Service Pack 2) Downloaded python-2.4.msi from python.org (10,632KB). When I double click on the file from Windows Explorer, the installation process presents the window in which I am prompted to either install for all users (the default) or install for just me. I selected the defaulted value. Installation process presents a window in which the user may select the directory for python 2.4 files. I selected the default value of the Python24 folder. After clicking Next, the process presents a window with the message, Python 2.4 installer ended prematurely. Python 2.4 ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again. My question is this: how do I determine what the error was that caused the installation process to end prematurely? I have the same problem and don't know what's happening, but ActivePython worked for me. Get it here: http://activestate.com/Products/ActivePython/ HTH, Wolfram -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
If you use IPython for your interactive mode stuff, you'll have a nice history... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: new style exception handleing
Peter Hansen wrote: Ola Natvig wrote: Does anybody know why it's not possible to raise Exceptions which are types (new-style-classes). I know all standard exceptions are classic classes, but if you make a custom exception which both inherits from a exception class and a new-style one the it causes a type error when raised. class b(Exception, object): pass This might not help you, but have you considered just making your old-style class *contain a reference* to an instance of whatever new-style class you want it to contain? Then the issue goes away. I can't actually think of a reason to need to base an exception on a new-style class, but perhaps you have a good one... -Peter It's quite simple to bypass the problem, it was more the reason I was wondering about too. -- -- Ola Natvig [EMAIL PROTECTED] infoSense AS / development -- http://mail.python.org/mailman/listinfo/python-list
Re: pyFMOD problem
[EMAIL PROTECTED] (Tian) writes: I am trying to use pyfmod in python to manipulate sound. i have installed pyfmod, ctype, numarray (if they are necessary), i also copied fmod.dll to python/DLLs as well as windows/system32, but First, you should copy fmod.dll to a directory somewhere where LoadLibrary can find it. That includes directories on PATH, plus the directory where the executable is. python/DLLs does probably not work. when i tried import pyFMOD I got: Traceback (most recent call last): File pyshell#0, line 1, in -toplevel- import pyFMOD File C:\Python24\Lib\site-packages\pyFMOD.py, line 177, in -toplevel- _FSOUND_Sample_Load = getattr(fmod, [EMAIL PROTECTED]) File C:\Python24\Lib\site-packages\ctypes\__init__.py, line 323, in __getattr__ func = self._StdcallFuncPtr(name, self) AttributeError: function '[EMAIL PROTECTED]' not found - How can I deal with this? Thanks! The fmod.dll that I just downloaded has a function named '[EMAIL PROTECTED]', which indicates an api change (the number of the '@' sign indicates how many bytes are needed as parameters). Probably pyFMOD needs an older version of fmod.dll, or pyFMOD should be updated? Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: new style exception handleing
Google is your friend. This has been discussed a lot in the past. For instance, google for the thread, Exceptions as New Style Classes, there was also a PEP by Steven Taschuk, IIRC. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Fuzzyman a écrit : If you use IPython for your interactive mode stuff, you'll have a nice history... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml Best event : if your EDITOR system variable in vim, using the ed command in ipython will bring vim with (eventually) the code you want to edit :) Now, I wonder if you could embed ipython inside vim ... Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: python and visual C++
Caleb Hattingh [EMAIL PROTECTED] a écrit dans le message de news: [EMAIL PROTECTED] Olivier If you consider using the ctypes module, you can write a dll (windows) or a shared object (linux) using anything that can make one of those. For example, I have successfully used FreePascal to make a dynamic library on both windows and linux and use that library within python on both platforms. Yes. I do this too. I make my own modules with C++/BOOST and compile them with gcc under Linux and Windows. But the problem is about modules thats are developped from others with distutils... Heck, even the objectpascal code for the dll was unchanged on both platforms. I simply needed to recompile the objectpascal file on each using FreePascal. Also FreePascal is available on many more platforms (though not quite as many as python, I'll wager). This is the only way I ever intend making native binary additions to my own programs. Regards Caleb On Wed, 2 Feb 2005 12:35:08 +0100, Olivier Ravard [EMAIL PROTECTED] wrote: Hi, When I tryed to compile a python module using distutils under windows, and there is an error message if we do not have Microsoft Visual C++ 6 installed. This is because python have been compiled with MSVC6 and distutils wants it in order to compile C++ python modules. One of the reasons why I use python is because this is a free language. But I need a non free compilator to compile my C++ module !!! Choosing MSVC to compile python is a strange choice since there are other free compilators like MinGW. I think that using another compilator should be possible in order to compile python modules since I use BOOST/MinGW to develop my own modules... Diffrerent solutions appears : - peoples who compile python for windows should use a free compilator (MinGW or Microsoft Visual C++ Toolkit 2003 for example) - modify distutils in order to use another compilator Is there anyone that have experienced this free problem and is there a solution that I did not note. I don't want to buy MSVC... Thanks O.R. -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating modul classes with eval
Hello! Note that we don't need eval anywhere. Uuups, that looks realy cool! Thanks for that! Im fooling around with generating html-tags. As there are only two kind of html tags, one who can nest chields, and one who cant, i wantet to play arround with something like: I've got two base classes, _Tag and _ContainerTag (for tags which can nest tags). Instead of getting an htmltag with _Tag(name='html'), I want to have a class for each html-tag. So, I thought of creating that classes dynamicly. my now (nearly) working code is: class _Tag(object): def __init__(self, name, flags=None, **props): [...] class _ContainerTag(_Tag): def __init__(self, name, contents=None, flags=None, **props): super(_ContainerTag, self).__init__(name=name, flags=flags, **props) self._contents = coalesce(contents, []) _module_name = sys.modules[__name__] class_dic = {} class_dic['Br'] = _Tag class_dic['Hr'] = _Tag class_dic['Html'] = _ContainerTag class_dic['Table'] = _ContainerTag for class_name, class_base in class_dic.items(): class TmpClass(class_base): def __init__(self, **props): name = class_name.lower() #super(TmpClass, self).__init__(name=name, **props) class_base.__init__(self, name=name, **props) setattr(_module_name, class_name, TmpClass) br = Br() print br table = Table() print table br is printed OK, but for table, I get: AttributeError: 'TmpClass' object has no attribute '_contents' so, it seems that __init__ of _Tag is not called. If I try to do the commented line super(TmpClass, self).__init__(name=name, **props) instead of class_base.__init__(self, name=name, **props) I get: TypeError: super(type, obj): obj must be an instance or subtype of type for print table, print br ist processed OK. Thanks for help and your perfekt examples, AXEL. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Daniel Bickett a écrit : This is certainly a worthy topic. There are several IDEs for Python (one I like very much being Komodo) that have plenty of fancy debugging features and advanced operations, however I have yet to encounter (elsewhere) the convenience that comes with being able to press F5 and have an interactive interpreter load my code and be ready for testing. Try emacs + python-mode. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Pierre Barbier de Reuille a écrit : Fuzzyman a écrit : If you use IPython for your interactive mode stuff, you'll have a nice history... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml Best event : if your EDITOR system variable in vim, using the ed command in ipython will bring vim with (eventually) the code you want to edit :) Now, I wonder if you could embed ipython inside vim ... holy-war Don't know, but you can embed ipython inside emacs !-) /holy-war Pierre -- http://mail.python.org/mailman/listinfo/python-list
convert ftp.retrbinary to file object? - Python language lacks expression?
I just tried to convert a (hugh size) ftp.retrbinary run into a pseudo-file object with .read(bytes) method in order to not consume 500MB on a copy operation. First I thought, its easy as usual with python using something like 'yield' or so. Yet I didn't manage to do (without using threads or rewriting 'retrbinary')? Any ideas? I tried a pattern like: def open(self,ftppath,mode='rb'): class FTPFile: #TODO ... def iter_retr() ... def callback(blk): how-to-yield-from-here-to-iter_retr blk??? ftp.retrbinary(RETR %s % relpath,callback) def read(self, bytes=-1): ... self.buf+=self.iter.next() ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding user's home dir
Miki Tebeka [EMAIL PROTECTED] wrote: Hello Nemesis, Hi all, I'm trying to write a multiplatform function that tries to return the actual user home directory. ... What's wrong with: from user import home which does about what your code does. Except it also execfile()s $HOME/.pythonrc.py, which might not be wanted. Saluton Marc -- http://mail.python.org/mailman/listinfo/python-list
Re: CONTEST - What is the (best) solution?
{Key11: Value11 {Keyn1: Valuen1 Keyn2: Valuen2 ... Keynn:Valuenn} Each pair in a dictionary is separated by CRLF and in each dictionary numbers of pairs can be different. I need to read only the last dictionary.What is a best solution? Thanks Lad What about (not tested): stmFile = file(rPath\FileNameOfTheFileWithDictionaries) strFile = stmFile.read() strLastDict = strFile[strFile.rfind('\n{):] ? Claudio -- http://mail.python.org/mailman/listinfo/python-list
pyGTK warning
Hello, GtkWarning: gtk_widget_grab_default: assertion `GTK_WIDGET_CAN_DEFAULT (widget)' failed I am using python gtk binding with glade. All I did was to create a gui interface with glade (Stored as xml) and to load it with gtk.glade.XML(filename.glade); Then I run it with gkt.main() and got this warning.. what can it possible be, since google seems not to know about it. thanx. -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging
Samuel Kilchenmann wrote: snip . logging._handlers.clear() . logging.root.handlers = [] . for l in logging.Logger.manager.loggerDict.values(): . l.handlers = [] after logging.shutdown() and before getting the new logger, your script will probably run without errors. snip Hello, Yeah, I worked that out after a bit, I solved it by keeping a record of all the handlers and then calling flush on the handler followed by removeHandler from the logger. It's a bit of a pain but I'd prefer to do that rather than go poking around inside the logging package but I will put the cleaning up of the dict on a shutdown() call as a feature request for logging. Thanks for the comm. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : [EMAIL PROTECTED] Cenix Website : http://www.cenix-bioscience.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 2.4.0)
Leeuw van der, Tim wrote: Do you have a file called drwtsn32.log anywhere on your computer? No, unfortunately I cannot find such file anywhere on my computer What do I do to get such file? Or anything equally useful? On my Windows 2000 box, just crash something :-) Perhaps this may help: http://www.windowsnetworking.com/kbase/WindowsTips/Windows2000/RegistryTips/RegistryTools/DrWatson.html -- http://mail.python.org/mailman/listinfo/python-list
Re: convert ftp.retrbinary to file object? - Python language lacks expression?
Robert wrote: I just tried to convert a (hugh size) ftp.retrbinary run into a pseudo-file object with .read(bytes) method in order to not consume 500MB on a copy operation. First I thought, its easy as usual with python using something like 'yield' or so. Yet I didn't manage to do (without using threads or rewriting 'retrbinary')? Any ideas? I tried a pattern like: def open(self,ftppath,mode='rb'): class FTPFile: #TODO ... def iter_retr() ... def callback(blk): how-to-yield-from-here-to-iter_retr blk??? ftp.retrbinary(RETR %s % relpath,callback) def read(self, bytes=-1): ... self.buf+=self.iter.next() ... H this is nearly there I think...: import ftplib class TransferAbort(Exception): pass class FTPFile: def __init__(self, server, filename): self.server = server self.filename = filename self.offset = 0 def callback(self, data): self.offset = self.offset + len(data) self.data = data ## now quit the RETR command? raise TransferAbort(stop right now) def read(self, amount): self.ftp = ftplib.FTP(self.server) self.ftp.login() try: self.ftp.retrbinary(RETR %s %self.filename, self.callback, blocksize=amount, rest=self.offset) except TransferAbort: return self.data f = FTPFile(HOSTNAME, FILENAME) print f.read(24) print f.read(24) I open the ftp connection inside the read method as it caused an error (on the second call to read) when I opened it in __init__ ??? HTH Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: new style exception handleing
Ola Natvig wrote: Peter Hansen wrote: I can't actually think of a reason to need to base an exception on a new-style class, but perhaps you have a good one... It's quite simple to bypass the problem, it was more the reason I was wondering about too. Basically because fixing it without killing backward compatibility with string exceptions is hard :) Doesn't mean people aren't trying though (Google the python-dev archives, as well as the python-list ones). Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Popularizing SimpleHTTPServer and CGIHTTPServer
Am Wed, 02 Feb 2005 22:37:34 -0800 schrieb Michele Simionato: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365606 The standard library modules SimpleHTTPServer and CGIHTTPServer are extremely useful, but the documentation hides their virtues. I hope to improve the situation with this recipe. Hi, I used SimpleHTTPServer to serve debian packages you get with apt-get. Unfortunately this did not work. I recieved a lot of connection reset by peer. See: http://mail.python.org/pipermail/python-list/2004-October/244173.html Have other people this problem, too? I got no response. Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: convert ftp.retrbinary to file object? - Python language lacks expression?
Martin Franklin wrote: Martin Franklin wrote: Robert wrote: I just tried to convert a (hugh size) ftp.retrbinary run into a pseudo-file object with .read(bytes) method in order to not consume 500MB on a copy operation. [snip] H this is nearly there I think...: whoops... spoke too soon.. Trigger happy this morning... import ftplib class TransferAbort(Exception): pass class FTPFile: def __init__(self, server, filename): self.server = server self.filename = filename self.offset = 0 def callback(self, data): self.offset = self.offset + len(data) self.data = data ## now quit the RETR command? raise TransferAbort(stop right now) def read(self, amount): self.ftp = ftplib.FTP(self.server) self.ftp.login() I needed to insert a time.sleep(0.1) here as the connections were falling over themselves - I guess testing with a blocksize of 24 is a little silly. try: self.ftp.retrbinary(RETR %s %self.filename, self.callback, blocksize=amount, rest=self.offset) except TransferAbort: also need to close the ftp connection here! self.ftp.close() return self.data f = FTPFile(HOSTNAME, FILENAME) print f.read(24) print f.read(24) ## new test... f = FTPFile(HOSTNAME, FILENAME) while 1: data = f.read(24) if not data: break print data, I open the ftp connection inside the read method as it caused an error (on the second call to read) when I opened it in __init__ ??? HTH Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
[Ashot] I have been frustrated for quite some time with a lack of a history command in IDLE To recall a line from your history in IDLE, cursor up to that line and hit Enter. I've tried something called pyCrust, but this too didn't have history To recall a line from your history in PyCrust, press Ctrl+UpArrow. -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Reinstall python 2.3 on OSX 10.3.5?
In article [EMAIL PROTECTED], Robert Kern [EMAIL PROTECTED] wrote: Christian Dieterich wrote: On Dé Céadaoin, Feabh 2, 2005, at 17:48 America/Chicago, [EMAIL PROTECTED] wrote: Hi there I started a very long and roundabout process of attempting to install python 2.3.4 along side my apple-installed 2.3 system. To make a long story short, I have completely confabulated my environment ( i deleted the 2.3 binaries and so forth from the system in an attempt to start things fresh), and now I cannot figure out how to reinstall the base 2.3 Apple python distribution. Can somebody please point me in the right direction? You could use fink install python which makes you a Python installation under /sw. But that doesn't solve his problem, which is to restore the Apple-supplied Python that he deleted. Also: fink is evil. I wouldn't touch it with a ten-foot pole. Just -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic file operation questions
On Wed, Feb 02, 2005 at 11:47:41PM -0500, Caleb Hattingh wrote: Hi Alex Assuming you have a file called data.txt: *** f = open('data.txt','r') lines = f.readlines() f.close() for line in lines: print line *** Can you not write this: f=open(data.txt, r) for line in f.readlines(): #do stuff to line f.close() Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: test_socket.py failure
[EMAIL PROTECTED] wrote: Marc, it is possible that there was a change between glibc-2.2.4 and 2.2.5 that would account for the difference in behaviour. I think i'll write a little test program in C to check out getservbyname's return values in a little more controled environment. I'll post the results tomorrow. The other question is which C library Python is actually using on your system. Maybe it's picking up whatever installed the funky man page which doesn't mention NULL proto arguments. So, find your Python 2.4 binary and run ldd python24 to see which shared C library it is linking to. For me, it's /lib/tls/libc.so.6. Running that library directly prints out the message about GNU C library 2.3.3. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy Q: dealing with object type
In article [EMAIL PROTECTED], Steven Bethard [EMAIL PROTECTED] wrote: Erik Johnson wrote: Erick [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Ah, you're running into the old-style classes vs. new style classes. Try subclassing from object. For example: class A(object): That works! :) I guess I am fortunate to be running 2.2 - looks kinda ugly prior to that. It's not horrible: py class A: ... pass ... py class B: ... pass ... py a = A() py a.__class__ == A True py a.__class__ == B False Uh, isinstance(a, A) works for both new-style and old-style classes. Heck, isinstance() even works in Python 1.5.2... Still, if you can use new-style classes, you should. Also, you should probably Google for duck typing. Generally, in Python it is frowned upon to check the type of an object. There are times when it's necessary, but if you're just starting off, my guess is that you haven't discovered one of these times yet... Just -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating .pyc/.pyo from a make file
In article [EMAIL PROTECTED], vincent wehren [EMAIL PROTECTED] wrote: Tim Daneliuk wrote: Steve Holden wrote: Roland Heiber wrote: Tim Daneliuk wrote: Aha! Exactly ... and that makes perfect sense too. D'oh! I guess a better distribution strategy would be to have the installation program generate the pyo file at installation time... Thanks - Also, the *.py? files contain the full pathname of the *.py they have been compiled from. True. Copying them to other path locations will give you the wrong __file___ information in tracebacks. This is not 100% accurate: yes, the traceback shows the original source file path, yet module.__file__ does point to the actual .pyc file it was loaded from. Just -- http://mail.python.org/mailman/listinfo/python-list
Re: errors
Joel Eusebio said the following on 2/2/2005 4:53 PM: Can someone help me on this, I don' know where the testmptest came from but the mptest.py is at the /usr/local/apache2/htdocs/test directory and this error came from apache's error_log PythonHandler mod_python.publisher: ImportError: No module named testmptest Thanks, Joel I found this link from Googling - http://www.modpython.org/pipermail/mod_python/2004-January/014857.html Please read the entire thread and see if it provides your resolutions (the mod_python OP's issue was similar but for a different module). It might also do you some good to join mod_python mailing list if you are going to use it regularly. Thanks, -Kartic -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic file operation questions
In article [EMAIL PROTECTED], Peter Nuttall wrote: On Wed, Feb 02, 2005 at 11:47:41PM -0500, Caleb Hattingh wrote: Hi Alex Assuming you have a file called data.txt: *** f = open('data.txt','r') lines = f.readlines() f.close() for line in lines: print line *** Can you not write this: f=open(data.txt, r) for line in f.readlines(): #do stuff to line f.close() sure you can f = open(data.txt, rb) while [ 1 ]: line = f.readlines() if not line:break line = somethingelse ... f.close() Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating modul classes with eval
Axel Straschil wrote: class_dic = {} class_dic['Br'] = _Tag class_dic['Hr'] = _Tag class_dic['Html'] = _ContainerTag class_dic['Table'] = _ContainerTag for class_name, class_base in class_dic.items(): class TmpClass(class_base): def __init__(self, **props): name = class_name.lower() #super(TmpClass, self).__init__(name=name, **props) class_base.__init__(self, name=name, **props) setattr(_module_name, class_name, TmpClass) While your workaround doesn't balk immediately, it doesn't do the right thing either. After the loop has finished, the global variable TmpClass will be bound to whatever class was created last, and the variable class_base will be bound to that the base class of that same TmpClass. Therefore only this last class is guaranteed to work as expected. A simplified example to demonstrate the binding problem: classes = [] for text in [alpha, beta]: ... class T: ... def __init__(self): print text ... classes.append(T) ... classes[0] is classes[1] False # two distinct classes, as expected classes[0]() beta __main__.T instance at 0x402a9e2c classes[1]() beta __main__.T instance at 0x402a9f8c And now the proof that you are actually accessing the global variable: text = gamma classes[0]() gamma __main__.T instance at 0x402a9f8c One way to fix this is to introduce a factory function: def make_class(text): ... class T: ... def __init__(self): print text ... return T ... classes = [] for text in [alpha, beta]: ... classes.append(make_class(text)) ... classes[0]() alpha __main__.T instance at 0x402a9e4c classes[1]() beta __main__.T instance at 0x402a9f8c Peter -- http://mail.python.org/mailman/listinfo/python-list
RE: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 2.4.0)
-Original Message- From: [EMAIL PROTECTED] on behalf of John Machin Sent: Thu 2/3/2005 12:00 PM To: python-list@python.org Subject: Re: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1,2.4.0) Leeuw van der, Tim wrote: Do you have a file called drwtsn32.log anywhere on your computer? No, unfortunately I cannot find such file anywhere on my computer What do I do to get such file? Or anything equally useful? On my Windows 2000 box, just crash something :-) Perhaps this may help: http://www.windowsnetworking.com/kbase/WindowsTips/Windows2000/RegistryTips/RegistryTools/DrWatson.html Using this URL, I found the log file and it's about 1Gb big... I'll have to find out what is the useful part of it (or remove it and crash again). I don't know why searching all drives using windows 'search' did not find the file! When I have a usefull crashdump, what should I do? Attach to e-mail and post it here? Should I include the user.dmp file too? Should I do the same for both python 2.3.5r1 and python 2.4? Or is it sufficient to do so for Python 2.4? Thanks for the assistance! --Tim -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic file operation questions
Peter Nuttall wrote: On Wed, Feb 02, 2005 at 11:47:41PM -0500, Caleb Hattingh wrote: Hi Alex Assuming you have a file called data.txt: *** f = open('data.txt','r') lines = f.readlines() f.close() for line in lines: print line *** Can you not write this: f=open(data.txt, r) for line in f.readlines(): #do stuff to line f.close() Pete Yes, you can even write f = open(data.txt) for line in f: # do stuff with line f.close() This has the additional benefit of not slurping in the entire file at once. Be aware, though, that this (newer) style of using a file as an iterator doesn't mix well with seek() operations. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: CONTEST - What is the (best) solution?
That's neater than my suggestion. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Ashot wrote: WingIDE looks nice though, and it seems that the interactive shell is built in from the screenshots. Can you run a program to a certain point break point and use the shell? Indeed you can - there's an interpreter available that executes in the context of the current stack frame when you reach a breakpoint. It's a great way to find out what's going on. [But don't I remember that IDLE can do that too? ...] regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Richie Hindle wrote: [Ashot] I have been frustrated for quite some time with a lack of a history command in IDLE To recall a line from your history in IDLE, cursor up to that line and hit Enter. The history is required to be available in a chunk, to copy and paste into a file. I've tried something called pyCrust, but this too didn't have history To recall a line from your history in PyCrust, press Ctrl+UpArrow. Ditto regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Ashot said the following on 2/2/2005 9:45 PM: Vim related: -- Ideally, it would be nice to have a command mapped to a keystroke that can append the last executed command to a file. Even better would be a system that would integrate the file editing and interactive command line tool more seamlessly. Something along the lines of a debugger + file editor + command line utility, where file editor = vim. I know that vim has a utility for running python commands from its command prompt, but I have had a hard time getting this to work in windows and haven't explored it. Has anyone seen/tried a system along these lines, perhaps incorporating the python debugger (pdb)? I can see something that will run the file you are editing in vim up to the cursor or a mark with a set_trace at the line you are editing. I am VIM guy too but I have not got to the point of writing a VIM macro to execute a selection. VIM on UNIXish OSes can be built with the Python interpreter (so using :python expr or exec string will execute it). AFAIK, Vim on Windows is able to execute Python using the :python notation; I guess it uses the Python installation. I actually did not have to do anything other than install GVim; it just works on windows with :python. Try :help python in Vim to read the relevant help entries. I was considering writing a macro, map it to a keystroke for one to execute a selected code block in VIM but have not yet got around to doing it. May be one of these days..sigh... This probably does not help you very much but there is hope :-) Like Fuzzyman said you can set the EDITOR environment variable and use IPython. The magic %edit slice notation from history or no arguments will fire up your editor and the script will be saved to a temp file. Though I am not entirely happy with that feature (may be something that I am missing) but I live it. So if you set EDITOR as gvim.exe in Windows, IPython fires up Gvim instead of the default notepad (yuck!). In IPython, you can type pdb at the prompt and it toggles the debugger state. So if your program raises an error, IPython starts pdb if debug is on. IPython is nifty but I am just getting a feel for it. Thanks, -Kartic -- http://mail.python.org/mailman/listinfo/python-list
Re: Awkwardness of C API for making tuples
Fredrik Lundh wrote: Dave Cole wrote: for (i = 0; i num_values; i++) { PyObject *obj; obj = PyInt_FromLong(value[i]); if (obj == NULL || PyTuple_SetItem(tuple, i, obj) != 0) { Py_DECREF(tuple); return NULL; } } in theory, if PyInt_FromLong succeeds, and PyTuple_SetItem fails, you'll leak an object. /F And in practice this will only happen during a period when you are relying critically on it *not* to ... regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
[Steve] The history is required to be available in a chunk, to copy and paste into a file. I see, sorry, I didn't catch that the first time round. (In PyCrust you can use Alt+LeftDrag to copy a rectangular selection - you'll still need to remove any output, but at least you can get rid of the prompts in one go.) -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Apache Python 500 Error
Jeremy Bowers schrieb: But first, check your apache error log. Then you will know what your error is, too. Thanks for help, here is my error log: [Thu Feb 3 13:52:49 2005] [error] PythonHandler python: Traceback (most recent call last): [Thu Feb 3 13:52:49 2005] [error] PythonHandler python: File /usr/lib/python2.3/site-packages/mod_python/apache.py, line 181, in Dispatch\nmodule = import_module(module_name, _req) [Thu Feb 3 13:52:49 2005] [error] PythonHandler python: File /usr/lib/python2.3/site-packages/mod_python/apache.py, line 335, in import_module\nmodule = imp.load_module(mname, f, p, d) [Thu Feb 3 13:52:49 2005] [error] PythonHandler python: File /var/www/python/python.py, line 1 [Thu Feb 3 13:52:49 2005] [error] PythonHandler python: from mod_python import apache [Thu Feb 3 13:52:49 2005] [error] PythonHandler python: ^ [Thu Feb 3 13:52:49 2005] [error] PythonHandler python: SyntaxError: invalid syntax My test script: #!/usr/bin/python print 'Content-Type: text/plain\r' print '\r' import os print os.getcwd() thanks to Fuzzyman for test script -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating modul classes with eval
Hello! After the loop has finished, the global variable TmpClass will be bound to whatever class was created last, and the variable class_base will be bound to that the base class of that same TmpClass. Therefore only this last class is guaranteed to work as expected. Great, now it workes! _module_name = sys.modules[__name__] def _tag_class_factory(name, base): class T(base): def __init__(self, **props): super(T, self).__init__(name=name.lower(), **props) setattr(_module_name, name, T) class_dic = {} class_dic['Br'] = _Tag class_dic['Hr'] = _Tag class_dic['Html'] = _ContainerTag class_dic['Table'] = _ContainerTag class_dic['Td'] = _ContainerTag class_dic['Tr'] = _ContainerTag for name, base in class_dic.items(): _tag_class_factory(name, base) print Table(contents=[Tr(contents=[Br()])]) gives: tabletrbr//tr/table Thanks, AXEL. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic file operation questions
[EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], Peter Nuttall wrote: On Wed, Feb 02, 2005 at 11:47:41PM -0500, Caleb Hattingh wrote: Hi Alex Assuming you have a file called data.txt: *** f = open('data.txt','r') lines = f.readlines() f.close() for line in lines: print line *** Can you not write this: f=open(data.txt, r) for line in f.readlines(): #do stuff to line f.close() sure you can f = open(data.txt, rb) while [ 1 ]: line = f.readlines() if not line:break line = somethingelse ... f.close() Shall we charitably assume this was untested code? For a non-empty file it executes the loop body twice, once to read the whole content of the file and throw it away, the second time to do something else unspecified. The intention wasn't, therefore, entirely clear, but newbies should not be using it as any kind of model. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: global variables
M.E.Farmer wrote: Ok it has been a long day, In my reply to Steven Bethard , Steve should read Steven ;) M.E.Farmer Well, since he signs himself Steve too I guess we'll just have to put up with the ambiguities. Or perhaps, given my (lack of) typing skill, I should just start signing myself Stvev? regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Apache Python 500 Error
On 2005-02-02, Christian [EMAIL PROTECTED] wrote: Hello, i have an apache 1.3 server with python on debian. Python works fine but the scripts wont´t work. This easy script i want to do on apache: #!/usr/bin/python import os os.getcwd() in apache config i have done this: Directory /var/www/python AddHandler python-program .py PythonHandler python Order allow,deny Allow from all #PythonDebug On /Directory the script is in this directory /var/www/python but i get an 500 error everytime, with every script You're confusing mod_python and cgi. And you're cgi isn't written properly... Try this to enable cgi for python files: Directory /var/www/python Options +ExecCGI AddHandler cgi-script py /Directory Don't forget to restart apache. A proper cgi-file outputs a header with at least the content-type. A header is followed by an empty line. #!/usr/bin/env python import os print Content-type: text/html print print os.getcwd() -- Peter van Kampen pterk -- at -- datatailors.com -- http://mail.python.org/mailman/listinfo/python-list
ModPython: passing variables between handlers?
Hi all, I'm writing an application which runs within Apache and uses mod_python to provide basic authentication and return content to the user, something like: import modpython def handler(): # main part of the application starts here ... def authenhandler(): ... # Store information about the user in an object u = new User(req.user, pass) I'd like to be able to pass the u object somehow from authenhandler to handler in an elegant fashion, but without using global variables (as I understand it these persist for the life of the child process which will be more than one request, which is not what I want, and could be a security hole). I suppose that I could use session variables, but since this part of my application provides a WebDAV server, basic authentication credentials are passed on each request (so I don't really want to have to look after keeping track of sessions when I don't have to). I would rather not modify all my existing classes to support an extra parameter in their constructors. What I'm really looking for is some sort of global dictionary like PHP's $REQUEST or $SESSION, which I can assign freely to during the life of the request *from anywhere in my application* and which gets cleaned up for me automatically afterwards. Does something like this exist in mod_python? If the approach above isn't possible, what would your recommendations be for a solution to this issue? Many thanks for your time, Andrew James -- http://mail.python.org/mailman/listinfo/python-list
Re: ModPython: passing variables between handlers?
import modpython def handler(): # main part of the application starts here ... def authenhandler(): ... # Store information about the user in an object u = new User(req.user, pass) snip What I'm really looking for is some sort of global dictionary like PHP's $REQUEST or $SESSION, which I can assign freely to during the life of the request *from anywhere in my application* and which gets cleaned up for me automatically afterwards. Does something like this exist in mod_python? If the approach above isn't possible, what would your recommendations be for a solution to this issue? I have absolutely no experience with mod_python, so take this with a grain of salt - but you code above suggests that there is a request object: req. You already use it: req. How about storing u in req like this: def authenhandler(): # Store information about the user in an object req.u = new User(req.user, pass) -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: ModPython: passing variables between handlers?
Andrew James wrote: Hi all, I'm writing an application which runs within Apache and uses mod_python to provide basic authentication and return content to the user, something like: import modpython . def handler(): # main part of the application starts here ... def authenhandler(): ... # Store information about the user in an object u = new User(req.user, pass) I'd like to be able to pass the u object somehow from authenhandler to handler in an elegant fashion, but without using global variables (as I understand it these persist for the life of the child process which will be more than one request, which is not what I want, and could be a security hole). I suppose that I could use session variables, but since this part of my application provides a WebDAV server, basic authentication credentials are passed on each request (so I don't really want to have to look after keeping track of sessions when I don't have to). I would rather not modify all my existing classes to support an extra parameter in their constructors. What I'm really looking for is some sort of global dictionary like PHP's $REQUEST or $SESSION, which I can assign freely to during the life of the request *from anywhere in my application* and which gets cleaned up for me automatically afterwards. Does something like this exist in mod_python? If the approach above isn't possible, what would your recommendations be for a solution to this issue? RTFM ;-) If you want these values to have the same lifetime as your requests then it would appear to make sense to have them be request attributes, no? Section 4.5.3 of the mod_python docs says little else about the request object but You can dynamically assign attributes to it as a way to communicate between handlers.. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding user's home dir
Miki Tebeka wrote: Hi all, I'm trying to write a multiplatform function that tries to return the actual user home directory. ... What's wrong with: from user import home which does about what your code does. :-) I suspect he simply didn't know about it. I didn't either... Nemesis, please use the above recipe instead, as it makes the more reasonable (IMHO) choice of checking for a HOME environment variable before trying the expanduser(~) approach. This covers folks like me who, though stuck using Windows, despise the ridiculous Microsoft convention of user folders named like C:\Documents and Settings\Peter and prefer to create sensible folder like c:\users\peter and set a HOME variable to point to it. Your approach ignores our HOME variable. c:\python Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 from user import home print home c:\users\peter Yay! :-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: streaming a file object through re.finditer
On Wed, 2 Feb 2005 22:22:27 -0500, rumours say that Daniel Bickett [EMAIL PROTECTED] might have written: Erick wrote: True, but it doesn't work with multiline regular expressions :( If your intent is for the expression to traverse multiple lines (and possibly match *across* multiple lines,) then, as far as I know, you have no choice but to load the whole file into memory. *If* the OP knows that their multiline re won't match more than, say, 4 lines at a time, the code attached at the end of this post could be useful. Usage: for group_of_lines in line_groups(file, line_count=4): # bla bla The OP should take care to ignore multiple matches as the n-line window scans through the input file; eg. if your re searches for '3\n4', it will match 3 times in the first example of my code. |import collections | |def line_groups(fileobj, line_count=2): |iterator = iter(fileobj) |group = collections.deque() |joiner = ''.join | |try: |while len(group) line_count: |group.append(iterator.next()) |except StopIteration: |yield joiner(group) |return | |for line in iterator: |group.append(line) |del group[0] |yield joiner(group) | |if __name__==__main__: |import os, tempfile | |# create two temp file for 4-line groups | |# write n+3 lines in first file |testname1= tempfile.mktemp() # depracated insecure but ok for this test |testfile= open(testname1, w) |testfile.write('\n'.join(map(str, range(7 |testfile.close() | |# write n-2 lines in second file |testname2= tempfile.mktemp() |testfile= open(testname2, w) |testfile.write('\n'.join(map(str, range(2 |testfile.close() | |# now iterate over four line groups | |for bunch_o_lines in line_groups( open(testname1), line_count=4): |print repr(bunch_o_lines), |print | |for bunch_o_lines in line_groups( open(testname2), line_count=4): |print repr(bunch_o_lines), |print | |os.remove(testname1); os.remove(testname2) -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: CONTEST - What is the (best) solution?
By the way - all suggestions so far rely on chopping the last dictionary out as a string (naturally) and then using 'eval' to evaluate it. This has the inherent security problem that embedded python code will also be run. This is not just a security risk (which may *not* be an issue) but might cause extremely unpredictable results - which will be I guess. Text might be evaluated as an expression. There already exists a small python module called ConstructParser by John Berninger that will read dictionaries from strings and reconstruct them without using eval. You'll still need to isolate the actual dictionary you want. Google for it, if you can't find it - email me and I'll send you a copy. It's nice and small. If you want a script that will load and save dictionaries you could use ConfigObj. It uses the text format of 'ini' files ( keyword=value), but is very easy to use. http://www.voidspace.org.uk/python/configobj.html Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding user's home dir
Works great with Python 2.3.4 on... dare I say it... windows xp getHomeDir() 'C:\\Documents and Settings\\Lars' Regards Lars Nemesis wrote: (..) Please, could you test it on your systems and tell me what you got? (..) -- http://mail.python.org/mailman/listinfo/python-list
Re: global variables
Steve Holden [EMAIL PROTECTED] writes: M.E.Farmer wrote: Ok it has been a long day, In my reply to Steven Bethard , Steve should read Steven ;) M.E.Farmer Well, since he signs himself Steve too I guess we'll just have to put up with the ambiguities. Or perhaps, given my (lack of) typing skill, I should just start signing myself Stvev? What's this doing *here*? I thought the discussion of the pitfalls of name rebinding was taking place in the variable declaration thread. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson People who write obscurely are either unskilled in writing or up to mischief. - Sir Peter Medawar -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding user's home dir
Peter Hansen [EMAIL PROTECTED] writes: Miki Tebeka wrote: Hi all, I'm trying to write a multiplatform function that tries to return the actual user home directory. ... What's wrong with: from user import home which does about what your code does. :-) I suspect he simply didn't know about it. I didn't either... The purpose of the user module is executing ~/.pythonrc.py, which may not desirable. It definitely shouldn't be done by a library, for instance. Also, that the user's home directory is available as user.home is not documented, and I for one wouldn't want to rely on that. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Reinstall python 2.3 on OSX 10.3.5?
In article [EMAIL PROTECTED], Just [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], Robert Kern [EMAIL PROTECTED] wrote: Christian Dieterich wrote: On Dé Céadaoin, Feabh 2, 2005, at 17:48 America/Chicago, [EMAIL PROTECTED] wrote: Hi there I started a very long and roundabout process of attempting to install python 2.3.4 along side my apple-installed 2.3 system. To make a long story short, I have completely confabulated my environment ( i deleted the 2.3 binaries and so forth from the system in an attempt to start things fresh), and now I cannot figure out how to reinstall the base 2.3 Apple python distribution. Can somebody please point me in the right direction? You could use fink install python which makes you a Python installation under /sw. But that doesn't solve his problem, which is to restore the Apple-supplied Python that he deleted. Also: fink is evil. I wouldn't touch it with a ten-foot pole. I'm curious, why do you not like fink? It's certainly easier than compiling things by hand. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hey, get this!
Bernhard Herzog [EMAIL PROTECTED] writes: Steve Holden [EMAIL PROTECTED] writes: if package: module.__path__ = sys.path You usually should initialize a package's __path__ to an empty list. Actually, normally it's a list that contains the name of the package directory as its only item. I'm not sure what you should do when you do not import from a file system. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 17, Issue 54
Diez/Steve, Thanks for your responses. I did consider using the req object to store my request-life variables, but then I'm still stuck with having to pass the req object to every class in my application (and have to import modpython into every script as well) if I want to get some information about the user. I've abstracted the communications to the client at a high level in my application and I don't really want to force knowledge of modpython any further down than I need to. Your responses will give me the required lifetime for my variables, but not the required access at all levels of code (unless req is a global variable?). Do you have any other suggestions as to how this might be implemented? Many thanks, Andrew Hi all, I'm writing an application which runs within Apache and uses mod_python to provide basic authentication and return content to the user, something like: import modpython def handler(): # main part of the application starts here ... def authenhandler(): ... # Store information about the user in an object u = new User(req.user, pass) I'd like to be able to pass the u object somehow from authenhandler to handler in an elegant fashion, but without using global variables (as I understand it these persist for the life of the child process which will be more than one request, which is not what I want, and could be a security hole). I suppose that I could use session variables, but since this part of my application provides a WebDAV server, basic authentication credentials are passed on each request (so I don't really want to have to look after keeping track of sessions when I don't have to). I would rather not modify all my existing classes to support an extra parameter in their constructors. What I'm really looking for is some sort of global dictionary like PHP's $REQUEST or $SESSION, which I can assign freely to during the life of the request *from anywhere in my application* and which gets cleaned up for me automatically afterwards. Does something like this exist in mod_python? If the approach above isn't possible, what would your recommendations be for a solution to this issue? Many thanks for your time, Andrew James Subject: Re: ModPython: passing variables between handlers? From: Diez B. Roggisch [EMAIL PROTECTED] Date: Thu, 03 Feb 2005 14:38:54 +0100 To: python-list@python.org To: python-list@python.org Content-Transfer-Encoding: 7Bit Precedence: list MIME-Version: 1.0 References: [EMAIL PROTECTED] Message-ID: [EMAIL PROTECTED] Content-Type: text/plain; charset=us-ascii Message: 8 import modpython def handler(): # main part of the application starts here ... def authenhandler(): ... # Store information about the user in an object u = new User(req.user, pass) snip What I'm really looking for is some sort of global dictionary like PHP's $REQUEST or $SESSION, which I can assign freely to during the life of the request *from anywhere in my application* and which gets cleaned up for me automatically afterwards. Does something like this exist in mod_python? If the approach above isn't possible, what would your recommendations be for a solution to this issue? I have absolutely no experience with mod_python, so take this with a grain of salt - but you code above suggests that there is a request object: req. You already use it: req. How about storing u in req like this: def authenhandler(): # Store information about the user in an object req.u = new User(req.user, pass) Subject: Re: ModPython: passing variables between handlers? From: Steve Holden [EMAIL PROTECTED] Date: Thu, 03 Feb 2005 08:31:24 -0500 To: python-list@python.org To: python-list@python.org Content-Transfer-Encoding: 7bit Precedence: list MIME-Version: 1.0 References: [EMAIL PROTECTED] In-Reply-To: [EMAIL PROTECTED] Message-ID: [EMAIL PROTECTED] Content-Type: text/plain; charset=us-ascii; format=flowed Message: 9 Andrew James wrote: Hi all, I'm writing an application which runs within Apache and uses mod_python to provide basic authentication and return content to the user, something like: import modpython . def handler(): # main part of the application starts here ... def authenhandler(): ... # Store information about the user in an object u = new User(req.user, pass) I'd like to be able to pass the u object somehow from authenhandler to handler in an elegant fashion, but without using global variables (as I understand it these persist for the life of the child process which will be more than one request, which is not what I want, and could be a security hole). I suppose that I could use session variables, but since this part of my application provides a WebDAV server, basic authentication credentials are passed on each request (so I don't really want to have to look after keeping track of
Re: Python-list Digest, Vol 17, Issue 54
Hi, first of all - please quote appropriately - especially if you receive the postings as digest. That prevents the signal-to-noise-ratio dropping to unknown lows... Your responses will give me the required lifetime for my variables, but not the required access at all levels of code (unless req is a global variable?). Do you have any other suggestions as to how this might be implemented? If the code you showed us _is_ what you use - then req seems to be a global variable. Otherwise it won't work. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Is there a market for python developers?
I am new to python and took my first attempts at working with this language today. Is there a market for people who work with Python? Mabon Dane -- http://mail.python.org/mailman/listinfo/python-list
test msg
tes tmsg -- http://mail.python.org/mailman/listinfo/python-list
Re: Popularizing SimpleHTTPServer and CGIHTTPServer
Michele Simionato [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: Just submitted a recipe with this goal in mind: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365606 You may want to warn people that if they run those commands in their home directory, they will instantly share all of their data with anyone that can access the machine. Because the server runs as the user, it will have permission to serve all of the files in the directory. I'd recommend that they cd into a directory created specifically for the purpose of testing. Does anyone know how to use SimpleHTTPServer to: 1. Support virtual hosts? 2. Support SSL? I'd like to use SimpleHTTPServer to create some simple reporting utilities, but can't get past these two points. Is there a NotSoSimpleHTTPServer? -- http://mail.python.org/mailman/listinfo/python-list
Re: Popularizing SimpleHTTPServer and CGIHTTPServer
Jorey Bump wrote: Does anyone know how to use SimpleHTTPServer to: 1. Support virtual hosts? 2. Support SSL? I'd like to use SimpleHTTPServer to create some simple reporting utilities, but can't get past these two points. Is there a NotSoSimpleHTTPServer? Give Snakelets a try (snakelets.sf.net). I started it based on SimpleHTTPServer (but it has grown quite a bit since), it supports virtual hosts, though not SSL (yet). Maybe it strikes a good balance for you between features and complexity (or simplicity, if you like). --Irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: Hey, get this!
In article [EMAIL PROTECTED], Bernhard Herzog [EMAIL PROTECTED] wrote: Bernhard Herzog [EMAIL PROTECTED] writes: Steve Holden [EMAIL PROTECTED] writes: if package: module.__path__ = sys.path You usually should initialize a package's __path__ to an empty list. Actually, normally it's a list that contains the name of the package directory as its only item. I'm not sure what you should do when you do not import from a file system. If it's a path importer, it could be a cookie, specific to the importer. I think in Steve's case initializing __path__ to [*db*] should work. Just -- http://mail.python.org/mailman/listinfo/python-list
Re: test msg
[EMAIL PROTECTED] wrote: tes tmsg if you meant to send this to a test group, it didn't work. complain to your provider. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding user's home dir
Bernhard Herzog wrote: Peter Hansen [EMAIL PROTECTED] writes: Miki Tebeka wrote: Hi all, I'm trying to write a multiplatform function that tries to return the actual user home directory. ... What's wrong with: from user import home which does about what your code does. :-) I suspect he simply didn't know about it. I didn't either... The purpose of the user module is executing ~/.pythonrc.py, which may not desirable. It definitely shouldn't be done by a library, for instance. Also, that the user's home directory is available as user.home is not documented, and I for one wouldn't want to rely on that. Then please interpret my please use the above recipe as suggesting he should do what the equivalent code in the user.py module does in terms of finding the home folder of the user, rather than his own home-grown approach. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a market for python developers?
Mabon Dane wrote: I am new to python and took my first attempts at working with this language today. Is there a market for people who work with Python? Yes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding user's home dir
Peter Hansen wrote: Nemesis, please use the above recipe instead, as it makes the more reasonable (IMHO) choice of checking for a HOME environment variable before trying the expanduser(~) approach. This covers folks like me who, though stuck using Windows, despise the ridiculous Microsoft convention of user folders named like C:\Documents and Settings\Peter and prefer to create sensible folder like c:\users\peter and set a HOME variable to point to it. Your approach ignores our HOME variable. You could just tell Windows to move your home directory location to c:\users\peter and then all the environment variables will be set for you automatically. It probably varies wildly between Windows versions, but to assign a home folder for a local user on XP go to Control Panel/Administrative Tools/Computer Management/Local Users and Groups/Users, select your account, right menu Properties, Profile tab, and edit the 'Home folder' setting. Press F1 while editing the home folder location and see that at least someone at Microsoft thinks c:\users\... is a sensible location. See also http://support.microsoft.com/?kbid=816313 for domain users etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a market for python developers?
Mabon Dane wrote: I am new to python and took my first attempts at working with this language today. Is there a market for people who work with Python? You can Google this newsgroup for [EMAIL PROTECTED] jobs to find two messages I posted with statistics. -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is WSAEnumNetworkEvents???
From a quick look, it wouldn't be too difficult to wrap this function. Both the input arguments can be already be handled by Swig, and the outputs would just be an int and a fixed size tuple of ints. Roger [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I was trying to write an asyncronous TCP server for win32 using WSAEventSelect (which lives if win32file). Such events require WaitForMultipleObjects (which lives if win32event) and WSAEnumNetworkEvents WHICH IS NOT EXPOSED. This makes WSAEventSelect useless. Does somebody know how to add the WSAEnumNetworkEvents and WSANetwotkEvents structure win32file? Maybe I'm missing something? == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- -- http://mail.python.org/mailman/listinfo/python-list
Re: Reinstall python 2.3 on OSX 10.3.5?
On Déardaoin, Feabh 3, 2005, at 01:52 America/Chicago, Robert Kern wrote: Christian Dieterich wrote: On Dé Céadaoin, Feabh 2, 2005, at 17:48 America/Chicago, [EMAIL PROTECTED] wrote: Hi there I started a very long and roundabout process of attempting to install python 2.3.4 along side my apple-installed 2.3 system. To make a long story short, I have completely confabulated my environment ( i deleted the 2.3 binaries and so forth from the system in an attempt to start things fresh), and now I cannot figure out how to reinstall the base 2.3 Apple python distribution. Can somebody please point me in the right direction? You could use fink install python which makes you a Python installation under /sw. But that doesn't solve his problem, which is to restore the Apple-supplied Python that he deleted. Agreed. I was not aware that the preinstalled Python differs from a normal one. I implicitely assumed he would link /usr-Python to /sw-Python, and then continue using fink for not to interfere with /usr anymore. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Hey, get this!
In article [EMAIL PROTECTED], Steve Holden [EMAIL PROTECTED] wrote: If it's a path importer, it could be a cookie, specific to the importer. I think in Steve's case initializing __path__ to [*db*] should work. Just And that's exactly the conclusion I came to when import of the package's submodules didn't work as anticipated. Coming to the question of writing a customer importer from the documentation I discovered there is a huge amount of layered cruft in the import scheme going all the way back to the days of the ni module. It took me two aborted attempts just to realize I should be using PEP 302 and not ihooks or some wrapper around __import__(). Yes. PEP 302 came about when I tried to reimplement PEP 273 (zip import) in a sane way (saner is probably as far as I got...). Import is indeed very confusing, especially because of packages. I tried to convince Guido at some point to simplfy package imports by getting rid of __path__ altogether (and then simply search for packagename/submodule.py on sys.path) but he disliked the idea of widening submodule imports that much. On the other hand, __path__ is a mutable list so people can get the same effect by adding stuff to it. While this may be interesting history it's very confusing, and I'm encouraging Alex Martelli to describe the current PEP-302-based scheme a little more fully in his forthcoming revision to the Nutshell. The PEP is just a little terse in places, I feel. Yeah, it's a PEP, not official documentation, but since there isn't any official documentation, all you've got is the PEP :( I'm also wondering if the inspect module shouldn't have a facility to hook into custom importers, since its code is pretty much filestore based at present. This should probably be via an *optional* API to avoid breakage in existing custom importers. Probably. Just -- http://mail.python.org/mailman/listinfo/python-list
Re: Computing class variable on demand?
This seems to be what I need. My use case is to do lengthy intialization as late as possible. In this case this is to initialize class variables. Does this make sense? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Calling a method using an argument
Dear All, I have a simple class class hello: def world(self): return 'hello' def test(self,arg): return self.arg When I want to do is: hello.test('world') 'hello' i.e. pass the method name as an argument. How should I do this? Thanks Colin -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is WSAEnumNetworkEvents???
[EMAIL PROTECTED] wrote: I was trying to write an asyncronous TCP server for win32 using WSAEventSelect (which lives if win32file). Such events require WaitForMultipleObjects (which lives if win32event) and WSAEnumNetworkEvents WHICH IS NOT EXPOSED. This makes WSAEventSelect useless. Does somebody know how to add the WSAEnumNetworkEvents and WSANetwotkEvents structure win32file? Maybe I'm missing something? You could both build the structures and call the functions in ctypes (http://starship.python.net/crew/theller/ctypes/) [untested code follows] from ctypes import * class WSANETWORKEVENTS(Structure): _fields_ = [('lNetworkEvents', c_long), ('iErrorCode', c_int * 10) # 10 = FD_MAX_EVENTS ] You'd access the API via windll.ws2_32.WSAEnumNetworkEvents, e.g. networkEvents = WSANETWORKEVENTS() i = windll.ws2_32.WSAEnumNetworkEvents(s, hEventObject, byref(networkEvents)) if i != 0: # Handle an error HTH, Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling a method using an argument
Diez B. Roggisch wrote: def test(self,arg): return getattr(self, arg) Oops, missed the calling: def test(self,arg): return getattr(self, arg)() If you have more args, do this: def test(self, *args): return getattr(self, args[0])(*args[1:]) -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Type inference, lessons learned from Vyper
Hey all, I came across a fascinating thread on the Caml mailing list this morning. It's about writing an interpreter for Python that can do type inference, and John Skaller shares a lot of his experiences with the Vyper project: http://groups-beta.google.com/group/fa.caml/browse_frm/thread/4f65d0484529848e/ As you may recall, Vyper was an implementation of Python written in OCaml. The source code has apparently gone to bit-heaven, but Skaller's analysis gives some illuminating insight into the kinds of problems we might run into if Python is to become more statically verifiable. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. talking about music is like dancing about architecture. -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes and class variables
Thanks, Nick and Alex, for the nice, detailed explanations. My understanding of Python bytecode is not deep enough to comment at this time. ;) -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. talking about music is like dancing about architecture. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling a method using an argument
Diez B. Roggisch wrote: If you have more args, do this: def test(self, *args): return getattr(self, args[0])(*args[1:]) This would be cleaner written as: def test(self, method, *args): return getattr(self, method)(*args) and for complete generality: def test(self, method, *args, **kw): return getattr(self, method)(*args, **kw) -- http://mail.python.org/mailman/listinfo/python-list
Sendmail with many attach and recipients
Here, my code of sendmail If Somebody had a doubt please contact me? [EMAIL PROTECTED] # -*- coding: cp1252 -*- ## Faz o import das bibliotecas necessarias. import mimetypes import os.path import smtplib import sys from email.Encoders import encode_base64 from email.MIMEAudio import MIMEAudio from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText ## Funcao para criar lista baseada nos argumentos ## Isto vai ser utilizado para os destinatarios ## como para os arquivos anexados. def cria_lista(arg): lista=[] for elemento in arg.split(): lista.append(elemento) return lista ##Faz o anexo dos arquivos a mensagem ##os parametros é o caminho completo do arquivo e o nome do arquivo ##para fazer o anexo. def getAttachment(path, filename): ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(path, 'rb') if maintype == 'text': attach = MIMEText(fp.read(),_subtype=subtype, _charset=iso-8859-15) elif maintype == 'message': attach = email.message_from_file(fp) elif maintype == 'image': attach = MIMEImage(fp.read(),_subtype=subtype) elif maintype == 'audio': attach = MIMEAudio(fp.read(),_subtype=subtype) else: print maintype, subtype attach = MIMEBase(maintype, subtype) attach.set_payload(fp.read()) encode_base64(attach) fp.close attach.add_header('Content-Disposition', 'attachment',filename=filename) return attach ## Verifica se o primeiro parametro passado para o programa e --h ## chama o help. if sys.argv[1] == '--h' : print 'sendmail servidor de email From To [Assunto] [Mensagem] [Anexos] [Arquivo de log]\n' print 'servidor: Servidor SMTP de email.\n' print 'From: Quem esta enviando o email. (Ex.: [EMAIL PROTECTED]) \n ' print 'To: lista de destinatarios do email. (Ex.: [EMAIL PROTECTED] [EMAIL PROTECTED]) \n' print '[Assunto]: Assunto do email \n' print '[Mensagem]: Mesangem do corpo do email \n' print '[Anexos]: Lista de arquivos anexos (Ex:C:\\relatorios\\rel1.pdf C:\\relatorios\\rel2.pdf) \n' print '[Arquivo de log] Diretório onde será gerado o log da aplicação ex: C:\\temp\\sendmail.log' print 'Ex: sendmail smtp.fx.com.br [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] teste de email isto e apenas um teste C:\\temp\\rel2.pdf C:\\temp\\rel1.pdf C:\\temp\\sendmail.log \n' print 'Parâmetros entre chaves[] são opcionais, os outros parâmetros são obrigatórios' else: msg = MIMEMultipart() ## o 1º parametro e o servidor SMTP. servidor_smtp=sys.argv[1] ## o 2º parametro e quem esta enviando o anexo. msg['From']=sys.argv[2] ## o 3º parametro e a lista de destinatários. toaddrs=cria_lista(sys.argv[3]) ## o 4º parametro e o assunto da mensagem. msg['Subject'] = sys.argv[4] ## o 5º parametro e a mensagem do corpo do email. mensagem=sys.argv[5] ## o 6º parametro cria a lista de arquivos. arquivos=cria_lista(sys.argv[6]) ## o 7º parametro especifica onde será gerado o arquivo de log dir_log=sys.argv[7] ##Verifica se é vazio o arquivo if dir_log == : dir_log=C:\\temp\\sendmail.log ## executa um loop na lista de arquivos ## e chama a funcao que anexa os arquivos. for arq in arquivos: path = arq filename = os.path.basename(arq) attach = getAttachment(path, filename) msg.attach(attach) ## texto do corpo do email que sera anexado. text=MIMEText(mensagem,_charset=iso-8859-15) msg.attach(text) ## Busca o servidor de SMTP e faz a conexao. try: server = smtplib.SMTP(servidor_smtp) ## Faz o envio do email. server.sendmail(msg['From'],toaddrs,msg.as_string()) ## Fecha a conexão com o servidor. server.quit() except Exception, e: arq=open(dir_log,'a') print arq, Falha no envio da mensagem de email, não foi possivel a conexão ao servidor %s % servidor_smtp arq.close -- http://mail.python.org/mailman/listinfo/python-list
Re: CONTEST - What is the (best) solution?
The data contains only references to variables in the local namespace an not literal values. Since local variable names cannot include '{' or '}' characters, my solution does in fact meet the criteria outlined. Larry Bates Fuzzyman wrote: Doesn't work if '{' or '}' can appear in the values. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirecting stdout/err under win32 platform
Pierre Barbier de Reuille [EMAIL PROTECTED] writes: AFAIK, there is no working bidirectionnal pipes on Windows ! The functions exists in order for them to claim being POSIX, but they're not working properly. (...) Can you clarify what you believe doesn't work properly? The os.popen* functions under Windows use native CreateProcess calls to create the child process and connect stdin/out/err handles to that child process, so should behave properly. (Subject of course to the same risk of deadlocks and what not due to buffering or queued up data that any system would have with these calls) -- David -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding user's home dir
My own, less than perfect, way of finding the users home directory is like this: def personal_directory ( default = None ): pdir = None if sys.platform.startswith ( 'win' ): import _winreg reg = _winreg.ConnectRegistry ( None, _winreg.HKEY_CURRENT_USER ) pkey = _winreg.OpenKey ( reg, rSoftware\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders ) pdir = _winreg.QueryValueEx ( pkey, 'Personal' )[0] _winreg.CloseKey ( pkey ) _winreg.CloseKey ( reg ) else: pdir = os.getenv ( 'HOME' ) if not pdir: pdir = default return pdir -- Michael [EMAIL PROTECTED] http://kavlon.org -- http://mail.python.org/mailman/listinfo/python-list
character sets? unicode?
I'm trying to import text from email I've received, run some regular expressions on it, and save the text into a database. I'm trying to figure out how to handle the issue of character sets. I've had some problems with my regular expressions on email that has interesting character sets. Korean text seems to be filled with a lot of '=3D=21' type of stuff. This doesn't look like unicode (or am I wrong?) so does anyone know how I should handle it? Do I need to do anything special when passing text with non-ascii characters to re, MySQLdb, or any other libraries? Is it better to save the text as-is in my db and save the character set type too or should I try to convert all text to some default format like UTF-8? Any advice? Thanks. -- Michael [EMAIL PROTECTED] http://kavlon.org -- http://mail.python.org/mailman/listinfo/python-list
Sendmail with many attach and recipients
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Here, my code of sendmail If Somebody had a doubt please contact me? [EMAIL PROTECTED] [snip] If you have multiple recipients, you need to modify server.sendmail(msg['From'],toaddrs,msg.as_string()) to failed = server.sendmail(msg['From'],toaddrs,msg.as_string()) # exception is only raised if ALL recips fail # failed is a list of failed recips, or empty You could also expand your smtplib exception handling [not tested] try: server = smtplib.SMTP(servidor_smtp) ## Faz o envio do email. try: failed = server.sendmail(msg['From'],toaddrs,msg.as_string()) if failed: do something ## Fecha a conexão com o servidor except smtplib.SMTPRecipientsRefused, x : #all recips failed before data sent = MSG failed do something except smtplip.SMTPDataError, x: # an error at the end of the message body receipt = MSG Failed do something except smtplib.SMTPSenderRefused, x : # the sender was refused = MSG failed do something except: #can't connect do something finally server.quit() except Exception, e: arq=open(dir_log,'a') print arq, Falha no envio da mensagem de email, não foi -- = Tim Williams -- http://mail.python.org/mailman/listinfo/python-list
Re: convert ftp.retrbinary to file object? - Python language lacks expression?
Robert wrote: That turns into periodic new RETR commands with offset. Think its more an odd trick. I'd even prefer a threaded approach (thread puts the blocks into a stack; a while ... yield generator loop in the main thread serves the .read() function of the pseudo file object, which is my wish). Yet such tricks are all kind of OS-level tricks with a lot of overhead. I wonder really, if the Python language itself can express an elegant flat solution to turn the block delivering callback function into a generator/.read(bytes) solution? I found no way. Don't know whether this would be helpful as a starting point, but a while (hmm, some years ...) ago I wrote an example of how FTP could be used as a file-like object. Look for ftpStream.py on http://www.holdenweb.com/Python/ Of course, in those days files could do a bit less than they can now, so there's no attempt to provide an iterator interface. (Looking over some Ruby stuff, Ruby seems to be able to do so from the language. I am not really familiar to Ruby. I always felt Python to be as complete - but much more clean. I became somewhat jealous ... :-) ) As the solution in my case has to stand many different file systems compatibly ( file.read(bytes) function !) and also other FTPS SFTP classes with different retrbinary functions have to be compatible, I cannot even make a simple FTP subclassed retrbinary without getting really weired. Thus the existing .retrbinary with callback is the official interface in this game. You will note that my code uses delegation to an FTP object rather than inheritance. Maybe you would find that approach more fruitful for your application. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: global variables
Probably naming it something other than 'globals' would be a good idea -- otherwise you'll hide the builtin globals() function. But I agree that the attributes of a class instance (as you suggest) or the attributes of a module (as Steve Holden suggests) is probably the right way to go. I like to use 'runtime' or 'runtime_options' to store the results of command-line options. I wasn't sure about this way of getting Python to handle global variables when I first tried it but after a little experience with it I think it works out pretty well. One thing I did learn though is that it's best to keep these modules simple. Don't make them import or define classes or functions if you can avoid it. It's easy to get into a mess of recursive imports if you start doing that. Just a good newbie tip. *** if runtime.verbose: print 'Something happened.' *** -- Michael [EMAIL PROTECTED] http://kavlon.org -- http://mail.python.org/mailman/listinfo/python-list
ModPython: passing variables between handlers?
Diez B. Roggisch wrote: Hi, first of all - please quote appropriately - especially if you receive the postings as digest. That prevents the signal-to-noise-ratio dropping to unknown lows... Your responses will give me the required lifetime for my variables, but not the required access at all levels of code (unless req is a global variable?). Do you have any other suggestions as to how this might be implemented? If the code you showed us _is_ what you use - then req seems to be a global variable. Otherwise it won't work. Yes, I've changed the subject line to try and avoid too much further confusion. Andrew, you are aware, I take it, that the request object is provided as an argument to each handler that's called for a request? Using any kind of global in mos_python code is dangerous because of the potential for one request's changes to overwrite another's. I've had to deal with similar complications in my own code, but you may want to think about biting the bullet. Globals are almost always a bad idea in multi-user contexts like this. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
exporting mesh from image data
I am trying to generate a mesh for a finite volume solver (gambit, fluent) from 3D image data (CT, MRI). To generate the fluent msh file, you need not only a list of vertices and polygons, much like what is available in the vtk file format, but also the volume elements in the mesh that the polygons abut. Eg for a given triangle in the mesh, you would have a line like 3 3 2 1 11 0 which is numfaces vert0 vert1 vert2 vol1 vol2 where vol1 and vol2 are indices that indicate the volume in the mesh that the triangle belongs to (vol2 is 0 for triangles on the surface). The specific problem at hand involves building a mesh for ventricles in the brain. I have no trouble building the isosurface that surrounds the ventricles using the marching cubes and connectivity filters in VTK, but now need to be able to generate a mesh over the interior and assign volumes to faces. Does such capability exist in VTK? and if so I would be thankful for pointers to class docs or examples. Are there other algorithms in the world of python 3D libraries that can provide 3D meshes for 2D surface isocontours, assigning volume elements from the mesh to the surfaces that surround the volume. Thanks! JDH -- http://mail.python.org/mailman/listinfo/python-list
Re: character sets? unicode?
Michael wrote: I'm trying to import text from email I've received, run some regular expressions on it, and save the text into a database. I'm trying to figure out how to handle the issue of character sets. I've had some problems with my regular expressions on email that has interesting character sets. Korean text seems to be filled with a lot of '=3D=21' type of stuff. looks like http://python.org/doc/lib/module-quopri.html plus perhaps some encoding. instead of rolling your own message handling code, consider using this package instead: http://python.org/doc/lib/module-email.html in either case, the MIME specification is required reading here (for a link, see the quopri page above). Do I need to do anything special when passing text with non-ascii characters to re depends on your patterns. by default, RE operators like \w and \s assume ASCII. to use other encodings, use the (?u) flag and convert your text to Unicode before passing it to the RE module. Is it better to save the text as-is in my db and save the character set type too or should I try to convert all text to some default format like UTF-8? depends on your application; using a standard encoding has many advantages, but storing the original text as is guarantees that no information is lost, even if you have bugs in your conversion code. when in doubt, save the original and do the conversion on the way out. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Integrated Testing - Peppable?
Thanks, Jeremy, No prose can compare to a live, functional demonstration. I agree; that's what my prototype amounts to: http://prdownloads.sourceforge.net/zbt/zbt.zip?download (sorry, it's Windows-only) But I take your larger message, and John's, to heart - this isn't worthy of making it into Python. OK; thanks anyway for taking the time to think about it and reply. Peace, --Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: global variables
Steve Holden wrote: M.E.Farmer wrote: Ok it has been a long day, In my reply to Steven Bethard , Steve should read Steven ;) M.E.Farmer Well, since he signs himself Steve too I guess we'll just have to put up with the ambiguities. Or perhaps, given my (lack of) typing skill, I should just start signing myself Stvev? regards Steve Or I can stop correcting it every time I type STeve[1]. ;) STeve [1] But of course, you probably do the same thing too. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy Q: dealing with object type
Just wrote: In article [EMAIL PROTECTED], Steven Bethard [EMAIL PROTECTED] wrote: py class A: ... pass ... py class B: ... pass ... py a = A() py a.__class__ == A True py a.__class__ == B False Uh, isinstance(a, A) works for both new-style and old-style classes. Heck, isinstance() even works in Python 1.5.2... The OP asked Given some object ... how do you test its type?. I interpreted this as a strict check, not a transitive check: py class A: ... pass ... py class B(A): ... pass ... py b = B() py isinstance(b, B) True py isinstance(b, A) True py b.__class__ == B True py b.__class__ == A False Of course, if the OP doesn't need the strict check here, isinstance is, of course, the right answer. STeve -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy Q: dealing with object type
Erik Johnson wrote: Steven Bethard [EMAIL PROTECTED] wrote: py class A: ... pass ... py class B: ... pass ... py a = A() py a.__class__ == A True py a.__class__ == B False Just [EMAIL PROTECTED] wrote Uh, isinstance(a, A) works for both new-style and old-style classes. Heck, isinstance() even works in Python 1.5.2... Oh, there! Not that there is anything wrong with new classes, but that is just the sort of thing that I expected to find. No, neither of these is bad at all. I was looking for something like the obj.__class__ attribute, but I couldn't see it under dir(obj). So, why is _class__ magically tucked away where you can't see it? That doesn't seem very Pythonic. I also looked in my two python books for instance(), or instanceof() functions - wasn't seeing anything. Actually, now that I check the indices of Learning Python 1E Programming Python 2E, I don't see isinstance() either. How unfortunate. :( Unfortunate but, given that this introspection is normally considered to be a fairly advanced language feature, hardly surprising. As an aside, I notice a lot of other people's interpreters actually print 'True' or 'False' where my system prints 0 or 1. Is that a configuration that can easily set somewhere? Nope, it's a version thing. I believe Booleans were introduced at some odd point like 2.2.1. Until then True and False were just names like any other. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
About standard library improvement
Hi! If I make some improvement to xmlrpclib module, where I should send this improvement to form part of next standard library release? Thank -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy Q: dealing with object type
Erik Johnson wrote: As an aside, I notice a lot of other people's interpreters actually print 'True' or 'False' where my system prints 0 or 1. Is that a configuration that can easily set somewhere? $ python2.1 -c print 1 == 1 1 $ python2.2 -c print 1 == 1 1 $ python2.3 -c print 1 == 1 True $ python2.4 -c print 1 == 1 True /F -- http://mail.python.org/mailman/listinfo/python-list
Re: About standard library improvement
Frank Abel Cancio Bello wrote: If I make some improvement to xmlrpclib module, where I should send this improvement to form part of next standard library release? http://sourceforge.net/tracker/?group_id=5470atid=305470 /F -- http://mail.python.org/mailman/listinfo/python-list
Re: About standard library improvement
Frank Abel Cancio Bello wrote: Hi! If I make some improvement to xmlrpclib module, where I should send this improvement to form part of next standard library release? Thank Well done! The standard place to lodge patches (whether for bug fixes or improvements) is SourceForge. You'll need an account to submit patches or bugs, IIRC. Once you've created your account, log in and go to http://sourceforge.net/tracker/?group_id=5470atid=305470 and click Submit New. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing Filenames with non-Ascii-Characters
Hi, Python's drive towards uncompromising explicitness pays off big time when you're dealing with multilingual data. Except for the very implicit choice of 'ascii' as an encoding when it cannot make a good guess of course :-). All in all I agree, however. Ciao, MM -- Marian Aldenhövel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de There is a procedure to follow in these cases, and if followed it can pretty well guarantee a generous measure of success, success here defined as survival with major extremities remaining attached. -- http://mail.python.org/mailman/listinfo/python-list
Re: [EVALUATION] - E01: The Java Failure - May Python Helps?
On Thu, 03 Feb 2005 09:26:08 +0200, Ilias Lazaridis wrote: My question is essentially: How many of those constructs are already supported by python (and the surrounding open-source-projects): http://lazaridis.com/case/stack/index.html This post is hard to follow, but I'm going to assume this is the core question, as it is labelled as such. The first thing that leaps to mind is that you need to play with Python for a bit to get a full analysis of it. Due to the nature of Python, some of the things you have in that list don't really apply. The most obvious example of this is code generation: Assuming you mean what I think you mean, the sort of thing you have in the C++ or Java world where you click a couple of boxes, push next a few times, and have several hundred kilobytes of impenetrable source code pop out as your project's framework, it doesn't generally apply. In Python, you can actually write frameworks that can be made to do useful things in a small handful of lines. For a good example of that, I'd recommend the Twisted tutorial: http://twistedmatrix.com/documents/current/howto/tutorial/index . In Python, if a framework makes you write reams of boilerplate... it's probably because someone just came from Java and isn't thinking in Python yet. :-) Code generation in Python is generally a non-starter. (Few rare counterexamples, but it's nothing like the Necessary Crutch it is in the C++ world.) Generally, every line in that Twisted tutorial, even in the final program, is *doing something*, not satisfying the framework with necessary boilerplate. As for the rest of your requirements, you have specified your technology stack in terms of *goals*, not capabilities, so for quite a lot of them, there is no answer except, Yes, Python can do that, and generally easier than most anything else. For instance, Use of metadata within the design (on text level [code file]) can mean a thousand things. For what it's worth, Python tends to make it so easy I do it all the time, but for any given way you mean it, I can't promise there exists a pre-rolled framework for you. So I can only speak generally. Given your list, you may find that Python is weak in the graphical programming department; drop-and-drop GUI generation isn't as well-tuned as VB. (I, for one, consider that development methodology toxic and actively dangerous, but I can understand why you miss it.) Skipping down to your evaluation sequence: * Create a class: Well, I'll show you this one: class Something: pass There, a class. * Simple GUI: You may wish to check out Boa Constructor, as the closest thing to the GUI generator you probably want. There are at least 3 major viable GUI toolkits for Python and several other minor (but still capable) ones. * Embedded DBs: I don't know, Google for your embedded DB name + Python. Failing that, there are several ways to wrap your embedded DB such that a Python program can use it. * Web GUI: There are more Python web frameworks than you can shake a stick at, and I don't mean some guys hacked together templating system either; there are a lot of very mature systems out there, expressing a lot of different philosophies. Given some of your other requirements, for a web-based application I'd recommend examining Zope. * Deployment: I don't generally have enough problems with this to be worth thinking about. I don't know what the state of the remote debugging is on Python; Google remote debugging Python. * For your complex updates, I see two distinct things there; half of the depend on the database, not Python. For the other half, it depends on if you mean while the program is still running. If so, they are challenging. If not, they are trivial. * I'd recommend adding testability to your stack, and refer you to the unittest module; others can suggest their preferred testing modules, but I tend to stick with that as the general framework is available in a lot of languages that I use. If by evolutive development you are including the ideas behind agile software development (hard to tell if you mean that, or a community open to change*) Based on what I see here, I have two basic comments. First, yes, Python is probably as close as you are going to get in an existing system to what I think you are looking for. It isn't perfect, but you will also be able to reasonably extend it for your needs. Second, Python has a different philosophy; you recognize the need for a different philosophy and I extremely strongly suggest that you take the time with Python to sort out what you truly need from what you think you need due to still thinking with your old philosophy. (For example, given my aforementioned reasons why code generation isn't an issue in Python, I strongly suggest you embrace Python and give it a chance, rather than force 'code generation' on top of it.) You've got some exciting learning to do, and some interesting philosophy shifts to absorb, but I think you'll find, as a lot of use have, that even
Re: Integrated Testing - Peppable?
On Thu, 03 Feb 2005 09:40:55 -0800, [EMAIL PROTECTED] wrote: Thanks, Jeremy, No prose can compare to a live, functional demonstration. I agree; that's what my prototype amounts to: http://prdownloads.sourceforge.net/zbt/zbt.zip?download (sorry, it's Windows-only) But I take your larger message, and John's, to heart - this isn't worthy of making it into Python. OK; thanks anyway for taking the time to think about it and reply. But I do encourage you, if you believe in this, to continue working on it as a module. Unfortunately, I don't run Windows so if it's Windows only I can't really look at that. I would certainly be interested in at least trying it if you ever got a more generally cross-platform release. Be sure to ANN: ounce it here, if you do. As I just wrote in another message (although stated another way), useful and in the standard library aren't necessarily related! -- http://mail.python.org/mailman/listinfo/python-list