Re: Optimization: Picking random keys from a dictionary and mutating values
On May 28, 4:41 pm, blaine [EMAIL PROTECTED] wrote: 1. Whats a good way to get the keys? I'm using a loop with random.choice() at the moment. Why not keep a separate list of keys and use random.sample()? Raymond -- http://mail.python.org/mailman/listinfo/python-list
How to get all the variables in a python shell
Hi! I'm currently working on a scientific computation software built in python. What I want to implement is a Matlab style command window - workspace interaction. For example, you type 'a=1' in the command window, and you see a list item named 'a' in the workspace. You double click the icon of the item, and you see its value. You can modify the value of the list item, 1 - 100 etc, after which if you go back to the command window and type 'a' and press enter, you see that varable a's value has been changed to 100. So my question is : if you have two DOS command windows running under WINDOWS OS, how can you make them share the same internal variable buffer? Or is there any easier way to implement such kind of interaction? Maybe I could just build a small database to store all the values and access them from both programs, but chances are sometimes I have to deal with big arrays, and they will eat extra memory if I keep them in a database. Is there anyway to access a shell's local memory buffer? I tried to use shell.interp.locals() in wxPython, but there's too many variables in the list which I don't actually need. Come on guys, give me some ideas. Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimization: Picking random keys from a dictionary and mutating values
On May 28, 7:41 pm, blaine [EMAIL PROTECTED] wrote: Hey everyone, Just a friendly question about an efficient way to do this. Friendly advance reminder: in many optimization problems, the objective function is far more expensive to calculate than the optimizing procedure. Your time is usually better spent optimizing the objective function, or tuning the optimizer. But what they hey. I have a graph with nodes and edges (networkx is am amazing library, check it out!). I also have a lookup table with weights of each edge. So: weights[(edge1, edge2)] = .12 weights[(edge2, edge5)] = .53 weights[(edge5, edge1)] = 1.23 weights[(edge3, edge2)] = -2.34 etc. I would like to take this weight table and subject it to evolutionary mutations. So given a probability p (mutation rate), mutate edge weights by some random value. So in effect, if p is .25, choose 25% random edges, and mutate them some amount. So: 1. Whats a good way to get the keys? I'm using a loop with random.choice() at the moment. That's probably the best way. You might be able to squeeze a little more speed out of it by using a partial random shuffle as opposed to removing the item from the list. This will minimize the amount of copying. Here's an example (without error checking): def partial_random_shuffle(lst,nshuffled): for i in xrange(nshuffled): j = random.randrange(i,len(lst)) t = lst[i] lst[i] = lst[j] lst[j] = t The first nshuffled items of lst upon return will be the selected items. Note: This might also be slower than removing items. It should scale better, though. 2. Any comments on how to get a 'fair' mutation on an existing edge value? random.normalvariate is usually a good choice for selecting random real-valued increments. val = random.normalvariate(val,sigma) where sigma, the standard deviation, is the amount I currently am doing something like this, which seems like it leaves something to be desired. import random weights = generateweights() # generates table like the one above p = 0.25 v = random.betavariate(2, 10) num = int(v*len(weights)) # How many weights should we mutate? keys = w.keys() for i in xrange(num): val = random.choice(keys) # Choose a single random key w[val] = w[val]*(random.random()*5-1) # Is this a 'good' way to 'mutate' the value? If you don't remove keys[val], there's a chance you'll mutate the same key twice, which I doubt is what you want. This is an evolutionary search, so mutate in this sense relates to a genetic algorithm, perhaps a gradient decent? A gradient descent method is not an evolutionary search and involves no randomness (unless noise is added to the objective, which is a possible way to attack a function with unimportant small scale features, and in that case normalvariate would be the thing used). Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Anyone using TestNG
-- http://mail.python.org/mailman/listinfo/python-list
Re: How to get all the variables in a python shell
On 2008-05-29, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi! I'm currently working on a scientific computation software built in python. What I want to implement is a Matlab style command window - workspace interaction. ok, although I personally favor the style of writing and running a script/program, since it scales much better (you can easier automate steps), and it is much easier reproducible (something you probably want in scientific software) and storable (in a VCS). For example, you type 'a=1' in the command window, and you see a list item named 'a' in the workspace. You double click the icon of the item, and you see its value. You can modify the value of the list item, 1 - 100 etc, after which if you go back to the command window and type 'a' and press enter, you see that varable a's value has been changed to 100. I do hope you have made a fair estimate of the amount of work that it costs to change the value of a variable in this way. I would propose to simply use the interactive Python prompt. It doesn't give you popup icons for clicking, but you do get the entire Python interpreter, and all its libraries for free. The Python library has a frame work for customizing the interpreter. Have a look at 'cmd' module. So my question is : if you have two DOS command windows running under WINDOWS OS, how can you make them share the same internal variable buffer? Or is there any easier way to implement such kind of interaction? Now you have lost me. One window is not enough for interaction? Obviously, you'll need to have a common interpreter/storage backend. One solution may be to have a common execution back-end, and for each window a 'frontend' which passes commands entered to the back-end, and echoes results from the back-end to the terminal. Maybe I could just build a small database to store all the values and access them from both programs, but chances are sometimes I have to deal with big arrays, and they will eat extra memory if I keep them in They eat memory when you keep them in a data base? It seems, you are making assumptions about implementations here without telling them. (ie pick a data base that uses a disk, and your problem is solved. Why is that not an option?) Sincerely, Albert -- http://mail.python.org/mailman/listinfo/python-list
How do I tell imconplete input from valid input?
Hi everyone, I am developing the console which has the embedded Python interactive interpreter. So, I want to judge whether current command is complete or not. Below is good example to solve this problem. // // http://effbot.org/pyfaq/how-do-i-tell-incomplete-input-from-invalid-input.htm // int testcomplete(char *code) /* code should end in \n */ /* return -1 for error, 0 for incomplete, 1 for complete */ { node *n; perrdetail e; n = PyParser_ParseString(code, _PyParser_Grammar, Py_file_input, e); if (n == NULL) { if (e.error == E_EOF) return 0; return -1; } PyNode_Free(n); return 1; } But, I think this code has a problem. For example, when argument 'code' has below python command, if x % 2: print odd at the current situation, this function returns COMPLETE! But, I think that sometimes users want to type else statement. So, I expected to get INCOMPLETE from this function, but I didn't. How should I do it? Thanks, urai -- http://mail.python.org/mailman/listinfo/python-list
Re: Struct usages in Python
Yes. That is the somewhat unfortunate difference between new-style and old-style classes. Use new-style if you can, and that means that object must be part of the inheritance graph. ... You are wrong for Python 2.X, but right for Python 3 where old-style classes are gone for good. Thanks, I don't knew it before and it's a sensitive information for me. -- Best regards, Alex Gusarov -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flaming Thunder
Dave Parker [EMAIL PROTECTED] wrote: Catch doesn't return just error types or numbers, it can return any object returned by the statements that are being caught; catch doesn't care what type they are. For example: Writeline catch(set x to hello world.). will write hello world. I really don't get this. Surely the point about an error being thrown to a catch statement is that the error path is separate from the normal execution path? What you are doing here is ensuring that unexpected errors have no chance at all of propagating up to the top level: they are invariably going to get caught by some other handler that was installed just because someone was too lazy to write a set statement followed by a writeline. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Struct usages in Python
Yes. That is the somewhat unfortunate difference between new-style and old-style classes. Use new-style if you can, and that means that object must be part of the inheritance graph. ... You are wrong for Python 2.X, but right for Python 3 where old-style classes are gone for good. Thanks, I don't knew it before and it's a sensitive information for me. -- Best regards, Alex Gusarov -- http://mail.python.org/mailman/listinfo/python-list
Re: Struct usages in Python
Yes. That is the somewhat unfortunate difference between new-style and old-style classes. Use new-style if you can, and that means that object must be part of the inheritance graph. ... You are wrong for Python 2.X, but right for Python 3 where old-style classes are gone for good. Thanks, I don't knew it before and it's a sensitive information for me. -- Best regards, Alex Gusarov -- http://mail.python.org/mailman/listinfo/python-list
Re: pydb remote debugging/cmd.Cmd over socket?
As part of the 2006 Google Summer of Code project Matt Flemming started working on remote debugging in pydb. Alas it wasn't completed and I let the code fall through the cracks. Matt claimed it worked to some degree but I could never get it to work for me. Most definitely the code has atrophied. The user interface was loosely based or reminiscent of gdb. So you'd run pydbserver either as a command inside the debugger or as an option to pydb or call inside Python pdbserver after importing. There is a connection class (file pydb/connection.rb) which was to allow different kinds of protocols, like a socket connection or a serial line connection, or maybe even two FIFO's so that you could connect to a different process on the same computer. And there were some commands on the user-interaction side to attach or detach the Python program you want to debug. If you look in pydb.py.in and gdb.py.in you'll see some code commented out with double hashes which is part of this effort. I invite you or others to try to resurrect this effort. However as I look at the code now, it doesn't make much sense other than the broad outline given above. Hm. Ok, I'll look into that. It's just that I don't get cmd.Cmd to work against two streams. Maybe I need to dive into unix-coding a bit deeper again. Another approach and possibly a much simpler one if you are looking for a Python debugger which supports remote debugging is Winpdb http://winpdb.org/ by Nir Aides. I've found that - and while it's nice, it has one problem: I can only start it with winpdb governing the process already, preventing python from starting. In contrast, the possibility to use a sginal to start the debugger of pydb is great, so that's the reason I want to stick with it. Diez -- http://mail.python.org/mailman/listinfo/python-list
code of a function
Hi, Is there any command in Python which gives the code for a function like just typing the name of a function (say svd) in R returns its code. Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get all the variables in a python shell
[EMAIL PROTECTED] wrote: I'm currently working on a scientific computation software built in python. What I want to implement is a Matlab style command window - workspace interaction. For example, you type 'a=1' in the command window, and you see a list item named 'a' in the workspace. You double click the icon of the item, and you see its value. You can modify the value of the list item, 1 - 100 etc, after which if you go back to the command window and type 'a' and press enter, you see that varable a's value has been changed to 100. So my question is : if you have two DOS command windows running under WINDOWS OS, how can you make them share the same internal variable buffer? Or is there any easier way to implement such kind of interaction? I stronly suggest you look at IPython [1]. To do what I think you're describing, you'd need to hack or reimplement the interpreter. And that's what they've done. ISTR that they even have a branch which is dealing with parallel instances. TJG [1] http://ipython.scipy.org/moin/ -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
On 2008-05-24, Fuzzyman [EMAIL PROTECTED] wrote: A worthwhile question for the OP - your patch seems fairly simple. Is it easy for you to extend unittest for your own testing needs by subclassing? I've been ill the last days, but I will look into this possibility. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
run a script in vista
Hi, I have a script which runs in xp, however now I have upgraded to vista this script now does'nt work Can someone help with this problem please ? this is the start of the script import cPAMIE import cModalPopUp import winGuiAuto as wga import time, datetime import os, sys, re import mx.ODBC.Windows as odbc appreciate any help here Regards Graham -- http://mail.python.org/mailman/listinfo/python-list
Finding file details...
I've been trying to figure out how to find the details of files (specifically music for now) for a little sorting script I'm making, My aim is to get details on the artist, album, and genre for mp3 and wma files (possibly more in the future). My closest match was when I stumbled accross PyMedia, but it only supports up to 2.4 (I have 2.5). Now I see a bit mentioned on GetFileVersionInfo, but that doesn't seem to help (and most of it went over my head). Is there any module I can use to find this sort of data? I'm trying to not make it specialised in music, because I may want to extend this to picture, movie, text etc. files in the future. Any ideas how I could go about this? -- http://mail.python.org/mailman/listinfo/python-list
Re: run a script in vista
Graham Feeley wrote: Hi, I have a script which runs in xp, however now I have upgraded to vista this script now does'nt work Can someone help with this problem please ? this is the start of the script import cPAMIE import cModalPopUp import winGuiAuto as wga import time, datetime import os, sys, re import mx.ODBC.Windows as odbc You're not helping very much here: what does now doesn't work mean? It doesn't even start? It runs but gives an error? If so, what's the traceback? etc. etc. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: code of a function
Dark Wind wrote: Hi, Is there any command in Python which gives the code for a function like just typing the name of a function (say svd) in R returns its code. Thank you Nope. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Compare 2 files and discard common lines
I have a requirement to compare 2 text files and write to a 3rd file only those lines that appear in the 2nd file but not in the 1st file. Rather than re-invent the wheel I am wondering if anyone has written anything already? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I tell imconplete input from valid input?
On May 29, 9:26 am, たか [EMAIL PROTECTED] wrote: Hi everyone, I am developing the console which has the embedded Python interactive interpreter. So, I want to judge whether current command is complete or not. Below is good example to solve this problem. // //http://effbot.org/pyfaq/how-do-i-tell-incomplete-input-from-invalid-i... // int testcomplete(char *code) /* code should end in \n */ /* return -1 for error, 0 for incomplete, 1 for complete */ { node *n; perrdetail e; n = PyParser_ParseString(code, _PyParser_Grammar, Py_file_input, e); if (n == NULL) { if (e.error == E_EOF) return 0; return -1; } PyNode_Free(n); return 1; } But, I think this code has a problem. For example, when argument 'code' has below python command, if x % 2: print odd at the current situation, this function returns COMPLETE! But, I think that sometimes users want to type else statement. So, I expected to get INCOMPLETE from this function, but I didn't. How should I do it? Thanks, urai I guess you should use Py_single_input instead of Py_file_input in your code, which requires extra NEWLINE to end complex statement. Plz check details in Grammar/Grammar from python source distribution --Inyeol -- http://mail.python.org/mailman/listinfo/python-list
Re: code of a function
On Thu, May 29, 2008 at 9:10 AM, Dark Wind [EMAIL PROTECTED] wrote: Hi, Is there any command in Python which gives the code for a function like just typing the name of a function (say svd) in R returns its code. Thank you If you're using IPython, you can type svd?? . -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare 2 files and discard common lines
On May 29, 10:36 am, loial [EMAIL PROTECTED] wrote: I have a requirement to compare 2 text files and write to a 3rd file only those lines that appear in the 2nd file but not in the 1st file. Rather than re-invent the wheel I am wondering if anyone has written anything already? How large are the files ? You could load up the smallest file into memory then while iterating over the other one just do 'if line in other_files_lines:' and do your processing from there. By your description it doesn't sound like you want to iterate over both files simultaneously and do a line for line comparison because that would mean if someone plonks an extra newline somewhere it wouldn't gel. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare 2 files and discard common lines
loial wrote: I have a requirement to compare 2 text files and write to a 3rd file only those lines that appear in the 2nd file but not in the 1st file. lines_in_file2 = set(open(file2).readlines()) for line in open(file1): if line not in lines_in_file2: print line Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare 2 files and discard common lines
Kalibr wrote: On May 29, 6:36 pm, loial [EMAIL PROTECTED] wrote: I have a requirement to compare 2 text files and write to a 3rd file only those lines that appear in the 2nd file but not in the 1st file. Rather than re-invent the wheel I am wondering if anyone has written anything already? You can use the cmp(x, y) function to tell if a string is similar to another. Or ==. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare 2 files and discard common lines
On May 29, 6:36 pm, loial [EMAIL PROTECTED] wrote: I have a requirement to compare 2 text files and write to a 3rd file only those lines that appear in the 2nd file but not in the 1st file. Rather than re-invent the wheel I am wondering if anyone has written anything already? You can use the cmp(x, y) function to tell if a string is similar to another. going cmp('spam', 'eggs') will return 1 (spam is greater than eggs) (have no idea why) swapping the two give -1 and having 'eggs' and 'eggs' gives 0. is that what you were looking for? -- http://mail.python.org/mailman/listinfo/python-list
请教,关于Python对多处理器的支持,Pyth on在AIX下但CPU的效率比多CPU的效率高?
最近在公司在优化平台(C + Python实现的一个业务处理框架:C实现的一个网络服务接受来自外界的请求,收到请求后创建一个进程调用Python解释器执行Python脚本进行业务逻辑处理)发现Python脚本在 AIX下多处理器环境下运行的效率还不如在单处理器环境下的运行效率。我觉得这个跟GIL有关系,但我们的Python脚本里用的基本上都是Python自带的lib做一些简单的业务逻辑处理和数据库操作(DB2, 数据库操作模块是我们用C实现的一套DB API) 且没有用多线程。这似乎不应该出现处理器增多而性能下降的抖动现象啊。请问大家是否有着方面的经验,分享一下。谢谢! 另外问一下,Python在多处理器下的运行效率,难道只能通过C扩展的方式来提高吗?!把多线程换成多进程是否能起到一定的效果?! Python版本: 2.4 系统: AIX 5.3 DB: DB2 8.2 -- About Cyril.Liu --- Cyril 是一个程序员, 现在是个穷光蛋, 他常常跟自己说:我�找���有理想牛仔仔 http://blog.405studio.cn/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding file details...
Kalibr wrote: I've been trying to figure out how to find the details of files (specifically music for now) for a little sorting script I'm making, My aim is to get details on the artist, album, and genre for mp3 and wma files (possibly more in the future). My closest match was when I stumbled accross PyMedia, but it only supports up to 2.4 (I have 2.5). Now I see a bit mentioned on GetFileVersionInfo, but that doesn't seem to help (and most of it went over my head). Is there any module I can use to find this sort of data? I'm trying to not make it specialised in music, because I may want to extend this to picture, movie, text etc. files in the future. Any ideas how I could go about this? You don't say, but I assume you're on Windows since you mention GetFileVersionInfo (which doesn't have anything to do with media files, by the way) and WMA. There may be packages out there to do all this already but if not you'll need to pull in a few disparate modules and mix'n'match. While ID3 readers (which determine the metadata for MP3) are reasonably common few of them come ready-compiled for Windows. I've used Ned Batchelder's id3reader [1] successfully for simple tasks so you might try that. On the WMA side, you can automate Windows Media Player to get metadata. (And it might work for .mp3; I've not tried). code import win32com.client player = win32com.client.gencache.EnsureDispatch (WMPlayer.OCX) wmedia = player.mediaCollection.add (rc:\temp\bells.mp3) try: artist = wmedia.getItemInfo (Artist) finally: player.mediaCollection.remove (wmedia, False) print bells.mp3 has artist, artist /code You're going to have to dig around for docs on this one. And it's not pretty. Try starting from: http://msdn.microsoft.com/en-us/library/bb249009(VS.85).aspx TJG [1] http://nedbatchelder.com/code/modules/id3reader.html -- http://mail.python.org/mailman/listinfo/python-list
Re: code of a function
Dark Wind schrieb: Hi, Is there any command in Python which gives the code for a function like just typing the name of a function (say svd) in R returns its code. Yes, it's posible to retrieve the source code IFF the function is implemented in Python and the .py file is available, too. print inspect.getsource(inspect.getsource) def getsource(object): Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved. lines, lnum = getsourcelines(object) return string.join(lines, '') -- http://mail.python.org/mailman/listinfo/python-list
cmd.Cmd bug or at least docu-bug
Hi, I'm fiddling around with module cmd. I tried to pass my own streams as replacements for stdin and stdout. However, stdin wasn't working. After a look into the sourcecode I discovered that there is an class-variable called use_rawinput that prevents using the passed stdin. I then read the docs again - and found it described. However, I think it should be mentioned on the first page where the constructor is described that without setting use_rawinput to False, stdin will be ignored. Or even better either make use_rawinput set to false in case stdin is passed anything but None or at least make it a keyword argument. Any thoughts about this? Diez -- http://mail.python.org/mailman/listinfo/python-list
Easy install / setuptools
Hi everyone I'm trying to figure out the best way to distribute my own python packages. Basicly, what I want is to have something like an installer.exe (on windows) which puts my package under Python/Lib/site-packages (so that it can be found via the PYTHONPATH). I've played around a bit with easy install and setuptools and the .egg format. I've already managed to create a myPackage.egg file with setup tools and install (it's just a copying) it ito the site-packages directory using easy install. What I was wondering now is if there's a way to actually EXTRACT the egg file and put the extracted file (i.e. the .py file) under site-packages. And not the .egg? The problem with egg files is that you can't use open(os.path.join(os.path.dirname(__file__),'myFile') and I'd need to rewrite such code which I'd like to avoid if possible. Also, I don't know whether leaving the python scripts packed inside the egg file is slower for execution or not... Would be cool if someone could give me some inputs on how to distribute python packages in an easy and effective way :-) Thx in advance Dominique * This e-mail and any files attached are strictly confidential, may be legally privileged and are intended solely for the addressee. If you are not the intended recipient please notify the sender immediately by return email and then delete the e-mail and any attachments immediately. The views and or opinions expressed in this e-mail are not necessarily the views of De La Rue plc or any of its subsidiaries and the De La Rue Group of companies, their directors, officers and employees make no representation about and accept no liability for its accuracy or completeness. You should ensure that you have adequate virus protection as the De La Rue Group of companies do not accept liability for any viruses. De La Rue plc Registered No.3834125, De La Rue Holdings plc Registered No 58025 and De La Rue International Limited Registered No 720284 are all registered in England with their registered office at: De La Rue House, Jays Close, Viables, Hampshire RG22 4BS * -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom log handler and logging.config.fileConfig()
On May 28, 9:53 pm, Lowell Alleman [EMAIL PROTECTED] wrote: Here is the situation: I wrote my own log handler class (derived fromlogging.Handler) and I want to be able to use it from aloggingconfig file, that is, a config file loaded with thelogging.config.fileConfig() function. Let say myloggingclass is called MyLogHandler and it's in a module called mylogmodule, I want to be able to make an entry something like this in myloggingconfig file: [handler_hand02] class=mylogmodule.MyLogHandler level=DEBUG formatter=form02 args=('python.log', 10, True) I did some digging in the code and documentation, and it doesn't appear that this question of writing and accessing your own log handlers is addressed. As per thelogging/config.py code, it looks like the actual file handler classes are being grabbed using an eval from the logging module's namespace, like so: klass = eval(klass, vars(logging)) So this basically means that I have to mess with the logging module's namespace if I want this to work, right? So I've come up with a couple of options, but I'm trying to figure out what approach is best: Option 1: Require the client (the user of myloggingmodule), first import my module and then copy it into theloggingmodule's namespace, before calling fileConfig(). Something like this: import mylogmodule importlogging logging.mylogmodule = mylogmodule Option 2: Have my module make a copy MyLogHandler class into thelogging(orlogging.handlers) module, and then let the client use it from their directly. They client would still have to load mylogging class first (which isn't any different they what they would have to do if they wanted to use the extended log handlers form thelogging.handlers module) My module would include: importlogging class MyLogHandler(logging.Handler): ... logging.MyLogHandler = MyLogHandler The config file would simply have: class=MyLogHandler Option 3: Is there an easy (and non-evil) way for me to make my module available as logging.mylogmodule directly? I am using setuptools, and it seems like what I've read about namespaces, they do something close to what I'm looking for, but I think that requires that all of the __init__.pys involved be empty (or have some special namespace declaration code). The __init__.py for theloggingmodule is not at all empty, so I suppose that rules out this option? Anyone have some insights on this? Thanks in advance, - Lowell Alleman Hi Lowell, I think it's OK to use the logging.handlers namespace to add your custom handlers - after all, the handlers namespace is for holding handlers other than the basic ones included in logging. So... # -- myhandler.py --- import logging.handlers class MySpecialHandler(logging.handlers.RotatingFileHandler): def __init__(self, fn): logging.handlers.RotatingFileHandler.__init__(self, fn, maxBytes=2000, backupCount=3) # -- logging.ini --- [loggers] keys=root [handlers] keys=hand01 [formatters] keys=form01 [logger_root] level=NOTSET handlers=hand01 [handler_hand01] class=handlers.MySpecialHandler level=NOTSET formatter=form01 args=(rotating.log,) [formatter_form01] format=%(asctime)s %(levelname)s %(message)s datefmt= class=Formatter # -- app.py --- import logging.handlers, logging.config from myhandler import MySpecialHandler logging.handlers.MySpecialHandler = MySpecialHandler logging.config.fileConfig(logging.ini) logger = logging.getLogger(test) for i in xrange(100): logger.debug(Message no. %d, i) should produce the expected results. -- http://mail.python.org/mailman/listinfo/python-list
Re: php vs python
A good OO programmer could easily write good functional code. You are aware that functional programming is *not* procedural or imperative programming? http://en.wikipedia.org/wiki/Functional_programming OO is *heavily* depending on state and state modification. I've seen OO programmers weep over functional programming assignments. Which is not to say that FP is in any sense bad - au contraire, knowing it is important because it is a different school of thought that's very valuable to know of. And Python allows for many of the FP concepts to be used. See map, filter and other HOFs. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I tell imconplete input from valid input?
thanks for your reply. I tried below python codes with Py_single_input instead of Py_file_input. sample 1 : result is INCOMPLETE for i in range(3):\n sample 2 : result is COMPLETE(I want to get INCOMPLETE or something) for i in range(3):\n\tprint i or for i in range(3):\n\tprint i\n Py_single_input and Py_file_input seem the same. How come? Plz check details in Grammar/Grammar from python source distribution thanks. I challenge it. --urai -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding file details...
On May 29, 7:55 pm, Tim Golden [EMAIL PROTECTED] wrote: You don't say, but I assume you're on Windows since you mention GetFileVersionInfo (which doesn't have anything to do with media files, by the way) and WMA. There may be packages out there to do all this already but if not you'll need to pull in a few disparate modules and mix'n'match. While ID3 readers (which determine the metadata for MP3) are reasonably common few of them come ready-compiled for Windows. I've used Ned Batchelder's id3reader [1] successfully for simple tasks so you might try that. On the WMA side, you can automate Windows Media Player to get metadata. (And it might work for .mp3; I've not tried). code import win32com.client player = win32com.client.gencache.EnsureDispatch (WMPlayer.OCX) wmedia = player.mediaCollection.add (rc:\temp\bells.mp3) try: artist = wmedia.getItemInfo (Artist) finally: player.mediaCollection.remove (wmedia, False) print bells.mp3 has artist, artist /code You're going to have to dig around for docs on this one. And it's not pretty. Try starting from: http://msdn.microsoft.com/en-us/library/bb249009(VS.85).aspx TJG [1]http://nedbatchelder.com/code/modules/id3reader.html Hmm, thanks for the info. Yes, I am using Winders (Vista to be exact) and I just assumed that there must be a way to programmatically get the stuff you get from choosing properties in the right click menu. But I guess there isn't (hard to believe, because I can't see MS hard- coding each and every file format's metadata into it's OS). I might have to learn more about the command prompt ( I hear there is a module for fiddling with it) and work from there. Cheers for the links though, I will be checking them out :) -- http://mail.python.org/mailman/listinfo/python-list
Error: Cannot convert Decimal(0.0000) to Decimal
Hi I got this wired exception periodically (Python 2.5, Django based application) what does it mean ? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get all the variables in a python shell
[EMAIL PROTECTED] wrote: I'm currently working on a scientific computation software built in python. What I want to implement is a Matlab style command window - workspace interaction. For example, you type 'a=1' in the command window, and you see a list item named 'a' in the workspace. You double click the icon of the item, and you see its value. You can modify the value of the list item, 1 - 100 etc, after which if you go back to the command window and type 'a' and press enter, you see that varable a's value has been changed to 100. So my question is : if you have two DOS command windows running under WINDOWS OS, how can you make them share the same internal variable buffer? Or is there any easier way to implement such kind of interaction? I stronly suggest you look at IPython [1]. To do what I think you're describing, you'd need to hack or reimplement the interpreter. And that's what they've done. ISTR that they even have a branch which is dealing with parallel instances. TJG [1] http://ipython.scipy.org/moin/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Any way to loop through object variables?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Ah thanks, vars(...) was exactly what I was after. I'd come across dir() before, but this returns more than I need. Thanks again, Dave Saju Pillai wrote: On 28-May-08, at 9:49 PM, Gary Herron wrote: Dave Challis wrote: Hi, Just wondering if there's a way to iterate through all variables which an object has set? Specifically, I'm using the OptionParser module, which returns an options object, containing all command line options as object variables. I'd like to iterate over these rather than getting at them by name. Cheers, Dave For this object (and many others), you can get at the attributes with the vars(...) builtin. It returns a dictionary of attribute names and values. Also dir(object) will get you the list of attributes of that object. -srp Gary Herron -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list - -- ~o . ( )Dave Challis)) _([EMAIL PROTECTED]((___ -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIPowrv26GZvAVVFERApQfAJ96bFa1wl1sbnDCNmbtf5/tpNqTaQCdHKwf k8+Uv8yXn2Bh5ri6sf5qMmA= =cnfO -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Error: Cannot convert Decimal(0.0000) to Decimal
Vitaliy wrote: I got this wired exception periodically (Python 2.5, Django based application) what does it mean ? A reload() maybe? import decimal d = decimal.Decimal() reload(decimal) module 'decimal' from '/usr/lib/python2.5/decimal.pyc' decimal.Decimal(d) Traceback (most recent call last): File stdin, line 1, in module File /usr/lib/python2.5/decimal.py, line 617, in __new__ raise TypeError(Cannot convert %r to Decimal % value) TypeError: Cannot convert Decimal(0) to Decimal Peter -- http://mail.python.org/mailman/listinfo/python-list
RE: [python-win32] How to get all the variables in a python shell
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Tim Golden Sent: Thursday, May 29, 2008 4:11 AM To: Python-Win32 List; python-list@python.org Cc: Python-Win32 List Subject: Re: [python-win32] How to get all the variables in a python shell [EMAIL PROTECTED] wrote: I'm currently working on a scientific computation software built in python. What I want to implement is a Matlab style command window - workspace interaction. For example, you type 'a=1' in the command window, and you see a list item named 'a' in the workspace. You double click the icon of the item, and you see its value. You can modify the value of the list item, 1 - 100 etc, after which if you go back to the command window and type 'a' and press enter, you see that varable a's value has been changed to 100. So my question is : if you have two DOS command windows running under WINDOWS OS, how can you make them share the same internal variable buffer? Or is there any easier way to implement such kind of interaction? I stronly suggest you look at IPython [1]. To do what I think you're describing, you'd need to hack or reimplement the interpreter. And that's what they've done. ISTR that they even have a branch which is dealing with parallel instances. TJG [1] http://ipython.scipy.org/moin/ ___ python-win32 mailing list [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/python-win32 I'd try looking at memcached (http://www.danga.com/memcached/apis.html). No hacking or reimplementation of the interpreter would be necessary, and there's a Python api available. I haven't used it for anything production related, but I have played with it a bit, and it's fast and stable. DISCLAIMER: This e-mail, and any attachments thereto, is intended only for use by the addressee(s) named herein and may contain legally privileged and/or confidential information. If you are not the intended recipient of this e-mail, you are hereby notified that any dissemination, distribution or copying of this e-mail, and any attachments thereto, is strictly prohibited. If you have received this in error, please immediately notify me and permanently delete the original and any copy of any e-mail and any printout thereof. E-mail transmission cannot be guaranteed to be secure or error-free. The sender therefore does not accept liability for any errors or omissions in the contents of this message which arise as a result of e-mail transmission. NOTICE REGARDING PRIVACY AND CONFIDENTIALITY Direct Edge ECN LLC may, at its discretion, monitor and review the content of all e-mail communications. www.directedge.com -- http://mail.python.org/mailman/listinfo/python-list
Re: cmd.Cmd bug or at least docu-bug
On May 29, 11:26 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: Hi, I'm fiddling around with module cmd. I tried to pass my own streams as replacements for stdin and stdout. However, stdin wasn't working. After a look into the sourcecode I discovered that there is an class-variable called use_rawinput that prevents using the passed stdin. I then read the docs again - and found it described. However, I think it should be mentioned on the first page where the constructor is described that without setting use_rawinput to False, stdin will be ignored. Or even better either make use_rawinput set to false in case stdin is passed anything but None or at least make it a keyword argument. Any thoughts about this? Diez I run into the same issue and I solved it by using a custom subclass of Cmd, but I agree that the cmd module could be improved. I even wrote a cmd2 module that I should publish one day or another. +1 to submit a bug report. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: [python-win32] How to get all the variables in a python shell
On 29/05/2008, Dahlstrom, Roger [EMAIL PROTECTED] wrote: I'd try looking at memcached (http://www.danga.com/memcached/apis.html). No hacking or reimplementation of the interpreter would be necessary, and there's a Python api available. I haven't used it for anything production related, but I have played with it a bit, and it's fast and stable. Is memcached available for Windows, then? I've heard nice things about it, but thought it was Unix-only. Paul. -- http://mail.python.org/mailman/listinfo/python-list
RE: [python-win32] How to get all the variables in a python shell
-Original Message- From: Paul Moore [mailto:[EMAIL PROTECTED] Sent: Thursday, May 29, 2008 7:23 AM To: Dahlstrom, Roger Cc: Python-Win32 List; python-list@python.org Subject: Re: [python-win32] How to get all the variables in a python shell On 29/05/2008, Dahlstrom, Roger [EMAIL PROTECTED] wrote: I'd try looking at memcached (http://www.danga.com/memcached/apis.html). No hacking or reimplementation of the interpreter would be necessary, and there's a Python api available. I haven't used it for anything production related, but I have played with it a bit, and it's fast and stable. Is memcached available for Windows, then? I've heard nice things about it, but thought it was Unix-only. Paul. It is available for Windows, yes. As a matter of fact, I've never used it on Unix. DISCLAIMER: This e-mail, and any attachments thereto, is intended only for use by the addressee(s) named herein and may contain legally privileged and/or confidential information. If you are not the intended recipient of this e-mail, you are hereby notified that any dissemination, distribution or copying of this e-mail, and any attachments thereto, is strictly prohibited. If you have received this in error, please immediately notify me and permanently delete the original and any copy of any e-mail and any printout thereof. E-mail transmission cannot be guaranteed to be secure or error-free. The sender therefore does not accept liability for any errors or omissions in the contents of this message which arise as a result of e-mail transmission. NOTICE REGARDING PRIVACY AND CONFIDENTIALITY Direct Edge ECN LLC may, at its discretion, monitor and review the content of all e-mail communications. www.directedge.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare 2 files and discard common lines
Another way of doing this might be to use the module difflib to calculate the differences. It has a sequence matcher under it which has the function get_matching_blocks difflib is included with python. On May 29, 2:02 pm, Chris [EMAIL PROTECTED] wrote: On May 29, 10:36 am, loial [EMAIL PROTECTED] wrote: I have a requirement to compare 2 text files and write to a 3rd file only those lines that appear in the 2nd file but not in the 1st file. Rather than re-invent the wheel I am wondering if anyone has written anything already? How large are the files ? You could load up the smallest file into memory then while iterating over the other one just do 'if line in other_files_lines:' and do your processing from there. By your description it doesn't sound like you want to iterate over both files simultaneously and do a line for line comparison because that would mean if someone plonks an extra newline somewhere it wouldn't gel. -- http://mail.python.org/mailman/listinfo/python-list
Unit tests?
Hello, it seems that I have a problem - I almost finished my program and it's necessary to test it. But I've never do it before. I even don't know how I can do it. Please, give me some links to testing techniques, either common or specific to Python. I searched in Google for information, but 'cause I don't know anything about subject, I don't know where to start from. Thanks -- Best regards, Alex Gusarov -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit tests?
Alex Gusarov [EMAIL PROTECTED] writes: Hello, it seems that I have a problem - I almost finished my program and it's necessary to test it. But I've never do it before. I even don't know how I can do it. Please, give me some links to testing techniques, either common or specific to Python. I searched in Google for information, but 'cause I don't know anything about subject, I don't know where to start from. Thanks -- Best regards, Alex Gusarov Try googling python unit test. I did it, and amongst the first hits were: * docs.python.org/lib/module-unittest.html * http://www.diveintopython.org/unit_testing/index.html -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare 2 files and discard common lines
On May 29, 6:36 pm, loial [EMAIL PROTECTED] wrote: I have a requirement to compare 2 text files and write to a 3rd file only those lines that appear in the 2nd file but not in the 1st file. Rather than re-invent the wheel I am wondering if anyone has written anything already? file1 = set((x for x in open('file1'))) file2 = set((x for x in open('file2'))) file3 = file2.difference(file1) open('file3','w').writelines(file3) -- http://mail.python.org/mailman/listinfo/python-list
Re: [python-win32] How to get all the variables in a python shell
Tim Golden wrote: [EMAIL PROTECTED] wrote: I'm currently working on a scientific computation software built in python. What I want to implement is a Matlab style command window - workspace interaction. For example, you type 'a=1' in the command window, and you see a list item named 'a' in the workspace. You double click the icon of the item, and you see its value. You can modify the value of the list item, 1 - 100 etc, after which if you go back to the command window and type 'a' and press enter, you see that varable a's value has been changed to 100. So my question is : if you have two DOS command windows running under WINDOWS OS, how can you make them share the same internal variable buffer? Or is there any easier way to implement such kind of interaction? I stronly suggest you look at IPython [1]. To do what I think you're describing, you'd need to hack or reimplement the interpreter. And that's what they've done. ISTR that they even have a branch which is dealing with parallel instances. Sorry, having seen Roger D's memcached suggestion, I realise I may have misinterpreted your requirement. I thought that you wanted a Python interpreter session to share its objects to another window, hence my IPython suggestion. If you're writing your own console app and want to share stuff, then there's any number of IPC possibilities. Roger's already mentioned memcached which I've no more than a passing knowledge of. But Pyro [1] is often a good bet for these things, and the pyprocessing [2] module is gaining a fair bit of traction at the moment. (To name just two out of many). TJG [1] http://pyro.sf.net [2] http://pyprocessing.berlios.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit tests?
Thx, it's quite enough for a start. Yes, googling is almost ultimate answer for such questions, sorry for uneasiness. Try googling python unit test. I did it, and amongst the first hits were: * docs.python.org/lib/module-unittest.html * http://www.diveintopython.org/unit_testing/index.html -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Tuple of coordinates
Hi, i am using a software which uses python as its scripting language. I want to generate a list of coordinates more or less this way: for i in (beg, end, step): for j in (beg, end, step): for k in (beg, end, step): . Coords = ((i1,j1,k1), (i2,j2,k2), ...,(in,jn.kn)) Can anyone give me some advice on how to achieve this ? I got a little idea, but still need to keep working til i get it. Thanks in advance, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple of coordinates
a = 1, 2 b = 3, 4, 5 c = 6, 7, 8, 9 coord = list() for i, j, k in zip(a, b, c): coord.append((i, j, k)) print coord -- http://mail.python.org/mailman/listinfo/python-list
Reporting the line number of an exception
I'm sure this is exceedingly simple but I can't find it anywhere. When I catch an exception I would like to report the line number of the exception as well as the error info. try: someError() except Exception, e: print_error_and_line_number How do I find the line number? Thanks for any help! -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange thing with types
TYR wrote: I'm doing some data normalisation, which involves data from a Web site being extracted with BeautifulSoup, cleaned up with a regex, then having the current year as returned by time()'s tm_year attribute inserted, before the data is concatenated with string.join() and fed to time.strptime(). Here's some code: timeinput = re.split('[\s:-]', rawtime) print timeinput #trace statement print year #trace statement t = timeinput.insert(2, year) print t #trace statement t1 = string.join(t, '') timeobject = time.strptime(t1, %d %b %Y %H %M) year is a Unicode string; so is the data in rawtime (BeautifulSoup gives you Unicode, dammit). And here's the output: [u'29', u'May', u'01', u'00'] (OK, so the regex is working) 2008 (OK, so the year is a year) None (...but what's this?) Traceback (most recent call last): File bothv2.py, line 71, in module t1 = string.join(t, '') File /usr/lib/python2.5/string.py, line 316, in join return sep.join(words) TypeError First - don't use module string anymore. Use e.g. ''.join(t) Second, you can only join strings. but year is an integer. So convert it to a string first: t = timeinput.insert(2, str(year)) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange thing with types
On May 29, 11:09 pm, TYR [EMAIL PROTECTED] wrote: I'm doing some data normalisation, which involves data from a Web site being extracted with BeautifulSoup, cleaned up with a regex, then having the current year as returned by time()'s tm_year attribute inserted, before the data is concatenated with string.join() and fed to time.strptime(). Here's some code: timeinput = re.split('[\s:-]', rawtime) print timeinput #trace statement print year #trace statement t = timeinput.insert(2, year) print t #trace statement t1 = string.join(t, '') timeobject = time.strptime(t1, %d %b %Y %H %M) year is a Unicode string; so is the data in rawtime (BeautifulSoup gives you Unicode, dammit). And here's the output: [u'29', u'May', u'01', u'00'] (OK, so the regex is working) 2008 (OK, so the year is a year) None (...but what's this?) Traceback (most recent call last): File bothv2.py, line 71, in module t1 = string.join(t, '') File /usr/lib/python2.5/string.py, line 316, in join return sep.join(words) TypeError list.insert modifies the list in-place: l = [1,2,3] l.insert(2,4) l [1, 2, 4, 3] It also returns None, which is what you're assigning to 't' and then trying to join. Replace your usage of 't' with 'timeinput' and it should work. -- http://mail.python.org/mailman/listinfo/python-list
seg. fault with Py_BuildValue?
Hi I'm having trouble with Py_BuildValue. I was able to pinpoint the following statement as the one causing a seg. fault with my script: static PyObject * funcname(PyObject *self, PyObject *args) { ... return Py_BuildValue((OO), x, y); } where x y are both of type PyObject. Any suggestions here? Do I need to handle the output of Py_BuildValue somehow before returning? How? Need to decref x y before returning? TIA Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple of coordinates
On May 29, 10:16 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, i am using a software which uses python as its scripting language. I want to generate a list of coordinates more or less this way: for i in (beg, end, step): for j in (beg, end, step): for k in (beg, end, step): . Coords = ((i1,j1,k1), (i2,j2,k2), ...,(in,jn.kn)) Can anyone give me some advice on how to achieve this ? I got a little idea, but still need to keep working til i get it. Thanks in advance, Victor coords = [(x,y,z) for x in range(0,10) for y in range(0,10) for z in range(0,10)] -- http://mail.python.org/mailman/listinfo/python-list
Re: Reporting the line number of an exception
sophie_newbie wrote: I'm sure this is exceedingly simple but I can't find it anywhere. When I catch an exception I would like to report the line number of the exception as well as the error info. try: someError() except Exception, e: print_error_and_line_number How do I find the line number? If you want just the line number: tb = sys.exc_info()[2] print tb.tb_lineno You may also have a look at the traceback module, e. g.: traceback.print_exc() Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: [python-win32] How to get all the variables in a python shell
[Bizarrely, my mail system seems to be randomly misfiring. If you've already seen this, please ignore!] Tim Golden wrote: Sorry, having seen Roger D's memcached suggestion, I realise I may have misinterpreted your requirement. I thought that you wanted a Python interpreter session to share its objects to another window, hence my IPython suggestion. If you're writing your own console app and want to share stuff, then there's any number of IPC possibilities. Roger's already mentioned memcached which I've no more than a passing knowledge of. But Pyro [1] is often a good bet for these things, and the pyprocessing [2] module is gaining a fair bit of traction at the moment. (To name just two out of many). TJG [1] http://pyro.sf.net [2] http://pyprocessing.berlios.de/ -- http://mail.python.org/mailman/listinfo/python-list
Strange thing with types
I'm doing some data normalisation, which involves data from a Web site being extracted with BeautifulSoup, cleaned up with a regex, then having the current year as returned by time()'s tm_year attribute inserted, before the data is concatenated with string.join() and fed to time.strptime(). Here's some code: timeinput = re.split('[\s:-]', rawtime) print timeinput #trace statement print year #trace statement t = timeinput.insert(2, year) print t #trace statement t1 = string.join(t, '') timeobject = time.strptime(t1, %d %b %Y %H %M) year is a Unicode string; so is the data in rawtime (BeautifulSoup gives you Unicode, dammit). And here's the output: [u'29', u'May', u'01', u'00'] (OK, so the regex is working) 2008 (OK, so the year is a year) None (...but what's this?) Traceback (most recent call last): File bothv2.py, line 71, in module t1 = string.join(t, '') File /usr/lib/python2.5/string.py, line 316, in join return sep.join(words) TypeError -- http://mail.python.org/mailman/listinfo/python-list
Re: seg. fault with Py_BuildValue?
Christian Meesters wrote: Hi I'm having trouble with Py_BuildValue. I was able to pinpoint the following statement as the one causing a seg. fault with my script: static PyObject * funcname(PyObject *self, PyObject *args) { ... return Py_BuildValue((OO), x, y); } where x y are both of type PyObject. Any suggestions here? Do I need to handle the output of Py_BuildValue somehow before returning? How? Need to decref x y before returning? Just a guess - but according to the docs of Py_BuildValue it will return a tuple already when given a format string of several format units. What happens if you get rid of the ()? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Any way to loop through object variables?
Dave Challis schrieb: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Ah thanks, vars(...) was exactly what I was after. I'd come across dir() before, but this returns more than I need. It seems vars() misses class attributes tho... cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple of coordinates
On Thu, May 29, 2008 at 8:16 AM, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, i am using a software which uses python as its scripting language. I want to generate a list of coordinates more or less this way: for i in (beg, end, step): for j in (beg, end, step): for k in (beg, end, step): . Coords = ((i1,j1,k1), (i2,j2,k2), ...,(in,jn.kn)) Can anyone give me some advice on how to achieve this ? I got a little idea, but still need to keep working til i get it. Thanks in advance, The pseudo-code and the intended result are two completely different things. The pseudo-code would give you [(i1,j1,k1),(i1,j1,k2),(i1,j2,k1)...]. That code would be written coords = list() for i in xrange(beg, end, step) : for j in xrange(beg, end, step) : for k in xrange(beg, end, step) : coords.append((i,j,k)) for the result you gave, you would do i = xrange(beg, end, step) j = xrange(beg, end, step) k = xrange(beg, end, step) coords = zip(i,j,k) Victor -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
feedparser html sanitizion how-to disable it
ok so I know about why its good but I am building a website that imports rss feeds form external place in this case Talkshoe.com and feedparser seens to think that podcast.feed.description has html in it and same with podcast.entries[0].description so how can I disable it p.s. new to python so baby speak would be greatly appercated thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding file details...
Kalibr wrote: On May 29, 7:55 pm, Tim Golden [EMAIL PROTECTED] wrote: You don't say, but I assume you're on Windows since you mention GetFileVersionInfo (which doesn't have anything to do with media files, by the way) and WMA. There may be packages out there to do all this already but if not you'll need to pull in a few disparate modules and mix'n'match. While ID3 readers (which determine the metadata for MP3) are reasonably common few of them come ready-compiled for Windows. I've used Ned Batchelder's id3reader [1] successfully for simple tasks so you might try that. On the WMA side, you can automate Windows Media Player to get metadata. (And it might work for .mp3; I've not tried). code import win32com.client player = win32com.client.gencache.EnsureDispatch (WMPlayer.OCX) wmedia = player.mediaCollection.add (rc:\temp\bells.mp3) try: artist = wmedia.getItemInfo (Artist) finally: player.mediaCollection.remove (wmedia, False) print bells.mp3 has artist, artist /code You're going to have to dig around for docs on this one. And it's not pretty. Try starting from: http://msdn.microsoft.com/en-us/library/bb249009(VS.85).aspx TJG [1]http://nedbatchelder.com/code/modules/id3reader.html Hmm, thanks for the info. Yes, I am using Winders (Vista to be exact) and I just assumed that there must be a way to programmatically get the stuff you get from choosing properties in the right click menu. Ah. You didn't quite say that. Well, the thing is that the stuff in the right-click menu (I think this is the case) comes from several different sources. Some of it's held in Alternate Data Streams. Some is Structured Storage within the docs themselves. Some is simply, eg, ID3 data held in an MP3 file etc. I don't think it all comes from one place. Again, I think. But I guess there isn't (hard to believe, because I can't see MS hard- coding each and every file format's metadata into it's OS). I might have to learn more about the command prompt ( I hear there is a module for fiddling with it) and work from there. If you come up with useful info, do post back here. It's an area several people have enquired about. TJG -- http://mail.python.org/mailman/listinfo/python-list
boost
Hi everybody. I'm trying to use boost, but just don't know how to set it up. My os is winXP (installed on disk D). Python is installed in D:\Python25 MigGW compiler is installed in D:\MinGW (i downloaded it because djgpp is making much more errors with bjam) I have downloaded boost_1_35_0.zip and boost-jam-3.1.16-1-ntx86.zip, extracted boost_1_35_0.zip to D:\Program Files (so I have now D:\Program Files\boost_1_35_0), extracted there bjam and used bjam in cmd: bjam --build-dir=D:\Program Files\boost_1_35_0 --toolset=gcc stage I got 12 failures and 8 warnings from this (other few hundrds were ok) I'm now trying to compile World.cpp and use it from python World.cpp: -- #include boost/python.hpp using namespace boost::python; BOOST_PYTHON_MODULE(hello) { class_World(World) .def(greet, World::greet) .def(set, World::set) ; } struct World { void set(std::string msg) { this-msg = msg; } std::string greet() { return msg; } std::string msg; }; -- When trying to compile it I get: E:\Sourceg++ World.cpp World.cpp:1:28: boost/python.hpp: No such file or directory World.cpp:2: error: `boost' has not been declared World.cpp:2: error: `python' is not a namespace-name World.cpp:2: error: expected namespace-name before ';' token World.cpp:4: error: expected constructor, destructor, or type conversion before '(' token World.cpp:15: error: `std::string' has not been declared World.cpp:15: error: ISO C++ forbids declaration of `msg' with no type World.cpp:16: error: using-declaration for non-member at class scope World.cpp:16: error: expected `;' before greet World.cpp:17: error: expected `;' before std World.cpp:17: error: using-declaration for non-member at class scope World.cpp:17: error: expected `;' before msg World.cpp: In member function `void World::set(int)': World.cpp:15: error: 'struct World' has no member named 'msg' What have i done wrong and what should have been done instead? Thank you in advance. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: seg. fault with Py_BuildValue?
What happens if you get rid of the ()? Can't see any difference. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange thing with types
On May 29, 2:23 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: TYR wrote: I'm doing some data normalisation, which involves data from a Web site being extracted with BeautifulSoup, cleaned up with a regex, then having the current year as returned by time()'s tm_year attribute inserted, before the data is concatenated with string.join() and fed to time.strptime(). Here's some code: timeinput = re.split('[\s:-]', rawtime) print timeinput #trace statement print year #trace statement t = timeinput.insert(2, year) print t #trace statement t1 = string.join(t, '') timeobject = time.strptime(t1, %d %b %Y %H %M) year is a Unicode string; so is the data in rawtime (BeautifulSoup gives you Unicode, dammit). And here's the output: [u'29', u'May', u'01', u'00'] (OK, so the regex is working) 2008 (OK, so the year is a year) None (...but what's this?) Traceback (most recent call last): File bothv2.py, line 71, in module t1 = string.join(t, '') File /usr/lib/python2.5/string.py, line 316, in join return sep.join(words) TypeError First - don't use module string anymore. Use e.g. ''.join(t) Second, you can only join strings. but year is an integer. So convert it to a string first: t = timeinput.insert(2, str(year)) Diez Yes, tm_year is converted to a unicode string elsewhere in the program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange thing with types
On May 29, 2:24 pm, alex23 [EMAIL PROTECTED] wrote: On May 29, 11:09 pm, TYR [EMAIL PROTECTED] wrote: I'm doing some data normalisation, which involves data from a Web site being extracted with BeautifulSoup, cleaned up with a regex, then having the current year as returned by time()'s tm_year attribute inserted, before the data is concatenated with string.join() and fed to time.strptime(). Here's some code: timeinput = re.split('[\s:-]', rawtime) print timeinput #trace statement print year #trace statement t = timeinput.insert(2, year) print t #trace statement t1 = string.join(t, '') timeobject = time.strptime(t1, %d %b %Y %H %M) year is a Unicode string; so is the data in rawtime (BeautifulSoup gives you Unicode, dammit). And here's the output: [u'29', u'May', u'01', u'00'] (OK, so the regex is working) 2008 (OK, so the year is a year) None (...but what's this?) Traceback (most recent call last): File bothv2.py, line 71, in module t1 = string.join(t, '') File /usr/lib/python2.5/string.py, line 316, in join return sep.join(words) TypeError list.insert modifies the list in-place: l = [1,2,3] l.insert(2,4) l [1, 2, 4, 3] It also returns None, which is what you're assigning to 't' and then trying to join. Replace your usage of 't' with 'timeinput' and it should work. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
adobe flex; return xml via turbogears/django
please excuse slightly off-topic; cannot access turbogears mailing list at the moment. There was an excellent video by James Ward that showed using turbogears to return json data to adoble's flex UI. It simply used @expose(JSON) def (): ... return dict(x=1, ...) Is there any equivalent for xml, such as @expose(XML) def return myElementTreeRoot I need to have more attribute data (for a grid) than I can cleanly do in json and while pyamf might do the trick, It adds a layer of magic code that I cannot sell to my team. Also with xml and json, I can do my UI design with the url pointing to a test data file, then build the backend to match. any ideas? thanks --- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --- -- http://mail.python.org/mailman/listinfo/python-list
Re: feedparser html sanitizion how-to disable it
oh sorry here is the rss feed I am using http://recordings.talkshoe.com/rss39293.xml -- http://mail.python.org/mailman/listinfo/python-list
Re: seg. fault with Py_BuildValue?
Christian Meesters schrieb: Hi I'm having trouble with Py_BuildValue. I was able to pinpoint the following statement as the one causing a seg. fault with my script: static PyObject * funcname(PyObject *self, PyObject *args) { return Py_BuildValue((OO), x, y); } where x y are both of type PyObject. Any suggestions here? Do I need to handle the output of Py_BuildValue somehow before returning? How? Need to decref x y before returning? Check if either x or y are NULL. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: adobe flex; return xml via turbogears/django
Sells, Fred wrote: please excuse slightly off-topic; cannot access turbogears mailing list at the moment. There was an excellent video by James Ward that showed using turbogears to return json data to adoble's flex UI. It simply used @expose(JSON) def (): ... return dict(x=1, ...) Is there any equivalent for xml, such as @expose(XML) def return myElementTreeRoot I need to have more attribute data (for a grid) than I can cleanly do in json and while pyamf might do the trick, It adds a layer of magic code that I cannot sell to my team. Also with xml and json, I can do my UI design with the url pointing to a test data file, then build the backend to match. any ideas? Why don't you create KID-template like this: div py:strip=True${root}/div and in the controller say @expose(thexmltemplate) def ... return dict(root=myElementTreeRoot) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: BadStatusLine error
On May 28, 11:24 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: Jim wrote: Hi I get a BadStatusLine error (indicated below). Can anyone help with how to catch error in code before abort? http://docs.python.org/tut/node10.html Diez Thanks Diez docs help. Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding file details...
On May 29, 5:26 am, Kalibr [EMAIL PROTECTED] wrote: On May 29, 7:55 pm, Tim Golden [EMAIL PROTECTED] wrote: You don't say, but I assume you're on Windows since you mention GetFileVersionInfo (which doesn't have anything to do with media files, by the way) and WMA. There may be packages out there to do all this already but if not you'll need to pull in a few disparate modules and mix'n'match. While ID3 readers (which determine the metadata for MP3) are reasonably common few of them come ready-compiled for Windows. I've used Ned Batchelder's id3reader [1] successfully for simple tasks so you might try that. On the WMA side, you can automate Windows Media Player to get metadata. (And it might work for .mp3; I've not tried). code import win32com.client player = win32com.client.gencache.EnsureDispatch (WMPlayer.OCX) wmedia = player.mediaCollection.add (rc:\temp\bells.mp3) try: artist = wmedia.getItemInfo (Artist) finally: player.mediaCollection.remove (wmedia, False) print bells.mp3 has artist, artist /code You're going to have to dig around for docs on this one. And it's not pretty. Try starting from: http://msdn.microsoft.com/en-us/library/bb249009(VS.85).aspx TJG [1]http://nedbatchelder.com/code/modules/id3reader.html Hmm, thanks for the info. Yes, I am using Winders (Vista to be exact) and I just assumed that there must be a way to programmatically get the stuff you get from choosing properties in the right click menu. But I guess there isn't (hard to believe, because I can't see MS hard- coding each and every file format's metadata into it's OS). I might have to learn more about the command prompt ( I hear there is a module for fiddling with it) and work from there. Cheers for the links though, I will be checking them out :) You might also check out the ID3 library: http://id3-py.sourceforge.net/ It doesn't look like it's been updated for a few years. I tested it on XP and it seems to work though. I also found this snippet, but it's pretty rudimentary: http://snipplr.com/view/1624/python--get-id3-from-mp3-file/ Finally, check out the ID3 Handling section on this site: http://wiki.python.org/moin/UsefulModules --- Mike Blog: http://blog.pythonlibrary.org/ -- http://mail.python.org/mailman/listinfo/python-list
bit parsing from file
Hello, I'm tring to make a cutting script. The problem is the following, i have a sample pattern, for example :'11101110' (0xEE) That is the sign of the data begining. How can i cut a file if the byte stepping is not the same, for example: file=open('test.bin','rb') data=file.read() print binascii.hexlify(data)# BB9A (1011101110011010) file.close() so i need to cut the first two bit and start to writeout the bit stream to another file If somebody have an idea to do this, please share with me. Thanx Rew -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flaming Thunder
On Thu, May 29, 2008 at 3:36 AM, Duncan Booth [EMAIL PROTECTED] wrote: Dave Parker [EMAIL PROTECTED] wrote: Catch doesn't return just error types or numbers, it can return any object returned by the statements that are being caught; catch doesn't care what type they are. For example: Writeline catch(set x to hello world.). will write hello world. I really don't get this. Surely the point about an error being thrown to a catch statement is that the error path is separate from the normal execution path? What you are doing here is ensuring that unexpected errors have no chance at all of propagating up to the top level: they are invariably going to get caught by some other handler that was installed just because someone was too lazy to write a set statement followed by a writeline. It also looks like an overloading of catch, semantically similar to the C: int retcode; if( retcode = doSomethingThatReturns0or1() ) printf(Hello world); Again, I don't think you want to start overloading your exception-handling mechanism. If you want a set expression to be equal to the l-value at the end, that's fine, but there's no reason that catch should evaluate to an object or an integral- or real-valued exception in error cases, or of the last statement of the block if there's no error. (Evaluating a block to be equal to its last statement is okay, I guess; I know at least that there's a call in Scheme that lets you do a more imperative programming style in the functional language--whether that's a good thing is probably a holy war.) I just think if you're shooting for an easily understandable language, overloading error handling requires more thought on the programmer's part, not less, because they have to reason about all outcomes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom log handler and logging.config.fileConfig()
Is there any reason not to do this assignment in the myhandler.py directly? This would save a step for each application that needs to use it. Starting from your example, it would now look like this: # -- myhandler.py --- import logging.handlers class MySpecialHandler(logging.handlers.RotatingFileHandler): def __init__(self, fn): logging.handlers.RotatingFileHandler.__init__(self, fn, maxBytes=2000, backupCount=3) # Register handler in the logging.handlers namespace logging.handlers.MySpecialHandler = MySpecialHandler # -- app.py --- import logging.handlers, logging.config import myhandler logging.config.fileConfig(logging.ini) ... Hi Lowell, I think it's OK to use the logging.handlers namespace to add your custom handlers - after all, the handlers namespace is for holding handlers other than the basic ones included in logging. So... # -- myhandler.py --- import logging.handlers class MySpecialHandler(logging.handlers.RotatingFileHandler): def __init__(self, fn): logging.handlers.RotatingFileHandler.__init__(self, fn, maxBytes=2000, backupCount=3) # -- logging.ini --- [loggers] keys=root [handlers] keys=hand01 [formatters] keys=form01 [logger_root] level=NOTSET handlers=hand01 [handler_hand01] class=handlers.MySpecialHandler level=NOTSET formatter=form01 args=(rotating.log,) [formatter_form01] format=%(asctime)s %(levelname)s %(message)s datefmt= class=Formatter # -- app.py --- import logging.handlers, logging.config from myhandler import MySpecialHandler logging.handlers.MySpecialHandler = MySpecialHandler logging.config.fileConfig(logging.ini) logger = logging.getLogger(test) for i in xrange(100): logger.debug(Message no. %d, i) should produce the expected results. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
mysqldb install problem
I am trying to install mysqldb-1.2.2 on my PPC running 10.5.2 and Activepython 2.5.1.1 when I get this error: running build running build_py copying MySQLdb/release.py - build/lib.macosx-10.3-fat-2.5/MySQLdb running build_ext building '_mysql' extension gcc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing - Wno-long-double -no-cpp-precomp -mno-fused-madd -fPIC -fno-common - dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes - Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/local/mysql/ include -I/Library/Frameworks/Python.framework/Versions/2.5/include/ python2.5 -c _mysql.c -o build/temp.macosx-10.3-fat-2.5/_mysql.o -g - Os -arch ppc64 -fno-common -D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -DIGNORE_SIGHUP_SIGQUIT - DDONT_DECLARE_CXA_PURE_VIRTUAL In file included from /Library/Frameworks/Python.framework/Versions/ 2.5/include/python2.5/Python.h:57, from pymemcompat.h:10, from _mysql.c:29: /Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/ pyport.h:734:2: error: #error LONG_BIT definition appears wrong for platform (bad gcc/glibc config?). In file included from _mysql.c:35: /usr/local/mysql/include/my_config.h:1095:1: warning: SIZEOF_LONG redefined In file included from /Library/Frameworks/Python.framework/Versions/ 2.5/include/python2.5/Python.h:8, from pymemcompat.h:10, from _mysql.c:29: /Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/ pyconfig.h:807:1: warning: this is the location of the previous definition error: command 'gcc' failed with exit status 1 Anyone know what is going on? Cheers Tommy -- http://mail.python.org/mailman/listinfo/python-list
Re: code of a function
On May 29, 2008, at 9:38 AM, Gary Herron wrote: Dark Wind wrote: Hi, Is there any command in Python which gives the code for a function like just typing the name of a function (say svd) in R returns its code. Thank you Nope. If you're using IPython, you can do svd?? . -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flaming Thunder
Dan Upton [EMAIL PROTECTED] wrote: On Thu, May 29, 2008 at 3:36 AM, Duncan Booth [EMAIL PROTECTED] wrote: Dave Parker [EMAIL PROTECTED] wrote: Catch doesn't return just error types or numbers, it can return any object returned by the statements that are being caught; catch doesn't care what type they are. For example: Writeline catch(set x to hello world.). will write hello world. I really don't get this. Surely the point about an error being thrown to a catch statement is that the error path is separate from the normal execution path? What you are doing here is ensuring that unexpected errors have no chance at all of propagating up to the top level: they are invariably going to get caught by some other handler that was installed just because someone was too lazy to write a set statement followed by a writeline. It also looks like an overloading of catch, semantically similar to the C: int retcode; if( retcode = doSomethingThatReturns0or1() ) printf(Hello world); Again, I don't think you want to start overloading your exception-handling mechanism. If you want a set expression to be equal to the l-value at the end, that's fine, but there's no reason that catch should evaluate to an object or an integral- or real-valued exception in error cases, or of the last statement of the block if there's no error. (Evaluating a block to be equal to its last statement is okay, I guess; I know at least that there's a call in Scheme that lets you do a more imperative programming style in the functional language--whether that's a good thing is probably a holy war.) I just think if you're shooting for an easily understandable language, overloading error handling requires more thought on the programmer's part, not less, because they have to reason about all outcomes. I like BCPL's way of handling block expressions: VALOF is followed by a block of statements and within that block RESULTIS gives the result. This lets you exit the block early (just like a return statement does), but without returning from the current procedure (unless of course the entire body of the procedure is a VALOF block). Naturally the result has to be explicitly specified (otherwise the value is undefined). Maybe FT should do something similar: Writeline value of (set x to hello world. Result is x.). and catch can then stick to catching errors. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding file details...
Kalibr wrote: I've been trying to figure out how to find the details of files (specifically music for now) for a little sorting script I'm making, My aim is to get details on the artist, album, and genre for mp3 and wma files (possibly more in the future). My closest match was when I stumbled accross PyMedia, but it only supports up to 2.4 (I have 2.5). Now I see a bit mentioned on GetFileVersionInfo, but that doesn't seem to help (and most of it went over my head). Is there any module I can use to find this sort of data? I'm trying to not make it specialised in music, because I may want to extend this to picture, movie, text etc. files in the future. Any ideas how I could go about this? You can use the shell COM objects to access media properties as shown by Explorer. import win32com.client sh=win32com.client.Dispatch('Shell.Application') folder= r'M:\Music\Bob Dylan\Highway 61 Revisited' ns=sh.NameSpace(folder) ## the column index for Artist may vary from folder to folder for c in range(0,255): colname=ns.GetDetailsOf(None, c) if colname=='Artists': ## This shows up as just Artist on XP for i in ns.Items(): artist=ns.GetDetailsOf(i, c) if artist: print ns.GetDetailsOf(i, 0), artist break Roger -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple of coordinates
[EMAIL PROTECTED] wrote: Hi, i am using a software which uses python as its scripting language. I want to generate a list of coordinates more or less this way: for i in (beg, end, step): for j in (beg, end, step): for k in (beg, end, step): . Coords = ((i1,j1,k1), (i2,j2,k2), ...,(in,jn.kn)) Your statement of the problem makes it look like all three coordinates cover the same sequence of values. Is that true? Or does i's range (beg, end, step) differ from j's and k's.If they differ, are they all the same length? You pseudo-code makes it look like you want all combinations, but your sample output does not indicate that. Which is it, [(1,1,1), (2,2,2)] or [(1,1,1), (1,1,2),(1,2,1),(1,2,2), ...]? Depending on the answers to those questions, one of the following list comprehensions may demonstrate how to achieve a solution. a = range(2,6,2) b = range(3,7,2) c = range(10,14,2) print a,b,c [2, 4] [3, 5] [10, 12] [(i,j,k) for i,j,k in zip(a,b,c)] # Using zip process three lists in lock-step [(2, 3, 10), (4, 5, 12)] [(i,j,k) for i in a for j in b for k in c] #Nested loop give all possible combos. [(2, 3, 10), (2, 3, 12), (2, 5, 10), (2, 5, 12), (4, 3, 10), (4, 3, 12), (4, 5, 10), (4, 5, 12)] Gary Herron Can anyone give me some advice on how to achieve this ? I got a little idea, but still need to keep working til i get it. Thanks in advance, Victor -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: boost
deepest1 wrote: bjam --build-dir=D:\Program Files\boost_1_35_0 --toolset=gcc stage I got 12 failures and 8 warnings from this (other few hundrds were ok) Hmm, I remember trying to use Boost 1.35 with Python 2.5 on my Debian system and also having problems, are you sure that at least the Python helper libs are correctly compiled? E:\Sourceg++ World.cpp World.cpp:1:28: boost/python.hpp: No such file or directory Try -I D:\Program Files\boost_1_35_0 as additional argument. Further, you will need to tell g++ to link with the according boost library (-lboost_python or something like that) and where it can find that lib (-LD:\Program Files\boost_1_35_0\stage). Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
[OT] Re: FW: php vs python
On Thu, 2008-05-29 at 08:47 +1200, Phil Runciman wrote: The Inuit have 13 terms for snow. Microsoft advocate DSLs. Why have DSLs if language does not matter? For that matter, the English have several terms for snow as well. snow flurry blizzard powder pack flakes crystals sleet slush And in some contexts (http://www.abc-of-snowboarding.com/snowtypes.asp) crud crust rime graupel hail That's 14. Inuits are unimaginative punks. ;) Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
should I put old or new style classes in my book?
Hi All, I am working on a revised edition of How To Think Like a Computer Scientist, which is going to be called Think Python. It will be published by Cambridge University Press, but there will still be a free version under the GNU FDL. You can see the latest version at thinkpython.com; I am revising now, so I welcome all comments, suggestions, corrections, etc. Anyway, I am posting to ask about the current status of new style classes. I am planning to present only one style in the book, because the differences between them don't matter for anything I am doing in the book. The current edition of the book presents old style classes. I am considering switching to new style classes on the assumption that this should be the default choice for new programs. The drawback is that a lot of the online documentation still uses old style classes. Thanks for any guidance you can provide. Cheers, Allen -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes, function pointers and a lot of trouble
Okay, thanks a lot for your reply Nick, I think you pushed me back on the right way. Now I started with trying to implement the callback functions and am stuck at the following point: I define my classes/structures/unions: --CODE- class cdStream(Structure): _fields_ = [(contextH, c_uint), (open, c_void_p), (close, c_void_p), (read, c_void_p), (write, c_void_p), (seek, c_void_p), (tell, c_void_p)] class memunion(Union): _fields_ = [(lpszFileName, c_char_p), (pStream, cdStream)] class cdStgMedium(Structure): _fields_ = [(Type, c_uint), (u, memunion)] --\CODE then i define my functions (right now I do just nothing) and at the same time I define the datatypes like they're listed in my C sample program: --CODE- def pystreamopen (contextH, mode, pErr): pass cstreamopen = CFUNCTYPE(c_uint, c_ushort, c_uint) def pystreamclose (contextH, pErr): pass cstreamclose = CFUNCTYPE(c_uint, c_uint) def pystreamread (contextH, pBuf, pBufsize, pErr): pass cstreamread = CFUNCTYPE(c_uint, c_void_p, c_uint, c_uint) def pystreamtell (contextH, pErr): pass cstreamtell = CFUNCTYPE(c_uint, c_uint) def pystreamwrite (contextH, origin, offset, pErr): print writing... pass cstreamwrite = CFUNCTYPE(c_uint, c_void_p, c_uint, c_uint) --\CODE and now the problem starts: i want the pointers in the cdStream Structure point at my functions and tried to do it the following way: --CODE- data = cdStgMedium() data.type = 0 data.u.pStream.contextH = c_uint(3) #must be some kind of identifier. data.u.pStream.open = cstreamopen(pystreamopen) data.u.pStream.close = cstreamclose(pystreamclose) data.u.pStream.write = cstreamwrite(pystreamwrite) data.u.pStream.tell = cstreamtell(pystreamtell) data.u.pStream.read = cstreamread(pystreamread) --\CODE unfortunately that doesn't work because Python returns a TypeError: incompatible types, CFunctionType instance instead of c_void_p instance Any ideas/help (please)? Best regards, Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: should I put old or new style classes in my book?
Hi, New style classes should be put as the default. This is what I did, based on the principle that new classes were introduces in Python 2.2 and that we are now at 2.5 and soon 2.6. Tutorials that use old style classes may be old and perhaps won't be updated ever. That's not a problem. Just tell people that there are two styles, but that new style classes are far more powerful and do what you think they should do. Matthieu 2008/5/29 [EMAIL PROTECTED]: Hi All, I am working on a revised edition of How To Think Like a Computer Scientist, which is going to be called Think Python. It will be published by Cambridge University Press, but there will still be a free version under the GNU FDL. You can see the latest version at thinkpython.com; I am revising now, so I welcome all comments, suggestions, corrections, etc. Anyway, I am posting to ask about the current status of new style classes. I am planning to present only one style in the book, because the differences between them don't matter for anything I am doing in the book. The current edition of the book presents old style classes. I am considering switching to new style classes on the assumption that this should be the default choice for new programs. The drawback is that a lot of the online documentation still uses old style classes. Thanks for any guidance you can provide. Cheers, Allen -- http://mail.python.org/mailman/listinfo/python-list -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -- http://mail.python.org/mailman/listinfo/python-list
Re: bit parsing from file
On May 29, 9:42�am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hello, I'm tring to make a cutting script. The problem is the following, i have a sample pattern, for example :'11101110' (0xEE) That is the sign of the data begining. How can i cut a file if the byte stepping is not the same, for example: file=open('test.bin','rb') data=file.read() print binascii.hexlify(data) � � � � � �# BB9A (1011101110011010) file.close() so i need to cut the first two bit and start to writeout the bit stream to another file If somebody have an idea to do this, please share with me. Thanx Cutting off the leading two bits isn't a problem, but once you write out the byte 11101110 you are left with 011010 which cannot be written as it's not a byte. How do you plan to handle that? Add two bits at the MSB (00011010) or two bits at the LSB (01101000) or discard the fractional byte? And do you always know what the bit offset is or do you have to search for the 11101110 starting pattern? Rew -- http://mail.python.org/mailman/listinfo/python-list
Re: bit parsing from file
On máj. 29, 18:26, Mensanator [EMAIL PROTECTED] wrote: On May 29, 9:42�am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hello, I'm tring to make a cutting script. The problem is the following, i have a sample pattern, for example :'11101110' (0xEE) That is the sign of the data begining. How can i cut a file if the byte stepping is not the same, for example: file=open('test.bin','rb') data=file.read() print binascii.hexlify(data) � � � � � �# BB9A (1011101110011010) file.close() so i need to cut the first two bit and start to writeout the bit stream to another file If somebody have an idea to do this, please share with me. Thanx Cutting off the leading two bits isn't a problem, but once you write out the byte 11101110 you are left with 011010 which cannot be written as it's not a byte. How do you plan to handle that? Add two bits at the MSB (00011010) or two bits at the LSB (01101000) or discard the fractional byte? And do you always know what the bit offset is or do you have to search for the 11101110 starting pattern? Thank's for the reply, Yes, I have to search for the pattern, the bit offset not always the same. for another thing, it's ok if i can fill up with zero at the LSB or discard that byte. (the last byte not important) Rew -- http://mail.python.org/mailman/listinfo/python-list
yum installs Tkinter in a way visible to only one python installation
My RHEL yum package-manager comes with Python-2.4.3. We also have a seperate Python-2.4.4 Installation on our box. When I added Tkinter using 'yum install tkinter' it seems to have added it in a manner that it is exclusively visible to Python-2.4.3. I cannot import Tkinter from Python-2.4.4. What's the best way to work around this? -- Rahul -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads and import
On May 28, 1:14 pm, [EMAIL PROTECTED] wrote: Hi, I'm trying to work out some strange (to me) behaviour that I see when running a python script in two different ways (I've inherited some code that needs to be maintained and integrated with another lump of code). The sample script is: # Sample script, simply create a new thread and run a # regular expression match in it. import re import threading class TestThread(threading.Thread): def run(self): print('start') try: re.search('mmm', '') except Exception, e: print e print('finish') tmpThread = TestThread() tmpThread.start() tmpThread.join() import time for i in range(10): time.sleep(0.5) print i # end of sample script Now if I run this using: $ python ThreadTest.py then it behaves as expected, ie an output like: start finish 0 1 2 ... But if I run it as follows (how the inherited code was started): $ python -c import TestThread then I just get: start I know how to get around the problem but could someone with more knowledge of how python works explain why this is the case? For reasons I haven't figured out, child threads always acquire the import lock. Since the main thread is already in an import, and is waiting for the child thread to finish, this deadlocks. python ThreadTest.py doesn't deadlock because ThreadTest isn't loaded as a module - it's loaded as a script. A script doesn't hold the import lock while it executes. The solution is to move all the thread spawning and whatnot into a main() function, use the if __name__ == '__main__': main() trick for when you are a script, and if a module require the caller to do ThreadTest.main() after importing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom log handler and logging.config.fileConfig()
On 29 May, 15:53, Lowell Alleman [EMAIL PROTECTED] wrote: Is there any reason not to do this assignment in the myhandler.py directly? This would save a step for each application that needs to use it. Starting from your example, it would now look like this: # -- myhandler.py --- importlogging.handlers class MySpecialHandler(logging.handlers.RotatingFileHandler): def __init__(self, fn): logging.handlers.RotatingFileHandler.__init__(self, fn, maxBytes=2000, backupCount=3) # Register handler in the logging.handlers namespacelogging.handlers.MySpecialHandler = MySpecialHandler # -- app.py --- importlogging.handlers,logging.config import myhandler logging.config.fileConfig(logging.ini) ... Doing it the way you suggest should be fine. Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
undocumented functions in pkgutil
I see that the pkgutil module has many useful functions which are however undocumented. Does anybody know why it is so? In particolar, can I safely use pkg.walk_packages without risking a change of interface in the future? I looks unlikely, since pkgutil is used in setuptools, but I want to be sure before relying on it. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: should I put old or new style classes in my book?
On Thu, May 29, 2008 at 12:07 PM, [EMAIL PROTECTED] wrote: Hi All, I am working on a revised edition of How To Think Like a Computer Scientist, which is going to be called Think Python. It will be published by Cambridge University Press, but there will still be a free version under the GNU FDL. You can see the latest version at thinkpython.com; I am revising now, so I welcome all comments, suggestions, corrections, etc. Anyway, I am posting to ask about the current status of new style classes. I am planning to present only one style in the book, because the differences between them don't matter for anything I am doing in the book. The current edition of the book presents old style classes. I am considering switching to new style classes on the assumption that this should be the default choice for new programs. The drawback is that a lot of the online documentation still uses old style classes. Thanks for any guidance you can provide. Cheers, Allen http://mail.python.org/mailman/listinfo/python-list Definitely go with the new-style classes. Python 3 is coming out soon, which doesn't have classic classes. http://docs.python.org/dev/3.0/whatsnew/3.0.html#new-class-and-metaclass-stuff -- http://mail.python.org/mailman/listinfo/python-list
RE: adobe flex; return xml via turbogears/django
Diez wrote: Why don't you create KID-template like this: div py:strip=True${root}/div and in the controller say @expose(thexmltemplate) def ... return dict(root=myElementTreeRoot) sounds good. Does that py:strip remove the div and anything outside it. I'll be doing a flex style ajax call and it wants just the xml data tree. -- http://mail.python.org/mailman/listinfo/python-list
Re: should I put old or new style classes in my book?
On May 29, 10:07 am, [EMAIL PROTECTED] wrote: Hi All, I am working on a revised edition of How To Think Like a Computer Scientist, which is going to be called Think Python. It will be published by Cambridge University Press, but there will still be a free version under the GNU FDL. You can see the latest version at thinkpython.com; I am revising now, so I welcome all comments, suggestions, corrections, etc. Anyway, I am posting to ask about the current status of new style classes. I am planning to present only one style in the book, because the differences between them don't matter for anything I am doing in the book. The current edition of the book presents old style classes. I am considering switching to new style classes on the assumption that this should be the default choice for new programs. The drawback is that a lot of the online documentation still uses old style classes. Thanks for any guidance you can provide. Cheers, Allen I've got Python 3.0 alpha 2. In this version, it looks like you can define classes in either the old style or new style. (I snipped the top line a bit in the following example): Python 3.0a2 (r30a2:59405M, Dec 7 2007, 15:23:28 Type help, copyright, credits or license class one(object): pass ... class two: pass ... two class '__main__.two' one class '__main__.one' type(one) type 'type' type(two) type 'type' That said, old-style classes can't use the staticmethod or classmethod properties correctly. New-style classes better support multiple inheritance and old-style classes can't use metaclasses. Metaclasses, and even multiple inheritance may be beyond the scope of your book, though. I'd recommend new-style classes myself, as it avoids some nasty subtle problems if your readers move to more advanced techniques. You are correct, though, that some of the classes in the Python library use the old style. So, you might want to acknowledge that there are two ways of doing classes, that a lot of old code uses the old way. The new way adds some powerful new techniques that may be beyond the scope of your book. In Python 3.0, it won't matter, as everything is a new-style class anyway. --Jason -- http://mail.python.org/mailman/listinfo/python-list
Saving tif file from tricky webserver
Greetings, I am attempting to automate accessing and saving a file (a TIF) from the following URL: http://patimg1.uspto.gov/.DImg?Docid=US007376435PageNum=1IDKey=E21184B8FAD5 I have tried some methods using urllib, httplib, and web32com.client(InternetExplorer), but haven't been successful. Currently I am using (in Python 2.5) import webbrowser url = [see above] webbrowser.open(url, new=0, autoraise=0) When this is run a windows popup dialog opens asking me to Open, Save, or Cancel. However, if I query multiple such URLs, I do not want to have to respond manually. Is there a way I can use Python to save the TIF? -- http://mail.python.org/mailman/listinfo/python-list
MACOSX_DEPLOYMENT_TARGET mismatch bug on Leopard using system Python
Hi all, I'm getting error messages like distutils.errors.DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET mismatch: now 10.3 but 10.5 during configure on Leopard using system Python when trying to build a third-party module. Can this be fixed without installing a different distribution of Python? Googling the problem turns up fixes that involve configuring source distributions, unless I'm mistaken. Thanks, Anand Patil -- http://mail.python.org/mailman/listinfo/python-list
NYC Python User Group Meeting Announcement....
Greetings! The next New York City Python Users Group meeting is planned for June 17th, 6:30pm at Daylife Inc. at 444 Broadway (between Howard St. and Grand St.) on the 5th Floor. We welcome all those in the NYC area who are interested in Python to attend. More information can be found on the users group wiki page: http://www.nycpython.org Hope to see you there! -John Clark -- http://mail.python.org/mailman/listinfo/python-list
so funny...
http://sitscape.com/topic/funny Just keep hit the Surprise- button there for amazing fun. Click on channel will show you other topics, lots of fun! -- http://mail.python.org/mailman/listinfo/python-list
Python threads and memory usage
Hi, I'm writing client-server application in Python. It's monitoring system, where server listen and waits for TCP connections, and every connection takes own thread. Every thread puts data from clients to Queue and exits. Then there is one DB loader thread, which loads all data from Queue to MySQL DB. I observed, that every thread reserved some memory, and after exit thread doesn't freed it. When i leaved my server working for 3 days, then it takes 15% of 512MB memory (during that time about 15000 threads were created and stopped). When server starts it only takes about 1% of memory. I know that I can made client which connects once and keep this session with server thread all time (it should resolve my problems), but I'm curious if this is normal or it is something like memory leak. Or maybe I'm doing something wrong :) If You need I can paste all my code. Regards -- http://mail.python.org/mailman/listinfo/python-list