Re: What happened with python? messed strings?
(top posting fixed; please keep discussion on this list) --- [EMAIL PROTECTED] escribió: In article [EMAIL PROTECTED] you wrote: En Sun, 20 Apr 2008 15:54:20 -0300, [EMAIL PROTECTED] escribi?: I used extensively python and now I find this mess with strings, I can't even reproduce tutorial examples: apfel.encode('utf-8') (it was with umlaut) File stdin, line 0 ^ SyntaxError: 'ascii' codec can't decode byte 0xc4 in position 1: ordinal not in range(128) Is there any good guide to this mess of codecs and hell ? [two links to unicode introductory articles] ok, and how do you explain that even the tutorial example is broken ??? Which tutorial example? -- Gabriel Genellina Los referentes más importantes en compra/ venta de autos se juntaron: Demotores y Yahoo! Ahora comprar o vender tu auto es más fácil. Vistá ar.autos.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
DO YOU KNOW ANY THING ABOUT ISLAM???
What you are about to read might sound unusual but it could be very enlightened. So I would be thankful if you give my article 5 minute of your value time. THANK YOU Islam is a total system of living. A Muslim is supposed to live in peace and harmony with all these segments; hence, a Muslim is any person anywhere in the world whose obedience, allegiance, and loyalty are to God, the Lord of the Universe. The legal sources of Islam are the Qur'an and the Hadith. The Qur'an is the exact word of God; its authenticity, originality and totality are intact. The Hadith is the report of the sayings, deeds and approvals of the Prophet Muhammad. The Prophet's sayings and deeds are called Sunnah. The Seerah is the writings of followers of Muhammad about the life of the Prophet. Hence, it is the life history of the Prophet Muhammad which provides examples of daily living for Muslims. Muslims are required to respect all those who are faithful and God conscious people, namely those who received messages. Christians and Jews are called People of the Book. Muslims are asked to call upon the People of the Book for common terms, namely, to worship One God, and to work together for the solutions of the many problems in the society. Some Basic Islamic Beliefs 1) Belief in God: Muslims believe in one, unique, incomparable God, Who has no son nor partner, and that none has the right to be worshipped but Him alone. He is the true God, and every other deity is false. He has the most magnificent names and sublime perfect attributes. No one shares His divinity, nor His attributes. In the Quran, God describes Himself: Say, “He is God, the One. God, to Whom the creatures turn for their needs. He begets not, nor was He begotten, and there is none like Him.” (Quran, 112:1-4) Chapter 112 of the Quran written in Arabic calligraphy. No one has the right to be invoked, supplicated, prayed to, or shown any act of worship, but God alone. God alone is the Almighty, the Creator, the Sovereign, and the Sustainer of everything in the whole universe. He manages all affairs. He stands in need of none of His creatures, and all His creatures depend on Him for all that they need. He is the All- Hearing, the All-Seeing, and the All-Knowing. In a perfect manner, His knowledge encompasses all things, the open and the secret, and the public and the private. He knows what has happened, what will happen, and how it will happen. No affair occurs in the whole world except by His will. Whatever He wills is, and whatever He does not will is not and will never be. His will is above the will of all the creatures. He has power over all things, and He is able to do everything. He is the Most Gracious, the Most Merciful, and the Most Beneficent. In one of the sayings of the Prophet Muhammad , we are told that God is more merciful to His creatures than a mother to her child.1 God is far removed from injustice and tyranny. He is All-Wise in all of His actions and decrees. If someone wants something from God, he or she can ask God directly without asking anyone else to intercede with God for him or her. God is not Jesus, and Jesus is not God.2 Even Jesus himself rejected this. God has said in the Quran: Indeed, they have disbelieved who have said, “God is the Messiah (Jesus), son of Mary.” The Messiah said, “Children of Israel, worship God, my Lord and your Lord. Whoever associates partners in worship with God, then God has forbidden Paradise for him, and his home is the Fire (Hell). For the wrongdoers,3 there will be no helpers.” (Quran, 5:72) God is not a trinity. God has said in the Quran: Indeed, they disbelieve who say, “God is the third of three (in a trinity),” when there is no god but one God. If they desist not from what they say, truly, a painful punishment will befall the disbelievers among them. Would they not rather repent to God and ask His forgiveness? For God is Oft-Forgiving, Most Merciful. The Messiah (Jesus), son of Mary, was no more than a messenger... (Quran, 5:73-75) Islam rejects that God rested on the seventh day of the creation, that He wrestled with one of His angels, that He is an envious plotter against mankind, or that He is incarnate in any human being. Islam also rejects the attribution of any human form to God. All of these are considered blasphemous. God is the Exalted. He is far removed from every imperfection. He never becomes weary. He does not become drowsy nor does he sleep. The Arabic word Allah means God (the one and only true God who created the whole universe). This word Allah is a name for God, which is used by Arabic speakers, both Arab Muslims and Arab Christians. This word cannot be used to designate anything other than the one true God. The Arabic word Allah occurs in the Quran about 2700 times. In Aramaic, a language related closely to Arabic and the language that Jesus habitually spoke,4 God is also referred to as Allah. 2) Belief in the Angels:
Re: library to do easy shell scripting in Python
Wow, this message turned out to be *LONG*. And it also took a long time to write. But I had fun with it, so ok. :-) Michael Torrie wrote: Recently a post that mentioned a recipe that extended subprocess to allow killable processes caused me to do some thinking. Some of my larger bash scripts are starting to become a bit unwieldy (hundreds of lines of code). Yet for many things bash just works out so well because it is so close to the file system and processes. As part of another project, I now have need of a really good library to make it almost as easy to do things in Python as it is in Bash. With a simple wrapper around subprocess, I'm pretty much able to do most things. Most of my complicated bash hackery involves using awk, sed, grep, and cut to process text, which python does quite nicely, thank you very much. But there's a few things to add. To wit, I'm wanting to write a library that can deal with the following things: - spawn a process, feed it std in, get stdout, stderr, and err code. This is largely already accomplished by subprocess It is accomplished by subprocess.Popen: The 'communicate' method handles stdin, stdout and stderr, waiting for the process to terminate. The 'wait' method just waits for the process to terminate and returns the return code. The 'returncode' attribute contains the return code (or None if the process hasn't terminated yet). You could write a convenience wrapper function if you want to do this in a more terse way. - spawn off processes as background daemons Couldn't you do this with subprocess by doing subprocess.Popen([prog]) and, well, nothing else? (You may have/want to set stdin/stdout/stderr too. I dunno.) - spawn multiple processes and pipe output to input. - can do fancier things like bash does, like combine stderr/stdout, switch stderr/stdout, redirects to and from files That's possible with subprocess. See this paragraph of http://docs.python.org/lib/node528.html: stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. And also http://docs.python.org/lib/node535.html. Not the least verbose, but pretty simple, and I bet it can do anything bash can. - transparently allow a python function or object to be a part of the pipeline at any stage. Hmmm. I can't think very well at the moment, but you could create file-like objects that do...I dunno, callbacks or something. Simple and incomplete mockup: class Pipe(object): def __init__(self, from_fh, to_fh, from_callback=None, to_callback=None): self.from_fh = from_fh self.to_fh = to_fh self.from_callback = from_callback self.to_callback = to_callback def read(self, *args, **kwargs): data = self.from_fh.read(*args, **kwargs) if self.from_callback is not None: self.from_callback(data) return data def write(self, data): # XXX Call the callback before or after the data is actually written? if self.to_callback is not None: self.to_callback(data) return self.to_fh.write(data) That just passes input and output through itself, also passing it to callback functions. You'd have to add all the other methods too, like readline and __iter__... Maybe inheriting from 'file' would get most of them. I dunno how it works internally. Questions include, how would one design the interface for things, like assembling pipes? Several ideas include: pipe([prog1,args],[prog2,args],...) or run([prog1,args]).pipe([prog2,args]).pipe(...) The former doesn't deal very well with re-plumbing of the pipes, nor is there an easy way to redirect to and from a file. The second syntax is more flexible but a bit cumbersome. Also it doesn't allow redirection or flexible plumbing either. Any ideas on how I could design this? Ok, the below is an edited-down, more formal-sounding brain dump. Idea 1: run([prog, args], from_fh, to_fh, from_callback, to_callback).run(...) It would basically just automate the construction of the intermediary pipe objects suggested above. It could also be done with tuples, like: run([prog, args], (from_fh, to_fh), (from_callback, to_callback)).run(...) Idea 2: This one would parse a list similar to a bash command line. run('prog', 'out', '|', 'other_prog', 'arg', '', 'foo.txt') Which would be like a bash: `prog 21 | other_prog arg foo.txt` (21 is how you combine stdout and stderr, right?) , ,
Re: Unix Device File Emulation
On 2008-04-23, blaine [EMAIL PROTECTED] wrote: On Apr 23, 2:01 pm, Martin Blume [EMAIL PROTECTED] wrote: blaine schrieb No, while 1: r = self.fifodev.readline() if r: print r else: time.sleep(0.1) is ok (note the if r: clause). Martin Beautiful! Thanks Martin! yes, but you have to follow the usual file handling rules, and close/re-open the fifo after detecting EOF. You will be blocked on attempting to re-open until there is another writing process. while 1: fp = open('my_fifo', 'r') while 1: line = fp.readline() if line == '': break print line.rstrip()# To prevent printing of \n in line fp.close() Albert -- http://mail.python.org/mailman/listinfo/python-list
annoying dictionary problem, non-existing keys
i use dictionaries to hold some config data, such as: conf={'key1':'value1','key2':'value2'} and so on... when i try to process conf, i have to code every time like: if conf.has_key('key1'): if conf['key1']'': other commands this is very annoying. in php, i was able to code only like: if conf['key1']=='someth' in python, this fails, because, if key1 does not exists, it raises an exception. MY question: is there a way to directly get value of an array/tuple/dict item by key, as in php above, even if key may not exist, i should not check if key exist, i should only use it, if it does not exist, it may return only empty, just as in php i hope you understand my question... -- İ.Bahattin Vidinli Elk-Elektronik Müh. --- iletisim bilgileri (Tercih sirasina gore): skype: bvidinli (sesli gorusme icin, www.skype.com) msn: [EMAIL PROTECTED] yahoo: bvidinli +90.532.7990607 +90.505.5667711 -- http://mail.python.org/mailman/listinfo/python-list
Re: python-ldap - Operations Error
Jason Scheirer wrote: On Apr 23, 5:16 pm, [EMAIL PROTECTED] wrote: Hello all, I am trying to integrate TurboGears with our Active Directory here at the office. TurboGears aside, i cannot get this to work. Seems more promising: http://tgolden.sc.sabren.com/python/active_directory.html This is based on ADSI? Then the caveat is that it only runs on Windows. Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: RE: Lucky gay sucking cock while butt fucked deep
in 344018 20080422 231351 Blubaugh, David A. [EMAIL PROTECTED] wrote: Is there a way to block these messages. I do not want to be caught with filth such as this material. I could lose my job with Belcan with evil messages such as these messages. =20 So don't repeat them! -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] annoying dictionary problem, non-existing keys
On Thu, Apr 24, 2008 at 11:13:25AM +0300, bvidinli wrote: if conf.has_key('key1'): if conf['key1']'': other commands this is very annoying. in php, i was able to code only like: if conf['key1']=='someth' in python, this fails, because, if key1 does not exists, it raises an exception. if conf.get('key1')=='someth':... PS. Please do not cross-post so extensively. Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] annoying dictionary problem, non-existing keys
this is very annoying. Posting to so many lists is even more annoying. You might not get a single helpful answer just because people are so frustrated by this behavior. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: annoying dictionary problem, non-existing keys
bvidinli wrote: i use dictionaries to hold some config data, such as: conf={'key1':'value1','key2':'value2'} and so on... when i try to process conf, i have to code every time like: if conf.has_key('key1'): if conf['key1']'': other commands this is very annoying. in php, i was able to code only like: if conf['key1']=='someth' in python, this fails, because, if key1 does not exists, it raises an exception. MY question: is there a way to directly get value of an array/tuple/dict item by key, as in php above, even if key may not exist, i should not check if key exist, i should only use it, if it does not exist, it may return only empty, just as in php i hope you understand my question... If I understand correctly you want default values for non-existing keys. There are two ways for achieving this: Way 1: use the get() method of the dict object: conf.get(key, default) which is the same as: conf[key] if key in conf else default Way 2: make conf a defaultdict instead of a dict, the documentation is there: http://docs.python.org/lib/defaultdict-objects.html Hope this helps, RB -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] annoying dictionary problem, non-existing keys
I posted to so many lists because, this issue is related to all lists, this is an idea for python, this is related to development of python... why are you so much defensive ? i think ideas all important for development of python, software i am sory anyway hope will be helpful. 2008/4/24, Terry Reedy [EMAIL PROTECTED]: Python-dev is for discussion of development of future Python. Use python-list / comp.lang.python / gmane.comp.python.general for usage questions. ___ Python-Dev mailing list [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/bvidinli%40gmail.com -- İ.Bahattin Vidinli Elk-Elektronik Müh. --- iletisim bilgileri (Tercih sirasina gore): skype: bvidinli (sesli gorusme icin, www.skype.com) msn: [EMAIL PROTECTED] yahoo: bvidinli +90.532.7990607 +90.505.5667711 -- http://mail.python.org/mailman/listinfo/python-list
Re: Explicit variable declaration
Filip Gruszczynski [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | If you want to just declare that name exist, but doesn't want to | declare the type, why don't you just do this: Names do not 'exist' in Python, nor do they have types. They are bound to objects that have types. Learn to program Python as Python, not one of those languages with a quite different model of names and values. | def somefunc(): | nonlocal = nonlocal Syntax error in 3.0. Error or nonsense in 2.x | local = 0 # or None or [] or an initial value | # | return nonlocal * local | | Err.. I don't quite get. How it may help me? Could you explain? Forget the above. The only 'declarations' in Python, 'global' and 'nonlocal' are for the specialized purpose of *binding* names that are not in the local namespace of a function or nested function. They are only needed because otherwise names that get bound are otherwise assumed to be local. See the language ref section on function defs. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: function that accepts any amount of arguments?
globalrev [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | if i want a function that can take any amount of arguments how do i | do? | | lets say i want a function average that accepts any number of integers | and returns the average. To add to the other comments, read the ref manual section of function defs. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] annoying dictionary problem, non-existing keys
bvidinli wrote: I posted to so many lists because, this issue is related to all lists, this is an idea for python, this is related to development of python... why are you so much defensive ? i think ideas all important for development of python, software i am sory anyway hope will be helpful. 2008/4/24, Terry Reedy [EMAIL PROTECTED]: Python-dev is for discussion of development of future Python. Use python-list / comp.lang.python / gmane.comp.python.general for usage questions. ___ Python-Dev mailing list [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/bvidinli%40gmail.com Is this an acceptable alternative? try: if conf['key1'] == 'something': ur commands except KeyError: pass Regards, Karthik -- http://mail.python.org/mailman/listinfo/python-list
Re: @classmethod question
Scott SA a écrit : Hi, I'm using the @classemethod decorator for some convenience methods and for some reason, either mental block or otherwise, can't seem to figure out how to elegantly detect if the call is from an instance or not. Well, the point is that a classmethod *always* receive the class as first argument, wether it's called on the class or an instance. If that's not what you want, then you don't use the right tool. Here's the problem: Within the class definition, 'isinstance' has nothing to compare to because the class does not appear to exist. This is NOT a great example, but it outlines the the code: class RecipieClass: def __init__(self): pass @classmethod def get_ingrendients(self, recipie_list=None): if isinstnace(self,RecipieClass): return self.do_something_interesting() else: return do_something_boring(recipie_list) Yes, I can test to see if the param exists, but that makes the call exclusive i.e. I can _only_ call it as an instance or with a parameter. Why am I doing this? It is a series of convenience methods, in this case I'm interacting with a database via an ORM (object-relational model). out of curiosity : which one ? I want the ability to call a class-ojbect and get related values, or pass some criteria and get related values for them without collecting the records first as instances, then iterating them. I need to call this from several places so I want to be DRY (don't repeat yourself). The easiest way to describe this as an analogy would be like having a recipie for cookies and wanting to know all of the ingredients ahead of time. Then, at another time, wanting to know what all the ingredients would be to make cookies, cake and bread (i.e. complete shopping list). cookie_recipie = RecipieClass.get_recipie('cookies') cookie_recipie.get_ingredients() 2C Flour 0.5 C Sugar ... RecipieClass.get_ingrendients(['cookies','cake','bread']) 8C Flour 2C Sugar ... Of course any suggestions on how this might be better approached would be interesting too. Why do you want the same method to do two different things ? You clearly have two distincts methods doing different things here, and as a user of your code I'd find your API confusing. May I suggest a much simpler approach: class Recipies(object): @property def ingredients(self): return dict of ingredient:qty for self @classmethod def get_ingredients_for(cls, *id_recipies): return dict of ingredient:summed_qty for all id_recipies print Recipie.get('cookie').ingredients print Recipies.get_ingredients_for('cookie', 'cake', 'bread') My 2 cents... -- http://mail.python.org/mailman/listinfo/python-list
Re: python-ldap - Operations Error
Michael Ströder wrote: Jason Scheirer wrote: On Apr 23, 5:16 pm, [EMAIL PROTECTED] wrote: Hello all, I am trying to integrate TurboGears with our Active Directory here at the office. TurboGears aside, i cannot get this to work. Seems more promising: http://tgolden.sc.sabren.com/python/active_directory.html This is based on ADSI? Then the caveat is that it only runs on Windows. Yes, it's Windows-only. (I've no idea if it would run under something like WINE). TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: @classmethod question
Scott SA [EMAIL PROTECTED] writes: A side note class RecipieClass: Recipe is a more widespread spelling, I believe. Moreover it is the convention in python that only class names are capitalized, so you don't need to append a 'Class'. class Recipe: ... clafoutis = Recipe('eggs', 'spam') -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: annoying dictionary problem, non-existing keys
bvidinli [EMAIL PROTECTED] writes: i use dictionaries to hold some config data, such as: conf={'key1':'value1','key2':'value2'} and so on... when i try to process conf, i have to code every time like: if conf.has_key('key1'): if conf['key1']'': other commands this is very annoying. Especially when you don't have to do this. in php, i was able to code only like: if conf['key1']=='someth' in python, this fails, because, if key1 does not exists, it raises an exception. MY question: is there a way to directly get value of an array/tuple/dict item by key, as in php above, even if key may not exist, i should not check if key exist, i should only use it, if it does not exist, it may return only empty, just as in php At the interactive prompt, type 'help(dict)' and read carefully about the different methods provided by dictionary objects (one called 'get' may be of particular interest to you). HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Lists: why is this behavior different for index and sliceassignments?
John Salerno [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | John Machin wrote: | | Deletion occurs *only* in the corner case where there are no assigned | elements i.e. only if the RHS list (sequence) is *empty*. | | Oh, it was my understanding that deletion always occurs, even when the | section is being assigned a non-empty value, i.e. delete the slice and | insert new value. Slice replacement means replace the slice with a new slice generated from the iterable on the left. John meant that deletion only only happens when the replacement is empty. Yes, deletion always occurs, but usually addition also occurs, so the net result is replacement rather than just deletion. | Otherwise | there would be no point at all in the language having assignment to a | slice -- del L[0:2] would suffice. | | Right, but I'm wondering why a statement like | L[0:2] = [] | doesn't assign an empty list as the new element in L. For example: Because, as others already told you, slice replacement is slice replacement, not item assignment. When you say to replace the slice with nothing, the deleted slice is replaced with nothing. L[0:2] = [[]] says to replace the slice with a slice consisting of one item -- [] That will get you what you are expecting. | L = [1, 2, 3, 4, 5] | L[0:2] = [] | | Why doesn't L now equal [[], 3, 4, 5] as it does with an index assignment? See above. | |L[0:2] = tuple('foobar') L[0:2] = 'foobar' has same effect because s string is an iterable. |L | ['f', 'o', 'o', 'b', 'a', 'r', 3, 4, 5] | | Hmm...why doesn't L equal [('f', 'o', 'o', 'b', 'a', 'r'), 3, 4, 5] ? | Shouldn't L be a 4 item list instead of 9? Because you replaced 2 items with 6. L[0:2] = ['foobar'] will replace 2 with 1, leaving 4 tjr -- http://mail.python.org/mailman/listinfo/python-list
Get Your Frozen Pills
http://twilight.110mb.com/gb/piac1.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Java or C++?
On Apr 21, 3:14 pm, NickC [EMAIL PROTECTED] wrote: On Apr 15, 1:46 pm, Brian Vanderburg II [EMAIL PROTECTED] wrote: [...] Yeah, C++ does try to be helpful, and all of those automatic copy constructor, assignment operator and destructor implementations screw up royally when confronted with pointers (and being able to use pointers is basically the whole reason for bothering to write anything in C or C++ in the first place). Code which relies on these default method implementations is almost certain to be rife with memory leaks and double-free bugs. So instead of being a convenience, they become a painfully easy way of writing code that silently does some very, very wrong things. When a class includes a pointer data member, there is no single, right way to handle it. C++ automatically generated member functions are defined so as to be consistent in dealing with *values*. Any C++ programmer that hasn't learnt this simple fact, shouldn't be trusted with any programming language. Python and especially Java will only make it harder to spot the mess he is making. Other things like methods (including destructors!) being non-virtual by default also make C++ code annoyingly easy to get wrong (without it obviously looking wrong). I can see how that might be confusing for programmer coming from Python, but it's more natural for those coming from C. The whole design of C++ is riddled with premature optimisation of speed and memory usage in the default settings, instead of choosing safe defaults and providing concise ways of allowing the programmer to say I know optimisation X is safe here, please use it. I absolutely agree. And the result? Any serious project in the language has to adopt it's own techniques for avoiding all those traps, and those techniques are likely to eliminate any supposed optimisations provided by the choices of the C++ committee, while filling a code base with boilerplate that only exists for the purpose of working around defects in the language design (Scott Meyers has written at length about the worst of these issues, far more clearly and eloquently than I ever could [1]). Did you give up on C++ in the early nineties? Things have changed a lot since then. Many standard/commonly accepted solutions to the problems you mention can be found in the C++ standard library and in Boost (http://boost.org). With std::vector and boost::shared_ptr you can go an extremely long way without giving pointers any special considerations. Cheers, Nicola Musatti -- http://mail.python.org/mailman/listinfo/python-list
Re: function that accepts any amount of arguments?
Steve Holden [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] globalrev wrote: if i want a function that can take any amount of arguments how do i do? lets say i want a function average that accepts any number of integers and returns the average. Use a parameter of the form *args - the asterisk tells the interpreter to collect positional arguments into a tuple. Untested: def mean(*x): total = 0.0 for v in x: total += v return v/len(x) think you want total/len(x) in return statement regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: python-ldap - Operations Error
[EMAIL PROTECTED] wrote: import ldap l = ldap.initialize(ldap://server.net;) l.simple_bind(DN, secret) 1 ^^^ You probably want to use the synchronous method simple_bind_s() since you want to impersonate on this LDAP connection immediately before doing anything else on that connection. l.result(1) (97, []) Could you please use argument trace_level=2 when calling ldap.initialize() and examine the debug log? It records all method calls of your particular LDAPObject instance. l = ldap.initialize(ldap://server.net,trace_level=2) Level 2 outputs a debug log with results received. Protect this log since it also contains passwords! l.search(dc=server,dc=net, ldap.SCOPE_SUBTREE, (sAMAccountName=user)) OPERATIONS_ERROR: {'info': ': LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'} Still something went wrong with your bind. Since I don't know your DN I can't say anything. The DN should be a local user in this domain and not a user from another trusted domain. If you have a complicated AD setup with various domains and delegated trust connecting to the GC (global catalog) on port 3268 might be easier. The simple bind works fine and returns a result, when i get the result, it returns 97 meaning successful. It would raise an exception if an LDAP error was received. So there was a successful bind on the connection, right? Don't know. Since I don't know your DN and AD domain configuation. I've added a new example script ms_ad_bind.py to python-ldap's Demo/ directory illustrating all the possible bind methods: http://python-ldap.cvs.sourceforge.net/*checkout*/python-ldap/python-ldap/Demo/ms_ad_bind.py?content-type=text%2Fplain For getting the SASL stuff to correctly work your DNS has to be properly set up for AD (A RRs and matching PTR RRs for the DCs). Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: @classmethod question
On 2008-04-24 05:27, Scott SA wrote: Hi, I'm using the @classemethod decorator for some convenience methods and for some reason, either mental block or otherwise, can't seem to figure out how to elegantly detect if the call is from an instance or not. Here's the problem: Within the class definition, 'isinstance' has nothing to compare to because the class does not appear to exist. This is NOT a great example, but it outlines the the code: class RecipieClass: def __init__(self): pass @classmethod def get_ingrendients(self, recipie_list=None): if isinstnace(self,RecipieClass): return self.do_something_interesting() else: return do_something_boring(recipie_list) Yes, I can test to see if the param exists, but that makes the call exclusive i.e. I can _only_ call it as an instance or with a parameter. I would turn the above method into a regular instance method and then add a new function or static method which then returns the summary output. A class method is clearly wrong here, since those are meant to be called with the class as first argument, e.g. to count the number of instances created from a class. Why am I doing this? It is a series of convenience methods, in this case I'm interacting with a database via an ORM (object-relational model). I want the ability to call a class-ojbect and get related values, or pass some criteria and get related values for them without collecting the records first as instances, then iterating them. I need to call this from several places so I want to be DRY (don't repeat yourself). The easiest way to describe this as an analogy would be like having a recipie for cookies and wanting to know all of the ingredients ahead of time. Then, at another time, wanting to know what all the ingredients would be to make cookies, cake and bread (i.e. complete shopping list). cookie_recipie = RecipieClass.get_recipie('cookies') cookie_recipie.get_ingredients() 2C Flour 0.5 C Sugar ... RecipieClass.get_ingrendients(['cookies','cake','bread']) 8C Flour 2C Sugar ... Of course any suggestions on how this might be better approached would be interesting too. TIA, Scott -- http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 24 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 -- http://mail.python.org/mailman/listinfo/python-list
Re: python-ldap: searching without specifying an OU?
hotani wrote: http://peeved.org/blog/2007/11/20/ BTW: This blog entry claims that LDAP_SERVER_DOMAIN_SCOPE_OID control cannot be used with python-ldap. But support for such simple LDAPv3 extended controls was added to python-ldap way back in 2005. Actually it's easy (relevant code excerpt): import ldap from ldap.controls import BooleanControl LDAP_SERVER_DOMAIN_SCOPE_OID='1.2.840.113556.1.4.1339' [..] l = ldap.initialize(ldap_uri,trace_level=trace_level) # Switch off chasing referrals within OpenLDAP's libldap l.set_option(ldap.OPT_REFERRALS, 0) # Simple bind with user's DN and password l.simple_bind_s(dn,password) res = l.search_ext_s( 'DC=dom,DC=example,DC=com', ldap.SCOPE_ONELEVEL, '(objectClass=subentry)', ['*'], serverctrls = [ BooleanControl( LDAP_SERVER_DOMAIN_SCOPE_OID, criticality=0,controlValue=1 ) ] ) Strange enough it has no effect. And setting criticality=1 raises an error indicating that this control is not supported although this control is explicitly mentioned in attribute 'supportedControl' of the server's rootDSE: ldap.UNAVAILABLE_CRITICAL_EXTENSION: {'info': '0057: LdapErr: DSID-0C09068F, comment: Error processing control, data 0, vece', 'desc': 'Critical extension is unavailable'} Might depend on the domain functional level AD is running with... Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for parsing this text?
On Apr 24, 4:05 am, Paul McGuire [EMAIL PROTECTED] wrote: On Apr 23, 8:00 pm, Eric Wertman [EMAIL PROTECTED] wrote: I have a set of files with this kind of content (it's dumped from WebSphere): [propertySet [[resourceProperties [[[description This is a required property. This is an actual database name, and its not the locally catalogued database name. The Universal JDBC Driver does not rely on ... A couple of comments first: - What is the significance of '[' vs. '[' ? I stripped them all out using The data can be thought of as a serialised object. A simple attribute looks like: [name someWebsphereObject] or [jndiName []] if 'jndiName is None'. A complex attribute is an attribute whose value is itself an object (or dict if you prefer). The *value* is indicated with [...]: [connectionPool [[agedTimeout 0] [connectionTimeout 180] [freePoolDistributionTableSize 0] [maxConnections 10] [minConnections 1] [numberOfFreePoolPartitions 0] [numberOfSharedPoolPartitions 0] [unusedTimeout 1800]]] However, 'propertySet' is effectively a keyword and its value may be thought of as a 'data table' or 'list of data rows', where 'data row' == dict/object You can see how the posted example is incomplete because the last 'row' is missing all but one 'column'. text = text.replace('[','[') - Your input text was missing 5 trailing ]'s. I think only 2 (the original isn't Python). To fix the example, remove the last 'description' and add two ]'s Here's the parser I used, using pyparsing: from pyparsing import nestedExpr,Word,alphanums,QuotedString from pprint import pprint content = Word(alphanums+_.) | QuotedString('',multiline=True) structure = nestedExpr([, ], content).parseString(text) pprint(structure.asList()) By the way, I think this would be a good example for the pyparsing recipes page (even an IBM developerworks article?) http://www.ibm.com/developerworks/websphere/library/techarticles/0801_simms/0801_simms.html Gerard example data (copied and pasted; doesn't have the case where a complex attribute has a complex attribute): [authDataAlias []] [authMechanismPreference BASIC_PASSWORD] [connectionPool [[agedTimeout 0] [connectionTimeout 180] [freePoolDistributionTableSize 0] [maxConnections 10] [minConnections 1] [numberOfUnsharedPoolPartitions 0] [properties []] [purgePolicy FailingConnectionOnly] [reapTime 180] [surgeThreshold -1] [testConnection false] [testConnectionInterval 0] [unusedTimeout 1800]]] [propertySet [[resourceProperties [[[description This is a required property. This is an actual database name, and its not the locally catalogued database name. The Universal JDBC Driver does not rely on information catalogued in the DB2 database directory.] [name databaseName] [required true] [type java.lang.String] [value DB2Foo]] [[description The JDBC connectivity-type of a data source. If you want to use a type 4 driver, set the value to 4. If you want to use a type 2 driver, set the value to 2. Use of driverType 2 is not supported on WAS z/OS.] [name driverType] [required true] [type java.lang.Integer] [value 4]] [[description The TCP/IP address or name for the DRDA server.] [name serverName] [required false] [type java.lang.String] [value ServerFoo]] [[description The TCP/IP port number where the DRDA server resides.] [name portNumber] [required false] [type java.lang.Integer] [value 007]] [[description The description of this datasource.] [name description] [required false] [type java.lang.String] [value []]] [[description The DB2 trace level for logging to the logWriter or trace file. Possible trace levels are: TRACE_NONE = 0,TRACE_CONNECTION_CALLS = 1,TRACE_STATEMENT_CALLS = 2,TRACE_RESULT_SET_CALLS = 4,TRACE_DRIVER_CONFIGURATION = 16,TRACE_CONNECTS = 32,TRACE_DRDA_FLOWS = 64,TRACE_RESULT_SET_META_DATA = 128,TRACE_PARAMETER_META_DATA = 256,TRACE_DIAGNOSTICS = 512,TRACE_SQLJ = 1024,TRACE_ALL = -1, .] [name traceLevel] [required false] [type java.lang.Integer] [value []]] ]] -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] annoying dictionary problem, non-existing keys
bvidinli schrieb: I posted to so many lists because, this issue is related to all lists, this is an idea for python, this is related to development of python... why are you so much defensive ? i think ideas all important for development of python, software i am sory anyway hope will be helpful. You could take the answers from the people (including core developers) as sign that it is *not* related to all lists. Crossposting is generally frowned upon and should be avoided. If you post here people think that it is a python devel issue, they will indicate that. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: library to do easy shell scripting in Python
On Apr 24, 12:22 pm, Michael Torrie [EMAIL PROTECTED] wrote: pipe([prog1,args],[prog2,args],...) Any ideas on how I could design this? There's a recipe on Activestate's Python Cookbook that does pretty much this: Allows arbitrary number of commands to be strung together with each one feeding into the next ones input. Syntax is simple: x=pipe(cmd1, cmd2, cmd3).read() is equivalent to bash command x=`cmd1 | cmd2 | cmd3`. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475171 I haven't used it myself, but it might make a good place to start. - alex23 -- http://mail.python.org/mailman/listinfo/python-list
xyplorer crack
xyplorer crack http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
civilization iv crack
civilization iv crack http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
xxx crack
xxx crack http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
intervideo windvd keygen
intervideo windvd keygen http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
the apple patch diet
the apple patch diet http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
orbital trader crack
orbital trader crack http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
crack xp
crack xp http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
ilife 08 keygen
ilife 08 keygen http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
crack spyder
crack spyder http://cracks.12w.net F R E E C R A C K S -- http://mail.python.org/mailman/listinfo/python-list
Re: annoying dictionary problem, non-existing keys
On Thu, 24 Apr 2008 10:24:37 +0200 Robert Bossy [EMAIL PROTECTED] wrote: Way 2: make conf a defaultdict instead of a dict, the documentation is there: http://docs.python.org/lib/defaultdict-objects.html Only for 2.5 and up though. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k concerns. An example
Martin v. Löwis [EMAIL PROTECTED] writes: In py3k string%dictionary is going away. Why do you say that? It's not going away in Python 3.0. I also got the impression that it was going away. PEP 3101's abstract says: This PEP proposes a new system for built-in string formatting operations, intended as a replacement [sic] for the existing '%' string formatting operator. Under Backward compatibility it says that both systems can coexist until it comes time to deprecate the older system. The PEP may say that it's going away, but it doesn't say that it goes away in 3.0 - and indeed, it won't. Thanks for clarifying it. It is certainly unclear from the wording of the PEP, given that 3.0 is regarded as the Python version allowed to break backward compatibility. At some point in the future, somebody will likely propose that the PEP will be executed. At that time, huge flame wars will start. I expect that they settle in changing the PEP to explain that the old mechanism gets removed in Python 4, to be release in 2018 :-) Indeed. -- http://mail.python.org/mailman/listinfo/python-list
restructured text in python
Hi all, I have a python prog: #!/usr/bin/env Author: BDS Version: 1.0 def Hello(): Prints a Hello World to the screen print Hello, World if __name__ == __main__: Hello() I want to use ReSt (reStructuredText) in my docstrings or comments. Any example of how to do it, w.r.t. above code ? Also how to invoke rst on the Python code to do the processing ? I know how to write in RST but I want to know how to process the resulting Python code -- http://mail.python.org/mailman/listinfo/python-list
Re: Python development tools
Torsten Bronger a écrit : Hallöchen! [EMAIL PROTECTED] writes: On 23 avr, 19:39, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Are there any completely free developent tools for python scripts like IDLE. I have used IDLE , but I want to try out others also. I saw stuff like PyCrust, but I don't see that it can run the script as well. emacs + python-mode (the one from Python, not the horror that ships with recent emacs versions) What's so bad about it? I'd have to reinstall it to tell you exactly, but I do remember something really bad wrt/ the embedded python-shell, which is one the very strength of the emacs+python-mode combo. I just installed python-mode (is this the one with the py- prefixes?), It's the one with ;; Copyright (C) 1992,1993,1994 Tim Peters and it ends multi-line strings at single quotes. it chokes on unbalanced single quotes in triple-single-quoted strings, and on unbalanced double-quotes in triple-double-quoted strings, yes. Given that I never use triple-single-quoted strings (and don't remember having seen such a thing in the thousands of third-part .py files I've read so far), I'd qualify this as at most a very minor annoyance. Not having proper python-shell and pdb integration is more annoying IMHO. -- http://mail.python.org/mailman/listinfo/python-list
Re: function that accepts any amount of arguments?
Ken wrote: Steve Holden [EMAIL PROTECTED] wrote in message [...] def mean(*x): total = 0.0 for v in x: total += v return v/len(x) think you want total/len(x) in return statement Yes indeed, how glad I am I wrote untested. I clearly wasn't pair programming when I wrote this post ;-) regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
How to get inner exception traceback
Hi, How can you get the traceback of the inner exception? try: try: import does_not_exit except ImportError: raise Exception(something wrong) except: ... Background: In Django some exceptions are caught and a new exception gets raised. Unfortunately the real error is hard to find. Sometimes I help myself and change (in this example) ImportError to e.g. IOError and then I can see the real root of the problem. But maybe there is a way to get the inner exception and its traceback. This could be displayed in the debug view. Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de -- http://mail.python.org/mailman/listinfo/python-list
Re: help needed with classes/inheritance
barbaros a écrit : On Apr 23, 10:48 am, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: My question is: can it be done using inheritance ? Technically, yes: class OrientedBody(Body): def __init__(self, orient=1): Body.__init__(self) self.orient = 1 Now if it's the right thing to do is another question... If I understand correctly, in the above implementation I cannot define firstly a (non-oriented) body, and then build, on top of it, two bodies with opposite orientations. The point is, I want both oriented bodies to share the same base Body object. Then it's not a job for inheritence, but for composition/delegation - Sorry but I didn't get your specs quite right :-/ Now the good news is that Python makes composition/delegation close to a no-brainer: class Body(object): # definitions here class OrientedBody(object): # notice that we *dont* inherit from Body def __init__(self, body, orient): self._body = body self.orient = orient def __getattr__(self, name): try: return getattr(self._body, name) except AttributeError: raise AttributeError( OrientedBody object has no attribute %s % name ) def __setattr__(self, name, val): # this one is a bit more tricky, since you have # to know which names are (or should be) bound to # which object. I use a QD approach here - which will break # on computed attributes (properties etc) in the Body class - # but you can also define a class attribute in either Body # or OrientedBody to explicitly declare what name goes where if name in self._body.__dict__: setattr(self._body, name, val) else: object.__setattr__(self, name, value) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python development tools
Hallöchen! Bruno Desthuilliers writes: [...] and it ends multi-line strings at single quotes. it chokes on unbalanced single quotes in triple-single-quoted strings, and on unbalanced double-quotes in triple-double-quoted strings, yes. Given that I never use triple-single-quoted strings (and don't remember having seen such a thing in the thousands of third-part .py files I've read so far), I'd qualify this as at most a very minor annoyance. Not having proper python-shell and pdb integration is more annoying IMHO. My formulation was unfortunate. What doesn't work (at least for me) is something like This is a docstring in which some variables are quoted. Here, variables doesn't seem to belong to the docstring for python-mode. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for further contact info.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Spawing a thread and printing dots until it finishes
On Apr 22, 3:10 pm, sophie_newbie [EMAIL PROTECTED] wrote: Hi, I'm trying to write a piece of code that spawns a thread and prints dots every half second until the thread spawned is finished. Code is something like this: import threading class MyThread ( threading.Thread ): def run ( self ): myLongCommand()... import time t = MyThread() t.start() while t.isAlive(): print . time.sleep(.5) print OK The thing is this doesn't print a dot every half second. It just pauses for ages until the thread is finished and prints prints .OK. But if I take out the time.sleep(.5) line it will keep printing dots really fast until the thread is finished. So it looks like its the time.sleep(.5) bit that is messing this up somehow? Any ideas? Thanks! As it happens I've managed to come up with a solution to this problem using a subprocess rather than a thread. Its not exactly rocket science but I thought I'd post it anyway. There are 3 files: ## dots.py ### # a script to print a dot every half second until it is terminated import time import sys while 1 == 1: sys.stdout.write(.) sys.stdout.flush() time.sleep(.5) # PrintDots.py ## # This is a simple class to spawn off another process that prints dots repeatedly on screen # when printDots() is called and stops when stopDots is called. It is useful in cgi-scripts # where you may want to let the user know that something is happening, rather than looking # at a blank screen for a couple of minutes. import time import subprocess import os from signal import SIGTERM class PrintDots: # the constructor, called when an object is created. def __init__(self): self.pid = 0 # the location of the script that prints the dots self.dotsScript = dots.py def printDots(self): self.pid = subprocess.Popen( [ python, self.dotsScript] ).pid def stopDots(self): os.kill(self.pid, SIGTERM) mainFile.py ## # The above can then be called from any cgi-script as follows from PrintDots import PrintDots p = PrintDots() p.printDots() print Doing R Stuff my_Call_To_R_That_Takes_A_Long_Time() p.stopDots() print OK And low and behold dots are printed on screen every half second while python is talking to R, with an output like this: Doing R Stuff.OK -- http://mail.python.org/mailman/listinfo/python-list
Re: Spawing a thread and printing dots until it finishes
On Apr 24, 12:32 pm, sophie_newbie [EMAIL PROTECTED] wrote: On Apr 22, 3:10 pm,sophie_newbie[EMAIL PROTECTED] wrote: Hi, I'm trying to write a piece of code that spawns a thread and prints dots every half second until the thread spawned is finished. Code is something like this: import threading class MyThread ( threading.Thread ): def run ( self ): myLongCommand()... import time t = MyThread() t.start() while t.isAlive(): print . time.sleep(.5) print OK The thing is this doesn't print a dot every half second. It just pauses for ages until the thread is finished and prints prints .OK. But if I take out the time.sleep(.5) line it will keep printing dots really fast until the thread is finished. So it looks like its the time.sleep(.5) bit that is messing this up somehow? Any ideas? Thanks! As it happens I've managed to come up with a solution to this problem using a subprocess rather than a thread. Its not exactly rocket science but I thought I'd post it anyway. There are 3 files: ## dots.py ### # a script to print a dot every half second until it is terminated import time import sys while 1 == 1: sys.stdout.write(.) sys.stdout.flush() time.sleep(.5) # PrintDots.py ## # This is a simple class to spawn off another process that prints dots repeatedly on screen # when printDots() is called and stops when stopDots is called. It is useful in cgi-scripts # where you may want to let the user know that something is happening, rather than looking # at a blank screen for a couple of minutes. import time import subprocess import os from signal import SIGTERM class PrintDots: # the constructor, called when an object is created. def __init__(self): self.pid = 0 # the location of the script that prints the dots self.dotsScript = dots.py def printDots(self): self.pid = subprocess.Popen( [ python, self.dotsScript] ).pid def stopDots(self): os.kill(self.pid, SIGTERM) mainFile.py ## # The above can then be called from any cgi-script as follows from PrintDots import PrintDots p = PrintDots() p.printDots() print Doing R Stuff my_Call_To_R_That_Takes_A_Long_Time() p.stopDots() print OK And low and behold dots are printed on screen every half second while python is talking to R, with an output like this: Doing R Stuff.OK Whoops that last bit of code should read as follows: from PrintDots import PrintDots p = PrintDots() print Doing R Stuff p.printDots() my_Call_To_R_That_Takes_A_Long_Time() p.stopDots() print OK -- http://mail.python.org/mailman/listinfo/python-list
Re: Python development tools
On 4/24/08, Banibrata Dutta [EMAIL PROTECTED] wrote: On Windows, I use PyScripter, and it's quite nice and functional. On 4/24/08, Torsten Bronger [EMAIL PROTECTED] wrote: Hallöchen! Bruno Desthuilliers writes: [...] and it ends multi-line strings at single quotes. it chokes on unbalanced single quotes in triple-single-quoted strings, and on unbalanced double-quotes in triple-double-quoted strings, yes. Given that I never use triple-single-quoted strings (and don't remember having seen such a thing in the thousands of third-part .py files I've read so far), I'd qualify this as at most a very minor annoyance. Not having proper python-shell and pdb integration is more annoying IMHO. My formulation was unfortunate. What doesn't work (at least for me) is something like This is a docstring in which some variables are quoted. Here, variables doesn't seem to belong to the docstring for python-mode. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for further contact info.) -- http://mail.python.org/mailman/listinfo/python-list -- regards, Banibrata http://www.linkedin.com/in/bdutta -- regards, Banibrata http://www.linkedin.com/in/bdutta -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting expirty data on a cookie
On Apr 22, 8:38 pm, David [EMAIL PROTECTED] wrote: On Tue, Apr 22, 2008 at 6:21 PM,sophie_newbie[EMAIL PROTECTED] wrote: Does anyone know how to do this? I can't seem to make it work. I'm using: c = Cookie.SimpleCookie() c['data'] = unamepwordwhatever c.expires = time.time() + 300 print c This doesn't seem to work, so I'm assuming isn't the correct way to set an expiry data? Anyone able to help me out here? You're probably looking for cookielib.Cookie I don't think so, to give you a more complete picture, if I run this code: import Cookie import time c = Cookie.SimpleCookie() c['data'] = unamepwordwhatever c.expires = time.time() + 300 print c This codes gives an output of: Set-Cookie: data=unamepwordwhatever As in there is no mention of an expiry date, when surely there should be? Thanks for any advice. -- http://mail.python.org/mailman/listinfo/python-list
Re: function that accepts any amount of arguments?
Paul McNett a écrit : def avg(*args): return sum(args) / len(args) There are some dangers (at least two glaring ones) with this code, though, which I leave as an exercise for the reader. try: avg(toto, 42) except TypeError, e: print this is the first one : %s % e try: avg() except ZeroDivisionError, e: print this is the second : %s % e As far as I'm concerned, I would not handle the first one in the avg function - just document that avg expects numeric args. Not quite sure what's the best thing to do in the second case - raise a ValueError if args is empty, or silently return 0.0 - but I'd tend to choose the first solution (Python's Zen, verses 9-11). -- http://mail.python.org/mailman/listinfo/python-list
Re: Python development tools
Torsten Bronger a écrit : Hallöchen! Bruno Desthuilliers writes: [...] and it ends multi-line strings at single quotes. it chokes on unbalanced single quotes in triple-single-quoted strings, and on unbalanced double-quotes in triple-double-quoted strings, yes. Given that I never use triple-single-quoted strings (and don't remember having seen such a thing in the thousands of third-part .py files I've read so far), I'd qualify this as at most a very minor annoyance. Not having proper python-shell and pdb integration is more annoying IMHO. My formulation was unfortunate. What doesn't work (at least for me) is something like This is a docstring in which some variables are quoted. Here, variables doesn't seem to belong to the docstring for python-mode. Nope, but it doesn't break anything neither. At this stage, this is a less than minor annoyance to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: annoying dictionary problem, non-existing keys
bvidinli wrote: I posted to so many lists because, this issue is related to all lists, No, it isn't, as you would have discovered had you bothered to read the purpose of each list. For example, python-help and python-dev are mutually exclusive. this is an idea for python, It isn't an idea for Python at all. It's you, telling the world that you haven't really used Python much and haven't read the manuals but would nevertheless like us to consider your ideas for improving the language. this is related to development of python... No it isn't. Python already has the feature you requested. why are you so much defensive ? Terry wasn't being defensive, he was protecting you form the abue you would receive of you kept posting to the wrong list! i think ideas all important for development of python, software i am sory anyway hope will be helpful. We hope you will be helpful too. For now it would probably be best to start by posting your questions on the regular comp.lang.python group, which is generally suitable for beginners who know something about programming. If you are new to programming as well then the python-tutor list would be more useful. Ask with a little humility (the people who answer questions here are doing it out of the goodness of their hearts, remember) and soon you will be able to pass their assistance on, returning the favor they did for you. Welcome to the Python community. regards Steve 2008/4/24, Terry Reedy [EMAIL PROTECTED]: Python-dev is for discussion of development of future Python. Use python-list / comp.lang.python / gmane.comp.python.general for usage questions. -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get inner exception traceback
Thomas Guettler wrote: How can you get the traceback of the inner exception? You have to record it yourself or it will be lost. try: try: import does_not_exit except ImportError: raise Exception(something wrong) except: ... Background: In Django some exceptions are caught and a new exception gets raised. Unfortunately the real error is hard to find. Sometimes I help myself and change (in this example) ImportError to e.g. IOError and then I can see the real root of the problem. But maybe there is a way to get the inner exception and its traceback. This could be displayed in the debug view. You can get the current exception and traceback with sys.exc_info() and later print or format it using the traceback module. try: ... 1/0 ... except Exception: ... x = sys.exc_info() ... raise ValueError ... Traceback (most recent call last): File stdin, line 5, in module ValueError traceback.print_exception(*x) Traceback (most recent call last): File stdin, line 2, in module ZeroDivisionError: integer division or modulo by zero Peter -- http://mail.python.org/mailman/listinfo/python-list
Tkinter scrollbar and checkbox
Hi, I'm stumped on how to have a scrollbar with a long list of checkboxes. Given code like: from Tkinter import * root = Tk() states = [] for i in range(150): var = IntVar() chk = Checkbutton(root, text=str(i), variable=var) chk.grid(sticky=W) states.append(var) root.mainloop() print map((lambda var: var.get()), states) I've tried adding this to a frame then adding the frame to a canvas and it gets complicated rather quickly... Is there a simple way to add a scroll bar? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting expirty data on a cookie
On Apr 24, 12:41 pm, sophie_newbie [EMAIL PROTECTED] wrote: On Apr 22, 8:38 pm, David [EMAIL PROTECTED] wrote: On Tue, Apr 22, 2008 at 6:21 PM,sophie_newbie[EMAIL PROTECTED] wrote: Does anyone know how to do this? I can't seem to make it work. I'm using: c = Cookie.SimpleCookie() c['data'] = unamepwordwhatever c.expires = time.time() + 300 print c This doesn't seem to work, so I'm assuming isn't the correct way to set an expiry data? Anyone able to help me out here? You're probably looking for cookielib.Cookie I don't think so, to give you a more complete picture, if I run this code: import Cookie import time c = Cookie.SimpleCookie() c['data'] = unamepwordwhatever c.expires = time.time() + 300 print c This codes gives an output of: Set-Cookie: data=unamepwordwhatever As in there is no mention of an expiry date, when surely there should be? Thanks for any advice. Ok this seems to work: import Cookie import time c = Cookie.SimpleCookie() c['data'] = unamepwordwhatever c['data']['expires'] = 30 * 24 * 60 * 60 print c Gives an output of: Set-Cookie: data=unamepwordwhatever; expires=Sat, 24-May-2008 12:11:36 GMT Bizarre that this information was so hard to find! -- http://mail.python.org/mailman/listinfo/python-list
Re: function that accepts any amount of arguments?
On Apr 24, 12:43 pm, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: [...] Not quite sure what's the best thing to do in the second case - raise a ValueError if args is empty, or silently return 0.0 - but I'd tend to choose the first solution (Python's Zen, verses 9-11). What's wrong with raising ZeroDivisionError (not stopping the exception in the first place)? k -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for parsing this text?
Eric Wertman [EMAIL PROTECTED] wrote: I have a set of files with this kind of content (it's dumped from WebSphere): [propertySet [[resourceProperties [[[description This is a required property. This is an actual database name, and its not the locally catalogued database name. The Universal JDBC Driver does not rely on information catalogued in the DB2 database directory.] [name databaseName] [required true] [type java.lang.String] [value DB2Foo]] ... Looks to me like S-expressions with square brackets instead of the normal round ones. I'll bet that the correct lexical analysis is approximately [ open-list propertySet symbol open-string [ open-list [ open-list resourcePropertiessymbol open-string (not close-string!) ... so it also looks as if strings aren't properly escaped. This is definitely not a pretty syntax. I'd suggest an initial tokenization pass for the lexical syntax [ open-list ] close-list [open-qlist ]close-qlist ... string whitespaceignore anything-else symbol Correct nesting should give you two kinds of lists -- which I've shown as `list' and `qlist' (for quoted-list), though given the nastiness of the dump you showed, there's no guarantee of correctness. Turn the input string (or file) into a list (generator?) of lexical objects above; then scan that recursively. The lists (or qlists) seem to have two basic forms: * properties, that is a list of the form [SYMBOL VALUE ...] which can be thought of as a declaration that some property, named by the SYMBOL, has a particular VALUE (or maybe VALUEs); and * property lists, which are just lists of properties. Property lists can be usefully turned into Python dictionaries, indexed by their SYMBOLs, assuming that they don't try to declare the same property twice. There are, alas, other kinds of lists too -- one of the property lists contains a property `[value []]' which simply contains an empty list. The right first-cut rule for disambiguation is probably that a property list is a non-empty list, all of whose items look like properties, and a property is an entry in a property list, and (initially at least) restrict properties to the simple form [SYMBOL VALUE] rather than allowing multiple values. Does any of this help? (In fact, this syntax looks so much like a demented kind of S-expression that I'd probably try to parse it, initially at least, by using a Common Lisp system's reader and a custom readtable, but that may not be useful to you.) -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get inner exception traceback
On 24 Apr, 13:20, Thomas Guettler [EMAIL PROTECTED] wrote: Hi, How can you get the traceback of the inner exception? try: try: import does_not_exit except ImportError: raise Exception(something wrong) except: ... Background: In Django some exceptions are caught and a new exception gets raised. Unfortunately the real error is hard to find. Sometimes I help myself and change (in this example) ImportError to e.g. IOError and then I can see the real root of the problem. But maybe there is a way to get the inner exception and its traceback. This could be displayed in the debug view. Thomas -- Thomas Guettler,http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de I'm not sure it ill work since sys.exc_info() might not return a deep copy of the traceback info, but you could try to store the inner exception and its traceback as attributes of the outer exception: class ReraisedException(Exception): def __init__(self, message, exc_info): Exception.__init__(self, message) self.inner_exception = exc_info try: try: import does_not_exit except ImportError: raise ReraisedException(Something wrong, sys.exc_info() ) except ReraisedException, e: ... # here you can use e.inner_exception except: ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get inner exception traceback
[EMAIL PROTECTED] schrieb: On 24 Apr, 13:20, Thomas Guettler [EMAIL PROTECTED] wrote: Hi, How can you get the traceback of the inner exception? try: try: import does_not_exit except ImportError: raise Exception(something wrong) except: ... Background: In Django some exceptions are caught and a new exception gets raised. Unfortunately the real error is hard to find. Sometimes I help myself and change (in this example) ImportError to e.g. IOError and then I can see the real root of the problem. But maybe there is a way to get the inner exception and its traceback. This could be displayed in the debug view. Thomas -- Thomas Guettler,http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de I'm not sure it ill work since sys.exc_info() might not return a deep copy of the traceback info, but you could try to store the inner exception and its traceback as attributes of the outer exception: class ReraisedException(Exception): def __init__(self, message, exc_info): Exception.__init__(self, message) self.inner_exception = exc_info try: try: import does_not_exit except ImportError: raise ReraisedException(Something wrong, sys.exc_info() ) except ReraisedException, e: ... # here you can use e.inner_exception except: This may lead to reference cycles, please read http://docs.python.org/dev/library/sys.html#sys.exc_info Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: restructured text in python
-On [20080424 13:16], bdsatish ([EMAIL PROTECTED]) wrote: #!/usr/bin/env #!/usr/bin/env what? I guess you meant #!/usr/bin/env python Author: BDS Version: 1.0 def Hello(): Prints a Hello World to the screen print Hello, World I want to use ReSt (reStructuredText) in my docstrings or comments. Any example of how to do it, w.r.t. above code ? Also how to invoke rst on the Python code to do the processing ? Just run epydoc (easy_install epydoc) on your code, for example, and observe the resulting output. Once you see the output it's quite easy, since you already know reSt, how to change your docstrings to use appropriate formatting for what you need. -- Jeroen Ruigrok van der Werven asmodai(-at-)in-nomine.org / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Give me the strength to be who I was, and forgive me for who I am... -- http://mail.python.org/mailman/listinfo/python-list
Re: Curious relation
On Apr 24, 12:08 am, Dan Bishop [EMAIL PROTECTED] wrote: On Apr 23, 11:51 pm, Greg J [EMAIL PROTECTED] wrote: I was reading the programming Reddit tonight and came across this (http://reddit.com/info/6gwk1/comments/): ([1]2)==True True [1](2==True) True [1]2==True False Odd, no? So, can anyone here shed light on this one? A long time ago, it wasn't possible for comparison operators to raise exceptions, so it was arbitrarily decided that numbers are less than strings. Thus, [1]2 and [1]False. This explains your first two examples. Sure, those I understood. For the third, remember that the comparison operators are chained, so ab==c means (ab) and (b==c). Since 2==True is false, so is the entire expression. Ach! Of course. For some reason I was blanking on the chained nature of relational operators in Python. Thanks for the reminder! In Python 3.0, all three of these expressions will raise a TypeError. -- http://mail.python.org/mailman/listinfo/python-list
Re: annoying dictionary problem, non-existing keys
bvidinli wrote: i use dictionaries to hold some config data, such as: conf={'key1':'value1','key2':'value2'} and so on... when i try to process conf, i have to code every time like: if conf.has_key('key1'): if conf['key1']'': other commands this is very annoying. in php, i was able to code only like: if conf['key1']=='someth' in python, this fails, because, if key1 does not exists, it raises an exception. That is one of python rules: import this (cut) Explicit is better than implicit. (cut) php hide some thing that python expose. MY question: is there a way to directly get value of an array/tuple/dict item by key, as in php above, even if key may not exist, i should not check if key exist, i should only use it, if it does not exist, it may return only empty, just as in php i hope you understand my question... You can simple modify the dict behavior: class my_dict(dict): ... def __getitem__(self, item): ... if item in self: ...return super(my_dict, self).__getitem__(item) ... else: ...return '' ... d = my_dict() d[a] '' d[a] = 5 d[a] 5 Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: help needed with classes/inheritance
Thanks to Paul McGuire and Bruno Desthuilliers for their comprehensive answers. This is exactly what I was looking for, except I did not know the correct name (composition/delegation). Now all I have to do is to study the supplied code, understand it and adapt it to my problem. Thank you very much. Cristian Barbarosie http://cmaf.ptmat.fc.ul.pt/~barbaros -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k concerns. An example
On Apr 21, 9:01 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: Perhaps you can manage to keep your code compatible with all versions, but AFAIK the reccomended strategy is to write code compatible with Python 2.6 and use the 2to3 tool to generate the 3.0 source. And *not* edit the 3.0 code unless one wants to maintain two branches. Gabriel - (Thanks for chiming in on this sub-thread, I really enjoy reading your posts.) My point is that the recommended strategy MAY work for those who write end point applications (I consider maintaining 2 branches to be in the not working category), but it does NOT WORK for people who maintain modules for other people to use, because those people may be on a range of Python versions that extend beyond 2.6-3.0. So if I upgrade my module to 2.6, those running on earlier versions can no longer use it. At some point in the future, I'll probably be able to say no more support for pre-2.6, but it is a bit early to start saying that now. Likewise, I don't want to say no support for 3.0 - people DO want to try 3.0 out, and I WANT them to want and be able to use my module too. Given the recommended strategy, and ruling out dual codebase, whom do I tell that they can't use the next version of my module? Again, to me, this is a non-issue because I've been able to create a cross-version compatible single codebase for pyparsing. But it was a bit dicey there for a while, and I think other module developers/ maintainers may not be so lucky. So, I feel that the recommended strategy was devised with a narrow group of developers in mind, and leaves module developers/maintainers, who wish to target as broad a set of users as possible, faced with choosing one of these strategies: - create (if possible) single cross-version compatible code - forego support of 3.0 users - discontinue pre-2.6 support for future versions of their module - maintain dual codebase -- Paul -- http://mail.python.org/mailman/listinfo/python-list
How to find the parent of an old-style class?
I'm stuck using a library based on old style classes, and need to find a class's parent at runtime. With new style classes you can use .__base__ to inspect a parent, but I can't remember how this was done in days of yore, before object. I've tried googling, but apparently my search term Fu is weak. :-( Can anyone help me out here? There must be something simple. -Jasper -- http://mail.python.org/mailman/listinfo/python-list
Re: annoying dictionary problem, non-existing keys
dict also has 'get' which provides a default if the key isn't defined: a={} print a.get('a','default') default -Rick King southfield MI -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k concerns. An example
Again, to me, this is a non-issue because I've been able to create a cross-version compatible single codebase for pyparsing. But it was a bit dicey there for a while, and I think other module developers/ maintainers may not be so lucky. I'm more optimistic. I tried it for Django, and while the port is not complete, it goes really well and supports basic operations (i.e. the Django tutorial). Based on your experience, and other reports, I think there is a fair chance that you can support a wide range of versions (2.x and 3.x) from a single code base for most projects. - create (if possible) single cross-version compatible code - forego support of 3.0 users - discontinue pre-2.6 support for future versions of their module - maintain dual codebase One needs to consider the drawbacks in each case; for the single codebase approach, the drawback probably is that readability suffers, and the need for testing increases (but it does always if you support multiple targets). It also requires expertise to create such cross-version code in the first place, but that's just a learning issue (i.e. you have to keep the rules in mind that you want to follow). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter scrollbar and checkbox
On Apr 24, 7:11 am, goldtech [EMAIL PROTECTED] wrote: Hi, I'm stumped on how to have a scrollbar with a long list of checkboxes. Given code like: from Tkinter import * root = Tk() states = [] for i in range(150): var = IntVar() chk = Checkbutton(root, text=str(i), variable=var) chk.grid(sticky=W) states.append(var) root.mainloop() print map((lambda var: var.get()), states) I've tried adding this to a frame then adding the frame to a canvas and it gets complicated rather quickly... Is there a simple way to add a scroll bar? Thanks I use wxPython most of the time, however effbot has a good tutorial on scrollbars for Tkinter that I think you might find helpful: http://effbot.org/zone/tkinter-scrollbar-patterns.htm Here's another link on the subject: http://www.pythonware.com/library/tkinter/introduction/scrollbar.htm HTH Mike -- http://mail.python.org/mailman/listinfo/python-list
NameError: global name 'Response' is not defined
Hi I am very new to web development. I started with Pylons. I am using http://www.rexx.com/~dkuhlman/pylons_quick_site.html as reference to create a sample web page using pylons. I got stuck up at step 4.3 i.e when modifying controller to return Response('pfirstapp default/p') I am getting error of type 'exceptions.NameError': global name 'Response' is not defined It seems I am missing some package. I am not really sure. I installed python 2.5 and through easy_install imported pakages (pylons). Any clues would be appreciated Thanks Lalit -- http://mail.python.org/mailman/listinfo/python-list
Re: Where to get BeautifulSoup--www.crummy.com appears to be down.
On Apr 23, 4:27 pm, John Nagle [EMAIL PROTECTED] wrote: Tim Golden wrote: John Nagle wrote: Mike Driscoll wrote: Ken, On Tue, Apr 22, 2008 at 1:36 PM, Kenneth McDonald [EMAIL PROTECTED] wrote: Sadly. Thanks, Ken -- http://mail.python.org/mailman/listinfo/python-list I've attached the 2.4 version. I also have some Windows binaries for Beautiful Soup uploaded to my website: http://www.pythonlibrary.org/python_modules.htm What on earth do you need a Windows binary for? BeautifulSoup is ONE PYTHON SOURCE FILE, BeautifulSoup.py. Ummm.. Why does it bother you? Mike seems to be offering a public service to Windows users: by downloading the .exe, I can double-click on one file, have the module or package installed (whether it contains one .py file or twenty or a series of compiled extension modules and their respective DLLs) and for a bonus it's registered in the system packages directory [*] and is therefore uninstallable from there. Executing strange executables is risky. One always wonders what else they install in addition to what they're supposed be installing. John Nagle This is a legitimate issue and one I don't know how to solve. It would be nice to have some kind of verification process, but I'm unaware of anything affordable. If you have any ideas, feel free to express them. I hope to get testimonials from developers or pythoneers eventually. Suggestions are welcome. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: annoying dictionary problem, non-existing keys
Thanks for your reply. Another point to note: if you get a personal reply (often you will just see replies on the list, but sometimes people will also mail you directly) it is usual to make sure the list gets copied in any reply. I hope you don't mind that I am sending a copy of this message to the list, so everyone understands that you are just learning the rules. regards Steve bvidinli wrote: Thank you for your answer, Please be tolerant a bit... 2008/4/24, Steve Holden [EMAIL PROTECTED]: bvidinli wrote: I posted to so many lists because, this issue is related to all lists, No, it isn't, as you would have discovered had you bothered to read the purpose of each list. For example, python-help and python-dev are mutually exclusive. May be, anyway, this is an idea for python, It isn't an idea for Python at all. It's you, telling the world that you haven't really used Python much and haven't read the manuals but would nevertheless like us to consider your ideas for improving the language. I am using python for months, currently i am using it by means of Object oriented, multi thread applications but i dont see myself a python expert yet.. this is related to development of python... No it isn't. Python already has the feature you requested. No, python does not have, php way is simpler, shorter. list.get('key') is a solution, but not the thing i want... i think list['key'] is simpler, this is my idea... python is generally better than php, but some aspects of php is better... such as web programming.. why are you so much defensive ? Terry wasn't being defensive, he was protecting you form the abue you would receive of you kept posting to the wrong list! Please be tolerant a bit.. The person who post may be a person who does not know list rules... Why hurt such people ? lets concentrate our energy on solutions... i think ideas all important for development of python, software i am sory anyway hope will be helpful. We hope you will be helpful too. For now it would probably be best to start by posting your questions on the regular comp.lang.python group, which is generally suitable for beginners who know something about programming. If you are new to programming as well then the python-tutor list would be more useful. I am not a beginner for programming, not for python, i am not python expert too... i do programming since 1988, i do web/php/system programming since 2000, python for 5 months.. Ask with a little humility (the people who answer questions here are doing it out of the goodness of their hearts, remember) and soon you will be able to pass their assistance on, returning the favor they did for you. Welcome to the Python community. Anyway, thank you for your answers, your guides, i am happy to hear from you, to hear from python community. At least, it is a live community... :) see you Bahattin. regards Steve 2008/4/24, Terry Reedy [EMAIL PROTECTED]: Python-dev is for discussion of development of future Python. Use python-list / comp.lang.python / gmane.comp.python.general for usage questions. -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get inner exception traceback
On 24 Apr, 15:00, Christian Heimes [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] schrieb: : class ReraisedException(Exception): def __init__(self, message, exc_info): Exception.__init__(self, message) self.inner_exception = exc_info try: try: import does_not_exit except ImportError: raise ReraisedException(Something wrong, sys.exc_info() ) except ReraisedException, e: ... # here you can use e.inner_exception except: This may lead to reference cycles, please readhttp://docs.python.org/dev/library/sys.html#sys.exc_info Christian- Nascondi testo tra virgolette - - Mostra testo tra virgolette - Thanks. I was not aware of that (Last time I read that section, the warning was not there). I usually do something like that in my scripts: try: do_something() except: err, detail, tb = sys.exc_info() print err, detail traceback.print_tb(tb) According to the document you linked to, also this causes circular reference, although in my case it is ininfluent , since I usually do it only before exiting a program after a fatal error. However, this seems like a dark spot in the implementation of CPython. Do you now if this has/will be cleaned in Python 3.x ? I'd like to see a 'print_tb' method in the exception class, so that I could do something like this: try: do_something() except Exception, e : # I know, in python 3.0 the syntax will be different print e e.print_tb() Ciao --- F.B. -- http://mail.python.org/mailman/listinfo/python-list
Loading associated files
I am trying to make a a simple databasing GUI interface and and have created a module to deal with parsing the data from a file and a GUI based program that displays this data using PyQt4, i know how to register files in the system registry using python and also using Inno Setup which i use to package my applications, but i cant work out how if a file is doubled clicked on to send the path of that file to python. I have looked into passing command line arguments to python and can send a specific pathname to python but ideally what i need is a generic command that i can write to the registry that passes the pathname of whichever file was doubled clicked!?! am i asking too much/does it exist/is there an easier way to do this!! CC -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] annoying dictionary problem, non-existing keys
bvidinli wrote: i use dictionaries to hold some config data, such as: conf={'key1':'value1','key2':'value2'} and so on... when i try to process conf, i have to code every time like: if conf.has_key('key1'): if conf['key1']'': other commands this is very annoying. in php, i was able to code only like: if conf['key1']=='someth' in python, this fails, because, if key1 does not exists, it raises an exception. MY question: is there a way to directly get value of an array/tuple/dict item by key, as in php above, even if key may not exist, i should not check if key exist, i should only use it, if it does not exist, it may return only empty, just as in php i hope you understand my question... See http://docs.python.org/lib/typesmapping.html for a description of the get method of dictionaries. Also look at the key in dict syntax on the same page. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Where to get BeautifulSoup--www.crummy.com appears to be down.
On 24 Apr, 16:33, Mike Driscoll [EMAIL PROTECTED] wrote: This is a legitimate issue and one I don't know how to solve. It would be nice to have some kind of verification process, but I'm unaware of anything affordable. If you have any ideas, feel free to express them. It'd be interesting (perhaps amusing) to adopt the infrastructure of one of the GNU/Linux distributions to maintain and distribute packages for Windows users. For a while, I've been tempted to experiment with cross-compilers and to try and produce Windows executables, but for simple Python-only modules, all you'd really need to do to prove the concept is to develop the client-side Windows software (eg. apt-get for Windows) which downloads package lists, verifies signatures, and works out where to put the package contents. Then, you could point your client at the appropriate sources and start obtaining the packages, knowing that there is some level of authenticity in the software you're getting. Of course, a lot of this could be more easily done with Cygwin, even if you disregard Cygwin's own installer, but I imagine that Windows users want the native experience. Paul -- http://mail.python.org/mailman/listinfo/python-list
Billing system written in python
Hi, I would like to develop a billing system for a cable tv system, basically what it does is have subscribers in db, compute billing statement, print for statement for distribution something like that. I was evaluating jbilling its a java base billing system that uses tomcat,mysql or postgress DB and java. Im looking similar to this but its written in python so that I wont start from scratch. Why not use jbilling instead if it solve you problem? Will the reason Im looking for a python solution is I want to learn python and java is bit complicated for me at this time since Im just a newbie in programing. Any suggestion? I was thinking of using django but Im more looking in to a ready made billing system that I will just do some tweaking and fine tunning to meet our need. like jbilling. Thanks, AC -- -- AC Perdon Registered Linux User #340122 -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for parsing this text?
Thanks to everyone for the help and feedback. It's amazing to me that I've been dealing with odd log files and other outputs for quite a while, and never really stumbled onto a parser as a solution. I got this far, with Paul's help, which manages my current set of files: from pyparsing import nestedExpr,Word,alphanums,QuotedString from pprint import pprint import re import glob files = glob.glob('wsout/*') for file in files : text = open(file).read() text = re.sub('\[',' [',text) # These 2 lines just drop double quotes text = re.sub('\]','] ',text) # that aren't related to a string text = re.sub('\[\]','None',text) # this drops the empty [] text = '[ ' + text + ' ]' # Needs an outer layer content = Word(alphanums+-_./()*=#\\${}| :,;[EMAIL PROTECTED]%%) | QuotedString('',multiline=True) structure = nestedExpr([, ], content).parseString(text) pprint(structure[0].asList()) I'm sure there are cooler ways to do some of that. I spent most of my time expanding the characters that constitute content. I'm concerned that over time I'll have things break as other characters show up. Specifically a few of the nodes are of German locale.. so I could get some odd international characters. It looks like pyparser has a constant for printable characters. I'm not sure if I can just use that, without worrying about it? At any rate, thumbs up on the parser! Definitely going to add to my toolbox. On Thu, Apr 24, 2008 at 8:19 AM, Mark Wooding [EMAIL PROTECTED] wrote: Eric Wertman [EMAIL PROTECTED] wrote: I have a set of files with this kind of content (it's dumped from WebSphere): [propertySet [[resourceProperties [[[description This is a required property. This is an actual database name, and its not the locally catalogued database name. The Universal JDBC Driver does not rely on information catalogued in the DB2 database directory.] [name databaseName] [required true] [type java.lang.String] [value DB2Foo]] ... Looks to me like S-expressions with square brackets instead of the normal round ones. I'll bet that the correct lexical analysis is approximately [ open-list propertySet symbol open-string [ open-list [ open-list resourcePropertiessymbol open-string (not close-string!) ... so it also looks as if strings aren't properly escaped. This is definitely not a pretty syntax. I'd suggest an initial tokenization pass for the lexical syntax [ open-list ] close-list [open-qlist ]close-qlist ... string whitespaceignore anything-else symbol Correct nesting should give you two kinds of lists -- which I've shown as `list' and `qlist' (for quoted-list), though given the nastiness of the dump you showed, there's no guarantee of correctness. Turn the input string (or file) into a list (generator?) of lexical objects above; then scan that recursively. The lists (or qlists) seem to have two basic forms: * properties, that is a list of the form [SYMBOL VALUE ...] which can be thought of as a declaration that some property, named by the SYMBOL, has a particular VALUE (or maybe VALUEs); and * property lists, which are just lists of properties. Property lists can be usefully turned into Python dictionaries, indexed by their SYMBOLs, assuming that they don't try to declare the same property twice. There are, alas, other kinds of lists too -- one of the property lists contains a property `[value []]' which simply contains an empty list. The right first-cut rule for disambiguation is probably that a property list is a non-empty list, all of whose items look like properties, and a property is an entry in a property list, and (initially at least) restrict properties to the simple form [SYMBOL VALUE] rather than allowing multiple values. Does any of this help? (In fact, this syntax looks so much like a demented kind of S-expression that I'd probably try to parse it, initially at least, by using a Common Lisp system's reader and a custom readtable, but that may not be useful to you.) -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
convert xhtml back to html
hi, I've got lots of xhtml pages that need to be fed to MS HTML Workshop to create CHM files. That application really hates xhtml, so I need to convert self-ending tags (e.g. br /) to plain html (e.g. br). Seems simple enough, but I'm having some trouble with it. regexps trip up because I also have to take into account 'img', 'meta', 'link' tags, not just the simple 'br' and 'hr' tags. Well, maybe there's a simple way to do that with regexps, but my simpleminded img[^(/)]+/ doesn't work. I'm not enough of a regexp pro to figure out that lookahead stuff. I'm not sure where to start now; I looked at BeautifulSoup and BeautifulStoneSoup, but I can't see how to modify the actual tag. thanks, --Tim Arnold -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for parsing this text?
On Apr 24, 10:42 am, Eric Wertman [EMAIL PROTECTED] wrote: I'm sure there are cooler ways to do some of that. I spent most of my time expanding the characters that constitute content. I'm concerned that over time I'll have things break as other characters show up. Specifically a few of the nodes are of German locale.. so I could get some odd international characters. If you want to add international characters without going to Unicode, a first cut would be to add pyparsing's string constant ascii8bit. It looks like pyparser has a constant for printable characters. I'm not sure if I can just use that, without worrying about it? I would discourage you from using printables, since it also includes '[', ']', and '', which are significant to other elements of the parser (but you could create your own variable initialized with printables, and then use replace([,) etc. to strip out the offending characters). I'm also a little concerned that you needed to add \t and \n to the content word - was this really necessary? None of your examples showed such words, and I would rather have you let pyparsing skip over the whitespace as is its natural behavior. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: convert xhtml back to html
Tim Arnold wrote: hi, I've got lots of xhtml pages that need to be fed to MS HTML Workshop to create CHM files. That application really hates xhtml, so I need to convert self-ending tags (e.g. br /) to plain html (e.g. br). Seems simple enough, but I'm having some trouble with it. regexps trip up because I also have to take into account 'img', 'meta', 'link' tags, not just the simple 'br' and 'hr' tags. Well, maybe there's a simple way to do that with regexps, but my simpleminded img[^(/)]+/ doesn't work. I'm not enough of a regexp pro to figure out that lookahead stuff. I'm not sure where to start now; I looked at BeautifulSoup and BeautifulStoneSoup, but I can't see how to modify the actual tag. thanks, --Tim Arnold -- http://mail.python.org/mailman/listinfo/python-list Whether or not you can find an application that does what you want, I don't know, but at the very least I can say this much. You should not be reading and parsing the text yourself! XHTML is valid XML, and there a lots of ways to read and parse XML with Python. (ElementTree is what I use, but other choices exist.) Once you use an existing package to read your files into an internal tree structure representation, it should be a relatively easy job to traverse the tree to emit the tags and text you want. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for parsing this text?
I would discourage you from using printables, since it also includes '[', ']', and '', which are significant to other elements of the parser (but you could create your own variable initialized with printables, and then use replace([,) etc. to strip out the offending characters). I'm also a little concerned that you needed to add \t and \n to the content word - was this really necessary? None of your examples showed such words, and I would rather have you let pyparsing skip over the whitespace as is its natural behavior. -- Paul You are right... I have taken those out and it still works. I was adding everything I could think of at one point in trying to determine what was breaking the parser. Some of the data in there is input free form... which means that any developer could have put just about anything in there... I find a lot of ^M stuff from day to day in other places. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem using copy.copy with my own class
George Sakkis wrote: First off, inheriting from a basic builtin type such as int and changing its constructor's signature is not typical; you should rethink your design unless you know what you're doing. Nah, I would never claim to know what I'm doing. However, I have to say that I have been finding this technique very useful. When I started developing this program, I used an int. Then I discovered that I needed to have a string associated with the int. By subclassing int to add a string, I managed to make the change transparent to the code I had already written. Only the new code that needed the associated string knew that it was available. In another case, I subclassed str so that I could have a long form for a string (e.g., a full name attached to the surname). Are these applications of subclassing bad form? What is the motivation for your warning? One way to make this work is to define the special __copy__ method [1], specifying explicitly how to create a copy of a Test instance: Normally (i.e. for pure Python classes that don't subclass a builtin other than object) copy.copy() is smart enough to know how to create a copy without an explicit __copy__ method, so in general you don't have to define it for every class that has to be copyable. Yes, I noted in my original posting (which seems to have fallen off this thread) that the __copy__method solved the problem (at least on one platform). However, I was wondering why it was necessary when what I was defining was supposedly the default action. Thanks for your explanation. The traceback is not obvious indeed. It turns out it involves calling the arcane __reduce_ex__ special method [2] defined for int, which returns a tuple of 5 items; the second is the tuple (class '__main__.Test', 0) and these are the arguments passed to Test.__new__. So another way of fixing it is keep Test.__new__ compatible with int.__new__ by making optional all arguments after the first: This suggestion is very interesting. It seems to be an alternative to the solution suggested by Gabriel. The reference that Gabriel provided includes the statement: Instances of a new-style type C are created using obj = C.__new__(C, *args) where args is the result of calling __getnewargs__() on the original object; if there is no __getnewargs__(), an empty tuple is assumed. Gabriel's solution using __getnewargs__ assures that args receives a non-empty tuple. Your solution renders the empty tuple impotent by specifying default values. Correct me if I am wrong. I would be interested in a translation into English of the following statement from the same reference that Gabriel provided: Implementing this method [i.e., __getnewargs__] is needed if the type establishes some internal invariants when the instance is created, or if the memory allocation is affected by the values passed to the __new__() method for the type (as it is for tuples and strings). What is an internal invariant? How do I know when the memory allocation is affected? Does my Test class affect the memory allocation? As a sidenote, your class works fine without changing anything when pickling/unpickling instead of copying, although pickle calls __reduce_ex__ too: from pickle import dumps,loads t = Test(0, 0) assert loads(dumps(t)) == t Perhaps someone more knowledgeable can explain the subtle differences between pickling and copying here. I have a situation in the full program where pickling seems to be failing in the same manner as copy, but I have not been able yet to reproduce the problem in a simple test program. Thanks to all for your comments. -- Jeffrey Barish -- http://mail.python.org/mailman/listinfo/python-list
Re: convert xhtml back to html
Tim Arnold [EMAIL PROTECTED] writes: hi, I've got lots of xhtml pages that need to be fed to MS HTML Workshop to create CHM files. That application really hates xhtml, so I need to convert self-ending tags (e.g. br /) to plain html (e.g. br). Seems simple enough, but I'm having some trouble with it. regexps trip up because I also have to take into account 'img', 'meta', 'link' tags, not just the simple 'br' and 'hr' tags. Well, maybe there's a simple way to do that with regexps, but my simpleminded img[^(/)]+/ doesn't work. I'm not enough of a regexp pro to figure out that lookahead stuff. Hi, I'm not sure if this is very helpful but the following works on the very simple example below. import re xhtml = 'phello img src=/img.png/ spam br/ bye /p' xtag = re.compile(r'([^]*?)/') xtag.sub(r'\1', xhtml) 'phello img src=/img.png spam br bye /p' -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
RE: MESSAGE RESPONSE
Dear Sir, Belcan has an absolute zero-tolerance policy toward material such as the material described. Thank you for your Concern, David Blubaugh From: Dan Upton [mailto:[EMAIL PROTECTED] Sent: Wed 4/23/2008 12:27 PM To: python-list@python.org Subject: Re: MESSAGE RESPONSE On Wed, Apr 23, 2008 at 10:24 AM, Diez B. Roggisch [EMAIL PROTECTED] wrote: Blubaugh, David A. schrieb: Is there a way to block these messages. I do not want to be caught with filth such as this material. I could lose my job with Belcan with evil messages such as these messages. If I (or *anybody*) knew how to block these messages, he or she would sell the resulting spam-filter for a fortunen that roughly amasses the one of scrooge mc duck - and go live on the bahamas or even buy them. Put up with it. It's (unfortunately) part of ze internet tubes. And as such, I find it hard to believe you could lose your job over it. This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Where to get BeautifulSoup--www.crummy.com appears to be down.
On Apr 24, 10:15 am, Paul Boddie [EMAIL PROTECTED] wrote: On 24 Apr, 16:33, Mike Driscoll [EMAIL PROTECTED] wrote: This is a legitimate issue and one I don't know how to solve. It would be nice to have some kind of verification process, but I'm unaware of anything affordable. If you have any ideas, feel free to express them. It'd be interesting (perhaps amusing) to adopt the infrastructure of one of the GNU/Linux distributions to maintain and distribute packages for Windows users. For a while, I've been tempted to experiment with cross-compilers and to try and produce Windows executables, but for simple Python-only modules, all you'd really need to do to prove the concept is to develop the client-side Windows software (eg. apt-get for Windows) which downloads package lists, verifies signatures, and works out where to put the package contents. Then, you could point your client at the appropriate sources and start obtaining the packages, knowing that there is some level of authenticity in the software you're getting. Of course, a lot of this could be more easily done with Cygwin, even if you disregard Cygwin's own installer, but I imagine that Windows users want the native experience. Paul I do download all my code from either PyPI or the extension developer's website. And I have experimented with MingW, but I haven't had a lot of luck with it. Of course, part of my problem is that I'm using a VM with MingW on it and I really need to just upgrade my dev box. Creating a client for this sort of thing does sound cool. Something else for me to think about anyway... Mike -- http://mail.python.org/mailman/listinfo/python-list
Installer
Hey all, I've created a python program that relies on pysqlite, wxpython, and matplotlib. Is there any way of creating an installer that will install all these modules, python 2.5 and my program? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: MESSAGE RESPONSE
On Thu, 24 Apr 2008 12:28:29 -0400 Blubaugh, David A. [EMAIL PROTECTED] wrote: Belcan has an absolute zero-tolerance policy toward material such as the material described. Hard to imagine that they would hold you responsible for something sent to you without your permission. On the other hand I can see them being concerned about the posting that you made when you resent it to the list. And really, who uses their business address for news/mailing lists. I own my own company and I won't even do that. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert xhtml back to html
Gary Herron [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Tim Arnold wrote: hi, I've got lots of xhtml pages that need to be fed to MS HTML Workshop to create CHM files. That application really hates xhtml, so I need to convert self-ending tags (e.g. br /) to plain html (e.g. br). Seems simple enough, but I'm having some trouble with it. regexps trip up because I also have to take into account 'img', 'meta', 'link' tags, not just the simple 'br' and 'hr' tags. Well, maybe there's a simple way to do that with regexps, but my simpleminded img[^(/)]+/ doesn't work. I'm not enough of a regexp pro to figure out that lookahead stuff. I'm not sure where to start now; I looked at BeautifulSoup and BeautifulStoneSoup, but I can't see how to modify the actual tag. thanks, --Tim Arnold -- http://mail.python.org/mailman/listinfo/python-list Whether or not you can find an application that does what you want, I don't know, but at the very least I can say this much. You should not be reading and parsing the text yourself! XHTML is valid XML, and there a lots of ways to read and parse XML with Python. (ElementTree is what I use, but other choices exist.) Once you use an existing package to read your files into an internal tree structure representation, it should be a relatively easy job to traverse the tree to emit the tags and text you want. Gary Herron I agree and I'd really rather not parse it myself. However, ET will clean up the file which in my case includes some comments required as metadata, so that won't work. Oh, I could get ET to read it and write a new parser--I see what you mean. I think I need to subclass so I could get ET to honor those comments too. That's one way to go, I was just hoping for something easier. thanks, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: NameError: global name 'Response' is not defined
Lalit schrieb: Hi I am very new to web development. I started with Pylons. I am using http://www.rexx.com/~dkuhlman/pylons_quick_site.html as reference to create a sample web page using pylons. I got stuck up at step 4.3 i.e when modifying controller to return Response('pfirstapp default/p') I am getting error of type 'exceptions.NameError': global name 'Response' is not defined It seems I am missing some package. I am not really sure. I installed python 2.5 and through easy_install imported pakages (pylons). Any clues would be appreciated Better ask such questions on the Pylons mailing list. Not that it is inappropriate here - but you will receive better answers because it is more specialized. Anyway, I doubt you miss a package - I'd rather guess you miss an import-statement. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: MESSAGE RESPONSE
Blubaugh, David A. schrieb: Dear Sir, Belcan has an absolute zero-tolerance policy toward material such as the material described. That pairs up nicely with them having zero knowledge about the internet. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find the parent of an old-style class?
On Apr 24, 7:16 am, Jasper [EMAIL PROTECTED] wrote: I'm stuck using a library based on old style classes, and need to find a class's parent at runtime. With new style classes you can use .__base__ to inspect a parent, but I can't remember how this was done in days of yore, before object. I've tried googling, but apparently my search term Fu is weak. :-( Can anyone help me out here? There must be something simple. It's very odd that you need to know a class's parent. I'm interested in hearing why you need this. In all my years, I've never had to do this. Regardless, I believe you are looking for __bases__. -- http://mail.python.org/mailman/listinfo/python-list
Re: Installer
I've created a python program that relies on pysqlite, wxpython, and matplotlib. Is there any way of creating an installer that will install all these modules, python 2.5 and my program? Sure. Look at Tools/msi in the Python code, and adjust it to your needs. Please don't use the official product code, but create your own one. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: convert xhtml back to html
Arnaud Delobelle [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Tim Arnold [EMAIL PROTECTED] writes: hi, I've got lots of xhtml pages that need to be fed to MS HTML Workshop to create CHM files. That application really hates xhtml, so I need to convert self-ending tags (e.g. br /) to plain html (e.g. br). Seems simple enough, but I'm having some trouble with it. regexps trip up because I also have to take into account 'img', 'meta', 'link' tags, not just the simple 'br' and 'hr' tags. Well, maybe there's a simple way to do that with regexps, but my simpleminded img[^(/)]+/ doesn't work. I'm not enough of a regexp pro to figure out that lookahead stuff. Hi, I'm not sure if this is very helpful but the following works on the very simple example below. import re xhtml = 'phello img src=/img.png/ spam br/ bye /p' xtag = re.compile(r'([^]*?)/') xtag.sub(r'\1', xhtml) 'phello img src=/img.png spam br bye /p' -- Arnaud Thanks for that. It is helpful--I guess I had a brain malfunction. Your example will work for me I'm pretty sure, except in some cases where the IMG alt text contains a gt sign. I'm not sure that's even possible, so maybe this will do the job. thanks, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: function that accepts any amount of arguments?
On Apr 24, 5:28 am, malkarouri [EMAIL PROTECTED] wrote: What's wrong with raising ZeroDivisionError (not stopping the exception in the first place)? Because when I use your module, call avg (or mean) without args, I should see an error that says, Hey, you have to pass at least one value in! ZeroDivisonError doesn't mean that. It means I tried to divide by zero. Naively, I don't see where I was dividing by zero (because I don't remember how to calculate the mean---that's what your code was for.) ValueError does mean that I didn't pass the right kind of arguments in. ValueError(No items specified) would be even clearer. (Or maybe TypeError?) In general, any exception thrown should be meaningful to the code you are throwing it to. That means they aren't familiar with how your code works. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert xhtml back to html
Arnaud Delobelle wrote: Tim Arnold [EMAIL PROTECTED] writes: hi, I've got lots of xhtml pages that need to be fed to MS HTML Workshop to create CHM files. That application really hates xhtml, so I need to convert self-ending tags (e.g. br /) to plain html (e.g. br). Seems simple enough, but I'm having some trouble with it. regexps trip up because I also have to take into account 'img', 'meta', 'link' tags, not just the simple 'br' and 'hr' tags. Well, maybe there's a simple way to do that with regexps, but my simpleminded img[^(/)]+/ doesn't work. I'm not enough of a regexp pro to figure out that lookahead stuff. Hi, I'm not sure if this is very helpful but the following works on the very simple example below. import re xhtml = 'phello img src=/img.png/ spam br/ bye /p' xtag = re.compile(r'([^]*?)/') xtag.sub(r'\1', xhtml) 'phello img src=/img.png spam br bye /p' You might try XIST (http://www.livinglogic.de/Python/xist): Code looks like this: from ll.xist import parsers from ll.xist.ns import html xhtml = 'phello img src=/img.png/ spam br/ bye /p' doc = parsers.parsestring(xhtml) print doc.bytes(xhtml=0) This outputs: phello img src=/img.png spam br bye /p (and a warning that the alt attribute is missing in the img ;)) Servus, Walter -- http://mail.python.org/mailman/listinfo/python-list
RE: convert xhtml back to html
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Tim Arnold Sent: Thursday, April 24, 2008 9:34 AM To: python-list@python.org Subject: convert xhtml back to html hi, I've got lots of xhtml pages that need to be fed to MS HTML Workshop to create CHM files. That application really hates xhtml, so I need to convert self-ending tags (e.g. br /) to plain html (e.g. br). Seems simple enough, but I'm having some trouble with it. regexps trip up because I also have to take into account 'img', 'meta', 'link' tags, not just the simple 'br' and 'hr' tags. Well, maybe there's a simple way to do that with regexps, but my simpleminded img[^(/)]+/ doesn't work. I'm not enough of a regexp pro to figure out that lookahead stuff. I'm not sure where to start now; I looked at BeautifulSoup and BeautifulStoneSoup, but I can't see how to modify the actual tag. thanks, --Tim Arnold -- http://mail.python.org/mailman/listinfo/python-list One method which wouldn't require much python code, would be to run the XHTML through a simple identity XSL tranform with the output method set to HTML. It would have the benefit that you wouldn't have to worry about any of the specifics of the transformation, though you would need an external dependency. As far as I know, both 4suite and lxml (my personal favorite: http://codespeak.net/lxml/) support XSLT in python. It might work out fine for you, but mixing regexps and XML always seems to work out badly in the end for me. - John Krukoff [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Installer
On Apr 24, 11:39 am, Chris [EMAIL PROTECTED] wrote: Hey all, I've created a python program that relies on pysqlite, wxpython, and matplotlib. Is there any way of creating an installer that will install all these modules, python 2.5 and my program? Thanks. Chris, If all you're doing is creating an installer for your custom Python program to be run on PCs without Python, then you should take a look at py2exe or gui2exe (a py2exe wrapper). I use the latter to roll my program into an exe, then I use Inno Setup (which is free) to create the installer. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: convert xhtml back to html
On 2008-04-24 19:16, John Krukoff wrote: -Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Tim Arnold Sent: Thursday, April 24, 2008 9:34 AM To: python-list@python.org Subject: convert xhtml back to html hi, I've got lots of xhtml pages that need to be fed to MS HTML Workshop to create CHM files. That application really hates xhtml, so I need to convert self-ending tags (e.g. br /) to plain html (e.g. br). Seems simple enough, but I'm having some trouble with it. regexps trip up because I also have to take into account 'img', 'meta', 'link' tags, not just the simple 'br' and 'hr' tags. Well, maybe there's a simple way to do that with regexps, but my simpleminded img[^(/)]+/ doesn't work. I'm not enough of a regexp pro to figure out that lookahead stuff. I'm not sure where to start now; I looked at BeautifulSoup and BeautifulStoneSoup, but I can't see how to modify the actual tag. You could filter the XHTML through mxTidy and set the hide_endtags to 1: http://www.egenix.com/products/python/mxExperimental/mxTidy/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 24 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 -- http://mail.python.org/mailman/listinfo/python-list
Re: Loading associated files
On Apr 24, 10:14 am, [EMAIL PROTECTED] wrote: I am trying to make a a simple databasing GUI interface and and have created a module to deal with parsing the data from a file and a GUI based program that displays this data using PyQt4, i know how to register files in the system registry using python and also using Inno Setup which i use to package my applications, but i cant work out how if a file is doubled clicked on to send the path of that file to python. I have looked into passing command line arguments to python and can send a specific pathname to python but ideally what i need is a generic command that i can write to the registry that passes the pathname of whichever file was doubled clicked!?! am i asking too much/does it exist/is there an easier way to do this!! CC I did this by writing the path to me script or exe and added %1 to the end, which basically means that my program can (or requires) a parameter passed to it. Here's an example: C:\Program Files\PyMail\wxsendmail.exe %1 That should work. Tested on Windows XP SP2 with Python 2.4/2.5. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: python-ldap - Operations Error
Thanks for the help guys, it works! I used the ldap.set_option(ldap.OPT_REFERRALS, 0) from http://peeved.org/blog/2007/11/20/ immedialtey after import, then did the initialize trace_level=2 and did the simple_bind_s. I was able to search and get the results. That trace_level thing is nice, i'm sure i will be debugging this more as i move forward :) Not sure if this is an AD thing or just something i needed to do with our particular server/config. Thanks again! -- http://mail.python.org/mailman/listinfo/python-list