Re: Dictionary from a list
Jan Kaliszewski wrote: 20-08-2009 o 02:05:57 Jan Kaliszewski z...@chopin.edu.pl wrote: Or probably better: from itertools import islice, izip dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) Or similarly, perhaps more readable: iterator = iter(li) dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) I just can't stop posting this one: from itertools import izip it = iter([1,2,3,4,5,6]) dict(izip(it, it)) {1: 2, 3: 4, 5: 6} I really tried, but yours drove me over the edge. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary from a list
On Thu, 20 Aug 2009 08:10:28 +0200, Peter Otten wrote: I just can't stop posting this one: from itertools import izip it = iter([1,2,3,4,5,6]) dict(izip(it, it)) {1: 2, 3: 4, 5: 6} I really tried, but yours drove me over the edge. If you want something to drive you over the edge: alist = [1, 2, 3, 4, 5, 6] dict(apply(zip, map(lambda n: map(lambda t: t[1], filter(lambda t: ((not (t[0]%2)) == 1) == n, enumerate(alist))), range(1, -1, -1 {1: 2, 3: 4, 5: 6} Enjoy :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
regular expression
Hello, I would like to change the string (1 and (2 or 3)) by (x[1] (x [2] || x[3])) using regular expression... Anyone can help me ? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create functors?
As near as I can tell, a functor is just an object which is callable like a function I believe that's how they're defined in the C++ world, in which, of course, functions aren't first-class objects... - Rami Chowdhury Never assume malice when stupidity will suffice. -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Aug 19, 2009, at 21:11 , Steven D'Aprano wrote: On Wed, 19 Aug 2009 18:42:32 -0700, Paul Rubin wrote: Robert Dailey rcdai...@gmail.com writes: I want to simply wrap a function up into an object so it can be called with no parameters. Nitpick: what you are asking for is called a closure. Functor means something completely different. I'm glad somebody else noticed this. I would have said something about it myself, except I wasn't entirely sure my understanding of functor is correct. As near as I can tell, a functor is just an object which is callable like a function without actually being implemented as a function, e.g.: class Functor: def __call__(self): return None f = Functor() result = f() -- Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression
On Thu, 20 Aug 2009 00:18:23 -0700, Pierre wrote: Hello, I would like to change the string (1 and (2 or 3)) by (x[1] (x [2] || x[3])) using regular expression... Anyone can help me ? Do you mean you want to change the string into (x[1] (x[2] || x[3])) ? Does it have to be using regular expressions? Would this be good enough? s = (1 and (2 or 3)) for c in '123': ... s = s.replace(c, 'x[%s]'%c) ... s = s.replace('or', '||') s = s.replace('and', '') s '(x[1] (x[2] || x[3]))' -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary from a list
Peter Otten wrote: it = iter([1,2,3,4,5,6]) dict(izip(it, it)) {1: 2, 3: 4, 5: 6} devoZip(it). Zip(it) good./devo it's-3:00am-and-i-seriously-need-to-sleep'ly yers... -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary from a list
Steven D'Aprano wrote: On Thu, 20 Aug 2009 08:10:28 +0200, Peter Otten wrote: I just can't stop posting this one: from itertools import izip it = iter([1,2,3,4,5,6]) dict(izip(it, it)) {1: 2, 3: 4, 5: 6} I really tried, but yours drove me over the edge. If you want something to drive you over the edge: I meant that figuratively... alist = [1, 2, 3, 4, 5, 6] dict(apply(zip, map(lambda n: map(lambda t: t[1], filter(lambda t: ((not (t[0]%2)) == 1) == n, enumerate(alist))), range(1, -1, -1 {1: 2, 3: 4, 5: 6} ...originally. Enjoy :) Not ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression
Pierre wrote: I would like to change the string (1 and (2 or 3)) by (x[1] (x [2] || x[3])) using regular expression... Anyone can help me ? re.compile(r(\d+)).sub(rx[\1], (1 and (2 or 3))) '(x[1] and (x[2] or x[3]))' re.compile(and|or).sub(lambda m, d={and:, or:||}: d[m.group()], _) '(x[1] (x[2] || x[3]))' Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL and Python
On my photo jpg i have this : Image Type: jpeg (The JPEG image format) Width: 1224 pixels Height: 1632 pixels Camera Brand: Sony Ericsson Camera Model: W810i Date Taken: 2009:07:09 08:16:21 Exposure Time: 1/19 sec. ISO Speed Rating: 320 Flash Fired: Flash did not fire, compulsory flash mode. Metering Mode: Center-Weighted Average Software: R4EA031 prgCXC1250321_ORANGE_HN 4.5 This is the data i want edit it to make some copyright for my site. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create functors?
Steven D'Aprano ste...@remove.this.cybersource.com.au writes: As near as I can tell, a functor is just an object which is callable like a function without actually being implemented as a function, e.g.: No it's not anything like that either, at least as I'm used to the term in programming or in mathematics. Maybe it's used other ways though. As I'm used to it, it's a feature of certain static type systems. The notion isn't that useful in Python but you could translate it something like this: imagine that the list datatype has a couple extra operations: # lift_value turns a normal value from a base type to a 1-element list list.lift_value(x) = [x] # lift_function turns a function on a base type to a higher order # function that operates on a whole list list.lift_function(f) = partial(map, f) Then given a function like def square(x): return x*x you could say lifted_square = list.lifted_function(square) print lifted_square([1,2,3,4,5]) and get [1,4,9,16,25]. Similarly if you had some other type (like a tree data structure), that type could also support a map-like operation so you could lift functions to it (lifting a function and applying it to a tree like [1,[2,3],4] would result in [1,[4,9],16] or whatever). If I remember properly, for type t to be a functor it needs the above two lifting operations, with the property that for a given function f, t.lifted_value(f(x)) = (t.lifted_function(f))(t.lifted_value(x)) I guess this explanation isn't going that well but basically in a statically typed language you'd use functors to convert the signatures of functions to versions that operate on higher types. The idea comes from ML and is used explicitly in Haskell, and I think some of the C++ standard template library can be explained in terms of functors. For the mathematical concept of functors and how they relate to programming (at least Haskell's version), see: http://en.wikibooks.org/Haskell/Category_theory -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create functors?
On Thu, 20 Aug 2009 01:36:14 -0700, Paul Rubin wrote: Steven D'Aprano ste...@remove.this.cybersource.com.au writes: As near as I can tell, a functor is just an object which is callable like a function without actually being implemented as a function, e.g.: No it's not anything like that either, at least as I'm used to the term in programming or in mathematics. Maybe it's used other ways though. According to Wikipedia, functor can be used as a synonym for function object: http://en.wikipedia.org/wiki/Function_object which is what I was thinking of. So it seems there are at least two meanings for the word, neither of which seems to apply to this thread :) As I'm used to it, it's a feature of certain static type systems. The notion isn't that useful in Python I find the Haskell page entirely opaque and unintelligible. Well, perhaps not *entirely* opaque, but pretty close: it assumes a mathematical sophistication that I don't think I even had when I was getting my maths degree, let alone can remember two decades later. (Pity the poor VB coders wondering what Haskell is good for...) The Wikipedia page is a little better, but it's section on Examples is laughable -- the examples are as unintelligible to this reader as the description before them. But let me try an example to see if I've got it right: class Int2StrFunctor: def map1(self, n): if type(n) is not int: raise TypeError('argument must be an int') return -*n def map2(self, f): if type(f) is not type(lambda: None): raise TypeError('argument must be a function') # assume f takes an int, and returns another int def inner(n): return self.map1(f(n)) return inner The functor can take an int and return a string: F = Int2StrFunctor() # F is a functor F.map1(3) '---' It can also take a function (of int - int) and return a new function (int - str): def myfunc(n): ... return n+2 ... f = F.map2(myfunc) f(3) '-' f(4) '--' There's nothing special about the methods map1() and map2(), I could call them anything I like, or even do this: def __call__(self, arg): ... if type(arg) is int: ... return self.map1(arg) ... else: ... return self.map2(arg) ... Int2StrFunctor.__call__ = __call__ F(2) '--' F(myfunc)(0) '--' There are some technical restrictions on functors, relating to the sorts of functions and types (strictly categories) they can accept, presumably to make them mathematically well-behaved. Have I got it correct? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: What file is foo in package bar in ?
On Thu, Aug 20, 2009 at 01:06:00AM +0200, Christian Heimes wrote: northof40 wrote: Given an arbitary package is there some programmatic way to 'ask' what file the method/function is implemented in ? Indeed, the inspect module contains several useful functions for the job, for example http://docs.python.org/library/inspect.html#inspect.getfile Stupid question from someone who ignores it all: since the OP is reading code from an existing tree in order to learn from it, wouldn't it make more sense to use something like Cscope? Assuming it works with Python, of course. If it doesn't, is there a similar tool that can be used? A related question too is whether any of these tools actually help in an object-oriented environment. http://cscope.sourceforge.net/ http://www.linux.com/archive/feature/114237 -- http://mail.python.org/mailman/listinfo/python-list
Re: difference between 2 arrays
(envoyé via news:\\news.wanadoo.fr\comp.lang.python) Hi! Yes, the module sets is written, in doc, like deprecated. But: - sets exist in Python 2.6 ( 2.5 or 2.4) - documentation of sets (module) is better tha, documentation of set (builtin) The best: read the documentaion of the module, and use the builtin... @-salutations -- MCI -- http://mail.python.org/mailman/listinfo/python-list
Polling a net address
Hi All, I'm writing a system tray application for windows, and the app needs to poll a remote site at a pre-defined interval, and then process any data returned. The GUI needs to remain responsive as this goes on, so the polling needs to be done in the background. I've been looking into Twisted as a way of achieving this, but can't seem to get anything to loop successfully. Does anyone have any pointers that they might be able to give me? TIA. -- http://mail.python.org/mailman/listinfo/python-list
difference between raw_input() and input()
Hi, I have used both raw_input() and input() for a same input value. But these gives different output. I have listed below what actually I have done a = raw_input(===) === 023 a '023' I have given the same value for the input() but it gives 19 as result a = input(===) === 023 a 19 Is there anything hide within this. Please illustrate the difference between raw_input() and input() Thanks in advance Baalu -- http://mail.python.org/mailman/listinfo/python-list
Zipimport leaks memory?
Hi, We are currently trying to identify and fix all the memory leaks by just doing Py_Initialize-PyRun_SimpleFile(some simple script)-Py_Finalize and found that there are around 70 malloc-ed blocks which are not freed. One of the significant contributor to this number is the 'files' object in ZipImporter. I am not able to identify the reason for this leak and was wondering if anyone on this list would help me out here. So, here goes : Since we have a zip file in our sys.path, this object is initialized and added to the zip_directory_cache dict during Py_Initialize. One point to note here is that there is no DECREF on the 'files' object after adding it to the zip_directory_cache dict. When a module in a directory is imported(encoding.alias) then the reference count of 'files' is increased. When this module is unloaded during Py_Finalize-PyImport_Cleanup, the ref count of files object is decremented properly. So at the end of Py_Finalize the files object still has one reference count which is a result of it being an entry in the zip_directory_cache. To summarize : ZipImporter-files - zipimporter_init function: Py_Initialize - Read files from zip - ref_count -1 Add files to zip_directory_cache - ref count - 2 Import some modules from different directory in zip - ref count - 3 Py_Finalze - PyImport_Cleanup - sub-directory - ref-count - 2 PyImport_Cleanup - main directory - ref-count - 1 So the reference count of 'files' is still 1 after Py_Finalize. The zip_directory_cache is the dict that has this 'files' object and this dict is added to the module during zipimport module initialization. This dict is destroyed during _PyModule_Clear(called by PyImport_Cleanup) but the 'files' object's reference count is not decremented. Please excuse me if I have misinterpreted the whole logic. Any pointers towards solving this would be great. Thank you. ~Ashwin -- http://mail.python.org/mailman/listinfo/python-list
Re: difference between raw_input() and input()
On Thu, Aug 20, 2009 at 3:24 AM, baalu aanandbaaluaan...@gmail.com wrote: Hi, I have used both raw_input() and input() for a same input value. But these gives different output. I have listed below what actually I have done a = raw_input(===) === 023 a '023' I have given the same value for the input() but it gives 19 as result a = input(===) === 023 a 19 Is there anything hide within this. Please illustrate the difference between raw_input() and input() input() === eval(raw_input()) eval(023) -- int(23, 8) -- 19 [an integer, not a string] raw_input() /always/ returns a string. Never use input() in Python 2.x. In Python 3, raw_input() was renamed to input() because it's a better name and the old input() was hardly ever used (correctly). Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
pexpect on QNX platform
Hi, I found that pexpect is available only for linux. But we need to port to QNX, Is pexpect is available? If yes, where can I find it. Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: #elements of seq A in seq B
Jan Kaliszewski wrote: 20-08-2009 o 01:19:24 Neal Becker ndbeck...@gmail.com wrote: What would be a time efficient way to count the number of occurrences of elements of sequence A in sequence B? (in this particular case, these sequences are strings, if that matters). If you mean: to count occurences of each element of A (separately) in B... Hm, maybe something like this: # result as a dict {element of A: how many occurences in B, ...} dict((element, B.count(element)) for element in A) If you mean: to count non overlaping occurences of string A in B -- simply: B.count(A) Regards, *j I meant #occurrences of characters from the set A in string B -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL and Python
On Aug 20, 10:23 am, catafest catalinf...@gmail.com wrote: On my photo jpg i have this : Image Type: jpeg (The JPEG image format) Width: 1224 pixels Height: 1632 pixels Camera Brand: Sony Ericsson Camera Model: W810i Date Taken: 2009:07:09 08:16:21 Exposure Time: 1/19 sec. ISO Speed Rating: 320 Flash Fired: Flash did not fire, compulsory flash mode. Metering Mode: Center-Weighted Average Software: R4EA031 prgCXC1250321_ORANGE_HN 4.5 This is the data i want edit it to make some copyright for my site. I don't know about PIL but you might want to try exif.py. http://sourceforge.net/projects/exif-py/ -- http://mail.python.org/mailman/listinfo/python-list
New Windows Mobile Smartphones from I-mate
Windows Mobile smart phone device manufacturer, i-mate has shown off its latest models -the Ultimate 9502 and the Ultimate 8502.for other details http://infomobilepk.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Hi everyone, I get a problem when using binhex module
Below is what I copy from the Internet: import binhex import sys infile = in.txt binhex.binhex(infile, sys.stdout) Every time I try to run this script, I get a message saying Traceback (most recent call last): File D:\eclipse_workspace\encode\src\binhex.sample.py, line 6, in module import binhex File C:\Python25\lib\binhex.py, line 12, in module # easy interface should work as expected on any platform. TypeError: 'module' object is not callable Does anyone encounter similar situation. Thank you for your help? -- http://mail.python.org/mailman/listinfo/python-list
Re: #elements of seq A in seq B
Neal Becker wrote: I meant #occurrences of characters from the set A in string B If a contains few characters: n = sum(b.count(c) for c in a) If a contains many characters: identity = .join(map(chr, range(256))) n = len(b) - len(b.translate(identity, a)) Peter -- http://mail.python.org/mailman/listinfo/python-list
pypi category
Hi, Would someone be able to inform me how a category can be added to the pypy list of categories? I'd like to add a CAD Geometry category. ( I develop PythonOCC, wrappers for the OpenCASCADE CAD kernel, which is why ) Thanks! -jelle -- http://mail.python.org/mailman/listinfo/python-list
Re: Hi everyone, I get a problem when using binhex module
On Thu, Aug 20, 2009 at 10:07 PM, Yan Jian ballack...@gmail.com wrote: Does anyone encounter similar situation. Thank you for your help? Yeah, in Python 3.1 I get this: Traceback (most recent call last): File test.py, line 6, in module binhex.binhex(file, sys.stdout) File c:\Python31\lib\binhex.py, line 228, in binhex ofp = BinHex(finfo, out) File c:\Python31\lib\binhex.py, line 149, in __init__ ofp.write(b'(This file must be converted with BinHex 4.0)\r\r:') TypeError: write() argument 1 must be str, not bytes Python 2.6.2 runs fine though: :QPZ,R4iG!849K82j!%!*!3#31#$6a...@%z$3t0fr*kb5ij6a*bb@%...@% !!!: I never used binhex however, so someone else might have a better insight. Cheers, Xav -- http://mail.python.org/mailman/listinfo/python-list
Re: Data visualization in Python
On Aug 17, 3:10 pm, kj no.em...@please.post wrote: I'm looking for a good Python package for visualizing scientific/statistical data. (FWIW, the OS I'm interested in is Mac OS X). Please take a look at the amcharts embedding in WHIFF http://aaron.oirt.rutgers.edu/myapp/amcharts/doc WHIFF is a collection of support services for WSGI applications which allows applications to be composed by dropping dynamic pages into container directories. http://aaron.oirt.rutgers.edu/myapp/docs/W.intro thanks, -- Aaron Watters === Sisyphus got ripped. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE is not as interactive as Maple
On Aug 20, 12:22 am, laser laser.y...@gmail.com wrote: In the future, will Python provide programe enviroment like Maple does? A quick, flip answer: perhaps if you design one? Tools for Python are designed by people scratching an itch. That being said, have a look at reinteract: http://www.reinteract.org/trac/wiki/Tutorial/Introduction In Maple, you can remove anything unneeded in the editor. And the code execution order are not necessary in one direction. You can run any command line on the screen by push Enter key. These functions gave a lot of flaxibility for users to start with programming something. André -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE is not as interactive as Maple
On Wed, Aug 19, 2009 at 11:22 PM, laserlaser.y...@gmail.com wrote: In the future, will Python provide programe enviroment like Maple does? In Maple, you can remove anything unneeded in the editor. And the code execution order are not necessary in one direction. You can run any command line on the screen by push Enter key. These functions gave a lot of flaxibility for users to start with programming something. -- http://mail.python.org/mailman/listinfo/python-list Maple is a very expensive IDE that happens to have a language that goes with it. Python is a language that happens to come with a free text editor/integrated shell. For languages like Mathematica and Maple, the IDE is everything- you almost never use the language without the integrated IDE. Python focuses more on language features. IDLE is not supposed to be a great editor on the level of Visual Studio or Maple, it's supposed to be a convenient way to run your code for people who are scared of the command line. I would venture a guess that very few people on this list use IDLE for their coding. Based on previous answers to questions, most people use Eclipse/PyDev, Netbeans, Wing, Komodo, emacs, and vim. Wing and Komodo are the only Python-specific IDEs on that list and neither of them are free (though the have stripped-down free versions). If you want a better editor, use one of those. -- http://mail.python.org/mailman/listinfo/python-list
Python libexpat and EXPAT are same/Different?
Hi all, Am very new to XML, I have a query, Does Python libexpat and EXPAT are same or they are diffrent? Thanks in advance. Regards, Hari -- http://mail.python.org/mailman/listinfo/python-list
Re: Python libexpat and EXPAT are same/Different?
hari wrote: Am very new to XML, I have a query, Does Python libexpat and EXPAT are same or they are diffrent? Depends on what you mean with EXPAT. Python's expat module that you can find in the standard library is the well known non-validating XML parser originally written by James Clark. BTW, if you are new to XML and want to use it in Python, you might want to start with the xml.etree package. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: pypi category
The pypi list of categories, sorry... -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE is not as interactive as Maple
On 19 Aug, 20:22, laser laser.y...@gmail.com wrote: In the future, will Python provide programe enviroment like Maple does? You might be looking for SAGE. http://www.sagemath.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: difference between raw_input() and input()
On Thu, 20 Aug 2009 03:24:15 -0700, baalu aanand wrote: Hi, I have used both raw_input() and input() for a same input value. But these gives different output. I have listed below what actually I have done a = raw_input(===) === 023 a '023' I have given the same value for the input() but it gives 19 as result a = input(===) === 023 a 19 Is there anything hide within this. Please illustrate the difference between raw_input() and input() Did you look them up in the documentation? Did you try the interactive help? help(input) help(raw_input) Perhaps you could try some further experiments: raw_input() hello world 'hello world' input() hello world Traceback (most recent call last): File stdin, line 1, in module File string, line 1 hello world ^ SyntaxError: unexpected EOF while parsing Does that give you a hint as to what is happening? How about this? 07 7 08 File stdin, line 1 08 ^ SyntaxError: invalid token 010 8 oct(8) 010 -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Hi everyone, I get a problem when using binhex module
Yan Jian wrote: Below is what I copy from the Internet: import binhex import sys infile = in.txt binhex.binhex(infile, sys.stdout) Every time I try to run this script, I get a message saying Traceback (most recent call last): File D:\eclipse_workspace\encode\src\binhex.sample.py, line 6, in module import binhex File C:\Python25\lib\binhex.py, line 12, in module # easy interface should work as expected on any platform. TypeError: 'module' object is not callable Does anyone encounter similar situation. Thank you for your help? First question: Are you running Python2.5 ? And do you actually have it installed in c:\Python25 directory? Do you in fact have 5 blank lines in front of the import binhex line? Assuming yes for all of those, the only cause I can figure for that particular error string is that binhex.pyc is out of synch with binhex.py. To test that theory, try deleting it (in general that means renaming it temporarily, so you could restore it if I'm wrong), and running again. I would also add the lines: import sys print sys.version in front of the import, just to make sure you're running what you think you are. And then I'd get a console prompt, change directory to D:\eclipse_workspace\encode\src\binhex and run sample.py from that command prompt. Compare the two version strings, and see if anything's different in the two error messages. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing untrusted code
Sorry for digging this back from the grave. I've had to chew on it for a little while. On Aug 8, 1:40 am, Nobody nob...@nowhere.com wrote: If you want to support restricted execution within a language, it has to be built into the language from day one. Trying to bolt it on later is a fool's errand. Fair enough. In this context, let's say I do this: import __builtin__ import imp originalBuiltins = imp.new_module(OriginalBuiltins) def readOnlyOpen(filename): return originalBuiltins.open(filename, r) __builtin__.open = readOnlyOpen exec(anUntrustedString, {}) In what ways would the untrusted string be able to obtain the original, built-in open function and open a file for writing? Manu -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing untrusted code
Emanuele D'Arrigo write: In what ways would the untrusted string be able to obtain the original, built-in open function and open a file for writing? Yes, if you know some tricks: [cls for cls in object.__subclasses__() if cls.__name__ == 'file'][0] type 'file' Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing untrusted code
They could, of course, use the file object constructor directly, e.g.: f = file(/etc/passwd, w) On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo man...@gmail.com wrote: Sorry for digging this back from the grave. I've had to chew on it for a little while. On Aug 8, 1:40 am, Nobody nob...@nowhere.com wrote: If you want to support restricted execution within a language, it has to be built into the language from day one. Trying to bolt it on later is a fool's errand. Fair enough. In this context, let's say I do this: import __builtin__ import imp originalBuiltins = imp.new_module(OriginalBuiltins) def readOnlyOpen(filename): return originalBuiltins.open(filename, r) __builtin__.open = readOnlyOpen exec(anUntrustedString, {}) In what ways would the untrusted string be able to obtain the original, built-in open function and open a file for writing? Manu -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
ncurses getch unicode (was: decoding keyboard input when using curses)
Hello, I have the same problem mentioned in http://groups.google.com/group/comp.lang.python/browse_thread/thread/c70c80cd9bc7bac6?pli=1some months ago. Python 2.6 program which uses ncurses module in a terminal configured to use UTF-8 encoding. When trying to get input from keyboard, a non-ascii character (like ç) is returned as 2 integers 255, needing 2 calls to getch method to get both. These two integers \xc3 \xa7 forms the utf-8 encoded representation of ç character. ncurses get_wch documentation states the function should return an unique integer 255 with the ordinal representation of that unicode char encoded in UTF-8, \xc3a7. [Please, read the link above, it explains the issue much better that what I could do.] Any idea or update on this? Thanks, Iñigo Serna PS: my system is a Linux Fedora 11 x86_64. Same happens on console, gnome-terminal or xterm. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary from a list
On Aug 20, 9:10 am, Peter Otten __pete...@web.de wrote: Jan Kaliszewski wrote: 20-08-2009 o 02:05:57 Jan Kaliszewski z...@chopin.edu.pl wrote: Or probably better: from itertools import islice, izip dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) Or similarly, perhaps more readable: iterator = iter(li) dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) I just can't stop posting this one: from itertools import izip it = iter([1,2,3,4,5,6]) dict(izip(it, it)) {1: 2, 3: 4, 5: 6} I really tried, but yours drove me over the edge. Peter Nice. (but looks like stepping towards the dark side ... :-) I also liked this one: iterator = iter(li) dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) which inspired me to do something quite similar: a=range(1, 11) a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] dict([[a.pop(0), a.pop(0)] for i in range(len(a)/2)]) {1: 2, 3: 4, 9: 10, 5: 6, 7: 8} Thanks -- http://mail.python.org/mailman/listinfo/python-list
Silly question
I just noticed that sequence[i:j:k] syntax in a post here. When did this happen? (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid - otoh if it was introduced in 2.x I'm just slow...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly question
On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrichdullr...@sprynet.com wrote: I just noticed that sequence[i:j:k] syntax in a post here. When did this happen? (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid - otoh if it was introduced in 2.x I'm just slow...) Well, I got some good news and some bad news. According to the docs, it existed in 1.4 but the built-in sequences didn't support it until 2.3. It's not used that often anyway so you haven't been missing much. http://www.python.org/doc/2.3.5/whatsnew/section-slices.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing untrusted code
On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo wrote: Fair enough. In this context, let's say I do this: import __builtin__ import imp originalBuiltins = imp.new_module(OriginalBuiltins) def readOnlyOpen(filename): return originalBuiltins.open(filename, r) __builtin__.open = readOnlyOpen Have you actually tested this? I don't think it works the way you think it does. import __builtin__ import imp originalBuiltins = imp.new_module(OriginalBuiltins) originalBuiltins.open Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'module' object has no attribute 'open' So your strategy fails to provide read-only file access. But moving on... In what ways would the untrusted string be able to obtain the original, built-in open function and open a file for writing? That's hardly even a challenge. __builtin__.open = readOnlyOpen anUntrustedString = import __builtin__ ... reload(__builtin__) ... open('junk', 'w').write('a') ... exec(anUntrustedString, {}) open('junk').read() 'a' Not only have I broken your read only open within the call to exec, but I've broken it outside as well. With a little bit more effort, I could probably save and restore the open, so that my untrusted string could write to files inside the exec(), but code outside of the exec() would still see the readOnlyOpen. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly question
David C Ullrich dullr...@sprynet.com wrote: I just noticed that sequence[i:j:k] syntax in a post here. When did this happen? (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid - otoh if it was introduced in 2.x I'm just slow...) Googling for 'python extended slice' returns this as the first hit: http://www.python.org/doc/2.3.5/whatsnew/section-slices.html 15 Extended Slices Ever since Python 1.4, the slicing syntax has supported an optional third ``step'' or ``stride'' argument. For example, these are all legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to Python at the request of the developers of Numerical Python, which uses the third argument extensively. However, Python's built-in list, tuple, and string sequence types have never supported this feature, raising a TypeError if you tried it. Michael Hudson contributed a patch to fix this shortcoming. So extended slices have existed since Python 1.4, but builtin types only started to support them from 2.3. -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing untrusted code
On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo wrote: In what ways would the untrusted string be able to obtain the original, built-in open function and open a file for writing? On a related topic, you should read this post here: http://tav.espians.com/a-challenge-to-break-python-security.html -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Annoying octal notation
Hi all, Is there some magic to make the 2.x CPython interpreter to ignore the annoying octal notation? I'd really like 012 to be 12 and not 10. If I want an octal I'll use oct()! Explicit is better than implicit... TIA David -- http://mail.python.org/mailman/listinfo/python-list
ANN: Wing IDE 3.2 released
Hi, Wingware has released version 3.2.0 final of Wing IDE, our integrated development environment for the Python programming language. *Release Highlights* This release includes the following new features: * Support for Python 3.0 and 3.1 * Rewritten version control integration with support for Subversion, CVS, Bazaar, git, Mercurial, and Perforce (*) * Added 64-bit Debian, RPM, and tar file installers for Linux * File management in Project view (**) * Auto-completion in the editor obtains completion data from live runtime when the debugger is active (**) * Perspectives: Create and save named GUI layouts and optionally automatically transition when debugging is started (*) * Improved support for Cython and Pyrex (*.pyx files) * Added key binding documentation to the manual * Added Restart Debugging item in Debug menu and tool bar (**) (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal and Professional only. The release also contains many other minor features and bug fixes; see the change log for details: http://wingware.com/pub/wingide/3.2.0/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE 101 can be used free of charge. Wing IDE Pro 3.2.0http://wingware.com/downloads/wingide/3.2 Wing IDE Personal 3.2.0 http://wingware.com/downloads/wingide-personal/3.2 Wing IDE 101 3.2.0http://wingware.com/downloads/wingide-101/3.2 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, version control, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.2 supports Python versions 2.0.x through 3.1.x. *Purchasing and Upgrading* Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license:https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com -- http://mail.python.org/mailman/listinfo/python-list
thread and win32com.client problem
Hi, I have a problem with thread and win32com.client running python 2.5 on vista (activestate python) import win32com.client, thread def child(test): problem=win32com.client.Dispatch(WScript.Shell) print 'hello from thread', test def parent(): i=0 while 1: i+=1 thread.start_new(child,('abc',)) if raw_input()=='q': break parent() above codes will give me error when I run it. but if without the line problem=win32com.client.Dispatch(WScript.Shell) it just works fine. errors are: Unhandled exception in thread started by function child at 0x01E690F0 Traceback (most recent call last): File C:\Users\Test\Desktop\Test\test_thread.py, line 3, in child problem=win32com.client.Dispatch(WScript.Shell) File C:\Python25\lib\site-packages\win32com\client\__init__.py, line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName (dispatch,userName,clsctx) File C:\Python25\lib\site-packages\win32com\client\dynamic.py, line 98, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File C:\Python25\lib\site-packages\win32com\client\dynamic.py, line 78, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) Traceback (most recent call last): File C:\Users\Test\Desktop\Test\test_thread.py, line 11, in module parent() File C:\Users\Test\Desktop\Test\test_thread.py, line 10, in parent if raw_input()=='q': break Thanks for any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly question
On Thu, 20 Aug 2009 18:41:34 +, Duncan Booth wrote: David C Ullrich dullr...@sprynet.com wrote: I just noticed that sequence[i:j:k] syntax in a post here. When did this happen? (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid - otoh if it was introduced in 2.x I'm just slow...) Googling for 'python extended slice' returns this as the first hit: http://www.python.org/doc/2.3.5/whatsnew/section-slices.html 15 Extended Slices Ever since Python 1.4, the slicing syntax has supported an optional third ``step'' or ``stride'' argument. For example, these are all legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to Python at the request of the developers of Numerical Python, which uses the third argument extensively. However, Python's built-in list, tuple, and string sequence types have never supported this feature, raising a TypeError if you tried it. Michael Hudson contributed a patch to fix this shortcoming. So extended slices have existed since Python 1.4, but builtin types only started to support them from 2.3. Fine (I knew they existed in Numerical Python way back when...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly question
On Thu, 20 Aug 2009 14:36:35 -0400, Benjamin Kaplan wrote: On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrichdullr...@sprynet.com wrote: I just noticed that sequence[i:j:k] syntax in a post here. When did this happen? (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid - otoh if it was introduced in 2.x I'm just slow...) Well, I got some good news and some bad news. According to the docs, it existed in 1.4 but the built-in sequences didn't support it until 2.3. It's not used that often anyway so you haven't been missing much. So I'm slow, fine. (There were several times when I was using 1.5.3 and wished they were there - transposing matrices, etc.) http://www.python.org/doc/2.3.5/whatsnew/section-slices.html -- http://mail.python.org/mailman/listinfo/python-list
Re: thread and win32com.client problem
I already find the way to fix it. :-) -- http://mail.python.org/mailman/listinfo/python-list
ANN: discover 0.3.0 released, automatic test discovery for unittest
The discover module is a backport of the automatic test discovery from the unittest module in Python-trunk (what will become Python 2.7 and 3.2). The discover module should work on versions of Python 2.4 upwards: * discover module on PyPI: http://pypi.python.org/pypi/discover The discover module can be used to run all, or a subset, of your unittest based tests automatically from the command line. See the PyPI page for details. Version 0.3.0 has two new features: * Failing to import a file (e.g. due to a syntax error) no longer halts discovery but is reported as an error. * Discovery will not attempt to import test files whose names are not valid Python identifiers, even if they match the pattern. -- http://mail.python.org/mailman/listinfo/python-list
Problem with arrays in a recursive class function
I have a list of nodes, and I need to find a path from one node to another. The nodes each have a list of nodes they are connected to, set up like this: class Node(object): def __init__(self, connectedNodes): self.connectedNodes = connectedNodes nodes = { 1: Node([4]), 2: Node([3]), 3: Node([2, 4, 5]), 4: Node([1, 6, 3]), 5: Node([3, 7]), 6: Node([4, 9]), 7: Node([5, 8]), 8: Node([7, 9]), 9: Node([6, 8]) } I made a quick brute-force pathfinder to solve it (in this case, a path from node 1 to node 9). Here it is: class PathFind(object): def __init__(self, source, destination): self.source = source self.destination = destination self.solved = [] def Search(self): self.PathFind([self.source]) if self.solved: print Solutions: for i in self.solved: print \t + str(i) else: print Couldn't solve. def PathFind(self, trail): location = trail[-1] if location == self.destination: self.solved.append(trail) print Solution found: + str(trail) else: possibilities = [] for i in nodes[location].connectedNodes: if not i in trail: possibilities.append(i) for i in possibilities: trail.append(i) self.PathFind(trail[:]) if not possibilities: print Dead end: + str(trail) finder = PathFind(1, 9) finder.Search() Unfortunately, it doesn't seem to be giving me the result I was after. This is the output: Solution found: [1, 4, 6, 9] Dead end: [1, 4, 6, 3, 2] Solution found: [1, 4, 6, 3, 2, 5, 7, 8, 9] Solutions: [1, 4, 6, 9] [1, 4, 6, 3, 2, 5, 7, 8, 9] The problem is the array trail[], which seems to survive from instance to instance of PathFind(). I thought that by calling self.PathFind (trail[:]), I was creating a new copy of trail[], but obviously something isn't running like I expected. Is there something I'm misunderstanding here, or is there just a stupid bug in my code I haven't caught? -- http://mail.python.org/mailman/listinfo/python-list
Re: Annoying octal notation
David schrieb: If I want an octal I'll use oct()! Explicit is better than implicit... A leading 0 *is* explicit. Implicit would be when some functions would interpret a 0 prefix as octal and others wouldn't. Regards, Johannes -- Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verlästerung von Gott, Bibel und mir und bewusster Blasphemie. -- Prophet und Visionär Hans Joss aka HJP in de.sci.physik 48d8bf1d$0$7510$54022...@news.sunrise.ch -- http://mail.python.org/mailman/listinfo/python-list
Re: thread and win32com.client problem
Ray wrote: I already find the way to fix it. :-) I consider it good style when people describe their solution to a problem, too. Other Python users may run into the same issue someday. :) Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Annoying octal notation
On Aug 20, 3:06 pm, David 71da...@libero.it wrote: Hi all, Is there some magic to make the 2.x CPython interpreter to ignore the annoying octal notation? No. You would have to modify and recompile the interpreter. This is not exactly trivial, see How to Change Python's Grammar http://www.python.org/dev/peps/pep-0306/ However, see Integer Literal Support and Syntax http://www.python.org/dev/peps/pep-3127/ (Basically in 2.6 and onwards you can use 0oNNN notation.) I'd really like 012 to be 12 and not 10. If I want an octal I'll use oct()! But that gives you a string, you're asking about literals. -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
6344a24de14243c76060bedd42f79bc302679dad -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with arrays in a recursive class function
Never mind -- ditched the attempt and implemented Dijkstra. -- http://mail.python.org/mailman/listinfo/python-list
incrementing string/hex value from file and write back
Hello guys I would like to read a hex number from an ASCII file, increment it and write it back. How can this be performed? I have tried several approaches: my file serial.txt contains: 0C -- f = open('serial.txt', 'r') val = f.read() val = val.encode('hex') print val -- -- 3043 -- f = open('serial.txt', 'r') val = f.read() print val val = val+1 -- -- TypeError: cannot concatenate 'str' and 'int' objects -- f = open('serial.txt', 'rb') val = f.read() val = val + 1 -- -- TypeError: cannot concatenate 'str' and 'int' objects hm -- http://mail.python.org/mailman/listinfo/python-list
Re: incrementing string/hex value from file and write back
val = val.encode('hex') That's the crucial line -- it's returning a new integer, which you are re-binding to val. If you then did: val = val + 1 you'd be fine, and could then write val back to your file :-) On Thu, 20 Aug 2009 14:08:34 -0700, Matthias Güntert matzeguent...@gmx.de wrote: Hello guys I would like to read a hex number from an ASCII file, increment it and write it back. How can this be performed? I have tried several approaches: my file serial.txt contains: 0C -- f = open('serial.txt', 'r') val = f.read() val = val.encode('hex') print val -- -- 3043 -- f = open('serial.txt', 'r') val = f.read() print val val = val+1 -- -- TypeError: cannot concatenate 'str' and 'int' objects -- f = open('serial.txt', 'rb') val = f.read() val = val + 1 -- -- TypeError: cannot concatenate 'str' and 'int' objects hm -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: incrementing string/hex value from file and write back
Matthias Güntert wrote: Hello guys I would like to read a hex number from an ASCII file, increment it and write it back. How can this be performed? I have tried several approaches: my file serial.txt contains: 0C -- f = open('serial.txt', 'r') val = f.read() val = val.encode('hex') val = int(val, 16) + 1 f.write('%02X' % val) print val -- -- 3043 -- f = open('serial.txt', 'r') val = f.read() print val val = val+1 -- -- TypeError: cannot concatenate 'str' and 'int' objects -- f = open('serial.txt', 'rb') val = f.read() val = val + 1 -- -- TypeError: cannot concatenate 'str' and 'int' objects hm -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: incrementing string/hex value from file and write back
On Aug 20, 5:08 pm, Matthias Güntert matzeguent...@gmx.de wrote: Hello guys I would like to read a hex number from an ASCII file, increment it and write it back. How can this be performed? I have tried several approaches: my file serial.txt contains: 0C -- f = open('serial.txt', 'r') val = f.read() val = val.encode('hex') print val -- -- 3043 -- f = open('serial.txt', 'r') val = f.read() print val val = val+1 -- -- TypeError: cannot concatenate 'str' and 'int' objects -- f = open('serial.txt', 'rb') val = f.read() val = val + 1 -- -- TypeError: cannot concatenate 'str' and 'int' objects hm Check this out: In [1]: val = '0C' In [2]: val.encode('hex') Out[2]: '3043' That's not what you want. Try this: In [3]: int(val, 16) Out[3]: 12 And to convert an int to a hex string. In [4]: '%x' % 13 Out[4]: 'd' The interpreter has a help() function that gives you quick access to information about python objects: help(str.encode) Help on method_descriptor: encode(...) S.encode([encoding[,errors]]) - object Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. help(int) Help on class int in module __builtin__: class int(object) | int(x[, base]) - integer | | Convert a string or number to an integer, if possible. A floating point | argument will be truncated towards zero (this does not include a string | representation of a floating point number!) When converting a string, use | the optional base. It is an error to supply a base when converting a | non-string. If the argument is outside the integer range a long object | will be returned instead. | | Methods defined here: | ... Unfortunately you can't use it on the '%' string formatting operator... help(%) SyntaxError: invalid syntax So here's a link to the docs: http://docs.python.org/library/stdtypes.html#string-formatting-operations HTH, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: incrementing string/hex value from file and write back
On Aug 20, 5:18 pm, Rami Chowdhury rami.chowdh...@gmail.com wrote: val = val.encode('hex') That's the crucial line -- it's returning a new integer, which you are re-binding to val. If you then did: No, it returns another string, which still isn't the decimal representation of the hex string. hex C = decimal 12 In [1]: '0C'.encode('hex') Out[1]: '3043' -- http://mail.python.org/mailman/listinfo/python-list
Re: incrementing string/hex value from file and write back
[fixed top-posting] Rami Chowdhury wrote: On Thu, 20 Aug 2009 14:08:34 -0700, Matthias Güntert matzeguent...@gmx.de wrote: Hello guys I would like to read a hex number from an ASCII file, increment it and write it back. How can this be performed? I have tried several approaches: my file serial.txt contains: 0C -- f = open('serial.txt', 'r') val = f.read() val = val.encode('hex') That's the crucial line -- it's returning a new integer, which you are re-binding to val. If you then did: val = val + 1 you'd be fine, and could then write val back to your file :-) .encode('hex') is returning a string -- attempting to add one to it will raise the same error the OP is getting below. To get a number you can do (after reading val from the file): val = int(val, '16') # convert from base 16 val += 1 # increment val = %X % val # back to heg digits and then write it back out again. Don't forget to close and reopen the file for writing. :) ~Ethan~ print val -- -- 3043 -- f = open('serial.txt', 'r') val = f.read() print val val = val+1 -- -- TypeError: cannot concatenate 'str' and 'int' objects -- f = open('serial.txt', 'rb') val = f.read() val = val + 1 -- -- TypeError: cannot concatenate 'str' and 'int' objects hm -- http://mail.python.org/mailman/listinfo/python-list
Re: incrementing string/hex value from file and write back
Of course - my apologies, I was being an idiot. On Thu, 20 Aug 2009 14:38:08 -0700, Simon Forman sajmik...@gmail.com wrote: On Aug 20, 5:18 pm, Rami Chowdhury rami.chowdh...@gmail.com wrote: val = val.encode('hex') That's the crucial line -- it's returning a new integer, which you are re-binding to val. If you then did: No, it returns another string, which still isn't the decimal representation of the hex string. hex C = decimal 12 In [1]: '0C'.encode('hex') Out[1]: '3043' -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing untrusted code
Christian, Rami and Steven, thank you all for your help. It wasn't meant to be a challenge, I knew it ought to be easily breakable. I'm no hacker and it just helps to have some examples to better understand the issue. On Aug 20, 7:42 pm, Steven D'Aprano st...@remove- On a related topic, you should read this post here: http://tav.espians.com/a-challenge-to-break-python-security.html Indeed I did read the post and my minimalistic test was inspired by some of the code in it (I didn't know you could replace the builtins!). Tav's effort kinda of ended nowhere though. My understanding of it is that it hasn't been broken and that Tav has submitted a patch to secure some of python's innards. But Steven, you are perfectly right, I didn't test it and I missed the crucial part in which I store the __builtins__ dictionary in the dictionary of the new originalBuiltins module. My bad. Still, you did understand my intentions and did give me a simple example of how it could be broken. Thank you. -However- I would suggest that conceptually the award goes to Christian. ;) In the same way the open builtin function can be replaced or removed, also reload, file, __import__, exec, execfile and any other potentially unsafe builtin can be replaced with safer versions. Or not? Christian's solution though, seems to be much trickier to evade. Can the object class be replaced at runtime with a version that does not provide a way to reach its subclasses? Manu -- http://mail.python.org/mailman/listinfo/python-list
Re: ncurses getch unicode (was: decoding keyboard input when using curses)
Hi again, 2009/8/20 Iñigo Serna inigose...@gmail.com I have the same problem mentioned in http://groups.google.com/group/comp.lang.python/browse_thread/thread/c70c80cd9bc7bac6?pli=1 some months ago. Python 2.6 program which uses ncurses module in a terminal configured to use UTF-8 encoding. When trying to get input from keyboard, a non-ascii character (like ç) is returned as 2 integers 255, needing 2 calls to getch method to get both. These two integers \xc3 \xa7 forms the utf-8 encoded representation of ç character. ncurses get_wch documentation states the function should return an unique integer 255 with the ordinal representation of that unicode char encoded in UTF-8, \xc3a7. Answering myself, I've copied at the bottom of this email a working solution, but the question still remains: why win.getch() doesn't return the correct value? Kind regards, Iñigo Serna ## # test.py import curses import locale locale.setlocale(locale.LC_ALL, '') print locale.getpreferredencoding() def get_char(win): def get_check_next_byte(): c = win.getch() if 128 = c = 191: return c else: raise UnicodeError bytes = [] c = win.getch() if c = 127: # 1 bytes bytes.append(c) elif 194 = c = 223: # 2 bytes bytes.append(c) bytes.append(get_check_next_byte()) elif 224 = c = 239: # 3 bytes bytes.append(c) bytes.append(get_check_next_byte()) bytes.append(get_check_next_byte()) elif 240 = c = 244: # 4 bytes bytes.append(c) bytes.append(get_check_next_byte()) bytes.append(get_check_next_byte()) bytes.append(get_check_next_byte()) buf = ''.join([chr(b) for b in bytes]) buf = buf.decode('utf-8') return buf def getcodes(win): codes = [] while True: try: ch = get_char(win) except KeyboardInterrupt: return codes codes.append(ch) lst = curses.wrapper(getcodes) print lst for c in lst: print c.encode('utf-8'), print ## -- http://mail.python.org/mailman/listinfo/python-list
Re: Annoying octal notation
On Aug 20, 2:06 pm, David 71da...@libero.it wrote: Hi all, Is there some magic to make the 2.x CPython interpreter to ignore the annoying octal notation? I'd really like 012 to be 12 and not 10. Use 3.1: int('012') 12 (Just kidding! That works in 2.5 also. How are you using it where it's coming out wrong? I can see you pulling '012' out of a text file and want to calculate with it, but how would you use a string without using int()? Passing it to functions that allow string representations of numbers?) If I want an octal I'll use oct()! Explicit is better than implicit... TIA David -- http://mail.python.org/mailman/listinfo/python-list
Re: incrementing string/hex value from file and write back
Matthias Güntert wrote: Hello guys I would like to read a hex number from an ASCII file, increment it and write it back. How can this be performed? I have tried several approaches: my file serial.txt contains: 0C -- f = open('serial.txt', 'r') val = f.read() val = val.encode('hex') print val -- -- 3043 -- f = open('serial.txt', 'r') val = f.read() print val val = val+1 -- -- TypeError: cannot concatenate 'str' and 'int' objects -- f = open('serial.txt', 'rb') val = f.read() val = val + 1 -- -- TypeError: cannot concatenate 'str' and 'int' objects hm You don't say much to constrain the file. Is it always two characters (nibbles) long? Or might it have a newline at the end? If it could be multiple lines, is each line limited to 2 columns? or to 8 columns? or no limit? To interpret val as an integer, trynew = int(val, 16) Then to convert back to hex digits, try line = %x % (val+1) For fancier conversions, look at binascii.unhexlify() and hexlify(). Look also at chr() and ord(). and str.format() DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: thread and win32com.client problem
Christian Heimes wrote: Ray wrote: I already find the way to fix it. :-) I consider it good style when people describe their solution to a problem, too. Other Python users may run into the same issue someday. :) Christian He probably used: pythoncom.CoInitialize() -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' -- http://mail.python.org/mailman/listinfo/python-list
Re: platform-specific overrides of functions and class methods (expanding on imputils demo code)
In article 77715735-2668-43e7-95da-c91d175b3...@z31g2000yqd.googlegroups.com, lkcl luke.leigh...@googlemail.com wrote: if somebody would like to add this to the python bugtracker, as a contribution, that would be great. alternatively, you might like to have a word with the python developers to get them to remove the censorship on my contributions. Excuse me? What censorship? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger. --Roy Smith -- http://mail.python.org/mailman/listinfo/python-list
Re: install package in a particular python version
whoops, sent it to you instead of the list On Thu, Aug 20, 2009 at 9:05 PM, Benjamin Kaplanbenjamin.kap...@case.edu wrote: On Thu, Aug 20, 2009 at 8:57 PM, Steve1234sflen...@comcast.net wrote: I installed the boto module in my Ubuntu system using python setup.py install and it installs in my python2.6 version and works great. Now I want to install boto into my python2.5 version because my hosting services supports 2.5 but not 2.6. and I want to test my code locally, sting.format() is not in 2.5. How do I install a package in a particular version of python? I tried several different install switches without any luck. -- http://mail.python.org/mailman/listinfo/python-list It's not an install switch- it's the version of python you use to install it. If you want to install it to Python 2.5, run python2.5 setup.py install -- http://mail.python.org/mailman/listinfo/python-list
Re: install package in a particular python version
On Thu, 20 Aug 2009 17:57:53 -0700 (PDT), Steve1234 sflen...@comcast.net wrote: I installed the boto module in my Ubuntu system using python setup.py install and it installs in my python2.6 version and works great. Now I want to install boto into my python2.5 version because my hosting services supports 2.5 but not 2.6. and I want to test my code locally, sting.format() is not in 2.5. How do I install a package in a particular version of python? I tried several different install switches without any luck. If you wish to do it in a gui rather than at the commandline then you could try the python package manager at : http://sourceforge.net/projects/pythonpkgmgr/ You will need to download it from source. In the Options Dialog, there is a dropdown list that allow you to easily change from one version of python to another. Regards David -- http://mail.python.org/mailman/listinfo/python-list
Re: #elements of seq A in seq B
a = set(a) n = sum(item in a for item in b) Why set? Does it matter if I say that items in A are already unique? Sets are hash-based, so it's (most probably) far more efficient for sets than for sequences (especially if we say about big/long ones). Regards, *j -- Jan Kaliszewski (zuo) z...@chopin.edu.pl -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create functors?
On Aug 20, 2009, at 5:25 AM, Steven D'Aprano wrote: On Thu, 20 Aug 2009 01:36:14 -0700, Paul Rubin wrote: Steven D'Aprano ste...@remove.this.cybersource.com.au writes: As near as I can tell, a functor is just an object which is callable like a function without actually being implemented as a function, e.g.: No it's not anything like that either, at least as I'm used to the term in programming or in mathematics. Maybe it's used other ways though. According to Wikipedia, functor can be used as a synonym for function object: http://en.wikipedia.org/wiki/Function_object which is what I was thinking of. So it seems there are at least two meanings for the word, neither of which seems to apply to this thread :) As I'm used to it, it's a feature of certain static type systems. The notion isn't that useful in Python I find the Haskell page entirely opaque and unintelligible. Well, perhaps not *entirely* opaque, but pretty close: it assumes a mathematical sophistication that I don't think I even had when I was getting my maths degree, let alone can remember two decades later. (Pity the poor VB coders wondering what Haskell is good for...) The Wikipedia page is a little better, but it's section on Examples is laughable -- the examples are as unintelligible to this reader as the description before them. To this reader -- an Rb coder -- the examples were pretty clear. But let me try an example to see if I've got it right: class Int2StrFunctor: def map1(self, n): if type(n) is not int: raise TypeError('argument must be an int') return -*n def map2(self, f): if type(f) is not type(lambda: None): raise TypeError('argument must be a function') # assume f takes an int, and returns another int def inner(n): return self.map1(f(n)) return inner The functor can take an int and return a string: F = Int2StrFunctor() # F is a functor F.map1(3) '---' It can also take a function (of int - int) and return a new function (int - str): def myfunc(n): ... return n+2 ... f = F.map2(myfunc) f(3) '-' f(4) '--' There's nothing special about the methods map1() and map2(), I could call them anything I like, or even do this: def __call__(self, arg): ... if type(arg) is int: ... return self.map1(arg) ... else: ... return self.map2(arg) ... Int2StrFunctor.__call__ = __call__ F(2) '--' F(myfunc)(0) '--' There are some technical restrictions on functors, relating to the sorts of functions and types (strictly categories) they can accept, presumably to make them mathematically well-behaved. Have I got it correct? I don't think so. Paul Rubin's square example was, I thought, particularly instructive. Charles Yeomans-- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE is not as interactive as Maple
Thanks very much for your information. Reinteract looks like exactly what I want. It give me the similary feeling of using Maple. I like this kind of programming style. People who did not have this experience really should take a try. On 8月20日, 下午9时11分, André andre.robe...@gmail.com wrote: On Aug 20, 12:22 am, laser laser.y...@gmail.com wrote: In the future, will Python provide programe enviroment like Maple does? A quick, flip answer: perhaps if you design one? Tools for Python are designed by people scratching an itch. That being said, have a look at reinteract:http://www.reinteract.org/trac/wiki/Tutorial/Introduction In Maple, you can remove anything unneeded in the editor. And the code execution order are not necessary in one direction. You can run any command line on the screen by push Enter key. These functions gave a lot of flaxibility for users to start with programming something. André -- http://mail.python.org/mailman/listinfo/python-list
Re: install package in a particular python version
Benjamin suggested: sudo python2.5 setup.py install and it works. This makes sense, thanks. I downloaded pythonpkgmgr from source and installed it. I got the error that reguired wx package was missing. I couldn't find this package for Linux or source. -- http://mail.python.org/mailman/listinfo/python-list
2.6 windows install
Hi, I installed python2.6 to a netapp device. I can use it from my local windows machine (XP). But others cannot use it from their pcs. They get this response The system cannot execute the specified program.. If they double click on python.exe, they get a window with: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. When I installed it I didn't see any mention of an 'administrators' install, it just installed. The permissions on the directories where it installed are set wide-open for everyone. Any ideas on what I'm missing here? thanks, --Tim Arnold -- http://mail.python.org/mailman/listinfo/python-list
Waiting for a subprocess to exit
Howdy all, I'm looking to replace some usages of ‘os.system’ with the more secure ‘subprocess.Popen’ methods. The module documentation has a section on replacing ‘os.system’ http://docs.python.org/library/subprocess#replacing-os-system, which says to use:: process = subprocess.Popen(mycmd + myarg, shell=True) status = os.waitpid(process.pid, 0) But a ‘Popen’ instance has its own ‘wait’ method, which waits for exit URL:http://docs.python.org/library/subprocess#subprocess.Popen.wait. Why would I use ‘os.waitpid’ instead of:: process = subprocess.Popen(mycmd + myarg, shell=True) process.wait() status = process.returncode -- \ “The best is the enemy of the good.” —Voltaire, _Dictionnaire | `\Philosophique_ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: 2.6 windows install
Tim Arnold tim.arn...@sas.com wrote: Any ideas on what I'm missing here? Most likely the required configuration of the local environments. Did you install Python to the network device from your XP box? That would explain why you can run it: the required registry settings environment variables are added by the installer, none of which is occurring on any computer other than the one from which you installed. To be honest, I've never seen a single-point-of-access network installation of Python for a Windows environment. If it was possible, I'd expect ActiveState's ActivePython to support it but there's no mention of it in the list of acceptable installer switches[1]. [1]: http://docs.activestate.com/activepython/2.6/installnotes.html#msi -- http://mail.python.org/mailman/listinfo/python-list
Re: install package in a particular python version
Steve1234 sflen...@comcast.net writes: I installed the boto module in my Ubuntu system using python setup.py install and it installs in my python2.6 version and works great. That's because your ‘python’ command is doing the same thing as if you'd typed:: $ python2.6 setup.py install The Python 2.6 interpreter knows where its ‘site-packages’ path is, and so ‘setup.py’ in turn knows where to put files. Now I want to install boto into my python2.5 version Invoke the specific Python interpreter you want:: $ python2.5 setup.py install -- \“Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats.” | _o__)—Howard Aiken | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
[issue6444] multiline exception logging via syslog handler
Simon Litchfield si...@s29.com.au added the comment: From the manual for logging.handlers.SysLogHandler -- emit(record) The record is formatted, and then sent to the syslog server. If exception information is present, it is not sent to the server. Ideal, for me, would be to have each traceback line logged as an individual DEBUG message. Maybe that should be an option. For now I'm using a custom handler to achieve this. -- nosy: +s29 status: pending - open ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6444 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6738] Wrong doc strings in itertools
New submission from Hagen Fürstenau hfuerste...@gmx.net: The doc strings of itertools.combinations and itertools.combinations_with_replacement are wrong: The parameter r is not optional here (like it is for itertools.permutations). Attached trivial patch. -- components: Library (Lib) files: docstring.patch keywords: patch messages: 91761 nosy: hagen severity: normal status: open title: Wrong doc strings in itertools type: behavior versions: Python 2.6, Python 2.7, Python 3.1, Python 3.2 Added file: http://bugs.python.org/file14746/docstring.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6738 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6739] IDLE window won't start or show up after assgining new key in options v2.5.2 and 3.1.1
New submission from CaribbeanCruise caribbeancruise...@gmail.com: I tried to assign a new key(lctrl+lshift instead of lctrl+F5) for run- mode in option in v.2.5.2. I tried the new key and it didn't work. And then I got lots of messages. So I killed the IDLE and the rest of python. And run IDLE again, background process indicates some activity for 5secs. And then it was gone. No IDLE window showed up. So I uninstalled the 2.5.2. and installed the v.3.1.1. The installation process went ok, but when I starts IDLE. Nothing happens. I tried and run idle.py in cmd, while I'm a vista user and got this: Traceback (most recent call last): File C:\Python31\Lib\idlelib\idle.py, line 11, in module idlelib.PyShell.main() File C:\Python31\Lib\idlelib\PyShell.py, line 1388, in main shell = flist.open_shell() File C:\Python31\Lib\idlelib\PyShell.py, line 277, in open_shell self.pyshell = PyShell(self) File C:\Python31\Lib\idlelib\PyShell.py, line 813, in __init__ OutputWindow.__init__(self, flist, None, None) File C:\Python31\Lib\idlelib\OutputWindow.py, line 16, in __init__ EditorWindow.__init__(self, *args) File C:\Python31\Lib\idlelib\EditorWindow.py, line 135, in __init__ self.apply_bindings() File C:\Python31\Lib\idlelib\EditorWindow.py, line 961, in apply_bindings text.event_add(event, *keylist) File C:\Python31\Lib\idlelib\MultiCall.py, line 359, in event_add widget.event_add(self, virtual, seq) File C:\Python31\Lib\tkinter\__init__.py, line 1353, in event_add self.tk.call(args) _tkinter.TclError: bad event type or keysym Shift What do I do to get this up and running? -- components: IDLE messages: 91762 nosy: CaribbeanCruise severity: normal status: open title: IDLE window won't start or show up after assgining new key in options v2.5.2 and 3.1.1 type: performance versions: Python 3.1 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6739 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6641] strptime doesn't support %z format ?
Andrew Brown abr...@freemail.gr added the comment: I think this bug is just a doc bug. If you check http://docs.python.org/library/datetime.html?highlight=strptime#strftime-behavior and http://docs.python.org/library/time.html?highlight=strptime#time.strptime You can see that the first link lists %z as a valid modifier, while in the second link (in footnote 1) it is mentioned as deprecated. -- nosy: +abrown ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6641 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6444] multiline exception logging via syslog handler
Max Arnold lwa...@gmail.com added the comment: Sorry for long delay, I was on vacation. I have installed sysklogd, metalog and syslog-ng on a virtual machine and executed test script. First two daemons log exception as single concatenated line. Syslog-ng splits it as described in original report. Do you suggest to file bug report to syslog-ng maintainer? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6444 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6734] Imap lib implicit conversion from bytes to string
Eric surprisin...@gmail.com added the comment: I checked the latest documentation for 3.1.1 (http://docs.python.org/3.1/library/imaplib.html), but I can't find any reference to needing to encode information myself for the login procedure. Is there some other documentation you are referring to? In any case, the error wasn't returned by the server, but by imaplib. If the arg needs to be encoded for the whole process, then the arg should be checked for the appropriate type (I think the doc even says plain text password), or an optional encoding argument for the relevant functions (or a catchall used when connecting to the server?) with a default encoding attempted. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6734 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6740] Compounded expressions with lambda functions are evaluated incorrectly
New submission from Michal Vyskocil mvysko...@suse.cz: The compounded expressions with lambda functions are evaluated incorrectly. The simple expressions, or a named functions are evaluated good. The problem is only in the evaluation of compounded expressions. It seems that after evaluate of the first lambda function the evaluation of whole expression is stopped and not continue (see cond_error, which may raises the exception during evaluation). Python 3.1 (r31:73572, Aug 15 2009, 22:04:19) [GCC 4.4.1 [gcc-4_4-branch revision 149935]] on linux2 Type help, copyright, credits or license for more information. cond = (lambda x : x == 'foo') or (lambda x : x == 'bar') cond('foo') True cond('bar') False c1 = lambda x : x == 'foo' c1('foo') True c2 = lambda x : x == 'bar' c2('bar') True def ham(x): return x == 'foo' ... def spam(x): return x == 'bar' ... cond2 = lambda x : ham(x) or spam(x) cond2('foo') True cond2('bar') True cond2('ham') False cond_error = (lambda x : x == 'foo') or (lambda x : y == 'bar') cond_error('d') False BTW: the same problem exists in Python 2.6.2 Python 2.6.2 (r262:71600, Aug 15 2009, 18:37:04) [GCC 4.4.1 [gcc-4_4-branch revision 149935]] on linux2 Type help, copyright, credits or license for more information. -- messages: 91766 nosy: mvyskocil severity: normal status: open title: Compounded expressions with lambda functions are evaluated incorrectly versions: Python 3.1 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6740 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6734] Imap lib implicit conversion from bytes to string
STINNER Victor victor.stin...@haypocalc.com added the comment: I can't find any reference to needing to encode information myself for the login procedure. Is there some other documentation you are referring to? Exactly, the Python imaplib documentation should be fixed (the doc, not the code). -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6734 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6734] Imap lib implicit conversion from bytes to string
Marcin Bachry hegel...@gmail.com added the comment: It seems most IMAP4 methods accept str as arguments right now (I checked: list, lsub, myrights, select, status, search, fetch) and login() is a sole exception. I know the protocol is mostly ascii only, but still having possibility of using str in the API feels convenient and reasonable to me. Can't we convert str parameters to login() to ascii too? It already done in other methods (the _command() method iterates over args and converts them). -- nosy: +marcin.bachry ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6734 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1294959] Problems with /usr/lib64 builds.
Matthias Klose d...@debian.org added the comment: both patches assume that everybody uses lib64 for 64bit libs, which is not true for Debian/Ubuntu. Even the FHS doesn't mandate the use of lib64. -- nosy: +doko ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1294959 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6722] collections.namedtuple: confusing example
Alexey Shamrin sham...@gmail.com added the comment: Raymond, sorry if I wasn't clear. I'm fine with the API (haven't used it yet though, because I was stuck after skimming through its documentation). I suggest to make *first* example simple (without verbose=True) and to move an example with verbose=True little furthere. I think it should be something like this: Example: .. doctest:: :options: +NORMALIZE_WHITESPACE Point = namedtuple('Point', 'x y') p = Point(11, y=22) # instantiate with positional or keyword arguments p[0] + p[1] # indexable like the plain tuple (11, 22) 33 x, y = p# unpack like a regular tuple x, y (11, 22) p.x + p.y # fields also accessible by name 33 p # readable __repr__ with a name=value style Point(x=11, y=22) namedtuple('Point', 'x y', verbose=True) # print class definition class Point(tuple): 'Point(x, y)' BLANKLINE __slots__ = () BLANKLINE _fields = ('x', 'y') BLANKLINE def __new__(_cls, x, y): return _tuple.__new__(_cls, (x, y)) BLANKLINE @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Point object from a sequence or iterable' result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result BLANKLINE def __repr__(self): return 'Point(x=%r, y=%r)' % self BLANKLINE def _asdict(t): 'Return a new dict which maps field names to their values' return {'x': t[0], 'y': t[1]} BLANKLINE def _replace(_self, **kwds): 'Return a new Point object replacing specified fields with new values' result = _self._make(map(kwds.pop, ('x', 'y'), _self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result BLANKLINE def __getnewargs__(self): return tuple(self) BLANKLINE x = _property(_itemgetter(0)) y = _property(_itemgetter(1)) -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6722 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6722] collections.namedtuple: confusing example
Alexey Shamrin sham...@gmail.com added the comment: Roundup broke formatting... I've attached a text file with the proposed example. -- Added file: http://bugs.python.org/file14747/namedtuple_doc_example.txt ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6722 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6741] Garbage collector release method
New submission from Lev lgards...@gmail.com: WinCRT debug detects several memory leaks after calling py_Initialize (); py_Finalize(); functions. Most of them are garbage collector visible python's objects. I suggest to create release method in garbage collector which will distruct all objects in GC list without reference count checking, and call this method at the end of py_Finalize () function. I think, that it will help to avoid memory leaks after calling py_Finalize() function. -- components: Interpreter Core messages: 91772 nosy: gardster severity: normal status: open title: Garbage collector release method type: feature request versions: Python 2.6 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6741 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6742] Embedding python into shared library crash on AIX
New submission from damahay123 hong@algorithmics.com: Hi there, I'm trying to embedding my python code into a .so on AIX and load it with my main application. Since there is no libpython2.6.so available on AIX, I have to link my .so with libpython2.6.a. I have to make some twist to make it compile. And so far so good until I run my main. My embedding python .so give me error like the following Fatal Python error: Interpreter not initialized (version mismatch?) I check the initialization status by calling Py_IsInitialized and it said yes. So I'm wondering if this embedding python into .so ever work on AIX. I have no problem to do the same thing on linux, solaris since python has libpython2.6.so on both system. But our system needs the supoort on AIX. My embedding python is very simple like the following #include Python.h #include iostream extern C void allocate() { std::cout am i ok = Py_IsInitialized() std::endl; Py_InitializeEx(0); std::cout am i ok 1 = Py_IsInitialized() std::endl; PyRun_SimpleString(from time import time, datetime, ctime\n print 'Today is',ctime(time())\n); Py_Finalize(); } my main application is also very simple #include iostream #include iomanip #include dlfcn.h //#include link.h #include Python.h typedef void (*ALLOCATE)(); int main (int argc, char ** argv) { // parse params to load shared object if (argc 2) { std::cerr Usage: argv[0] sharedObject(s) std::endl; return 0; } //Py_Initialize(); for (int i = 1; i argc; ++i) { void * handle = ::dlopen(argv[i], RTLD_LAZY); if (!handle) { std::cerr dlerror() argv[i] std::endl; return 0; } // Use that handle to locate the symbol. The symbol must be // demangled so it has to be compiled with extern C. ALLOCATE dlmAllocate = (ALLOCATE) ::dlsym(handle, allocate); if (!dlmAllocate) { std::cerr dlerror() std::endl; return 0; } dlmAllocate(); } return 0; } here is my makefile CXX := g++ default: DLOpenTest mypython.so DLOpenTest: DLOpen.C $(CXX) -o DLOpenTest DLOpen.C -ldl -Wl,-bE:/mnts/cdstools/Python-2.6.2/aix-ppc-5.3/lib/python2.6/config/python.exp -lld -I/mnts/cdstools/Python-2.6.2/aix-ppc-5.3/include/python2.6 -L/mnts/cdstools/Python-2.6.2/aix-ppc-5.3/lib/ -lpython2.6 -lpthread mypython.so: mypython.C $(CXX) -shared -nostartfiles -I/mnts/cdstools/Python-2.6.2/aix-ppc-5.3/include/python2.6 -L/mnts/cdstools/Python-2.6.2/aix-ppc-5.3/lib/ -lpython2.6 -lpthread -o mypython.so mypython.C clean: rm *.o DLOpenTest mypython.so Can someone help me out? Or has anyone even tried same thing on AIX? NOTE, the issue is not like issue 4434 or 1332869. Please don't reply this issue with those two number. I've seen them already. It's not helpful Thanks a log -- components: Interpreter Core messages: 91773 nosy: damahay123 severity: normal status: open title: Embedding python into shared library crash on AIX type: crash versions: Python 2.6 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6742 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6743] pprint.pprint should support no objects to print blank lines allow args
New submission from Mary Stern maryst...@yahoo.com: Using print in python 3 I would like to simple replace print with pprint.pprint. However pprint cannot be called with no arguments, so this cannot currently be done (the error is TypeError: pprint() takes at least 1 positional argument (0 given)). A simple improvement is to allow no object to be passed in and pprint would then print a newline rather than fail. Another problem is that if you try this: print('hello', True) and replace print with print, the second arg gets interpreted as the stream parameter. Both of the above can be fixed (I think) by changing pprint.py as follows: instead of the current code: def pprint(object, stream=None, indent=1, width=80, depth=None): change to this: def pprint(object='\n', *args, stream=None, indent=1, width=80, depth=None) -- messages: 91774 nosy: marystern severity: normal status: open title: pprint.pprint should support no objects to print blank lines allow args type: feature request versions: Python 3.1 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6743 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6734] Imap lib implicit conversion from bytes to string
STINNER Victor victor.stin...@haypocalc.com added the comment: It seems most IMAP4 methods accept str as arguments right now (I checked: list, lsub, myrights, select, status, search, fetch) and login() is a sole exception. I know the protocol is mostly ascii only, but still having possibility of using str in the API feels convenient and reasonable to me. Ok, that sounds like a good compromise. Can you write a patch? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6734 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6743] pprint.pprint should support no objects to print blank lines allow args
Mary Stern maryst...@yahoo.com added the comment: Sorry: you also need to print out the args! :) .. like this: def pprint(object='\n', *args, stream=None, indent=1, width=80, depth=None): Pretty-print a Python object to a stream [default is sys.stdout]. printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object) for arg in args: printer.pprint(arg) -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6743 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1424148] urllib.FancyURLopener.redirect_internal looses data on POST!
Senthil orsent...@gmail.com added the comment: I agree with John on this ticket. At the outset, this is Not a bug. And reading through the referenced ticket indicates the design decision for the behavior. In summary: quote This suggests to me that *no* automatic repeat of POST requests should ever be done, and that in the case of a 302 or 303 response, a POST should be replaced by a GET; this may also be done for a 301 response -- even though the standard calls that an error, it admits that it is done by old clients. /quote That was Guido's point at that time. The least that could be done is take a call on 301 response, but this would break the other clients which rely on 'earlier standard behavior though not compliant with RFC'. At the moment, this wont be necessary as it just break clients using urllib. Giorgio's point in rekindling this issue, is not related to urllib module and specifically w.r.t to redirect_request implementation. So, an alternate behavior is desired on urllib2's redirects (if they are observed by existing clients), it could be handled by another request. So, effectively closing this request. -- resolution: - invalid status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1424148 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6711] macurl2path has typos that raise AttributeError
Changes by Senthil orsent...@gmail.com: -- status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6711 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue2637] urllib.quote() escapes characters unnecessarily and contrary to docs
Senthil orsent...@gmail.com added the comment: I see adding this information to the docs, might clarify a bit. By default, this function is intended for quoting the path section of the URL. This is already present in the function docstring. If there is no objection, I shall commit the attached patch and close this issue. -- keywords: +patch Added file: http://bugs.python.org/file14748/issue2637.diff ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue2637 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com