"AttributeError: 'module' object has no attribute 'getdefaultlocale'" on Python start
Hi Fellow Pythonians, I stated getting the following when starting Python (2.5.2 on Windows XP): C:\Documents and Settings\RBARAK>python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # D:\Python25\lib\site.pyc matches D:\Python25\lib\site.py import site # precompiled from D:\Python25\lib\site.pyc # D:\Python25\lib\os.pyc matches D:\Python25\lib\os.py import os # precompiled from D:\Python25\lib\os.pyc import errno # builtin import nt # builtin # D:\Python25\lib\ntpath.pyc matches D:\Python25\lib\ntpath.py import ntpath # precompiled from D:\Python25\lib\ntpath.pyc # D:\Python25\lib\stat.pyc matches D:\Python25\lib\stat.py import stat # precompiled from D:\Python25\lib\stat.pyc # D:\Python25\lib\UserDict.pyc matches D:\Python25\lib\UserDict.py import UserDict # precompiled from D:\Python25\lib\UserDict.pyc # D:\Python25\lib\copy_reg.pyc matches D:\Python25\lib\copy_reg.py import copy_reg # precompiled from D:\Python25\lib\copy_reg.pyc # D:\Python25\lib\types.pyc matches D:\Python25\lib\types.py import types # precompiled from D:\Python25\lib\types.pyc import _types # builtin import locale # directory D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale import locale # precompiled from D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale\__init__.pyc # D:\Python25\lib\codecs.pyc matches D:\Python25\lib\codecs.py import codecs # precompiled from D:\Python25\lib\codecs.pyc import _codecs # builtin import encodings # directory D:\Python25\lib\encodings # D:\Python25\lib\encodings\__init__.pyc matches D:\Python25\lib\encodings\__init__.py import encodings # precompiled from D:\Python25\lib\encodings\__init__.pyc # D:\Python25\lib\encodings\aliases.pyc matches D:\Python25\lib\encodings\aliases.py import encodings.aliases # precompiled from D:\Python25\lib\encodings\aliases.pyc 'import site' failed; traceback: Traceback (most recent call last): File "d:\Python25\lib\site.py", line 415, in main() File "d:\Python25\lib\site.py", line 406, in main aliasmbcs() File "d:\Python25\lib\site.py", line 357, in aliasmbcs enc = locale.getdefaultlocale()[1] AttributeError: 'module' object has no attribute 'getdefaultlocale' # D:\Python25\lib\warnings.pyc matches D:\Python25\lib\warnings.py import warnings # precompiled from D:\Python25\lib\warnings.pyc # D:\Python25\lib\linecache.pyc matches D:\Python25\lib\linecache.py import linecache # precompiled from D:\Python25\lib\linecache.pyc Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Has anyone else gotten this error ? Could anyone suggest a solution ? Thanks, Ron. -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric literal syntax
On Tue, 09 Sep 2008 08:32:29 +1000, Tom Harris wrote: > I agree. So did Forth's early designers. That is why Forth's number > parser considers a word that starts with a number and has embedded > punctuation to be a 32 bit integer, and simply ignores the punctuation. > I haven't used Forth in years, but it seems a neat solution to the > problem of decoding a long string of numbers: let the user put in > whatever they want, the parser ignores it. I usually used a comma (with > no surrounding whitespace of course), but it was your choice. You could > also do this in whatever base you were working in, so you could > punctuate a 32 bit hex number to correspond to the bit fields inside it. > Of course not applicable to Python. That sounds like a great idea, except I'd specify non-period (.) punctuation, so it would go for floating points as well. Is there a language design guru who can say why inputs like 123,456.00 couldn't be handles as above? the only problem I can see is an abiguity in argument lists (e.g. mult(2,4) ) which could be handled by the inclusion of whitespace. -- http://mail.python.org/mailman/listinfo/python-list
Re: "AttributeError: 'module' object has no attribute 'getdefaultlocale'" on Python start
Barak, Ron wrote: > Hi Fellow Pythonians, > > I stated getting the following when starting Python (2.5.2 on Windows XP): > > C:\Documents and Settings\RBARAK>python -v > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # D:\Python25\lib\site.pyc matches D:\Python25\lib\site.py > import site # precompiled from D:\Python25\lib\site.pyc > # D:\Python25\lib\os.pyc matches D:\Python25\lib\os.py > import os # precompiled from D:\Python25\lib\os.pyc > import errno # builtin > import nt # builtin > # D:\Python25\lib\ntpath.pyc matches D:\Python25\lib\ntpath.py > import ntpath # precompiled from D:\Python25\lib\ntpath.pyc > # D:\Python25\lib\stat.pyc matches D:\Python25\lib\stat.py > import stat # precompiled from D:\Python25\lib\stat.pyc > # D:\Python25\lib\UserDict.pyc matches D:\Python25\lib\UserDict.py > import UserDict # precompiled from D:\Python25\lib\UserDict.pyc > # D:\Python25\lib\copy_reg.pyc matches D:\Python25\lib\copy_reg.py > import copy_reg # precompiled from D:\Python25\lib\copy_reg.pyc > # D:\Python25\lib\types.pyc matches D:\Python25\lib\types.py > import types # precompiled from D:\Python25\lib\types.pyc > import _types # builtin > import locale # directory > D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale > import locale # precompiled from > D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale\__init__.pyc For some reason, when you run "import locale", it's importing wx.locale instead of the "locale" module from the stdlib. However, I have no idea why that would be happening... Did you do something to add wx to your PYTHONPATH? Maybe do "import sys; print sys.path" or "import os; print os.environ['PYTHONPATH']" to verify this. (Hopefully someone more knowledgeable than me will come along soon.) > # D:\Python25\lib\codecs.pyc matches D:\Python25\lib\codecs.py > import codecs # precompiled from D:\Python25\lib\codecs.pyc > import _codecs # builtin > import encodings # directory D:\Python25\lib\encodings > # D:\Python25\lib\encodings\__init__.pyc matches > D:\Python25\lib\encodings\__init__.py > import encodings # precompiled from D:\Python25\lib\encodings\__init__.pyc > # D:\Python25\lib\encodings\aliases.pyc matches > D:\Python25\lib\encodings\aliases.py > import encodings.aliases # precompiled from > D:\Python25\lib\encodings\aliases.pyc > 'import site' failed; traceback: > Traceback (most recent call last): > File "d:\Python25\lib\site.py", line 415, in > main() > File "d:\Python25\lib\site.py", line 406, in main > aliasmbcs() > File "d:\Python25\lib\site.py", line 357, in aliasmbcs > enc = locale.getdefaultlocale()[1] > AttributeError: 'module' object has no attribute 'getdefaultlocale' > # D:\Python25\lib\warnings.pyc matches D:\Python25\lib\warnings.py > import warnings # precompiled from D:\Python25\lib\warnings.pyc > # D:\Python25\lib\linecache.pyc matches D:\Python25\lib\linecache.py > import linecache # precompiled from D:\Python25\lib\linecache.pyc > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > > Has anyone else gotten this error ? > Could anyone suggest a solution ? > > Thanks, > Ron. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Correcting for Drift between Two Dates
On Mon, 08 Sep 2008 21:53:18 -0700, W. eWatson wrote: > I have two dates, ts1, ts2 as below in the sample program. I know the > clock drift in seconds per day. I would like to calculate the actual > date of ts2. See my question at the end of the program. When faced with a complicated task, break it down into simpler subtasks. Functions are your friends. Here you go: from __future__ import division from datetime import datetime as DT from datetime import timedelta SITE_DRIFT = 4.23 # drift in seconds per day # negative drift means the clock falls slow SEC_PER_DAY = 60*60*24 # number of seconds per day def calc_drift(when, base, drift=SITE_DRIFT): """Return the amount of drift at date when since date base.""" x = when - base days = x.days + x.seconds/SEC_PER_DAY return drift*days def fix_date(when, base, drift=SITE_DRIFT): """Return date when adjusted to the correct time.""" d = calc_drift(when, base, drift) delta = timedelta(seconds=-d) return when + delta And here it is in action: >>> fix_date(DT(2008,9,9), DT(2008,9,8)) datetime.datetime(2008, 9, 8, 23, 59, 55, 77) I leave it to you to convert date/time strings into datetime objects. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: universal unicode font for reportlab
-On [20080909 05:23], Terry Reedy ([EMAIL PROTECTED]) wrote: >Ariel Unicode MS is the one that seems pretty complete. Not really. It misses a lot of characters. Might I recommend using BabelMap (http://www.babelstone.co.uk/Software/BabelMap.html) so you can investigate your fonts? The only font I am aware of that supports a lot of Unicode fonts is James Kass' Code 200x fonts (http://www.code2000.net/). In almost all cases you will need to gather a collection of fonts in order to typeset your documents as it is hard to find font designers who know enough about all languages to properly design the fonts. Not to mention such fonts would quickly grow unwieldy. -- Jeroen Ruigrok van der Werven / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B A kiss is a lovely trick designed by nature to stop speech when words become superfluous... -- http://mail.python.org/mailman/listinfo/python-list
Re: finding the parent class (not superclass) of the currently executing method derived from a Borg class
seanacais a écrit : I want to create a class derived from a Borg class that can instantiated as part of a script or be contained in other classes. When methods from the Borg class are called, I would like to know the name of the class that contains the Borg class. I've played a bit with inspect and _getframe from the sys module but get inconsistent results. The main problem is if the Borg class is instantiated outside a containing class, then I need to go up a different number of stack frames. But this information isn't available till after I've run out of stack frames. The simplest solution is usually the better : explicitely pass the caller (whether instance or module or whatever you want) Hopefully the following code better describes what I'm looking to do. import sys class Borg: _shared_state = {} def __init__(self): self.__dict__=self._shared_state class Assimilated(Borg): valueByCaller = {} You understand that, being a class attribute, valueByCaller won't be part of the Borg's _shared_state ? def __init__(self, setupvalue): print "In Assimilated.__init__()" print "setupvalue is: " + str(setupvalue) # would like key to be name of class (or module) that # contins Assimilated callerID = sys._getframe(1).f_code.co_name self.valueByCaller[callerID] = setupvalue print self.valueByCaller Anyway, since you override __init__ and don't call Borg.__init__, your Assimilated class doesn't behave as a Borg. (snip) When I run this, I get the following output: In Assimilated.__init__() setupvalue is: 2 {'A': 2} In Assimilated.__init__() setupvalue is: 3 {'A': 2, 'B': 3} In Assimilated.__init__() setupvalue is: 4 {'A': 2, 'C': 4, 'B': 3} > (snip) What I found most peculiar when I started this was that the valueByCaller dictionary was completely populated before the __init__ method of a was executed. Indeed. In classes A, B and C, assim_object is class attribute - so it is instanciated when the class statement is executed. I'm pretty sure that this has to do with the difference between when the object gets instanced and when it gets initialized, Not at all. It has to do with the fact that all statements within a class block are executed before the class statement itself is executed. And since your class statements are at the top-level, they are executed when the module is initialised (that is, passed to the python runtime or first imported). but I need to do some more research and reading to be able to explain it to myself. Indeed. May I suggest that you *learn* Python's object model and Python's execution model instead of assuming anything ? This will save you a whole lot of time and frustration !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: class(object) and (type)??
On Mon, Sep 8, 2008 at 2:35 PM, AON LAZIO <[EMAIL PROTECTED]> wrote: Hi again pythoners, I notice in the class of a code having (object) and (type) attached to the name of the class. I know that in other cases, that means the class inherits methods and properties from other but In this case, what does it mean? The very same thing. Why should it have a different meaning ? For the record : - 'object' is the base class for 'new-style' classes - that is, the 'new' (hem) object model that came with Python 2.2 (released december 2001 - so it's not that 'new'). The old one - known as 'classic classes' has been kept so far for backward compat only, and will finally disappear with Python 3.x. - 'type' is the base metaclass. Python's classes being objects, they have to be instances of a class - known as the metaclass. To avoid metametaclasses, metametametaclasses etc ad infinitum, 'type' is an instance of itself. And FWIW, a subclass of 'object', which is itself an instance of 'type' (usually, brains start melting here...) You'll find more informations (and hopefully clearer explanations) here: http://www.python.org/doc/newstyle/ and of course in the FineManual(tm): http://docs.python.org/ref/datamodel.html HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Test if list contains another list
Matimus a écrit : On Sep 8, 12:32 am, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: (snip) >>> set(a).issubset(set(b)) True >>> Just to clarify, doing it using sets is not going to preserve order OR number of elements that are the same. That is: a = [1,1,2,3,4] b = [4,5,3,7,2,6,1] set(a).issubset(set(b)) True This will return True if b contains at least on of each element found in a. If the OP wanted to check that list `a` appeared in order somewhere in list `b` then sets won't work. Indeed, and I should have mentionned this myself. Thanks for this reminder. -- http://mail.python.org/mailman/listinfo/python-list
biopython
Hi all, I am using Biopython to fetch pumed Id's ,The module i use is (from Bio import Entrez) But i am getting this error >>> from Bio import Entrez Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name Entrez what should i do know can anybody suggest me an alternative for this -- Beema Shafreen -- http://mail.python.org/mailman/listinfo/python-list
Python Installation and Running on Windows Vista
Please help with issue... I heard of compatimbiltity issues and would like clarification. -- http://mail.python.org/mailman/listinfo/python-list
How to record audio from Python on Mac?
(I asked this on pythonmac-sig a couple days ago but got no response, so I'm casting a broader net.) Can I easily control audio record/playback from Python on my Mac? I know zip about audio recording or about Apple APIs via Python. Pointers to simple examples would be much appreciated. Thanks, Skip -- http://mail.python.org/mailman/listinfo/python-list
видео Бритни и Кевина.
Смотри, как она сосет член, она лучшая! http://ragdai.info/golaya-pravda.htm Это видео супер! -- http://mail.python.org/mailman/listinfo/python-list
Re: biopython
>>> from Bio import Entrez Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name Entrez Can you import Bio, e.g.: import Bio ? If not, check to see where it's installed and make sure the directory containing Bio (or Bio.py) is in sys.path, either by setting the PYTHONPATH environment variable before running Python or adding a Bio.pth file to a directory which is in sys.path so it can be found. http://docs.python.org/lib/module-site.html http://docs.python.org/tut/node8.html Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Installation and Running on Windows Vista
I don't use it often in Vista, but I haven't had any issues. Matter-of- fact, some things seem nicer in Vista... for instance it resets IDLE whenever I rerun a module. Mchizi_Crazy wrote: > Please help with issue... I heard of compatimbiltity issues and would > like clarification. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Installation and Running on Windows Vista
On Sep 9, 3:46 pm, Mchizi_Crazy <[EMAIL PROTECTED]> wrote: > Please help with issue... I heard of compatimbiltity issues and would > like clarification. The win32 installer available from python.org works absolutely fine with Vista. So, go ahead and try it out. It works for all of my friends and myself -- http://mail.python.org/mailman/listinfo/python-list
Re: Correcting for Drift between Two Dates
Steven D'Aprano wrote: On Mon, 08 Sep 2008 21:53:18 -0700, W. eWatson wrote: I have two dates, ts1, ts2 as below in the sample program. I know the clock drift in seconds per day. I would like to calculate the actual date of ts2. See my question at the end of the program. When faced with a complicated task, break it down into simpler subtasks. Functions are your friends. Here you go: from __future__ import division from datetime import datetime as DT from datetime import timedelta SITE_DRIFT = 4.23 # drift in seconds per day # negative drift means the clock falls slow SEC_PER_DAY = 60*60*24 # number of seconds per day def calc_drift(when, base, drift=SITE_DRIFT): """Return the amount of drift at date when since date base.""" x = when - base days = x.days + x.seconds/SEC_PER_DAY return drift*days def fix_date(when, base, drift=SITE_DRIFT): """Return date when adjusted to the correct time.""" d = calc_drift(when, base, drift) delta = timedelta(seconds=-d) return when + delta And here it is in action: fix_date(DT(2008,9,9), DT(2008,9,8)) datetime.datetime(2008, 9, 8, 23, 59, 55, 77) I leave it to you to convert date/time strings into datetime objects. Ah, ha. x.days and x.seconds. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39° 15' 7" N, 121° 2' 32" W, 2700 feet Web Page: -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Installation and Running on Windows Vista
Mchizi_Crazy <[EMAIL PROTECTED]> writes: > Please help with issue... What is the issue? What have you tried, what is happening, and what behaviour were you expecting instead? > I heard of compatimbiltity issues and would like clarification. Same here. Can you please clarify what the issue is, as above. -- \ “There's no excuse to be bored. Sad, yes. Angry, yes. | `\Depressed, yes. Crazy, yes. But there's no excuse for boredom, | _o__) ever.” —Viggo Mortensen | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Python training in Colorado, October 15-17
Python author and trainer Mark Lutz will be teaching another 3-day Python class at a conference center in Longmont, Colorado, on October 15-17, 2008. This is a public training session open to individual enrollments, and covers the same topics as the 3-day onsite sessions that Mark teaches, with hands-on lab work. The class provides an in-depth introduction to Python and its common applications, and parallels the instructor's popular Python books. For more information on this session, please visit its web page: http://home.earthlink.net/~python-training/longmont-public-classes.htm For additional background on the class itself, see our home page: http://home.earthlink.net/~python-training Thanks for your interest. --Python Training Services -- http://mail.python.org/mailman/listinfo/python-list
creating an (inefficent) alternating regular expression from a list of options
Pyparsing has a really nice feature that I want in PLY. I want to specify a list of strings and have them converted to a regular expression. A Perl module which does an aggressively optimizing job of this is Regexp::List - http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm I really dont care if the expression is optimal. So the goal is something like: vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| u|ii|i)' Is there a public module available for this purpose? -- http://mail.python.org/mailman/listinfo/python-list
biopython
On 9/9/08, Beema Shafreen <[EMAIL PROTECTED]> wrote: > I am using Biopython to fetch pumed Id's ,The module i use is (from Bio > import Entrez) > But i am getting this error from Bio import Entrez > Traceback (most recent call last): > File "", line 1, in ? > ImportError: cannot import name Entrez Looks like is bad installed. It works for me: /home/user/MMC-SD/Kingston/py252/bin> ./python2.5 Python 2.5.2 (r252:60911, Jul 7 2008, 16:11:08) [GCC 3.3.5 (Debian 1:3.3.5-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Bio import Entrez >>> dir(Entrez) ['File', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '_open', 'efetch', 'egquery', 'einfo', 'elink', 'epost', 'esearch', 'espell', 'esummary', 'os', 'query', 'read', 'time', 'urllib'] -- Sebastián Bassi. Diplomado en Ciencia y Tecnología. Vendo isla: http://www.genesdigitales.com/isla What's new in Python 3: http://tinyurl.com/5cd89r Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 -- http://mail.python.org/mailman/listinfo/python-list
Re: creating an (inefficent) alternating regular expression from a list of options
metaperl.com wrote: Pyparsing has a really nice feature that I want in PLY. I want to specify a list of strings and have them converted to a regular expression. A Perl module which does an aggressively optimizing job of this is Regexp::List - http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm I really dont care if the expression is optimal. So the goal is something like: vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| u|ii|i)' Is there a public module available for this purpose? Perhaps I'm missing something but your function call oneOf(...) is longer than than actually specifying the result. You can certainly write quite easily: def oneOf(s): return "|".join(s.split()) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: creating an (inefficent) alternating regular expression from a list of options
>> I really dont care if the expression is optimal. So the goal is >> something like: >> vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| >> u|ii|i)' >> Is there a public module available for this purpose? Check Ka-Ping Yee's rxb module: http://lfw.org/python/ Needs translating from the old regex module to the current re module, but it shouldn't take a lot of effort. You can find regex docs in old distributions (probably through 2.1 or 2.2?). Also, check PyPI to see if someone has already updated rxb for use with re. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: creating an (inefficent) alternating regular expression from a list of options
On Tue, 09 Sep 2008 08:19:04 -0500, Larry Bates wrote: >> I really dont care if the expression is optimal. So the goal is >> something like: >> >> vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| >> u|ii|i)' >> >> Is there a public module available for this purpose? >> >> >> > Perhaps I'm missing something but your function call oneOf(...) is > longer than than actually specifying the result. > > You can certainly write quite easily: > > def oneOf(s): > return "|".join(s.split()) I'd throw `re.escape()` into that function just in case `s` contains something with special meaning in regular expressions. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Orientation on MySql using python
Hello everyone, I want to make a program in python that uses Mysql aswell.. I don't know anything about mysql can you tell me some good books/tutorials where I can read something about mysql using python? Thanks. _ Invite your mail contacts to join your friends list with Windows Live Spaces. It's easy! http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mkt=en-us-- http://mail.python.org/mailman/listinfo/python-list
Re: max(), sum(), next()
castironpi wrote: On Sep 8, 8:54 am, Boris Borcic <[EMAIL PROTECTED]> wrote: David C. Ullrich wrote: (ii) If A is a subset of B then we should have max(A) <= max(B). This requires that max(empty set) be something that's smaller than everything else. So we give up on that. Er, what about instances of variations/elaborations on class Smaller(object) : __cmp__ = lambda *_ : -1 ? Cheers, BB You still don't have the property max(X) is in X. Frankly, I would favor order-independence over that property. compare max(X) for 1) X = [set([1]),set([2])] and 2) X = [set([2]),set([1])] Shouldn't then max and min in fact return lub and glb, despite their names ? In the case X is a non-empty finite set/list of totally ordered values, max(X)==lub(X) and min(X)=glb(X) in any case. And it's the equivalent of a special builtin constant for max on the empty set. Of course (except the object might have other uses, who knows). So what ? Cheers, BB -- http://mail.python.org/mailman/listinfo/python-list
noob help request - how to make a list of defined class?
I have defined two classes with one common field (called code) and several different fields. In class A there is only one instance of any given code as all items are individual. In class B, there may be none, one or many instances of each code, as there can be any number of Bs referring to a single A. I need to make a list of Bs, remove dupes, and then create a list of As that have Bs. (I hope this makes sense!) with much research and reading of my book I managed to get this working, but at one stage I had errors that talked about being unable to concatenate type A. So I converted my As to string, and then did a split on commas to make a list. This worked fine for all the As that didn't have a comma in a field (about 85%) but I can't help feeling that this is a kludge, and that if Icould find a way to get a proper list of As instead of a list of lists created by converting to string and splitting, then my app would work properly. So I am hoping some of the nice folk here will help me out. The relevent function looks like this: def gen_B_A_list(): Bcodes = get_codes() all_As = read_A("A.csv") B_A = [] for i in range(len(codes)): Bcode = Bcodes[i] for A in all_As: filename = getattr(A, 'code') if filename == Bcode: BA = str(A) BA = string.split(BA, ',') B_A.append(BA) return B_A The element in question is after if filename == Bcode. How do I construct a list of my defined class A objects here instead of this? ( I can post the full code if needed, just thought it was better netiquette not to) TIA nuffi -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and M2Crypto question
Graham, thanks, I will try with that. On Sep 8, 1:02 am, Graham Dumpleton <[EMAIL PROTECTED]> wrote: > On Sep 7, 11:07 pm, Bojan Mihelac <[EMAIL PROTECTED]> wrote: > > > Hi all! > > > I am trying to install M2Crypto to work on OSX10.5 apache > > (mod_python). Error I receive: > > > Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5- > > macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image > > found. Did find: > > /Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg- > > tmp/M2Crypto/__m2crypto.so: no matching architecture in universal > > wrapper > > > I guess that have to do something with x64 architecture but I am > > stucked and not able to find a way and to make this work. M2Crypto lib > > works good stand alone. > > See: > > http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX#Missing_Co... > > This is mod_wsgi documentation, but same issue applies to mod_python. > > Graham -- http://mail.python.org/mailman/listinfo/python-list
Re: creating an (inefficent) alternating regular expression from a list of options
metaperl.com <[EMAIL PROTECTED]> wrote: > Pyparsing has a really nice feature that I want in PLY. I want to > specify a list of strings and have them converted to a regular > expression. > > A Perl module which does an aggressively optimizing job of this is > Regexp::List - > http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm > > I really dont care if the expression is optimal. So the goal is > something like: > > vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| > u|ii|i)' > > Is there a public module available for this purpose? I wrote one of these in perl a while ago http://www.craig-wood.com/nick/pub/words-to-regexp.pl It transforms the regular expression recursively into more efficient ones. It uses regular expressions to do that. I considered porting it to python but looking at the regular expressions made me feel weak at the knees ;-) -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: creating an (inefficent) alternating regular expression from a list of options
On Sep 9, 9:12 am, "metaperl.com" <[EMAIL PROTECTED]> wrote: > Pyparsing has a really nice feature that I want in PLY. I want to > specify a list of strings and have them converted to a regular > expression. > > A Perl module which does an aggressively optimizing job of this is > Regexp::List > -http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/Lis... > > I really dont care if the expression is optimal. So the goal is > something like: > > vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| > u|ii|i)' > > Is there a public module available for this purpose? I was about to start a thread about a very similar problem; hope I'm not hijacking this thread. However I am interested in a solution that (1) scales to a potentially large number of alternate strings (hundreds or thousands), which will hit, sooner or later, some max limit in the builtin regexps and (2) is not limited to strings but can be used for arbitrary objects. Therefore I am looking for a different approach, perhaps a specialization of the general regexp search algorithm. More formally, given (a) an input sequence I and (b) a set of 'censored' sequences S, find and remove all the sequences in S that appear in I. For instance, if S = set([(a,), (a,b), (a,c), (c,), (d,a)]) and I = (x, a, b, c, y, d, a, b), the filtered sequence would be: O = (x, y, b) i.e. the censored subsequences are (a,b), (c,), and (d,a). As with regexps, if sequence `x` is a prefix of `y`, the longer sequence `y` wins when both match (e.g. if (a,b) matches, it supersedes (a,)). For extra bonus, the algorithm should remove overlapping subsequences too, i.e. for the input I above, the output would be (x, y) since both (d,a) and (a,b) would match for (d,a,b). With respect to complexity, I am mainly interested in len(S); len(I) is small for my application, typically no more than 10. Of course, an algorithm that scales decently in both len(S) and len(I) would be even better. Any ideas or relevant links ? George PS: This is not a homework ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Orientation on MySql using python
On Tue, Sep 9, 2008 at 9:36 AM, João Abrantes <[EMAIL PROTECTED]>wrote: > Hello everyone, I want to make a program in python that uses Mysql aswell.. > I don't know anything about mysql can you tell me some good books/tutorials > where I can read something about mysql using python? Thanks. > > -- > Did you try looking at MySQL's website? http://dev.mysql.com/usingmysql/python/ -- http://mail.python.org/mailman/listinfo/python-list
XML-RPC "filter"
Dear all, I'm writing an XML-RPC server which should be able to modify the incoming request before dispatching it. In particular I wand to added two fixed parameters to the method called: one is the client host address, and the other is the user name provided as for Basic Authentication (http://[EMAIL PROTECTED]). To do this, at the present I've overwritten the do_POST method of SimpleXMLRPCRequestHandler, including at a certain point this code: data = ''.join(L) params, method = xmlrpclib.loads(data) user = "unknown" if self.headers.has_key('Authorization'): # handle Basic authentication (enctype, encstr) = self.headers.get('Authorization').split() user, password = base64.standard_b64decode(encstr).split(':') params = list(params) params.append(self.address_string()) params.append(user) params = tuple(params) data = xmlrpclib.dumps(params, methodname=method) (I slightly modified it to make it more readable at mail level) It works, but I don't really like it because it completely overwrites the do_POST method that in the future Python releases is going to change (I verified it). Do you know a better way to do this? Thanks in advance. Luigi -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-RPC "filter"
Luigi wrote: > Dear all, > > I'm writing an XML-RPC server which should be able to modify the > incoming request before dispatching it. In particular I wand to added > two fixed parameters to the method called: one is the client host > address, and the other is the user name provided as for Basic > Authentication (http://[EMAIL PROTECTED]). > > To do this, at the present I've overwritten the do_POST method of > SimpleXMLRPCRequestHandler, including at a certain point this code: > > > data = ''.join(L) > > params, method = xmlrpclib.loads(data) > user = "unknown" > if self.headers.has_key('Authorization'): > # handle Basic authentication > (enctype, encstr) = self.headers.get('Authorization').split() > user, password = base64.standard_b64decode(encstr).split(':') > params = list(params) > params.append(self.address_string()) > params.append(user) > params = tuple(params) > data = xmlrpclib.dumps(params, methodname=method) > > (I slightly modified it to make it more readable at mail level) > > It works, but I don't really like it because it completely overwrites > the do_POST method that in the future Python releases is going to > change (I verified it). Do you know a better way to do this? I would go for a slightly different approach: make your server have a dispatch-method that delegates the calls to the underlying actual implementation. But *before* that happens, extract the information as above, and either - prepend it to the argument list - stuff it into threadlocal variables, and only access these if needed in your implementation. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: max(), sum(), next()
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote: > David C. Ullrich: > > I didn't mention what's below because it doesn't seem > > likely that saying max([]) = -infinity and > > min([]) = +infinity is going to make the OP happy... > > Well, it sounds cute having Neginfinite and Infinite as built-int > objects that can be compared to any other type and are < of or > of > everything else but themselves. Like I said, I'm not going to say anything about how Python should be. If I were going to comment on that I'd say it would be cute but possibly silly to actually add to the core. But in the math library I made some time ago there was an AbsoluteZero with the property that when you added it to x you got x for any x whatever (got used as the default additive identity for classes that didn't have an add_id defined...) > Probably they can be useful as > sentinels, but in Python I nearly never use sentinels anymore, and > they can probably give some other problems... > > Bye, > bearophile -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: max(), sum(), next()
In article <[EMAIL PROTECTED]>, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Fri, 05 Sep 2008 10:22:22 -0500, David C. Ullrich wrote about why max > and min shouldn't accept a default argument: > > > Think about all the previously elected female or black presidents of the > > US. Which one was the tallest? > > I know the answer to that one: > > All of them! Heh. Mysteries of the empty set. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Clearing a session and reload() problem (with repro error)
En Mon, 08 Sep 2008 05:37:24 -0300, Rafe <[EMAIL PROTECTED]> escribió: I've tried to use reload with a very simple algorithm. Simply run through every imported module, ignoring anything that is "None" or on the C: drive (all of our python is on a network drive so this hack works for me for now) and reload() it. I've come to realize that this isn't near intelligent enough to handle sub-packages. Package Structure: --- inheritRepro __init__.py baseLib.py child __init__.py To summarize your code: inheritRepro.__init__.py only contains the reload support; baselib is an independent module; child/__init__.py imports and uses baseLib. # Iterate over all IMPORTED modules modules = sys.modules for modName in modules: mod = modules[modName] (note: sys.modules could change along the iteration; I'd iterate this way instead) modules = sys.modules for modName in modules.keys(): mod = modules.get(modName) Output: Reloading Python Modules... Reloaded 'C:\TEMP\problema_con_reload\inheritRepro\_ _init__.pyc'> Reloaded 'C:\TEMP\problema_con_reload\inheritR epro\child\__init__.pyc'> Reloaded 'C:\TEMP\problema_con_reload\inheri tRepro\baseLib.pyc'> Note that child is reloaded *before* baseLib - when child imports baseLib, it still finds the old module. One should reload baseLib before reloading child, in that case it works fine. This dependency between modules, applied to all modules in your project, defines a "dependency graph". In some cases, one can define a partial ordering of its nodes, such that no module depends on any other module *after* it (it may depend only on modules *before* it). Look for "topological sort". Doing that in the generic case is not easy. If you *know* your dependencies, reload the modules in the right order by hand. NOTE: this works if I don't use a sub-package for 'child' (child.py instead). Is it overly simple to assume reloading by file structure might work? You're iterating over sys.modules in whatever ordering the keys are in the dictionary; using other module names may yield the "right" ordering just by chance. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Test if list contains another list
On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > Matimus a écrit : > > On Sep 8, 12:32 am, Bruno Desthuilliers > > <[EMAIL PROTECTED]> wrote: > (snip) > >> >>> set(a).issubset(set(b)) > >> True > >> >>> > >> > > Just to clarify, doing it using sets is not going to preserve order OR > > number of elements that are the same. > > > > That is: > > > a = [1,1,2,3,4] > b = [4,5,3,7,2,6,1] > set(a).issubset(set(b)) > > True > > > > This will return True if b contains at least on of each element found > > in a. If the OP wanted to check that list `a` appeared in order > > somewhere in list `b` then sets won't work. > > Indeed, and I should have mentionned this myself. Thanks for this reminder. > If preserving order is important, strings have many of the properties you're looking for, but it might take some work to figure out a suitable way to convert to a string. The problem is easier if you know something about the inputs. If all inputs are known to be numbers between 0 and 15, you can just do: if ''.join(map(hex, a)) in ''.join(map(hex, b)): return True Hmm... actually, with the '0x' prefix that hex() puts on numbers, I think this works for arbitrary integers. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
Re: creating an (inefficent) alternating regular expression from a list of options
Larry Bates wrote: vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| u|ii|i)' Is there a public module available for this purpose? Perhaps I'm missing something but your function call oneOf(...) is longer than than actually specifying the result. You can certainly write quite easily: def oneOf(s): return "|".join(s.split()) "|" works strictly from left to right, so that doesn't quite work since it doesn't place "aa" before "a". a simple reverse sort will take care of that: return "|".join(sorted(s.split(), reverse=True)) you may also want to do re.escape on all the words, to avoid surprises when the choices contain special characters. -- http://mail.python.org/mailman/listinfo/python-list
F2PY changing integers to arrays???
I have a simple module which performs basic operations on plot3d files (below). I wrapped like: f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 That seems to work fine, but i get some unexpected results... >>> from plot3d import plot3d as p3 >>> dir(p3) ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', 'writeit2d'] >>> p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) >>> p3.imax array(409) "409" is correct, but "imax" is declared as an INTEGER in fortran and now it's an array in python??? Any ideas? # prec.f90 MODULE prec IMPLICIT NONE INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) END MODULE prec # plot3d.f90 MODULE PLOT3D USE prec IMPLICIT NONE INTEGER, PARAMETER :: prc=single REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z INTEGER :: mg, imax, jmax, kmax CONTAINS !-- SUBROUTINE READIT( fname, ftype, fmg ) ! reads the plot3d, formatted, mg file in xyz IMPLICIT NONE CHARACTER(len=20), INTENT(IN) :: fname, ftype LOGICAL :: fmg INTEGER :: i, j, k, n, f=1 SELECT CASE (ftype) CASE ('FORMATTED') OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', FORM=ftype ) IF (fmg) READ(f,*) mg ! only read if multigrid READ(f,*) imax, jmax, kmax ALLOCATE( x(mg, imax, jmax, kmax) ) ALLOCATE( y(mg, imax, jmax, kmax) ) ALLOCATE( z(mg, imax, jmax, kmax) ) READ(f,*) x(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & y(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & z(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) CASE ('UNFORMATTED') OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', FORM=ftype ) IF (fmg) READ(f) mg ! only read if multigrid READ(f) imax, jmax, kmax ALLOCATE( x(mg, imax, jmax, kmax) ) ALLOCATE( y(mg, imax, jmax, kmax) ) ALLOCATE( z(mg, imax, jmax, kmax) ) READ(f) x(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & y(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & z(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) CASE DEFAULT WRITE(*,*) 'filetype not supported in ' STOP END SELECT CLOSE(f) END SUBROUTINE READIT END MODULE PLOT3D -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use execfile with input parameters
En Mon, 08 Sep 2008 08:08:33 -0300, Shi, Shaozhong <[EMAIL PROTECTED]> escribió: I have a Python script expecting 11 or 12 input parameters. How do I use execfile to execute the Python script in my new Python script? How do I pass in the input parameters? You might use the subprocess module to run the script with all its parameters. But probably you want to call a *function* in a module. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
MySQLdb + AMD64
After searching around for a bit for a build of MySQLdb, i have found that i will probably need to build the module for AMD64 on windows. Is there a guide or something that shows what needs to be done to build a module for a certain architecture? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: F2PY changing integers to arrays???
john wrote: > I have a simple module which performs basic operations on plot3d files > (below). I wrapped like: > > f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 > > That seems to work fine, but i get some unexpected results... > from plot3d import plot3d as p3 dir(p3) > ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', > 'writeit2d'] p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) p3.imax > array(409) > > > "409" is correct, but "imax" is declared as an INTEGER in fortran and > now it's an array in python??? Any ideas? > > > > > > > > > # prec.f90 > MODULE prec > IMPLICIT NONE > INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) > INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) > END MODULE prec > > > > > # plot3d.f90 > MODULE PLOT3D > USE prec > IMPLICIT NONE > INTEGER, PARAMETER :: prc=single > REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z > INTEGER :: mg, imax, jmax, kmax > > CONTAINS > > !-- > SUBROUTINE READIT( fname, ftype, fmg ) > ! reads the plot3d, formatted, mg file in xyz > IMPLICIT NONE > CHARACTER(len=20), INTENT(IN) :: fname, ftype > > LOGICAL :: fmg > INTEGER :: i, j, k, n, f=1 > > SELECT CASE (ftype) > CASE ('FORMATTED') > OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > IF (fmg) READ(f,*) mg ! only read if multigrid > READ(f,*) imax, jmax, kmax > ALLOCATE( x(mg, imax, jmax, kmax) ) > ALLOCATE( y(mg, imax, jmax, kmax) ) > ALLOCATE( z(mg, imax, jmax, kmax) ) > READ(f,*) x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > CASE ('UNFORMATTED') > OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > IF (fmg) READ(f) mg ! only read if multigrid > READ(f) imax, jmax, kmax > ALLOCATE( x(mg, imax, jmax, kmax) ) > ALLOCATE( y(mg, imax, jmax, kmax) ) > ALLOCATE( z(mg, imax, jmax, kmax) ) > READ(f) x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > CASE DEFAULT > WRITE(*,*) 'filetype not supported in ' > STOP > END SELECT > > CLOSE(f) > > END SUBROUTINE READIT > > END MODULE PLOT3D I'm not sure why you obtain array(409) instead 409, but you can use this type in python as normal integer. For example array(409)+409 gives integer value 818. Greetings -- Marek -- http://mail.python.org/mailman/listinfo/python-list
PYTHONSITEDIR environment variable
Dear all, These days I often find myself using working-env.py, virtual-python.py & co. The main reason in most cases is to insulate my working environment so that I can use custom site-package libs together with the default stdlib. PYTHONHOME and/or PYTHONPATH (particularly with python -S) get close, but not quite there, and the above scripts seem a bit over the top. Wouldn't it be possible to support a PYTHONSITEDIR environment variable in site.py for this purpose? I have attached a possible patch. In what follows, if PYTHONSITEDIR is defined, that dir is used as the only source of site-packages, extra paths can easily be added by creating a .pth file in there. A different variable could be used to prepend a sitedir to the list of default sitedirs (similar code without "return None"). --- /usr/lib/python2.5/site.py 2008-05-29 22:03:04.0 +0100 +++ /tmp/site.py2008-09-09 18:06:42.0 +0100 @@ -167,6 +167,10 @@ def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" +sitedir = os.environ.get('PYTHONSITEDIR') +if sitedir and os.path.isdir(sitedir): +addsitedir(sitedir, known_paths) +return None prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONSITEDIR environment variable
ago wrote: Wouldn't it be possible to support a PYTHONSITEDIR environment variable in site.py for this purpose? I have attached a possible patch. In what follows, if PYTHONSITEDIR is defined, that dir is used as the only source of site-packages, extra paths can easily be added by creating a .pth file in there. A different variable could be used to prepend a sitedir to the list of default sitedirs (similar code without "return None"). I had a similar idea, wrote a PEP and implemented it for 2.6 and 3.0: http://www.python.org/dev/peps/pep-0370/ Christian -- http://mail.python.org/mailman/listinfo/python-list
check if the values are prensent in a list of values
Hello All, I will appreciate the help from the more skillfull pythonistas.. I have a small app that generates a sequence like 00341 01741 03254 This values I am putting in a list. So I have a list = [00341,01741,03254] after the programs find the sequence 03401 this sequence is "new" so it appends on the list. But I want to avoid that as the values are already on the first sequence of the list (00341). If I try to use a "in" statement it will give false. as 00341 is different from 00341 (but for my goal not..) How can I check against this list and avoid to put "different" sequences but same values? as 34100 --> dont append on the list 14300 ---> dont append on the list 05321 --> append to the list. Am I doing some conceptual error using lists? There is a better approach? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONSITEDIR environment variable
On Sep 9, 6:56 pm, Christian Heimes <[EMAIL PROTECTED]> wrote: > I had a similar idea, wrote a PEP and implemented it for 2.6 and 3.0: > > http://www.python.org/dev/peps/pep-0370/ > > Christian Christian, I like your pep :), The only thing I would add is that in my experience I often use different working-envs for different projects, so I'd prefer to have a more generic solution as opposed to a single working-env per user. The latter could still be achieved by setting the appropriate environment variable in the user profile. Do you think it would be possible to accommodate for the above in your PEP? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to record audio from Python on Mac?
[EMAIL PROTECTED] wrote: (I asked this on pythonmac-sig a couple days ago but got no response, so I'm casting a broader net.) Can I easily control audio record/playback from Python on my Mac? I know zip about audio recording or about Apple APIs via Python. Pointers to simple examples would be much appreciated. Thanks, Skip You can probably access this functionality via PyObjC--it provides access to the Cocoa frameworks. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: check if the values are prensent in a list of values
flit wrote: Hello All, I will appreciate the help from the more skillfull pythonistas.. I have a small app that generates a sequence like 00341 01741 03254 Consider using a dict with sorted tuple keys, eg d = {} for seq in ['00341','01741','03254']: ky = list(seq) ky.sort() d[tuple(ky)] = None then d.keys() are the unique combinations. HTH, Emile This values I am putting in a list. So I have a list = [00341,01741,03254] after the programs find the sequence 03401 this sequence is "new" so it appends on the list. But I want to avoid that as the values are already on the first sequence of the list (00341). If I try to use a "in" statement it will give false. as 00341 is different from 00341 (but for my goal not..) How can I check against this list and avoid to put "different" sequences but same values? as 34100 --> dont append on the list 14300 ---> dont append on the list 05321 --> append to the list. Am I doing some conceptual error using lists? There is a better approach? Thanks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: F2PY changing integers to arrays???
Hmmm... I didn't even try that... I thought this might have caused problems down the road passing this var to other classes, etc., but i guess not! Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONSITEDIR environment variable
ago wrote: The only thing I would add is that in my experience I often use different working-envs for different projects, so I'd prefer to have a more generic solution as opposed to a single working-env per user. The latter could still be achieved by setting the appropriate environment variable in the user profile. Do you think it would be possible to accommodate for the above in your PEP? Isn't PYTHONUSERBASE sufficient for your needs? The env var alters the base directory. I can neither change the PEP nor the implementation at this stage of the development cycle. Python 2.6 and 3.0 are in beta and the API is set in stone. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONSITEDIR environment variable
Small variation on the above patch, using 2 environment variables: PYTHONSITEDIR allows for local site-packages (that override system site packages), and PYTHONNOSYSSITES skips system site-packages for "clean-room" operation (similar to virtual-python.py --no-site- packages). --- /usr/lib/python2.5/site.py 2008-05-29 22:03:04.0 +0100 +++ /tmp/site.py2008-09-09 19:56:44.0 +0100 @@ -167,6 +167,11 @@ def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" +sitedir = os.environ.get('PYTHONSITEDIR') +if sitedir and os.path.isdir(sitedir): +addsitedir(sitedir, known_paths) +if os.environ.get('PYTHONNOSYSSITES'): +return None prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) -- http://mail.python.org/mailman/listinfo/python-list
Re: Unable to start a process with subprocess Popen()
En Mon, 08 Sep 2008 13:35:21 -0300, <[EMAIL PROTECTED]> escribió: cmd = subprocess.Popen([batchFilePath], \ shell = True, \ stdin = subprocess.PIPE, stdout = subprocess.PIPE, \ stderr = subprocess.PIPE \ ) cmd.stdin.close() outPipe, errPipe = PipeThread(cmd.stdout), PipeThread(cmd.stderr) outPipe.run(), errPipe.run() retcode = cmd.wait() out, err = outPipe.getOutput(), errPipe.getOutput() Although, this solved my problem. But I know there is no need for using threading in this problem. This problem could've been solved just by the subprocess module. I'm unnecessarily using the threading module. Not only that, you're misusing the Thread class. To actually create a separate execution thread, you should call outPipe.start() instead of outPipe.run() (same for errPipe). Note that if your batch file emits a large output it really may be necesary to use a separate thread to read the output. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Using NamedTemporaryDir instead of multiple NamedTemporaryFiles
I am writing a library that creates temporary files and calls a series of external programs to process these files. Sometimes these external programs create files in the same directory as the input files, so to make sure they are all deleted, one must create them in a temporary directory, then delete it. I've written a NamedTemporaryDir class which is derived somewhat from tempfile.NamedTemporaryFile in the standard library. Right now I am using NamedTemporaryFile to create individual files, but since I am putting them in a directory that will be deleted anyway, I'm wondering if I can simplify things (and not have to keep track of all fo the NamedTemporaryFile instances) by using tempfile.mkstemp() specifying my temporary directory, and relying on the directory deletion when exiting its with block. Is there any reason I should keep track of each temporary files myself instead of deleting the whole directory? I am using Linux, but I would also be interested in cross-platform considerations. Also, the code is below. Is this worth submitting as a patch? # NamedTemporaryFile is based somewhat on Python 2.5.2 # tempfile._TemporaryFileWrapper # # Original Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python # Software Foundation; All Rights Reserved # # License at http://www.python.org/download/releases/2.5.2/license/ from tempfile import mkdtemp class NamedTemporaryDir(object): def __init__(self, *args, **kwargs): self.name = mkdtemp(*args, **kwargs) self.close_called = False def __enter__(self): return self unlink = os.unlink def close(self): if not self.close_called: self.close_called = True self.unlink(self.name) def __del__(self): self.close() def __exit__(self, exc, value, tb): result = self.file.__exit__(exc, value, tb) self.close() return result -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONSITEDIR environment variable
On Sep 9, 7:45 pm, Christian Heimes <[EMAIL PROTECTED]> wrote: > ago wrote: > > The only thing I would add is that in my experience I often use > > different working-envs for different projects, so I'd prefer to have a > > more generic solution as opposed to a single working-env per user. The > > latter could still be achieved by setting the appropriate environment > > variable in the user profile. Do you think it would be possible to > > accommodate for the above in your PEP? > > Isn't PYTHONUSERBASE sufficient for your needs? The env var alters the > base directory. > > I can neither change the PEP nor the implementation at this stage of the > development cycle. Python 2.6 and 3.0 are in beta and the API is set in > stone. > > Christian I had missed that, yes I think that PYTHONUSERBASE will do fine! It might be useful though to be able to skip other system site dirs altogether so that only local site packages are used, as in the second patch I sent (see PYTHONNOSYSSITES). Thanks a lot, Ago -- http://mail.python.org/mailman/listinfo/python-list
Re: How to record audio from Python on Mac?
On Sep 9, 1:11 pm, Kevin Walzer <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > > casting a broader net.) > > > Can I easily control audio record/playback from Python on my Mac? I know > > zip about audio recording or about Apple APIs via Python. Pointers to > > simple examples would be much appreciated. > > > Thanks, > > > Skip > > You can probably access this functionality via PyObjC--it provides > access to the Cocoa frameworks. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Another option you could use is calling Applescript from the command line, to open, execute, and handle audio. An easy example of this is with iTunes actually. Once you get iTunes down, doing this for other apps should be easy (if they have applescript bindings): http://www.macosxhints.com/article.php?story=20011108211802830 You could probably also do what Kevin recommends, but depending on your needs, this may be a whole lot more simple. -David Thole http://www.thedarktrumpet.com -- http://mail.python.org/mailman/listinfo/python-list
Re: check if the values are prensent in a list of values
On Sep 9, 2:04 pm, flit <[EMAIL PROTECTED]> wrote: > Hello All, > > I will appreciate the help from the more skillfull pythonistas.. > > I have a small app that generates a sequence like > > 00341 > 01741 > 03254 > > This values I am putting in a list. > > So I have a list = [00341,01741,03254] > > after the programs find the sequence 03401 this sequence is "new" so > it appends on the list. But I want to avoid that as the values are > already on the first sequence of the list (00341). > If I try to use a "in" statement it will give false. as 00341 is > different from 00341 (but for my goal not..) > > How can I check against this list and avoid to put "different" > sequences but same values? > > as 34100 --> dont append on the list > 14300 ---> dont append on the list > 05321 --> append to the list. > > Am I doing some conceptual error using lists? > There is a better approach? Whenever you want to keep track of unique values, think of using a set or dict, not list. Since you don't care about the character order within each string, sort the characters so that two strings are equivalent if and only if their sorted character lists are equal. One more thing to bear in mind is that the elements of a set (or the keys of a dict) have to be hashable. Lists are not hashable so there needs to be an extra step to convert the sorted list into an "equivalent" hashable object. A common choice that works for any list [*] is to convert it to a tuple. An alternative that works for strings only is to join() them into a single string: >>> values = '00341 01741 03254 34100 14300 05321'.split() >>> set(''.join(sorted(v)) for v in values) set(['01235', '00134', '01147', '02345']) HTH, George [*] Assuming that every element of the list is hashable. -- http://mail.python.org/mailman/listinfo/python-list
Re: check if the values are prensent in a list of values
Emile van Sebille wrote: > flit wrote: >> Hello All, >> >> I will appreciate the help from the more skillfull pythonistas.. >> >> I have a small app that generates a sequence like >> >> 00341 >> 01741 >> 03254 > > Consider using a dict with sorted tuple keys, eg > > d = {} > > for seq in ['00341','01741','03254']: > ky = list(seq) > ky.sort() > d[tuple(ky)] = None > > > then d.keys() are the unique combinations. > > HTH, > > Emile I'm not judging whether this is a good solution or not, but that's a silly use of a dict. A set would be better. s = set() for seq in ['00341','01741','03254']: s.add(tuple(sorted(ky))) Then you just, well, access the set directly, instead of using d.keys() or something. (I also replaced the sorting with the sorted() function for brevity. This all assumes you have at least Python 2.4...) >> This values I am putting in a list. >> >> So I have a list = [00341,01741,03254] >> >> after the programs find the sequence 03401 this sequence is "new" so >> it appends on the list. But I want to avoid that as the values are >> already on the first sequence of the list (00341). >> If I try to use a "in" statement it will give false. as 00341 is >> different from 00341 (but for my goal not..) >> >> >> How can I check against this list and avoid to put "different" >> sequences but same values? >> >> as 34100 --> dont append on the list >> 14300 ---> dont append on the list >> 05321 --> append to the list. >> >> Am I doing some conceptual error using lists? >> There is a better approach? >> >> Thanks -- -- http://mail.python.org/mailman/listinfo/python-list
[OT] top-posting and quoting (was: Re: Coming from .NET and VB and C)
Could you please timh and belindelof learn to quote properly and stop top-posting ? TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles
Please accept my apologies if this message was posted several times. My newsreader claimed that a timeout error kept the message from being posted, but I think it got through. -- http://mail.python.org/mailman/listinfo/python-list
Re: check if the values are prensent in a list of values
Matt Nordhoff a écrit : (snip) I'm not judging whether this is a good solution or not, but that's a silly use of a dict. Yeps, but a somewhat common one in code predating the apparition of sets as builtin type. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles
Michael Hoffman wrote: unlink = os.unlink Actually, I need to use shutil.rmtree instead, but you get the idea. -- http://mail.python.org/mailman/listinfo/python-list
Deflate with urllib2...
I'm using urllib2 and accepting gzip and deflate. It turns out that almost every site returns either normal text or gzip. But I finally found one that returns deflate. Here's how I un-gzip: compressedstream = StringIO.StringIO(data) gzipper = gzip.GzipFile(fileobj=compressedstream) data = gzipper.read() Un-gzipping works great! Here's how I un-deflate (inflate??) data = zlib.decompress(data) Un-deflating doesn't work. I get "zlib.error: Error -3 while decompressing data: incorrect header check" I'm using python 2.5.2. Can someone tell me exactly how to handle deflated web pages? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: F2PY changing integers to arrays???
On 9 Sep., 18:41, john <[EMAIL PROTECTED]> wrote: > I have a simple module which performs basic operations on plot3d files > (below). I wrapped like: > > f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 > > That seems to work fine, but i get some unexpected results... > > >>> from plot3d import plot3d as p3 > >>> dir(p3) > > ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', > 'writeit2d']>>> p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) > >>> p3.imax > > array(409) > > "409" is correct, but "imax" is declared as an INTEGER in fortran and > now it's an array in python??? Any ideas? > > # prec.f90 > MODULE prec > IMPLICIT NONE > INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) > INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) > END MODULE prec > > # plot3d.f90 > MODULE PLOT3D > USE prec > IMPLICIT NONE > INTEGER, PARAMETER :: prc=single > REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z > INTEGER :: mg, imax, jmax, kmax > > CONTAINS > > !-- > SUBROUTINE READIT( fname, ftype, fmg ) > ! reads the plot3d, formatted, mg file in xyz > IMPLICIT NONE > CHARACTER(len=20), INTENT(IN) :: fname, ftype > > LOGICAL :: fmg > INTEGER :: i, j, k, n, f=1 > > SELECT CASE (ftype) > CASE ('FORMATTED') > OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > IF (fmg) READ(f,*) mg ! only read if multigrid > READ(f,*) imax, jmax, kmax > ALLOCATE( x(mg, imax, jmax, kmax) ) > ALLOCATE( y(mg, imax, jmax, kmax) ) > ALLOCATE( z(mg, imax, jmax, kmax) ) > READ(f,*) x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > CASE ('UNFORMATTED') > OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > IF (fmg) READ(f) mg ! only read if multigrid > READ(f) imax, jmax, kmax > ALLOCATE( x(mg, imax, jmax, kmax) ) > ALLOCATE( y(mg, imax, jmax, kmax) ) > ALLOCATE( z(mg, imax, jmax, kmax) ) > READ(f) x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > CASE DEFAULT > WRITE(*,*) 'filetype not supported in ' > STOP > END SELECT > > CLOSE(f) > > END SUBROUTINE READIT > > END MODULE PLOT3D You can generate the according .pyf file with some command line flag I forgot. There you can see what the parser derived from the fortran code and you can edit this file for further configuration of the generated python module. Greetings, Uwe -- http://mail.python.org/mailman/listinfo/python-list
Re: check if the values are prensent in a list of values
On 9 set, 15:13, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Matt Nordhoff a écrit : > (snip) > > > I'm not judging whether this is a good solution or not, but that's a > > silly use of a dict. > > Yeps, but a somewhat common one in code predating the apparition of sets > as builtin type. Thanks for all contributions, sure I learn a lot with all samples. Very good thread and answers. Thank you all -- http://mail.python.org/mailman/listinfo/python-list
Re: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles
En Tue, 09 Sep 2008 15:49:32 -0300, Michael Hoffman <[EMAIL PROTECTED]> escribió: I've written a NamedTemporaryDir class which is derived somewhat from tempfile.NamedTemporaryFile in the standard library. Right now I am using NamedTemporaryFile to create individual files, but since I am putting them in a directory that will be deleted anyway, I'm wondering if I can simplify things (and not have to keep track of all fo the NamedTemporaryFile instances) by using tempfile.mkstemp() specifying my temporary directory, and relying on the directory deletion when exiting its with block. Looks fine... def close(self): if not self.close_called: self.close_called = True self.unlink(self.name) Windows won't let you remove a non-empty directory. def __exit__(self, exc, value, tb): result = self.file.__exit__(exc, value, tb) self.close() return result self.file? -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Wx Python - Code Structure & Event Handling
Hi, I have just started writing a GUI using wxpython after finding a limitation using Tkinter. I have read most tutorials on wxpython and slowly becoming accustomed considering I started with the latter GUI tool first! I must quote first that I am a novice user of python so the issue(s) I have may seem very obvious but please be patient with me! I have noticed that all the wxpython references I used for creating my application(s) "cram" all the code in the frame subclass. This is fine when you consider small applications but what about when they grow into very complex applications? This creates my first question : Where is it possible to find information on wxpython code practise/ structure when considering complex larger Gui's? Without any reference I decided to attempt my owm method by breaking up the top level panels in my frame as individiual class objects. and then construct the widgets for the panels within the respective classes. This led to my second problem, how do I use and event in one Panel to cause an effect in the other Panel ? For example, if I have button in one Panel and wish to change the text of a label in the other Panel, what is the best way to do this? Should I break the code into modules instead? Of course, you may explain that the way I have approached this is completely wrong, if so please tell me, I really want to get the basic structure right before I start making the code more complex. I look forward to your help - I have listed some code below to help explain what concept I wish to achieve, import wx class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Application",size=(400,400)) Panel1 = wx.Panel(self, -1,size=(200,200)) Panel2 = wx.Panel(self, -1,size=(200,200)) Sizer = wx.FlexGridSizer(2,2,5,5) Sizer.Add(Panel1) Sizer.Add(Panel2) self.SetSizerAndFit(Sizer) Util1 = Utils1(Panel1) Util2 = Utils2(Panel2) class Utils1(): def __init__(self, Panel): button = wx.Button(Panel,-1, "Button 1") Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) self.Label = wx.StaticText(Panel,-1, "Handler to me", name="Lab1") Sizer = wx.BoxSizer(wx.VERTICAL) Sizer.Add(button) Sizer.Add(self.Label) Panel.SetSizerAndFit(Sizer) def OnClick(self, Evt): self.Label.SetLabel("you changed me") class Utils2(): def __init__(self, Panel): self.button = wx.Button(Panel,-1, "Button 2") Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) def OnClick(self, Evt): """ what is the easiest & accepted Method of changing the text in a different class instance?""" pass #???.SetLabel("you changed me") app = wx.PySimpleApp() frame = Frame() frame.Show() app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Iowa Python Users Group - First Meeting
Hi all, The first meeting date for the Iowa Python Users Group has been decided. Here are the details: Time / Date: Wednesday, Sept. 24 from 7-9 p.m. Location: Marshall County Sheriff's Office, 3rd floor 2369 Jessup Ave Marshalltown, IA 50158 Unofficial website: http://www.ipug.pythonlibrary.org Don't know how to get there? Check out maps.yahoo.com or maps.google.com. The Sheriff's Office is not actually in Marshalltown. If you take Highway 30 East, towards Marshalltown you'll see it on your left. There's a large water tower there and the building is a rusty red color. There are some signs for a Tractor convention there as well. If you're coming from the other direction, then skip ALL the exits and keep driving until the lanes go from 4 lanes to 2. It should be the second right after that. I am still developing the agenda for our first meeting, but here are some of the things we're going to discuss: - What day really works best for meeting? (if you can't make the first one, you can email me your votes!) - Figure out what domain name our group should have - Decide on what Python web framework to use to create said site (which will be a group project) - Try to come up with what format we want our meetings to take. Plone and Zope users are welcome. In fact, anyone who is interested in Python (regardless of their experience with it) is welcome to come. Let your Iowan Python friends know. Questions or ideas? Send them to me. Thanks! --- Mike Driscoll email: mike (at) pythonlibrary (dot) org Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Deflate with urllib2...
Try this http://www.paul.sladen.org/projects/pyflate/ 2008/9/9 Sam <[EMAIL PROTECTED]>: > I'm using urllib2 and accepting gzip and deflate. > > It turns out that almost every site returns either normal text or > gzip. But I finally found one that returns deflate. > > Here's how I un-gzip: > compressedstream = StringIO.StringIO(data) > gzipper = gzip.GzipFile(fileobj=compressedstream) > data = gzipper.read() > > Un-gzipping works great! > > Here's how I un-deflate (inflate??) > data = zlib.decompress(data) > > Un-deflating doesn't work. I get "zlib.error: Error -3 while > decompressing data: incorrect header check" > > I'm using python 2.5.2. Can someone tell me exactly how to handle > deflated web pages? > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: biopython
En Tue, 09 Sep 2008 05:53:19 -0300, Beema Shafreen <[EMAIL PROTECTED]> escribió: Hi all, I am using Biopython to fetch pumed Id's ,The module i use is (from Bio import Entrez) But i am getting this error from Bio import Entrez Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name Entrez what should i do know can anybody suggest me an alternative for this Ensure that you don't have *another* Bio module that is being imported instead of the true one. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: universal unicode font for reportlab
Terry Reedy <[EMAIL PROTECTED]> wrote: >Sorry, I posted the wrong name. >Ariel Unicode MS is the one that seems pretty complete. ... > From the MS, I would guess that is a Windows font too ;-). It's made by Microsoft, but it's not a standard Windows font. I think it comes with Microsoft Office. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] [EMAIL PROTECTED] -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // -- http://mail.python.org/mailman/listinfo/python-list
wxpython ms-dos black window popping up in background
platform: windows xp professional, python 2.5, wxpython When I double-check on my program file test.py (for simplicity I'll be using this code below), I see the window just fine. But the ms-dos black window pops up in the background. On Linux, no issues at all. How can I get rid of that ms-dos black window in the background? something I need to add to my code? a setting to adjust in windows? thanks in advance. #!/usr/bin/python import wx appwx = wx.App() frame = wx.Frame(None, -1, 'test.py') frame.Show() appwx.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython ms-dos black window popping up in background
You need to have the script be run by pythonw.exe as opposed to python.exe pythonw.exe suppresses the DOS box from coming up and should be used for running GUI applications such as yours. Regards, Chris On Tue, Sep 9, 2008 at 1:33 PM, icarus <[EMAIL PROTECTED]> wrote: > platform: windows xp professional, python 2.5, wxpython > > When I double-check on my program file test.py (for simplicity I'll be > using this code below), I see the window just fine. But the ms-dos > black window pops up in the background. On Linux, no issues at all. > > How can I get rid of that ms-dos black window in the background? > something I need to add to my code? a setting to adjust in windows? > thanks in advance. > > > #!/usr/bin/python > import wx > > appwx = wx.App() > > frame = wx.Frame(None, -1, 'test.py') > frame.Show() > > appwx.MainLoop() > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: noob help request - how to make a list of defined class?
On Sep 9, 3:11 pm, [EMAIL PROTECTED] wrote: > I have defined two classes with one common field (called code) and > several different fields. > In class A there is only one instance of any given code as all items > are individual. > In class B, there may be none, one or many instances of each code, as > there can be any number of Bs referring to a single A. > > I need to make a list of Bs, remove dupes, and then create a list of > As that have Bs. > > (I hope this makes sense!) > > with much research and reading of my book I managed to get this > working, but at one stage I had errors that talked about being unable > to concatenate type A. So I converted my As to string, and then did a > split on commas to make a list. This worked fine for all the As that > didn't have a comma in a field (about 85%) but I can't help feeling > that this is a kludge, and that if Icould find a way to get a proper > list of As instead of a list of lists created by converting to string > and splitting, then my app would work properly. > > So I am hoping some of the nice folk here will help me out. > > The relevent function looks like this: > > def gen_B_A_list(): > Bcodes = get_codes() > all_As = read_A("A.csv") > B_A = [] > for i in range(len(codes)): > Bcode = Bcodes[i] > for A in all_As: > filename = getattr(A, 'code') > if filename == Bcode: > BA = str(A) > BA = string.split(BA, ',') > B_A.append(BA) > return B_A > > The element in question is after if filename == Bcode. How do I > construct a list of my defined class A objects here instead of this? > ( I can post the full code if needed, just thought it was better > netiquette not to) > > TIA > > nuffi Looks like homework, but as you've made some kind of effort, some hints to where to refer to in the manual. 1) Use the csv module for reading CSV files 2) A dict maps one value to another... (check it out) 3) Don't use getattr, use member access (the . symbol, eg: A.code) 4) The for statement can loop over each item in term without an explicit range (eg, for bcode in codes...) 5) Read the help for str, and read up on how to create objects, for instance str(A) returns A's string representation, while A() creates a new A object... Work your way through a python tutorial and make sure you understand the examples and principals... It might take you a while though, so I hope the assignment's not due soon! Jon. -- http://mail.python.org/mailman/listinfo/python-list
Python-URL! - weekly Python news and links (Sep 9)
QOTW: "So why am I supposed to care about SOAP again? Oh yes, the wizards I can use to generate 'web service end-points' from programming language code. My years in the SOAP trenches just makes me laugh myself half to death at that notion: I would probably have been twice as productive if every time I reached for a SOAP toolkit I instead just coded straight XML in HTTP. And this represents experience with Python, Java and C WS tools." - Uche Ogbuji How to cancel instance creation given certain conditions: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7083ed99c5237485 Implement a dictionary with case-insensitive keys: http://groups.google.com/group/comp.lang.python/browse_thread/thread/90a7e967d0bd1e0f/ The behavior of hash(): http://groups.google.com/group/comp.lang.python/browse_thread/thread/6c2d5030a833858f/ A generic attempt to add "verbosity" to scripts: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c2fa072005c9aaba/ max() and sum() applied to empty sequences, or those containing None, and how these differ from their SQL counterparts: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f4b98d6fa5d6b514/ Distributed processes, multiple threads, multicore CPUs: what are Python's options? http://groups.google.com/group/comp.lang.python/browse_thread/thread/fe55f38c64f58a9d/ Allowing underscores or other punctuation inside numeric literals: http://groups.google.com/group/comp.lang.python/browse_thread/thread/93dc57f9190b93bc/85dfbb163ba7f15b#85dfbb163ba7f15b How to manage two interdependent properties: http://groups.google.com/group/comp.lang.python/browse_thread/thread/66846422b6c2848f/ A generic GUI library, and the future of GUI development: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8904fbc731586533/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available,
Re: Wx Python - Code Structure & Event Handling
On Sep 9, 3:05 pm, [EMAIL PROTECTED] wrote: > Hi, > > I have just started writing a GUI using wxpython after finding a > limitation using Tkinter. I have read most tutorials on wxpython and > slowly becoming accustomed considering I started with the latter GUI > tool first! > I must quote first that I am a novice user of python so the issue(s) I > have may seem very obvious but please be patient with me! > > I have noticed that all the wxpython references I used for creating my > application(s) "cram" all the code in the frame subclass. This is > fine when you consider small applications but what about when they > grow into very complex applications? This creates my first question : > Where is it possible to find information on wxpython code practise/ > structure when considering complex larger Gui's? > > Without any reference I decided to attempt my owm method by breaking > up the top level panels in my frame as individiual class objects. and > then construct the widgets for the panels within the respective > classes. This led to my second problem, how do I use and event in one > Panel to cause an effect in the other Panel ? For example, if I have > button in one Panel and wish to change the text of a label in the > other Panel, what is the best way to do this? Should I break the code > into modules instead? > > Of course, you may explain that the way I have approached this is > completely wrong, if so please tell me, I really want to get the basic > structure right before I start making the code more complex. > > I look forward to your help > > - > > I have listed some code below to help explain what concept I wish to > achieve, > > import wx > > class Frame(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, > title="Application",size=(400,400)) > Panel1 = wx.Panel(self, -1,size=(200,200)) > Panel2 = wx.Panel(self, -1,size=(200,200)) > Sizer = wx.FlexGridSizer(2,2,5,5) > Sizer.Add(Panel1) > Sizer.Add(Panel2) > self.SetSizerAndFit(Sizer) > Util1 = Utils1(Panel1) > Util2 = Utils2(Panel2) > > class Utils1(): > def __init__(self, Panel): > button = wx.Button(Panel,-1, "Button 1") > Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) > self.Label = wx.StaticText(Panel,-1, "Handler to me", > name="Lab1") > Sizer = wx.BoxSizer(wx.VERTICAL) > Sizer.Add(button) > Sizer.Add(self.Label) > Panel.SetSizerAndFit(Sizer) > > def OnClick(self, Evt): > self.Label.SetLabel("you changed me") > > class Utils2(): > def __init__(self, Panel): > self.button = wx.Button(Panel,-1, "Button 2") > Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) > > def OnClick(self, Evt): > """ what is the easiest & accepted Method of changing the text > in > a different class instance?""" > pass > #???.SetLabel("you changed me") > > app = wx.PySimpleApp() > frame = Frame() > frame.Show() > app.MainLoop() These are good questions for the wxPython list. You'll learn a lot there: http://wxpython.org/maillist.php You'll also find the Style Guide helpful: http://wiki.wxpython.org/wxPython%20Style%20Guide In my more complex applications, I'll do the widgets in their own function, or for a wx.Notebook, I'll do each "book" in their own module by subclassing a wx.Panel object or some such. If you do that sort of thing in their own module subclasses, then the event handlers can go there too. Mike -- http://mail.python.org/mailman/listinfo/python-list
rss feed generation
I'm looking for suggestions on how to approach generating rss feed .xml files using python. What modules to people recommend I start with? Thanks! Blake -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython ms-dos black window popping up in background
Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw That did it. one more question... how do I create a pythonw standalone executable that works on w32, linux, mac, etc..? My intent is to have the process transparent to the user. He wouldn't even know the app was written in python. All he knows that when he double-clicks on it, the application pops up without the DOS black screen in the background (for w32 users.) On Sep 9, 10:49 am, "Chris Rebert" <[EMAIL PROTECTED]> wrote: > You need to have the script be run by pythonw.exe as opposed to python.exe > pythonw.exe suppresses the DOS box from coming up and should be used > for running GUI applications such as yours. > > Regards, > Chris > > > > On Tue, Sep 9, 2008 at 1:33 PM, icarus <[EMAIL PROTECTED]> wrote: > > platform: windows xp professional, python 2.5, wxpython > > > When I double-check on my program file test.py (for simplicity I'll be > > using this code below), I see the window just fine. But the ms-dos > > black window pops up in the background. On Linux, no issues at all. > > > How can I get rid of that ms-dos black window in the background? > > something I need to add to my code? a setting to adjust in windows? > > thanks in advance. > > > #!/usr/bin/python > > import wx > > > appwx = wx.App() > > > frame = wx.Frame(None, -1, 'test.py') > > frame.Show() > > > appwx.MainLoop() > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to record audio from Python on Mac?
On 9 Sep, 19:55, David Thole <[EMAIL PROTECTED]> wrote: > Another option you could use is calling Applescript from the command > line, to open, execute, and handle audio. For example, using QuickTime Player (which is a buggy, poorly designed piece of junk, but might suffice if you only need something quick-n- dirty and aren't too fussy): #!/usr/bin/python from time import sleep from appscript import * duration = 5 # seconds outpath = '/Users/foo/test.aiff' qtp = app('QuickTime Player') qtp.new_audio_recording() qtp.documents[1].start() sleep(duration) qtp.documents[1].stop() qtp.documents[1].export(to=mactypes.File(outpath), as_=k.AIFF) Or, if you're on Leopard and want something a bit more polished, you could look into using the new QTKit framework via PyObjC. Dunno about Python-specific examples, but I imagine you could dig up some ObjC code if you search around a bit and then convert that over to Python yourself. HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: How to record audio from Python on Mac?
I want to do this as well, and also some other audio processing via python. I have not tried yet, but much of my research points to pyaudio, PortAudio bindings for python, which is supposed to be multi- platform including Mac OS X, but as I say, I've not tried it yet. Related to this are some examples that get the audio data into numpy arrays for signal processing work. cheers, I'm interested to hear how any of this works out, I'm trying to start a python audio project in the next couple months. cheers. On Sep 9, 1:06 am, [EMAIL PROTECTED] wrote: > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > casting a broader net.) > > Can I easily control audio record/playback from Python on my Mac? I know > zip about audio recording or about Apple APIs via Python. Pointers to > simple examples would be much appreciated. > > Thanks, > > Skip -- http://mail.python.org/mailman/listinfo/python-list
dynamic allocation file buffer
I will try my idea again. I want to talk to people about a module I want to write and I will take the time to explain it. I think it's a "cool idea" that a lot of people, forgiving the slang, could benefit from. What are its flaws? A user has a file he is using either 1/ to persist binary data after the run of a single program (persistence) or 2/ share binary data between concurrently running programs (IPC / shared memory). The data are records of variable types and lengths that can change over time. He wants to change a record that's already present in the file. Here are two examples. Use Case 1: Hierarchical ElementTree-style data A user has an XML file like the one shown here. Foo ... He wants to change "Foo" to "Foobar". Foobar ... The change he wants to make is at the beginning of a 4GB file, and recopying the remainder is an unacceptable resource drain. Use Case 2: Web session logger A tutor application has written a plugin to a webbrowser that records the order of a user's mouse and keyboard activity during a browsing session, and makes them concurrently available to other applications in a suite, which are written in varying lanugages. The user takes some action, such as surfing to a site or clicking on a link. The browser plugin records that sequence into shared memory, where it is marked as acknowledged by the listener programs, and recycled back into an unused block. URLs, user inputs, and link text can be of any length, so truncating them to fit a fixed length is not an option. Existing Solutions - Shelve - A Python Standard Library shelf object can store a random access dictionary mapping strings to pickled objects. It does not provide for hierarchical data stores, and objects must be unpickled before they can be examined. - Relational Database - Separate tables of nodes, attributes, and text, and the relations between them are slow and unwieldy to reproduce the contents of a dynamic structure. The VARCHAR data type still carries a maximum size, no more flexible than fixed-length records. - POSH - Python Object Sharing - A module currently in its alpha stage promises to make it possible to store Python objects directly in shared memory. In its current form, its only entry point is 'fork' and does not offer persistence, only sharing. See: http://poshmodule.sourceforge.net/ Dynamic Allocation The traditional solution, dynamic memory allocation, is to maintain a metadata list of "free blocks" that are available to write to. See: http://en.wikipedia.org/wiki/Dynamic_memory_allocation http://en.wikipedia.org/wiki/Malloc http://en.wikipedia.org/wiki/Mmap http://en.wikipedia.org/wiki/Memory_leak The catch, and the crux of the proposal, is that the metadata must be stored in shared memory along with the data themselves. Assuming they are, a program can acquire the offset of an unused block of a sufficient size for its data, then write it to the file at that offset. The metadata can maintain the offset of one root member, to serve as a 'table of contents' or header for the remainder of the file. It can be grown and reassigned as needed. An acquaintence writes: It could be quite useful for highly concurrent systems: the overhead involved with interprocess communication can be overwhelming, and something more flexible than normal object persistence to disk might be worth having. Python Applicability The usual problems with data persistence and sharing apply. The format of the external data is only established conventionally, and conversions between Python objects and raw memory bytes take the usual overhead. 'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' currently offer this functionality, and the buffer offset obtained from 'alloc' can be used with all three. Ex 1. s= struct.Struct( 'III' ) x= alloc( s.size ) s.pack_into( mem, x, 2, 4, 6 ) Struct in its current form does not permit random access into structure contents; a user must read or write the entire converted strucutre in order to update one field. Alternative: s= struct.Struct( 'I' ) x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) s.pack_into( mem, x1, 2 ) s.pack_into( mem, x2, 4 ) s.pack_into( mem, x3, 6 ) Ex 2. class Items( ctypes.Structure ): _fields_= [ ( 'x1', ctypes.c_float ), ( 'y1', ctypes.c_float ) ] x= alloc( ctypes.sizeof( Items ) ) c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents c.x1, c.y1= 2, 4 The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. Ex 3. s= pickle.dumps( ( 2, 4, 6 ) ) x= alloc( len( s ) ) mem[ x: x+ len( s ) ]= s 'dumps' is still slow and nor does permit random access into contents. Use Cases Revisited Use Case 1: Hierarchical ElementTree-style data Solution: Dynamically allocate the tree and its elements. Node: tag: a Node: tag: b Node: tag: c Node: text: Foo The user wants to change "Foo
Re: Wx Python - Code Structure & Event Handling
Lee, have you considered using the Model-View-Presenter pattern? There is a nice example on the wxPython wiki: http://wiki.wxpython.org/ModelViewPresenter This scales well to complex GUIs. Grasping the concept and writing the initial code is the difficult part. Code is then much easier to develop and maintain. There is also the Model-View-Controller pattern. Discussions about both of these patterns can be found on the wxPython wiki and wxPython list archives. For further simplification/maintainability I would recommend using XRC resources to create your widget hierarchies where possible. My preference is to use XRCed to generate python code with the resources embedded. Again consult the wxPython wiki, wxPython list archives - plus the wxPython DEMO (under Window Layout->XMLResource) Stephen <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi, > > I have just started writing a GUI using wxpython after finding a > limitation using Tkinter. I have read most tutorials on wxpython and > slowly becoming accustomed considering I started with the latter GUI > tool first! > I must quote first that I am a novice user of python so the issue(s) I > have may seem very obvious but please be patient with me! > > I have noticed that all the wxpython references I used for creating my > application(s) "cram" all the code in the frame subclass. This is > fine when you consider small applications but what about when they > grow into very complex applications? This creates my first question : > Where is it possible to find information on wxpython code practise/ > structure when considering complex larger Gui's? > > Without any reference I decided to attempt my owm method by breaking > up the top level panels in my frame as individiual class objects. and > then construct the widgets for the panels within the respective > classes. This led to my second problem, how do I use and event in one > Panel to cause an effect in the other Panel ? For example, if I have > button in one Panel and wish to change the text of a label in the > other Panel, what is the best way to do this? Should I break the code > into modules instead? > > Of course, you may explain that the way I have approached this is > completely wrong, if so please tell me, I really want to get the basic > structure right before I start making the code more complex. > > I look forward to your help > > - > > I have listed some code below to help explain what concept I wish to > achieve, > > import wx > > class Frame(wx.Frame): >def __init__(self): >wx.Frame.__init__(self, None, > title="Application",size=(400,400)) >Panel1 = wx.Panel(self, -1,size=(200,200)) >Panel2 = wx.Panel(self, -1,size=(200,200)) >Sizer = wx.FlexGridSizer(2,2,5,5) >Sizer.Add(Panel1) >Sizer.Add(Panel2) >self.SetSizerAndFit(Sizer) >Util1 = Utils1(Panel1) >Util2 = Utils2(Panel2) > > class Utils1(): >def __init__(self, Panel): >button = wx.Button(Panel,-1, "Button 1") >Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) >self.Label = wx.StaticText(Panel,-1, "Handler to me", > name="Lab1") >Sizer = wx.BoxSizer(wx.VERTICAL) >Sizer.Add(button) >Sizer.Add(self.Label) >Panel.SetSizerAndFit(Sizer) > >def OnClick(self, Evt): >self.Label.SetLabel("you changed me") > > class Utils2(): >def __init__(self, Panel): >self.button = wx.Button(Panel,-1, "Button 2") >Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) > >def OnClick(self, Evt): >""" what is the easiest & accepted Method of changing the text > in >a different class instance?""" >pass >#???.SetLabel("you changed me") > > app = wx.PySimpleApp() > frame = Frame() > frame.Show() > app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic allocation file buffer
castironpi wrote: I will try my idea again. I want to talk to people about a module I want to write and I will take the time to explain it. I think it's a "cool idea" that a lot of people, forgiving the slang, could benefit from. What are its flaws? A user has a file he is using either 1/ to persist binary data after the run of a single program (persistence) or 2/ share binary data between concurrently running programs (IPC / shared memory). The data are records of variable types and lengths that can change over time. He wants to change a record that's already present in the file. Here are two examples. Use Case 1: Hierarchical ElementTree-style data A user has an XML file like the one shown here. Foo ... He wants to change "Foo" to "Foobar". Foobar ... The change he wants to make is at the beginning of a 4GB file, and recopying the remainder is an unacceptable resource drain. Use Case 2: Web session logger A tutor application has written a plugin to a webbrowser that records the order of a user's mouse and keyboard activity during a browsing session, and makes them concurrently available to other applications in a suite, which are written in varying lanugages. The user takes some action, such as surfing to a site or clicking on a link. The browser plugin records that sequence into shared memory, where it is marked as acknowledged by the listener programs, and recycled back into an unused block. URLs, user inputs, and link text can be of any length, so truncating them to fit a fixed length is not an option. Existing Solutions - Shelve - A Python Standard Library shelf object can store a random access dictionary mapping strings to pickled objects. It does not provide for hierarchical data stores, and objects must be unpickled before they can be examined. - Relational Database - Separate tables of nodes, attributes, and text, and the relations between them are slow and unwieldy to reproduce the contents of a dynamic structure. The VARCHAR data type still carries a maximum size, no more flexible than fixed-length records. - POSH - Python Object Sharing - A module currently in its alpha stage promises to make it possible to store Python objects directly in shared memory. In its current form, its only entry point is 'fork' and does not offer persistence, only sharing. See: http://poshmodule.sourceforge.net/ Dynamic Allocation The traditional solution, dynamic memory allocation, is to maintain a metadata list of "free blocks" that are available to write to. See: http://en.wikipedia.org/wiki/Dynamic_memory_allocation http://en.wikipedia.org/wiki/Malloc http://en.wikipedia.org/wiki/Mmap http://en.wikipedia.org/wiki/Memory_leak The catch, and the crux of the proposal, is that the metadata must be stored in shared memory along with the data themselves. Assuming they are, a program can acquire the offset of an unused block of a sufficient size for its data, then write it to the file at that offset. The metadata can maintain the offset of one root member, to serve as a 'table of contents' or header for the remainder of the file. It can be grown and reassigned as needed. An acquaintence writes: It could be quite useful for highly concurrent systems: the overhead involved with interprocess communication can be overwhelming, and something more flexible than normal object persistence to disk might be worth having. Python Applicability The usual problems with data persistence and sharing apply. The format of the external data is only established conventionally, and conversions between Python objects and raw memory bytes take the usual overhead. 'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' currently offer this functionality, and the buffer offset obtained from 'alloc' can be used with all three. Ex 1. s= struct.Struct( 'III' ) x= alloc( s.size ) s.pack_into( mem, x, 2, 4, 6 ) Struct in its current form does not permit random access into structure contents; a user must read or write the entire converted strucutre in order to update one field. Alternative: s= struct.Struct( 'I' ) x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) s.pack_into( mem, x1, 2 ) s.pack_into( mem, x2, 4 ) s.pack_into( mem, x3, 6 ) Ex 2. class Items( ctypes.Structure ): _fields_= [ ( 'x1', ctypes.c_float ), ( 'y1', ctypes.c_float ) ] x= alloc( ctypes.sizeof( Items ) ) c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents c.x1, c.y1= 2, 4 The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. Ex 3. s= pickle.dumps( ( 2, 4, 6 ) ) x= alloc( len( s ) ) mem[ x: x+ len( s ) ]= s 'dumps' is still slow and nor does permit random access into contents. Use Cases Revisited Use Case 1: Hierarchical ElementTree-style data Solution: Dynamically allocate the tree and its elements. Node: tag: a Node: tag: b Node: tag: c Node: text: Foo The user
Re: wxpython ms-dos black window popping up in background
On 9 sep, 23:35, icarus <[EMAIL PROTECTED]> wrote: > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > That did it. > > one more question... > > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? > > My intent is to have the process transparent to the user. He wouldn't > even know the app was written in python. All he knows that when he > double-clicks on it, the application pops up without the DOS black > screen in the background (for w32 users.) > > On Sep 9, 10:49 am, "Chris Rebert" <[EMAIL PROTECTED]> wrote: > > > You need to have the script be run by pythonw.exe as opposed to python.exe > > pythonw.exe suppresses the DOS box from coming up and should be used > > for running GUI applications such as yours. > > > Regards, > > Chris > > > On Tue, Sep 9, 2008 at 1:33 PM, icarus <[EMAIL PROTECTED]> wrote: > > > platform: windows xp professional, python 2.5, wxpython > > > > When I double-check on my program file test.py (for simplicity I'll be > > > using this code below), I see the window just fine. But the ms-dos > > > black window pops up in the background. On Linux, no issues at all. > > > > How can I get rid of that ms-dos black window in the background? > > > something I need to add to my code? a setting to adjust in windows? > > > thanks in advance. > > > > #!/usr/bin/python > > > import wx > > > > appwx = wx.App() > > > > frame = wx.Frame(None, -1, 'test.py') > > > frame.Show() > > > > appwx.MainLoop() > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > -- > > Follow the path of the Iguana...http://rebertia.com py2exe could be what you are looking for. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython ms-dos black window popping up in background
icarus wrote: Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw That did it. one more question... how do I create a pythonw standalone executable that works on w32, linux, mac, etc..? My intent is to have the process transparent to the user. He wouldn't even know the app was written in python. All he knows that when he double-clicks on it, the application pops up without the DOS black screen in the background (for w32 users.) On Sep 9, 10:49 am, "Chris Rebert" <[EMAIL PROTECTED]> wrote: You need to have the script be run by pythonw.exe as opposed to python.exe pythonw.exe suppresses the DOS box from coming up and should be used for running GUI applications such as yours. Regards, Chris On Tue, Sep 9, 2008 at 1:33 PM, icarus <[EMAIL PROTECTED]> wrote: platform: windows xp professional, python 2.5, wxpython When I double-check on my program file test.py (for simplicity I'll be using this code below), I see the window just fine. But the ms-dos black window pops up in the background. On Linux, no issues at all. How can I get rid of that ms-dos black window in the background? something I need to add to my code? a setting to adjust in windows? thanks in advance. #!/usr/bin/python import wx appwx = wx.App() frame = wx.Frame(None, -1, 'test.py') frame.Show() appwx.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list -- Follow the path of the Iguana...http://rebertia.com On Windows use py2exe and Inno Setup to create "frozen" application that is easy to distribute. On Mac/Linux there are other solutions. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic allocation file buffer
On Tue, 09 Sep 2008 14:59:19 -0700, castironpi wrote: > I will try my idea again. I want to talk to people about a module I > want to write and I will take the time to explain it. I think it's a > "cool idea" that a lot of people, forgiving the slang, could benefit > from. What are its flaws? [snip long description with not-very-credible use-cases] You've created a solution to a problem which (probably) only affects a very small number of people, at least judging by your use-cases. Who has a 4GB XML file, and how much crack did they smoke? Castironpi, what do *you* use this proof-of-concept module for? Don't bother tell us what you think *we* should use it for. Tell us what you're using it for, or at least what somebody else is using it for. If this is just a module that you think will be cool, I don't like your chances of people caring. There is no shortage of "cool" software that isn't useful for anything, and unlike eye-candy, nobody is going to use your module just because they like the algorithm. If you don't have an existing application for the software, then explain what it does (not how) and give some idea of the performance ("it's alpha and written in Python and really slow, but I will re-write it in C and expect it to make a billion random accesses in a 10GB file per millisecond", or whatever). You might be lucky and have somebody say "Hey, that's just the tool I need to solve my problem!". -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Cancel instance create
On Sep 6, 1:23 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > Mohamed Yousef schrieb: > > > ðWhat about no Constructor , and a custom instancing function that can > > return either None or the instance wanted > > That doesn't solve the underlying problem - the instance is created. > Just because it wasn't *returned*, doesn't mean it isn't there. > > Diez def __new__(cls, *args, **kwargs): if some_condition: return None return object.__new__(cls) Michael Foord -- http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list
Pexpect echoes twice for each read
For some reason, Using pexpect causes my output to echo twice when I connect from my MAC Darwin (10.4) to Linux (CentOS release 5 ): The program: - #!/usr/bin/python # Automatic scp to remote host # Input 1 : filename # Input 2 : destination folder # Input 3 : hostname import pexpect import sys,re ssh_cmd = "ssh " + sys.argv[3] ssh_handle = pexpect.spawn (ssh_cmd) ssh_handle.logfile = sys.stdout PROMPT = "\$\ $" try: ssh_handle.expect(PROMPT) ssh_handle.sendline ("scp "+ sys.argv[1] +" [EMAIL PROTECTED]:" + sys.argv[2] ) ssh_handle.expect("password:") ssh_handle.sendline(" ") ssh_handle.expect(PROMPT) except pexpect.TIMEOUT: ssh_handle.logfile.write("\n Pexpect timeout !!\n") sys.exit(1) except KeyboardInterrupt: ssh_handle.logfile.write("\n User interrupt!\n") sys.exit(2) ssh_handle.close() Output: --- $ python pexpect_test.py replace_line_break.sh /tmp/ 10.5.254.18 Last login: Tue Sep 9 15:45:05 2008 from sriram-macbook.dhcp.2wire.com $ scp replace_line_break.sh [EMAIL PROTECTED]:/tmp/ scp replace_line_break.sh [EMAIL PROTECTED]:/tmp/ [EMAIL PROTECTED]'s password: replace_line_break.sh 100% 296 0.3KB/s 00:00 $ $ -- http://mail.python.org/mailman/listinfo/python-list
Looking for a Duo - file comparison and a file parser
HI, I'm thinking of writing a file comparison utility in python. This utility will work as: 1. Compare 2 files for the differences. Both files contain some numerical results. 2. Generate a common file containing the differences (the same way as 'diff' generate an output) 3. Now, I will parse this file containing differences to check as to how much is the difference of one file from other. So, for this I hope a parser will be required. Is there a utility available that performs similar job ( that some one might have created considering the huge number of users of python) ? Or may be some one has written some parser? Any help is greatly appreciated. Thanks and regards, Rajat -- http://mail.python.org/mailman/listinfo/python-list
Re: universal unicode font for reportlab
Jeroen Ruigrok van der Werven wrote: -On [20080909 05:23], Terry Reedy ([EMAIL PROTECTED]) wrote: Ariel Unicode MS is the one that seems pretty complete. Not really. It misses a lot of characters. Well, it has Latin, Greek, Cyrillic, Hebrew, Arabic, several south Asian, Tibetan, CJK, Japanese, Korean, and numerous symbols and special forms. I don't know what it misses, but I think that covers what the OP asked for. -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] top-posting and quoting
Bruno Desthuilliers <[EMAIL PROTECTED]> writes: > Could you please timh and belindelof learn to quote properly and stop > top-posting ? In case it's not clear, by "quote properly" I believe Bruno means to trim quoted material irrelevant to one's reply, and use standard inline replies http://en.wikipedia.org/wiki/Posting_style#Inline_replying>. Certainly that's what I'd prefer to see. -- \“None can love freedom heartily, but good men; the rest love | `\ not freedom, but license.” —John Milton | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a Duo - file comparison and a file parser
[EMAIL PROTECTED] wrote: HI, I'm thinking of writing a file comparison utility in python. This utility will work as: 1. Compare 2 files for the differences. Both files contain some numerical results. 2. Generate a common file containing the differences (the same way as 'diff' generate an output) 3. Now, I will parse this file containing differences to check as to how much is the difference of one file from other. So, for this I hope a parser will be required. Is there a utility available that performs similar job ( that some one might have created considering the huge number of users of python) ? Or may be some one has written some parser? There are a couple of ways to do #3. One would be to use the difflib module from the standard library. The Differ.compare() method will give you a sequence of lines with prefixed character saying whether the line was the same in both files, deleted from the first or added by the second. Lines that are recognized as having changed (rather than just being deleted then readded with modifications) are also noted. The parsing you would have to do would be minimal. http://docs.python.org/dev/library/difflib Or you could use diff and diffstat: http://invisible-island.net/diffstat/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic allocation file buffer
On Sep 9, 5:44 pm, Larry Bates <[EMAIL PROTECTED]> wrote: > castironpi wrote: > > I will try my idea again. I want to talk to people about a module I > > want to write and I will take the time to explain it. I think it's a > > "cool idea" that a lot of people, forgiving the slang, could benefit > > from. What are its flaws? > > > A user has a file he is using either 1/ to persist binary data after > > the run of a single program (persistence) or 2/ share binary data > > between concurrently running programs (IPC / shared memory). The data > > are records of variable types and lengths that can change over time. > > He wants to change a record that's already present in the file. Here > > are two examples. > > > Use Case 1: Hierarchical ElementTree-style data > > > A user has an XML file like the one shown here. > > > > > > > Foo > > > > ... > > > He wants to change "Foo" to "Foobar". > > > > > > > Foobar > > > > ... > > > The change he wants to make is at the beginning of a 4GB file, and > > recopying the remainder is an unacceptable resource drain. > > > Use Case 2: Web session logger > > > A tutor application has written a plugin to a webbrowser that records > > the order of a user's mouse and keyboard activity during a browsing > > session, and makes them concurrently available to other applications > > in a suite, which are written in varying lanugages. The user takes > > some action, such as surfing to a site or clicking on a link. The > > browser plugin records that sequence into shared memory, where it is > > marked as acknowledged by the listener programs, and recycled back > > into an unused block. URLs, user inputs, and link text can be of any > > length, so truncating them to fit a fixed length is not an option. > > > Existing Solutions > > > - Shelve - A Python Standard Library shelf object can store a random > > access dictionary mapping strings to pickled objects. It does not > > provide for hierarchical data stores, and objects must be unpickled > > before they can be examined. > > - Relational Database - Separate tables of nodes, attributes, and > > text, and the relations between them are slow and unwieldy to > > reproduce the contents of a dynamic structure. The VARCHAR data type > > still carries a maximum size, no more flexible than fixed-length > > records. > > - POSH - Python Object Sharing - A module currently in its alpha stage > > promises to make it possible to store Python objects directly in > > shared memory. In its current form, its only entry point is 'fork' > > and does not offer persistence, only sharing. See: > > http://poshmodule.sourceforge.net/ > > > Dynamic Allocation > > > The traditional solution, dynamic memory allocation, is to maintain a > > metadata list of "free blocks" that are available to write to. See: > > http://en.wikipedia.org/wiki/Dynamic_memory_allocation > > http://en.wikipedia.org/wiki/Malloc > > http://en.wikipedia.org/wiki/Mmap > > http://en.wikipedia.org/wiki/Memory_leak > > The catch, and the crux of the proposal, is that the metadata must be > > stored in shared memory along with the data themselves. Assuming they > > are, a program can acquire the offset of an unused block of a > > sufficient size for its data, then write it to the file at that > > offset. The metadata can maintain the offset of one root member, to > > serve as a 'table of contents' or header for the remainder of the > > file. It can be grown and reassigned as needed. > > > An acquaintence writes: It could be quite useful for highly concurrent > > systems: the overhead involved with interprocess communication can be > > overwhelming, and something more flexible than normal object > > persistence to disk might be worth having. > > > Python Applicability > > > The usual problems with data persistence and sharing apply. The > > format of the external data is only established conventionally, and > > conversions between Python objects and raw memory bytes take the usual > > overhead. 'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' > > currently offer this functionality, and the buffer offset obtained > > from 'alloc' can be used with all three. > > > Ex 1. > > s= struct.Struct( 'III' ) > > x= alloc( s.size ) > > s.pack_into( mem, x, 2, 4, 6 ) > > Struct in its current form does not permit random access into > > structure contents; a user must read or write the entire converted > > strucutre in order to update one field. Alternative: > > s= struct.Struct( 'I' ) > > x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) > > s.pack_into( mem, x1, 2 ) > > s.pack_into( mem, x2, 4 ) > > s.pack_into( mem, x3, 6 ) > > > Ex 2. > > class Items( ctypes.Structure ): > > _fields_= [ > > ( 'x1', ctypes.c_float ), > > ( 'y1', ctypes.c_float ) ] > > x= alloc( ctypes.sizeof( Items ) ) > > c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents > >
Re: rss feed generation
On Sep 10, 7:30 am, "Blake Garner" <[EMAIL PROTECTED]> wrote: > I'm looking for suggestions on how to approach generating rss feed > .xml files using python. What modules to people recommend I start > with? http://www.dalkescientific.com/Python/PyRSS2Gen.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Read and write binary data
On Sep 7, 6:41 pm, Mars creature <[EMAIL PROTECTED]> wrote: > Hi guys, > I am new to Python, and thinking about migrating to it from matlab > as it is a really cool language. Right now, I am trying to figure out > how to control read and write binary data, like > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > I googled, but can not find a clear answer. Anyone has clue where can > I learn it? Thanks!! > Jinbo the struct module should be useful -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic allocation file buffer
On Sep 9, 5:58 pm, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > On Tue, 09 Sep 2008 14:59:19 -0700, castironpi wrote: > > I will try my idea again. I want to talk to people about a module I > > want to write and I will take the time to explain it. I think it's a > > "cool idea" that a lot of people, forgiving the slang, could benefit > > from. What are its flaws? > > [snip long description with not-very-credible use-cases] Steven, > You've created a solution to a problem which (probably) only affects a > very small number of people, at least judging by your use-cases. Who has > a 4GB XML file, and how much crack did they smoke? I judge from the existence of 'shelve' and 'pickle' modules, and relational database packages, that the problem I am addressing is not rare. It could be the millionaire investor across the street, the venture capitalist down the hall, or the guy with a huge CD catalog. > Castironpi, what do *you* use this proof-of-concept module for? Honestly, nothing yet. I just wrote it. My user community and customer base are very small. Originally, I wanted to store variable- length strings in a file, where shelves and databases were overkill. I created it for its beauty, sorry to disappoint. > Don't > bother tell us what you think *we* should use it for. Tell us what you're > using it for, or at least what somebody else is using it for. If this is > just a module that you think will be cool, I don't like your chances of > people caring. There is no shortage of "cool" software that isn't useful > for anything, and unlike eye-candy, nobody is going to use your module > just because they like the algorithm. Unfortunately, nobody is going to care about most of the uses I have for it 'til I have a job. I'm goofing around with a laptop, remembering when my databases professor kept dropping the ball on VARCHARs. If you want a sound byte, think, "imagine programming without 'new' and 'malloc'." > If you don't have an existing application for the software, then explain > what it does (not how) and give some idea of the performance ("it's alpha > and written in Python and really slow, but I will re-write it in C and > expect it to make a billion random accesses in a 10GB file per > millisecond", or whatever). You might be lucky and have somebody say > "Hey, that's just the tool I need to solve my problem!". I wrote a Rope implementation just to test drive it. It exceeded the native immutable string type at 2 megs. It used 'struct' instead of 'ctypes', so that number could conceivably come down. I am intending to leave it in pure Python, so there. > -- > Steven Pleasure chatting as always sir. -- http://mail.python.org/mailman/listinfo/python-list
Re: Coming from .NET and VB and C
On Sep 8, 9:31 pm, sturlamolden <[EMAIL PROTECTED]> wrote: > On 3 Sep, 18:52, ToPostMustJoinGroup22 <[EMAIL PROTECTED]> > wrote: > > > I'm coming from a .NET, VB, C background. > > Any suggestions for someone new to the scene like me? > > Welcome! Unfortunately, you probably have a lot of bad habits to > unlearn. Don't use Python like another C, VB or Java. It will cause a > lot of grief, and you'll end up with the idea that Python is slow like > a slug. Python is more like Lisp or Haskell, but with a readable > syntax. There are list comprehensions, generator expressions, > dictionaries, sets, lists, list slicing, lambdas, map, reduce, filter, > closures, etc. They are there to be used, and be used a lot. Learning > to use Python efficiently is what has the steepest learning curve. Variable argument lists, first-class function objects. -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic allocation file buffer
On Sep 9, 5:59 pm, castironpi <[EMAIL PROTECTED]> wrote: > I will try my idea again. I want to talk to people about a > module I want to write and I will take the time to explain it. > I think it's a "cool idea" that a lot of people, forgiving the > slang, could benefit from. > > (snipped) > > A pure Python alloc-free implementation based on the GNU PAVL > tree library is on Google Code. It is only in proof-of-concept > form and not commented, but does contain a first-pass test > suite. See: > http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk So at best (i.e. if it actually makes any sense; I didn't read it), this is an ANNouncement of a pre-alpha piece of code. ANN posts rarely attract replies, even when they are about production/stable software. Thankfully, most people don't expect (let alone "require") readers to share their interest or enthusiasm by replying to the ANN. Given your past semi-coherent and incoherent posts, expecting people to jump on such a thread is a rather tall order. George -- http://mail.python.org/mailman/listinfo/python-list
Re: Clearing a session and reload() problem (with repro error)
On Sep 9, 11:03 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Mon, 08 Sep 2008 05:37:24 -0300,Rafe<[EMAIL PROTECTED]> escribió: > ... > This dependency between modules, applied to all modules in your project, > defines a "dependency graph". In some cases, one can define a partial > ordering of its nodes, such that no module depends on any other module > *after* it (it may depend only on modules *before* it). Look for > "topological sort". > > Doing that in the generic case is not easy. If you *know* your > dependencies, reload the modules in the right order by hand. > ... > -- > Gabriel Genellina Hi Gabriel, Thank you for clarifying and re-presenting parts of my case. I appreciate the time. I was hoping there would be a way to just wipe out the module cache and let it get rebuilt by executing my code (since I'm not using reload as part of my program, but rather, to test it in an environment where I cannot restart the Python session). I have been keeping a diagram of my module inheritance to make sure it is as clean as possible, so I could just right a list of reloads as you suggest. However, one of the sub-packages is designed to allow users to add more modules. Because these get dynamically imported, a guess I could add an argument to the reload function to allow a user to give the 'add-on' module they are working on... so much work just to get a clean environment... Separate of my program, I was really hoping to write a generic reload tool for anyone developing in the same application as I am. I just don't see a way to trace import dependencies in systems which include dynamic imports. Any ideas? Thanks again, - Rafe -- http://mail.python.org/mailman/listinfo/python-list
Simplest solution for formatting local time in iso 8601 including time zone.
What's the simplest solution for formatting the output of local time in iso 8601 including the time zone information? Example: "2008-07-25T14:28:43.934-04:00" Thanks, Rowland -- http://mail.python.org/mailman/listinfo/python-list
NumPy arrays that use memory allocated from other libraries or tools
I wanted to point anybody interested to a blog post that describes a useful pattern for having a NumPy array that points to the memory created by a different memory manager than the standard one used by NumPy. The pattern shows how to create a NumPy array that points to previously allocated memory and then shows how to construct an object that allows the correct deallocator to be called when the NumPy array is freed. This may be useful if you are wrapping code that has it's own memory management scheme. Comments and feedback is welcome. The post is http://blog.enthought.com/?p=62 Best regards, -Travis Oliphant -- http://mail.python.org/mailman/listinfo/python-list
Re: Simplest solution for formatting local time in iso 8601 including time zone.
On Tue, Sep 9, 2008 at 9:32 PM, <[EMAIL PROTECTED]> wrote: > What's the simplest solution for formatting the output of local time > in iso 8601 including the time zone information? > > Example: > >"2008-07-25T14:28:43.934-04:00" You want the isoformat() method of datetime objects. See http://docs.python.org/lib/datetime-datetime.html for details. You'll need to pass 'T' as the separator to isoformat() and pass in a tzinfo object when constructing the datetime object. Regards, Chris > > > Thanks, > Rowland > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list