title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Python Printing StdOut As It Received
1,152,160
<p>I'm trying to run wrap a simple (windows) command line tool up in a PyQt GUI app that I am writing. The problem I have is that the command line tool throws it's progress out to stdout (it's a server reset command so you get "Attempting to stop" and "Restarting" type output.</p> <p>What I am trying to do is capture the output so I can display it as part of my app. I assumed it would be quite simple to do something like the following :</p> <pre><code>import os import subprocess as sub cmd = "COMMAND LINE APP NAME -ARGS" proc = sub.Popen(cmd, shell=True, stdout=sub.PIPE).stdout while 1: line = proc.readline() if not line: break print line </code></pre> <p>This partially works in that I do get the contents of StdOut but instead of as the progress messages are sent I get it once the command line application exits and it seems to flush StdOut in one go.</p> <p>Is there a simple answer?</p>
2
2009-07-20T07:41:19Z
1,152,178
<p>Interactive communication through stdin/stdout is a common problem.</p> <p>You're in luck though, with PyQt you can use QProcess, as described here: <a href="http://diotavelli.net/PyQtWiki/Capturing%5FOutput%5Ffrom%5Fa%5FProcess" rel="nofollow">http://diotavelli.net/PyQtWiki/Capturing_Output_from_a_Process</a></p>
1
2009-07-20T07:47:39Z
[ "python", "stdout" ]
Python Printing StdOut As It Received
1,152,160
<p>I'm trying to run wrap a simple (windows) command line tool up in a PyQt GUI app that I am writing. The problem I have is that the command line tool throws it's progress out to stdout (it's a server reset command so you get "Attempting to stop" and "Restarting" type output.</p> <p>What I am trying to do is capture the output so I can display it as part of my app. I assumed it would be quite simple to do something like the following :</p> <pre><code>import os import subprocess as sub cmd = "COMMAND LINE APP NAME -ARGS" proc = sub.Popen(cmd, shell=True, stdout=sub.PIPE).stdout while 1: line = proc.readline() if not line: break print line </code></pre> <p>This partially works in that I do get the contents of StdOut but instead of as the progress messages are sent I get it once the command line application exits and it seems to flush StdOut in one go.</p> <p>Is there a simple answer?</p>
2
2009-07-20T07:41:19Z
1,198,143
<p>Do I understand the question? I believe you're running something like "echo first; sleep 60; echo second" and you want see the "first" well-ahead of the "second", but they're both spitting out at the same time.</p> <p>The reason you're having issues is that the operating system stores the output of processes in its memory. It will only take the trouble of sending the output to your program if the buffer has filled, or the other program has ended. So, we need to dig into the O/S and figure out how to tell it "Hey, gimme that!" This is generally known as asynchronous or non-blocking mode. </p> <p>Luckily someone has done the hard work for us. This guy has added a send() and recv() method to the python built-in Popen class. It also looks like he fixed the bugs that people found in the comments.</p> <p>Try it out: <a href="http://code.activestate.com/recipes/440554/" rel="nofollow">http://code.activestate.com/recipes/440554/</a></p>
0
2009-07-29T05:07:16Z
[ "python", "stdout" ]
Python iterators – how to dynamically assign self.next within a new style class?
1,152,238
<p>As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator.</p> <p>This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class?</p> <p>Example:</p> <pre><code>class IteratorWrapper1: def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here class IteratorWrapper2(object): def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here if __name__ == "__main__": for i in IteratorWrapper1(iter([1, 2, 3])): print i for j in IteratorWrapper2(iter([1, 2, 3])): print j </code></pre> <p>Gives the following output:</p> <pre><code>1 2 3 Traceback (most recent call last): ... TypeError: iter() returned non-iterator of type 'IteratorWrapper2' </code></pre>
11
2009-07-20T08:07:03Z
1,152,294
<p>Just return the iterator. That's what <code>__iter__</code> is for. It makes no sense to try to monkey-patch the object into being in iterator and return it when you already have an iterator.</p> <p>EDIT: Now with two methods. Once, monkey patching the wrapped iterator, second, kitty-wrapping the iterator.</p> <pre><code>class IteratorWrapperMonkey(object): def __init__(self, otheriter): self.otheriter = otheriter self.otheriter.close = self.close def close(self): print "Closed!" def __iter__(self): return self.otheriter class IteratorWrapperKitten(object): def __init__(self, otheriter): self.otheriter = otheriter def __iter__(self): return self def next(self): return self.otheriter.next() def close(self): print "Closed!" class PatchableIterator(object): def __init__(self, inp): self.iter = iter(inp) def next(self): return self.iter.next() def __iter__(self): return self if __name__ == "__main__": monkey = IteratorWrapperMonkey(PatchableIterator([1, 2, 3])) for i in monkey: print i monkey.close() kitten = IteratorWrapperKitten(iter([1, 2, 3])) for i in kitten: print i kitten.close() </code></pre> <p>Both methods work both with new and old-style classes.</p>
2
2009-07-20T08:23:43Z
[ "python", "iterator" ]
Python iterators – how to dynamically assign self.next within a new style class?
1,152,238
<p>As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator.</p> <p>This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class?</p> <p>Example:</p> <pre><code>class IteratorWrapper1: def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here class IteratorWrapper2(object): def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here if __name__ == "__main__": for i in IteratorWrapper1(iter([1, 2, 3])): print i for j in IteratorWrapper2(iter([1, 2, 3])): print j </code></pre> <p>Gives the following output:</p> <pre><code>1 2 3 Traceback (most recent call last): ... TypeError: iter() returned non-iterator of type 'IteratorWrapper2' </code></pre>
11
2009-07-20T08:07:03Z
1,152,328
<p>Looks like built-in <code>iter</code> doesn't check for <code>next</code> callable in an instance but in a class and <code>IteratorWrapper2</code> doesn't have any <code>next</code>. Below is simpler version of your problem</p> <pre><code>class IteratorWrapper2(object): def __init__(self, otheriter): self.next = otheriter.next def __iter__(self): return self it=iter([1, 2, 3]) myit = IteratorWrapper2(it) IteratorWrapper2.next # fails that is why iter(myit) fails iter(myit) # fails </code></pre> <p>so the solution would be to return <code>otheriter</code> in <code>__iter__</code></p> <pre><code>class IteratorWrapper2(object): def __init__(self, otheriter): self.otheriter = otheriter def __iter__(self): return self.otheriter </code></pre> <p>or write your own <code>next</code>, wrapping inner iterator</p> <pre><code>class IteratorWrapper2(object): def __init__(self, otheriter): self.otheriter = otheriter def next(self): return self.otheriter.next() def __iter__(self): return self </code></pre> <p>Though I do not understand why doesn't <code>iter</code> just use the <code>self.next</code> of instance.</p>
3
2009-07-20T08:31:11Z
[ "python", "iterator" ]
Python iterators – how to dynamically assign self.next within a new style class?
1,152,238
<p>As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator.</p> <p>This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class?</p> <p>Example:</p> <pre><code>class IteratorWrapper1: def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here class IteratorWrapper2(object): def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here if __name__ == "__main__": for i in IteratorWrapper1(iter([1, 2, 3])): print i for j in IteratorWrapper2(iter([1, 2, 3])): print j </code></pre> <p>Gives the following output:</p> <pre><code>1 2 3 Traceback (most recent call last): ... TypeError: iter() returned non-iterator of type 'IteratorWrapper2' </code></pre>
11
2009-07-20T08:07:03Z
1,152,353
<p>What you're trying to do makes sense, but there's something evil going on inside Python here.</p> <pre><code>class foo(object): c = 0 def __init__(self): self.next = self.next2 def __iter__(self): return self def next(self): if self.c == 5: raise StopIteration self.c += 1 return 1 def next2(self): if self.c == 5: raise StopIteration self.c += 1 return 2 it = iter(foo()) # Outputs: &lt;bound method foo.next2 of &lt;__main__.foo object at 0xb7d5030c&gt;&gt; print it.next # 2 print it.next() # 1?! for x in it: print x </code></pre> <p>foo() is an iterator which modifies its next method on the fly--perfectly legal anywhere else in Python. The iterator we create, it, has the method we expect: it.next is next2. When we use the iterator directly, by calling next(), we get 2. Yet, when we use it in a for loop, we get the original next, which we've clearly overwritten.</p> <p>I'm not familiar with Python internals, but it seems like an object's "next" method is being cached in <code>tp_iternext</code> (<a href="http://docs.python.org/c-api/typeobj.html#tp_iternext">http://docs.python.org/c-api/typeobj.html#tp_iternext</a>), and then it's not updated when the class is changed.</p> <p>This is definitely a Python bug. Maybe this is described in the generator PEPs, but it's not in the core Python documentation, and it's completely inconsistent with normal Python behavior.</p> <p>You could work around this by keeping the original next function, and wrapping it explicitly:</p> <pre><code>class IteratorWrapper2(object): def __init__(self, otheriter): self.wrapped_iter_next = otheriter.next def __iter__(self): return self def next(self): return self.wrapped_iter_next() for j in IteratorWrapper2(iter([1, 2, 3])): print j </code></pre> <p>... but that's obviously less efficient, and you should <em>not</em> have to do that.</p>
8
2009-07-20T08:33:45Z
[ "python", "iterator" ]
Python iterators – how to dynamically assign self.next within a new style class?
1,152,238
<p>As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator.</p> <p>This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class?</p> <p>Example:</p> <pre><code>class IteratorWrapper1: def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here class IteratorWrapper2(object): def __init__(self, otheriter): self._iterator = otheriter self.next = otheriter.next def __iter__(self): return self def close(self): if getattr(self._iterator, 'close', None) is not None: self._iterator.close() # other arbitrary resource cleanup code here if __name__ == "__main__": for i in IteratorWrapper1(iter([1, 2, 3])): print i for j in IteratorWrapper2(iter([1, 2, 3])): print j </code></pre> <p>Gives the following output:</p> <pre><code>1 2 3 Traceback (most recent call last): ... TypeError: iter() returned non-iterator of type 'IteratorWrapper2' </code></pre>
11
2009-07-20T08:07:03Z
12,657,458
<p>There are a bunch of places where CPython take surprising shortcuts based on <em>class</em> properties instead of <em>instance</em> properties. This is one of those places.</p> <p>Here is a simple example that demonstrates the issue:</p> <pre><code>def DynamicNext(object): def __init__(self): self.next = lambda: 42 </code></pre> <p>And here's what happens:</p> <pre> >>> instance = DynamicNext() >>> next(instance) … TypeError: DynamicNext object is not an iterator >>> </pre> <p>Now, digging into the CPython source code (from 2.7.2), here's the implementation of the <code>next()</code> builtin:</p> <pre><code>static PyObject * builtin_next(PyObject *self, PyObject *args) { … if (!PyIter_Check(it)) { PyErr_Format(PyExc_TypeError, "%.200s object is not an iterator", it-&gt;ob_type-&gt;tp_name); return NULL; } … } </code></pre> <p>And here's the implementation of PyIter_Check:</p> <pre><code>#define PyIter_Check(obj) \ (PyType_HasFeature((obj)-&gt;ob_type, Py_TPFLAGS_HAVE_ITER) &amp;&amp; \ (obj)-&gt;ob_type-&gt;tp_iternext != NULL &amp;&amp; \ (obj)-&gt;ob_type-&gt;tp_iternext != &amp;_PyObject_NextNotImplemented) </code></pre> <p>The first line, <code>PyType_HasFeature(…)</code>, is, after expanding all the constants and macros and stuff, equivalent to <code>DynamicNext.__class__.__flags__ &amp; 1L&lt;&lt;17 != 0</code>:</p> <pre> >>> instance.__class__.__flags__ & 1L&lt;&lt;17 != 0 True </pre> <p>So that check obviously isn't failing… Which must mean that the next check — <code>(obj)-&gt;ob_type-&gt;tp_iternext != NULL</code> — <em>is</em> failing.</p> <p>In Python, this line is roughly (roughly!) equivalent to <code>hasattr(type(instance), "next")</code>:</p> <pre> >>> type(instance) __main__.DynamicNext >>> hasattr(type(instance), "next") False </pre> <p>Which obviously fails because the <code>DynamicNext</code> type doesn't have a <code>next</code> method — only instances of that type do.</p> <p>Now, my CPython foo is weak, so I'm going to have to start making some educated guesses here… But I believe they are accurate.</p> <p>When a CPython type is created (that is, when the interpreter first evaluates the <code>class</code> block and the class' metaclass' <code>__new__</code> method is called), the values on the type's <code>PyTypeObject</code> struct are initialized… So if, when the <code>DynamicNext</code> type is created, no <code>next</code> method exists, the <code>tp_iternext</code>, field will be set to <code>NULL</code>, causing <code>PyIter_Check</code> to return false.</p> <p>Now, as the Glenn points out, this is almost certainly a bug in CPython… Especially given that correcting it would only impact performance when either the object being tested isn't iterable or dynamically assigns a <code>next</code> method (<em>very</em> approximately):</p> <pre><code>#define PyIter_Check(obj) \ (((PyType_HasFeature((obj)-&gt;ob_type, Py_TPFLAGS_HAVE_ITER) &amp;&amp; \ (obj)-&gt;ob_type-&gt;tp_iternext != NULL &amp;&amp; \ (obj)-&gt;ob_type-&gt;tp_iternext != &amp;_PyObject_NextNotImplemented)) || \ (PyObject_HasAttrString((obj), "next") &amp;&amp; \ PyCallable_Check(PyObject_GetAttrString((obj), "next")))) </code></pre> <p><strong>Edit</strong>: after a little bit of digging, the fix would not be this simple, because at least some portions of the code assume that, if <code>PyIter_Check(it)</code> returns <code>true</code>, then <code>*it-&gt;ob_type-&gt;tp_iternext</code> will exist… Which isn't necessarily the case (ie, because the <code>next</code> function exists on the instance, not the type).</p> <p>SO! That's why surprising things happen when you try to iterate over a new-style instance with a dynamically assigned <code>next</code> method.</p>
5
2012-09-29T23:40:18Z
[ "python", "iterator" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
1,152,484
<p>I don't think using <code>with</code> is the solution in this case. You'd have to raise an exception in the <code>BLOCK</code> part (which is specified by the user) and have the <code>__exit__</code> method return <code>True</code> to "swallow" the exception. So it would never look good.</p> <p>I'd suggest going for a syntax similar to the Perl syntax. Make your own extended <code>re</code> module (I'll call it <code>rex</code>) and have it set variables in its module namespace:</p> <pre><code>if rex.match('(\d+)g', '123g'): print rex._1 </code></pre> <p>As you can see in the comments below, this method is neither scope- nor thread-safe. You would only use this if you were completely certain that your application wouldn't become multi-threaded in the future and that any functions called from the scope that you're using this in will <em>also</em> use the same method.</p>
0
2009-07-20T09:05:03Z
[ "python", "code-golf", "idioms" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
1,152,490
<p>I don't think it's trivial. I don't want to have to sprinkle a redundant conditional around my code if I'm writing code like that often.</p> <p>This is slightly odd, but you can do this with an iterator:</p> <pre><code>import re def rematch(pattern, inp): matcher = re.compile(pattern) matches = matcher.match(inp) if matches: yield matches if __name__ == '__main__': for m in rematch("(\d+)g", "123g"): print(m.group(1)) </code></pre> <p>The odd thing is that it's using an iterator for something that isn't iterating--it's closer to a conditional, and at first glance it might look like it's going to yield multiple results for each match.</p> <p>It does seem odd that a context manager can't cause its managed function to be skipped entirely; while that's not explicitly one of the use cases of "with", it seems like a natural extension.</p>
11
2009-07-20T09:06:08Z
[ "python", "code-golf", "idioms" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
1,152,578
<p>If you're doing a lot of these in one place, here's an alternative answer:</p> <pre><code>import re class Matcher(object): def __init__(self): self.matches = None def set(self, matches): self.matches = matches def __getattr__(self, name): return getattr(self.matches, name) class re2(object): def __init__(self, expr): self.re = re.compile(expr) def match(self, matcher, s): matches = self.re.match(s) matcher.set(matches) return matches pattern = re2("(\d+)g") m = Matcher() if pattern.match(m, "123g"): print(m.group(1)) if not pattern.match(m, "x123g"): print "no match" </code></pre> <p>You can compile the regex once with the same thread safety as re, create a single reusable Matcher object for the whole function, and then you can use it very concisely. This also has the benefit that you can reverse it in the obvious way--to do that with an iterator, you'd need to pass a flag to tell it to invert its result.</p> <p>It's not much help if you're only doing a single match per function, though; you don't want to keep Matcher objects in a broader context than that; it'd cause the same issues as Blixt's solution.</p>
0
2009-07-20T09:25:15Z
[ "python", "code-golf", "idioms" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
7,669,147
<p>This is not really pretty-looking, but you can profit from the <code>getattr(object, name[, default])</code> built-in function using it like this:</p> <pre><code>&gt;&gt;&gt; getattr(re.match("(\d+)g", "123g"), 'group', lambda n:'')(1) '123' &gt;&gt;&gt; getattr(re.match("(\d+)g", "X23g"), 'group', lambda n:'')(1) '' </code></pre> <p>To mimic the <em>if match print group</em> flow, you can (ab)use the <code>for</code> statement this way:</p> <pre><code>&gt;&gt;&gt; for group in filter(None, [getattr(re.match("(\d+)g", "123g"), 'group', None)]): print(group(1)) 123 &gt;&gt;&gt; for group in filter(None, [getattr(re.match("(\d+)g", "X23g"), 'group', None)]): print(group(1)) &gt;&gt;&gt; </code></pre> <p>Of course you can define a little function to do the dirty work:</p> <pre><code>&gt;&gt;&gt; matchgroup = lambda p,s: filter(None, [getattr(re.match(p, s), 'group', None)]) &gt;&gt;&gt; for group in matchgroup("(\d+)g", "123g"): print(group(1)) 123 &gt;&gt;&gt; for group in matchgroup("(\d+)g", "X23g"): print(group(1)) &gt;&gt;&gt; </code></pre>
0
2011-10-06T00:08:25Z
[ "python", "code-golf", "idioms" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
8,512,642
<p>Not the perfect solution, but does allow you to chain several match options for the same str:</p> <pre><code>class MatchWrapper(object): def __init__(self): self._matcher = None def wrap(self, matcher): self._matcher = matcher def __getattr__(self, attr): return getattr(self._matcher, attr) def match(pattern, s, matcher): m = re.match(pattern, s) if m: matcher.wrap(m) return True else: return False matcher = MatchWrapper() s = "123g"; if _match("(\d+)g", line, matcher): print matcher.group(1) elif _match("(\w+)g", line, matcher): print matcher.group(1) else: print "no match" </code></pre>
0
2011-12-14T22:30:17Z
[ "python", "code-golf", "idioms" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
13,722,876
<p>Another nice syntax would be something like this:</p> <pre><code>header = re.compile('(.*?) = (.*?)$') footer = re.compile('(.*?): (.*?)$') if header.match(line) as m: key, value = m.group(1,2) elif footer.match(line) as m key, value = m.group(1,2) else: key, value = None, None </code></pre>
4
2012-12-05T12:05:15Z
[ "python", "code-golf", "idioms" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
19,917,971
<p>I have another way of doing this, based on Glen Maynard's solution:</p> <pre><code>for match in [m for m in [re.match(pattern,key)] if m]: print "It matched: %s" % match </code></pre> <p>Similar to Glen's solution, this itterates either 0 (if no match) or 1 (if a match) times.</p> <p>No sub needed, but less tidy as a result.</p>
1
2013-11-11T23:22:42Z
[ "python", "code-golf", "idioms" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
23,440,622
<p>Here's my solution:</p> <pre><code>import re s = 'hello world' match = [] if match.append(re.match('w\w+', s)) or any(match): print('W:', match.pop().group(0)) elif match.append(re.match('h\w+', s)) or any(match): print('H:', match.pop().group(0)) else: print('No match found') </code></pre> <p>You can use as many <strong>elif</strong> clauses as needed.</p> <p>Even better:</p> <pre><code>import re s = 'hello world' if vars().update(match=re.match('w\w+', s)) or match: print('W:', match.group(0)) elif vars().update(match=re.match('h\w+', s)) or match: print('H:', match.group(0)) else: print('No match found') </code></pre> <p>Both <strong>append</strong> and <strong>update</strong> return <strong>None</strong>. So you have to actually check the result of your expression by using the <strong>or</strong> part in every case.</p> <p>Unfortunately, this only works as long as the code resides top-level, i.e. not in a function.</p>
0
2014-05-03T05:24:06Z
[ "python", "code-golf", "idioms" ]
Alternative to the `match = re.match(); if match: ...` idiom?
1,152,385
<p>If you want to check if something matches a regex, if so, print the first group, you do..</p> <pre><code>import re match = re.match("(\d+)g", "123g") if match is not None: print match.group(1) </code></pre> <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p> <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p> <pre><code>if($blah ~= /(\d+)g/){ print $1 } </code></pre> <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment%5Fadding%5Fre%5Fto%5Fpython%5Fstring%5Fobjects/c0b7895">this reddit comment</a>,</p> <pre><code>with re_context.match('^blah', s) as match: if match: ... else: ... </code></pre> <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p> <pre><code>#!/usr/bin/env python2.6 import re class SRE_Match_Wrapper: def __init__(self, match): self.match = match def __exit__(self, type, value, tb): pass def __enter__(self): return self.match def __getattr__(self, name): if name == "__exit__": return self.__exit__ elif name == "__enter__": return self.__name__ else: return getattr(self.match, name) def rematch(pattern, inp): matcher = re.compile(pattern) x = SRE_Match_Wrapper(matcher.match(inp)) return x return match if __name__ == '__main__': # Example: with rematch("(\d+)g", "123g") as m: if m: print(m.group(1)) with rematch("(\d+)g", "123") as m: if m: print(m.group(1)) </code></pre> <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p> <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p> <pre><code>with rematch("(\d+)g", "123") as m: print(m.group(1)) # only executed if the match occurred </code></pre> <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a></p> <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>
23
2009-07-20T08:40:43Z
26,278,129
<p>This is what I do:</p> <pre><code>def re_match_cond (match_ref, regex, text): match = regex.match (text) del match_ref[:] match_ref.append (match) return match if __name__ == '__main__': match_ref = [] if re_match_cond (match_ref, regex_1, text): match = match_ref[0] ### ... elif re_match_cond (match_ref, regex_2, text): match = match_ref[0] ### ... elif re_match_cond (match_ref, regex_3, text): match = match_ref[0] ### ... else: ### no match ### ... </code></pre> <p>That is, I pass a list to the function to emulate pass-by-reference.</p>
0
2014-10-09T12:11:58Z
[ "python", "code-golf", "idioms" ]
django documentation locally setting up
1,152,479
<p>I was trying to setup django . I do have Django-1.1-alpha-1. I was trying to make the documentation which is located at Django-1.1-alpha-1/doc using make utility.</p> <p>But I am getting some error saying </p> <pre> > C:\django\Django-1.1-alpha-1\docs>C:\cygwin\bin\make.exe html <br>mkdir -p _build/html _build/doctrees sphinx-build -b html -d _build/doctrees . _build/html make: sphinx-build: Command not found make: *** [html] Error 127 </pre> <p>Do anybody knows how to solve this issue and make a html documentation</p> <p>Thanks J</p>
6
2009-07-20T09:03:42Z
1,152,499
<p>Install <a href="http://sphinx.pocoo.org/">sphinx</a>.</p> <pre><code>$ easy_install -U Sphinx </code></pre>
8
2009-07-20T09:08:29Z
[ "python", "django", "python-sphinx" ]
Is it better to use an exception or a return code in Python?
1,152,541
<p>You may know this recommendation from Microsoft about the use of exceptions in .NET:</p> <blockquote> <p>Performance Considerations</p> <p>... </p> <p>Throw exceptions only for extraordinary conditions, ...</p> <p>In addition, do not throw an exception when a return code is sufficient...</p> </blockquote> <p>(See the whole text at <a href="http://msdn.microsoft.com/en-us/library/system.exception.aspx">http://msdn.microsoft.com/en-us/library/system.exception.aspx</a>.)</p> <p>As a point of comparison, would you recommend the same for Python code? </p>
34
2009-07-20T09:18:45Z
1,152,556
<p>The pythonic thing to do is to raise and handle exceptions. The excellent book "Python in a nutshell" discusses this in 'Error-Checking Strategies' in Chapter 6.</p> <p>The book discusses EAFP ("it's easier to ask forgiveness than permission") vs. LBYL ("look before you leap").</p> <p>So to answer your question:</p> <p>No, I would not recommend the same for python code. I suggest you read chapter 6 of <a href="http://oreilly.com/catalog/9780596100469/">Python in a nutshell</a>. </p>
31
2009-07-20T09:21:54Z
[ "python", "performance", "exception" ]
Is it better to use an exception or a return code in Python?
1,152,541
<p>You may know this recommendation from Microsoft about the use of exceptions in .NET:</p> <blockquote> <p>Performance Considerations</p> <p>... </p> <p>Throw exceptions only for extraordinary conditions, ...</p> <p>In addition, do not throw an exception when a return code is sufficient...</p> </blockquote> <p>(See the whole text at <a href="http://msdn.microsoft.com/en-us/library/system.exception.aspx">http://msdn.microsoft.com/en-us/library/system.exception.aspx</a>.)</p> <p>As a point of comparison, would you recommend the same for Python code? </p>
34
2009-07-20T09:18:45Z
1,152,562
<p>In Python exceptions are not very expensive like they are in some other languages, so I wouldn't recommend trying to avoid exceptions. But if you do throw an exception you would usually want catch it somewhere in your code, the exception being if a fatal error occurs.</p>
7
2009-07-20T09:23:05Z
[ "python", "performance", "exception" ]
Is it better to use an exception or a return code in Python?
1,152,541
<p>You may know this recommendation from Microsoft about the use of exceptions in .NET:</p> <blockquote> <p>Performance Considerations</p> <p>... </p> <p>Throw exceptions only for extraordinary conditions, ...</p> <p>In addition, do not throw an exception when a return code is sufficient...</p> </blockquote> <p>(See the whole text at <a href="http://msdn.microsoft.com/en-us/library/system.exception.aspx">http://msdn.microsoft.com/en-us/library/system.exception.aspx</a>.)</p> <p>As a point of comparison, would you recommend the same for Python code? </p>
34
2009-07-20T09:18:45Z
1,153,109
<p>Usually, Python is geared towards expressiveness.<br> I would apply the same principle here: usually, you expect a function to return a <strong>result</strong> (in line with its name!) and not an error code.<br> For this reason, it is usually better raising an exception than returning an error code.</p> <p>However, what is stated in the MSDN article applies to Python as well, and it's not really connected to returning an error code instead of an exception.<br> In many cases, you can see exception handling used for normal flow control, and for handling <em>expected</em> situations. In certain environments, this has a huge impact on performance; in all environments it has a big impact on program expressiveness and maintainability.</p> <p>Exceptions are for <strong>exceptional</strong> situations, that are outside of normal program flow; if you expect something will happen, then you should handle directly, and then raise anything that you cannot expect / handle.</p> <p>Of course, this is not a recipe, but only an heuristic; the final decision is always up to the developer and onto the context and cannot be stated in a fixed set of guidelines - and this is much truer for exception handling.</p>
7
2009-07-20T11:49:51Z
[ "python", "performance", "exception" ]
Is it better to use an exception or a return code in Python?
1,152,541
<p>You may know this recommendation from Microsoft about the use of exceptions in .NET:</p> <blockquote> <p>Performance Considerations</p> <p>... </p> <p>Throw exceptions only for extraordinary conditions, ...</p> <p>In addition, do not throw an exception when a return code is sufficient...</p> </blockquote> <p>(See the whole text at <a href="http://msdn.microsoft.com/en-us/library/system.exception.aspx">http://msdn.microsoft.com/en-us/library/system.exception.aspx</a>.)</p> <p>As a point of comparison, would you recommend the same for Python code? </p>
34
2009-07-20T09:18:45Z
1,153,149
<p>The best way to understand exceptions is "<a href="http://www.hanselman.com/blog/IfYourMethodCantDoWhatItsNamePromisesItCanThrow.aspx">if your method can't do what its name says it does, throw</a>." My personal opinion is that this advice should be applied equally to both .NET and Python.</p> <p>The key difference is where you have methods that frequently can't do what their name says they should do, for instance, parsing strings as integers or retrieving a record from a database. The C# style is to avoid an exception being thrown in the first place:</p> <pre><code>int i; if (Int32.TryParse(myString, out i)) { doWhatever(i); } else { doWhatever(0); } </code></pre> <p>whereas Python is much more at ease with this kind of thing:</p> <pre><code>try: i = int(myString) except ValueError: i = 0 doWhatever(i); </code></pre>
8
2009-07-20T12:02:16Z
[ "python", "performance", "exception" ]
Is it better to use an exception or a return code in Python?
1,152,541
<p>You may know this recommendation from Microsoft about the use of exceptions in .NET:</p> <blockquote> <p>Performance Considerations</p> <p>... </p> <p>Throw exceptions only for extraordinary conditions, ...</p> <p>In addition, do not throw an exception when a return code is sufficient...</p> </blockquote> <p>(See the whole text at <a href="http://msdn.microsoft.com/en-us/library/system.exception.aspx">http://msdn.microsoft.com/en-us/library/system.exception.aspx</a>.)</p> <p>As a point of comparison, would you recommend the same for Python code? </p>
34
2009-07-20T09:18:45Z
1,269,369
<p>I think whether to return an error code or throw an exception is something very valid to think about, and a cross-linguistic comparison may be helpful and informative. I guess the very generalized answer to this concern is simply the consideration: that <strong>the set of legal return values for any function should be made as small as possible, and as large as necessary</strong>.</p> <p>Generally, this will mean that if a given method returns an integer number in a single test case, users can rightfully expect the method to <em>always</em> return an integer number <em>or</em> throw an exception. But, of course, the conceptually <em>simplest</em> way is not always the <em>best</em> way to handle things.</p> <p>The return-value-of-least-surprise is usually <code>None</code>; and if you look into it, you’ll see that it’s the very semantics of <code>None</code> that license its usage across the board: it is a singleton, immutable value that, in a lot of cases, evaluates to <code>False</code> or prohibits further computation—no concatenation, no arithmetics. So if you chose to write a <code>frob(x)</code> method that returns a number for a string input, and <code>None</code> for non-numeric strings and any other input, and you use that inside an expression like <code>a=42+frob('foo')</code>, you still get an exception very close to the point where bogus things happened. Of course, if you stuff <code>frob('foo')</code> into a database column that has not been defined with <code>NOT NULL</code>, you might run into problems perhaps months later. This may or may not be justifiable.</p> <p>So in most cases where you e.g. want to derive a number from a string, using somwething like a bare <code>float(x)</code> or <code>int(x)</code> is the way to go, as these built-ins will raise an exception when not given a digestable input. If that doesn’t suit your use case, consider returning <code>None</code> from a custom method; basically, this return value tells consumers that ‘Sorry, I was unable to understand your input.’. <strong>But</strong> you only want to do this if you positively know that going on in your program does make sense from that point onwards.</p> <p>You see, I just found out how to turn each notice, warning, and error message into a potentially show-stopping exception in, uhm, PHP. It just drives me crazy that a typo in a variable name generates in the standard PHP configuration, <strong>nothing but a notice to the user</strong>. This is <strong>so</strong> bad. The program just goes on doing things with a program code that does not make sense at all! I can’t believe people find this a feature.</p> <p>Likewise, one should view it like this: if, at any given point in time, it can be asserted with reasonable costs that the execution of a piece of code does no more make sense — since values are missing, are out of bounds, or are of an unexpected type, or when resources like a database connection have gone down — it is imperative, to minimize debugging headaches, to break execution and hand control up to any level in the code which feels entitled to handle the mishap.</p> <p>Experience shows that refraining from early action and allowing bogus values to creep into your data is good for nothing but making your code harder to debug. So are many examples of over-zealous type-casting: allowing integers to be added to floats is reasonable. To allow a string with nothing but digits to be added to a number is a bogus practice that is likely to create strange, unlocalized errors that may pop up on any given line that happens to be processing that data.</p>
3
2009-08-13T00:03:53Z
[ "python", "performance", "exception" ]
Is it better to use an exception or a return code in Python?
1,152,541
<p>You may know this recommendation from Microsoft about the use of exceptions in .NET:</p> <blockquote> <p>Performance Considerations</p> <p>... </p> <p>Throw exceptions only for extraordinary conditions, ...</p> <p>In addition, do not throw an exception when a return code is sufficient...</p> </blockquote> <p>(See the whole text at <a href="http://msdn.microsoft.com/en-us/library/system.exception.aspx">http://msdn.microsoft.com/en-us/library/system.exception.aspx</a>.)</p> <p>As a point of comparison, would you recommend the same for Python code? </p>
34
2009-07-20T09:18:45Z
17,359,901
<p>I did a simple experiment to compare the performance of raising exceptions with the following code:</p> <pre><code>from functools import wraps from time import time import logging def timed(foo): @wraps(foo) def bar(*a, **kw): s = time() foo(*a, **kw) e = time() print '%f sec' % (e - s) return bar class SomeException(Exception): pass def somefunc(_raise=False): if _raise: raise SomeException() else: return @timed def test1(_reps): for i in xrange(_reps): try: somefunc(True) except SomeException: pass @timed def test2(_reps): for i in xrange(_reps): somefunc(False) def main(): test1(1000000) test2(1000000) pass if __name__ == '__main__': main() </code></pre> <p>With the following results:</p> <ul> <li>Raising exceptions: 3.142000 sec</li> <li>Using <code>return</code>: 0.383000 sec</li> </ul> <p>Exceptions are about 8 times slower than using <code>return</code>.</p>
5
2013-06-28T07:55:11Z
[ "python", "performance", "exception" ]
memcache entities without ReferenceProperty
1,152,690
<p>I have a list of entities which I want to store in the memcache. The problem is that I have large Models referenced by their ReferenceProperty which are automatically also stored in the memcache. As a result I'm exceeding the size limit for objects stored in memcache. </p> <p>Is there any possibility to prevent the ReferenceProperties from loading the referenced Models while putting them in memcache? </p> <p>I tried something like </p> <pre><code>def __getstate__(self): odict = self.__dict__.copy() odict['model'] = None return odict </code></pre> <p>in the class I want to store in memcache, but that doesn't seem to do the trick. </p> <p>Any suggestions would be highly appreciated.</p> <p><strong>Edit:</strong> I verified by adding a logging-statement that the <code>__getstate__</code>-Method is executed.</p>
2
2009-07-20T09:57:29Z
1,152,934
<pre><code>odict = self.copy() del odict.model </code></pre> <p>would probably be better than using <strong>dict</strong> (unless getstate needs to return dict - i'm not familiar with it). Not sure if this solves Your problem, though... You could implement <strong>del</strong> in Model to test if it's freed. For me it looks like You still hold a reference somewhere.</p> <p>Also check out the pickle module - you would have to store everything under a single key, but it automaticly protects You from multiple references to the same object (stores it only once). Sorry no link, mobile client ;)</p> <p>Good luck!</p>
0
2009-07-20T11:08:06Z
[ "python", "google-app-engine", "memcached" ]
memcache entities without ReferenceProperty
1,152,690
<p>I have a list of entities which I want to store in the memcache. The problem is that I have large Models referenced by their ReferenceProperty which are automatically also stored in the memcache. As a result I'm exceeding the size limit for objects stored in memcache. </p> <p>Is there any possibility to prevent the ReferenceProperties from loading the referenced Models while putting them in memcache? </p> <p>I tried something like </p> <pre><code>def __getstate__(self): odict = self.__dict__.copy() odict['model'] = None return odict </code></pre> <p>in the class I want to store in memcache, but that doesn't seem to do the trick. </p> <p>Any suggestions would be highly appreciated.</p> <p><strong>Edit:</strong> I verified by adding a logging-statement that the <code>__getstate__</code>-Method is executed.</p>
2
2009-07-20T09:57:29Z
1,185,319
<p>For large entities, you might want to manually handle the loading of the related entities by storing the keys of the large entities as something other than a ReferenceProperty. That way you can choose when to load the large entity and when not to. Just use a long property store ids or a string property to store keynames.</p>
1
2009-07-26T19:16:15Z
[ "python", "google-app-engine", "memcached" ]
Is it possible to fetch a https page via an authenticating proxy with urllib2 in Python 2.5?
1,152,980
<p>I'm trying to add authenticating proxy support to an existing script, as it is the script connects to a https url (with urllib2.Request and urllib2.urlopen), scrapes the page and performs some actions based on what it has found. Initially I had hoped this would be as easy as simply adding a urllib2.ProxyHandler({"http": MY_PROXY}) as an arg to urllib2.build_opener which in turn is passed to urllib2.install_opener. Unfortunately this doesn't seem to work when attempting to do a urllib2.Request(ANY_HTTPS_PAGE). Googling around lends me to believe that the proxy support in urllib2 in python 2.5 does not support https urls. This surprised me to say the least. </p> <p>There appear to be solutions floating around the web, for example <a href="http://bugs.python.org/issue1424152" rel="nofollow">http://bugs.python.org/issue1424152</a> contains a patch for <code>urllib2</code> and <code>httplib</code> which purports to solve the issue (when I tried it the issue I began to get the following error instead: <code>urllib2.URLError: &lt;urlopen error (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol')&gt;</code>). There is a cookbook recipe here <a href="http://code.activestate.com/recipes/456195" rel="nofollow">http://code.activestate.com/recipes/456195</a> which I am planning to try next. All in all though I'm surprised this isn't supported "out of the box", which makes me wonder if I'm simply missing out on an obvious solutions, so in short — has anyone got a simple method for fetching https pages using an authenticating proxy with urllib2 in Python 2.5? Ideally this would work:</p> <pre><code>import urllib2 #perhaps the dictionary below needs a corresponding "https" entry? #That doesn't seem to work out of the box. proxy_handler = urllib2.ProxyHandler({"http": "http://user:pass@myproxy:port"}) urllib2.install_opener( urllib2.build_opener( urllib2.HTTPHandler, urllib2.HTTPSHandler, proxy_handler )) request = urllib2.Request(A_HTTPS_URL) response = urllib2.urlopen( request) print response.read() </code></pre> <p>Many Thanks</p>
3
2009-07-20T11:20:31Z
1,153,048
<p>You may want to look into <a href="http://code.google.com/p/httplib2/" rel="nofollow">httplib2</a>. One of the <a href="http://code.google.com/p/httplib2/wiki/Examples" rel="nofollow">examples</a> claims support for SOCKS proxies if the <a href="http://socksipy.sourceforge.net/" rel="nofollow">socks</a> module is installed.</p>
1
2009-07-20T11:36:22Z
[ "python", "proxy", "https", "urllib2" ]
Simple python / Beautiful Soup type question
1,153,167
<p>I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>:</p> <pre><code>from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('&lt;a href="http://www.some-site.com/"&gt;Some Hyperlink&lt;/a&gt;') href = soup.find("a")["href"] print href print href[href.indexOf('/'):] </code></pre> <p>All I get is:</p> <pre><code>Traceback (most recent call last): File "test.py", line 5, in &lt;module&gt; print href[href.indexOf('/'):] AttributeError: 'unicode' object has no attribute 'indexOf' </code></pre> <p>How should I convert whatever <code>href</code> is into a normal string?</p>
3
2009-07-20T12:05:38Z
1,153,182
<p>Python strings do not have an <code>indexOf</code> method.</p> <p>Use <code>href.index('/')</code></p> <p><code>href.find('/')</code> is similar. But <code>find</code> returns <code>-1</code> if the string is not found, while <code>index</code> raises a <code>ValueError</code>.</p> <p>So the correct thing is to use <code>index</code> (since '...'[-1] will return the last character of the string).</p>
7
2009-07-20T12:08:10Z
[ "python", "string", "beautifulsoup" ]
Simple python / Beautiful Soup type question
1,153,167
<p>I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>:</p> <pre><code>from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('&lt;a href="http://www.some-site.com/"&gt;Some Hyperlink&lt;/a&gt;') href = soup.find("a")["href"] print href print href[href.indexOf('/'):] </code></pre> <p>All I get is:</p> <pre><code>Traceback (most recent call last): File "test.py", line 5, in &lt;module&gt; print href[href.indexOf('/'):] AttributeError: 'unicode' object has no attribute 'indexOf' </code></pre> <p>How should I convert whatever <code>href</code> is into a normal string?</p>
3
2009-07-20T12:05:38Z
1,153,200
<p>href is a unicode string. If you need the regular string, then use </p> <pre><code>regular_string = str(href) </code></pre>
0
2009-07-20T12:11:12Z
[ "python", "string", "beautifulsoup" ]
Simple python / Beautiful Soup type question
1,153,167
<p>I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>:</p> <pre><code>from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('&lt;a href="http://www.some-site.com/"&gt;Some Hyperlink&lt;/a&gt;') href = soup.find("a")["href"] print href print href[href.indexOf('/'):] </code></pre> <p>All I get is:</p> <pre><code>Traceback (most recent call last): File "test.py", line 5, in &lt;module&gt; print href[href.indexOf('/'):] AttributeError: 'unicode' object has no attribute 'indexOf' </code></pre> <p>How should I convert whatever <code>href</code> is into a normal string?</p>
3
2009-07-20T12:05:38Z
1,153,687
<p>You mean find(), not indexOf().</p> <p><a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">Python docs on strings</a>.</p>
0
2009-07-20T13:47:23Z
[ "python", "string", "beautifulsoup" ]
Python: question about parsing human-readable text
1,153,183
<p>I'm parsing human-readable scientific text that is mostly in the field of chemistry. What I'm interested in is breaking the text into a list of words, scientific terms (more on that below), and punctuation marks.</p> <p>So for example, I expect the text "hello, world." to break into 4 tokens: 1) "hello"; 2) comma; 3) "world" and 4) period. Note that spaces don't require specialized tokens. </p> <p>The problem is related to the "scientific terms": these are names of chemical formulas such as "1-methyl-4-phenylpyridinium". Anyone who has ever learned chemistry knows these formulas can get quite long and may contain numbers, dashes and commas, and sometimes even parentheses, but I think it's safe to assume these lovely expressions can't contain spaces. Also, I believe these expressions must start with a number. I would like each such expression to come out as a single token.</p> <p>Today I use manual parsing to find "chunks" of text that begin with a number and end with either a space, a line break, or a punctuation mark followed by either a space or line break. </p> <p>I wondered if there's a smart solution (regex or other) I can use to tokenize the text according to the above specifications. I'm working in Python but this may be language agnostic.</p> <p>An example input (obviously disregard the content...):</p> <p>"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse."</p> <p>Example output (each token in its own line):</p> <pre><code>Hello . 1-methyl-4-phenylpyridinium is ultra - bad . However , 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse . </code></pre>
2
2009-07-20T12:08:21Z
1,153,254
<p>There might be a regex parsing what you want, but I don't think it will be very readable/maintainable. My advice would be to use a parser generator like ANTLR. I think you'll have to throw the notion overboard that you can make the chemical descriptions a single token, much too complex. ANTLR even has a debugger so you can see why it's not parsing something you think it should, I don't think that's possible using regexps.</p> <p>Regards,</p> <p>Sebastiaan</p>
0
2009-07-20T12:19:11Z
[ "python", "parsing" ]
Python: question about parsing human-readable text
1,153,183
<p>I'm parsing human-readable scientific text that is mostly in the field of chemistry. What I'm interested in is breaking the text into a list of words, scientific terms (more on that below), and punctuation marks.</p> <p>So for example, I expect the text "hello, world." to break into 4 tokens: 1) "hello"; 2) comma; 3) "world" and 4) period. Note that spaces don't require specialized tokens. </p> <p>The problem is related to the "scientific terms": these are names of chemical formulas such as "1-methyl-4-phenylpyridinium". Anyone who has ever learned chemistry knows these formulas can get quite long and may contain numbers, dashes and commas, and sometimes even parentheses, but I think it's safe to assume these lovely expressions can't contain spaces. Also, I believe these expressions must start with a number. I would like each such expression to come out as a single token.</p> <p>Today I use manual parsing to find "chunks" of text that begin with a number and end with either a space, a line break, or a punctuation mark followed by either a space or line break. </p> <p>I wondered if there's a smart solution (regex or other) I can use to tokenize the text according to the above specifications. I'm working in Python but this may be language agnostic.</p> <p>An example input (obviously disregard the content...):</p> <p>"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse."</p> <p>Example output (each token in its own line):</p> <pre><code>Hello . 1-methyl-4-phenylpyridinium is ultra - bad . However , 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse . </code></pre>
2
2009-07-20T12:08:21Z
1,153,461
<p>This will solve your current example. It can be tweaked for a larger data set.</p> <pre><code>import re splitterForIndexing = re.compile(r"(?:[a-zA-Z0-9\-,]+[a-zA-Z0-9\-])|(?:[,.])") source = "Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse." print "\n".join( splitterForIndexing.findall(source)) </code></pre> <p>The result is:</p> <pre><code>""" Hello . 1-methyl-4-phenylpyridinium is ultra-bad . However , 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse . """ </code></pre> <p>Sorry didn't see ultra-bad. If it's necessary for those words to be split..</p> <pre><code>import re splitterForIndexing = re.compile(r"(?:[a-zA-Z]+)|(?:[a-zA-Z0-9][a-zA-Z0-9\-(),]+[a-zA-Z0-9\-()])|(?:[,.-])") source = "Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine is worse." print "\n".join( splitterForIndexing.findall(source)) </code></pre> <p>Gives:</p> <pre><code>""" Hello . 1-methyl-4-phenylpyridinium is ultra - bad . However , 1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine is worse . """ </code></pre>
2
2009-07-20T13:06:02Z
[ "python", "parsing" ]
Python: question about parsing human-readable text
1,153,183
<p>I'm parsing human-readable scientific text that is mostly in the field of chemistry. What I'm interested in is breaking the text into a list of words, scientific terms (more on that below), and punctuation marks.</p> <p>So for example, I expect the text "hello, world." to break into 4 tokens: 1) "hello"; 2) comma; 3) "world" and 4) period. Note that spaces don't require specialized tokens. </p> <p>The problem is related to the "scientific terms": these are names of chemical formulas such as "1-methyl-4-phenylpyridinium". Anyone who has ever learned chemistry knows these formulas can get quite long and may contain numbers, dashes and commas, and sometimes even parentheses, but I think it's safe to assume these lovely expressions can't contain spaces. Also, I believe these expressions must start with a number. I would like each such expression to come out as a single token.</p> <p>Today I use manual parsing to find "chunks" of text that begin with a number and end with either a space, a line break, or a punctuation mark followed by either a space or line break. </p> <p>I wondered if there's a smart solution (regex or other) I can use to tokenize the text according to the above specifications. I'm working in Python but this may be language agnostic.</p> <p>An example input (obviously disregard the content...):</p> <p>"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse."</p> <p>Example output (each token in its own line):</p> <pre><code>Hello . 1-methyl-4-phenylpyridinium is ultra - bad . However , 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse . </code></pre>
2
2009-07-20T12:08:21Z
1,157,062
<p>I agree with Sebastiaan Megens that a regex solution may be possible, but probably not very readable or maintainable, especially if you are not already good with regular expressions. I would recommend the <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing module</a>, if you're sticking with Python (which I think is a good choice).</p> <p>Extra maintainability will come in very handy if your parsing needs should grow or change. (And I'm sure plenty of folks would say "when" rather than "if"! For example, someone already commented that you may need a more sophisticated notion of what needs to be allowed as a chemical name. Maybe your requirements are already changing before you've even chosen your tool!)</p>
0
2009-07-21T02:51:46Z
[ "python", "parsing" ]
Stopping a Long-Running Subprocess
1,153,407
<p>I create a subprocess using subprocess.Popen() that runs for a long time. It is called from its own thread, and the thread is blocked until the subprocess completes/returns.</p> <p>I want to be able to interrupt the subprocess so the process terminates when I want.</p> <p>Any ideas?</p>
1
2009-07-20T12:55:40Z
1,153,442
<p>I think you're looking for <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate" rel="nofollow"><code>Popen.terminate</code></a> or <code>.kill</code> function. They were added in python 2.6.</p>
4
2009-07-20T13:02:16Z
[ "python", "subprocess" ]
Mercurial scripting with python
1,153,469
<p>I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.</p> <p>The reason is that I want to add it to the css/js files on our website like so:</p> <pre><code>&lt;link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /&gt; </code></pre> <p>So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version.</p> <p><strong><em>OR</em></strong> if you know where to find good documentation for the mercurial <strong>python module</strong>, that would also be helpful. I can't seem to find it anywhere.</p> <h3>My Solution</h3> <p>I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:</p> <pre><code>import subprocess def get_hg_rev(file_path): pipe = subprocess.Popen( ["hg", "log", "-l", "1", "--template", "{node}", file_path], stdout=subprocess.PIPE ) return pipe.stdout.read() </code></pre> <p>example use:</p> <pre><code>&gt; path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css" &gt; get_hg_rev(path_to_file) '0ed525cf38a7b7f4f1321763d964a39327db97c4' </code></pre>
28
2009-07-20T13:08:01Z
1,153,499
<p>give a try to <a href="http://mercurial.selenic.com/wiki/KeywordExtension" rel="nofollow">the keyword extension</a></p>
3
2009-07-20T13:14:48Z
[ "python", "documentation", "mercurial", "revision" ]
Mercurial scripting with python
1,153,469
<p>I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.</p> <p>The reason is that I want to add it to the css/js files on our website like so:</p> <pre><code>&lt;link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /&gt; </code></pre> <p>So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version.</p> <p><strong><em>OR</em></strong> if you know where to find good documentation for the mercurial <strong>python module</strong>, that would also be helpful. I can't seem to find it anywhere.</p> <h3>My Solution</h3> <p>I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:</p> <pre><code>import subprocess def get_hg_rev(file_path): pipe = subprocess.Popen( ["hg", "log", "-l", "1", "--template", "{node}", file_path], stdout=subprocess.PIPE ) return pipe.stdout.read() </code></pre> <p>example use:</p> <pre><code>&gt; path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css" &gt; get_hg_rev(path_to_file) '0ed525cf38a7b7f4f1321763d964a39327db97c4' </code></pre>
28
2009-07-20T13:08:01Z
1,153,698
<p>Do you mean <a href="http://mercurial.selenic.com/wiki/MercurialApi">this documentation</a>?<br /> Note that, as stated in that page, there is no <em>official</em> API, because they still reserve the right to change it at any time. But you can see the list of changes in the last few versions, it is not very extensive.</p>
8
2009-07-20T13:49:47Z
[ "python", "documentation", "mercurial", "revision" ]
Mercurial scripting with python
1,153,469
<p>I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.</p> <p>The reason is that I want to add it to the css/js files on our website like so:</p> <pre><code>&lt;link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /&gt; </code></pre> <p>So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version.</p> <p><strong><em>OR</em></strong> if you know where to find good documentation for the mercurial <strong>python module</strong>, that would also be helpful. I can't seem to find it anywhere.</p> <h3>My Solution</h3> <p>I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:</p> <pre><code>import subprocess def get_hg_rev(file_path): pipe = subprocess.Popen( ["hg", "log", "-l", "1", "--template", "{node}", file_path], stdout=subprocess.PIPE ) return pipe.stdout.read() </code></pre> <p>example use:</p> <pre><code>&gt; path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css" &gt; get_hg_rev(path_to_file) '0ed525cf38a7b7f4f1321763d964a39327db97c4' </code></pre>
28
2009-07-20T13:08:01Z
1,154,440
<p>It's true there's no official API, but you can get an idea about best practices by reading other extensions, particularly those bundled with hg. For this particular problem, I would do something like this:</p> <pre><code>from mercurial import ui, hg from mercurial.node import hex repo = hg.repository('/path/to/repo/root', ui.ui()) fctx = repo.filectx('/path/to/file', 'tip') hexnode = hex(fctx.node()) </code></pre> <p><strong>Update</strong> At some point the parameter order changed, now it's like this:</p> <pre><code> repo = hg.repository(ui.ui(), '/path/to/repo/root' ) </code></pre>
14
2009-07-20T16:06:03Z
[ "python", "documentation", "mercurial", "revision" ]
Mercurial scripting with python
1,153,469
<p>I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.</p> <p>The reason is that I want to add it to the css/js files on our website like so:</p> <pre><code>&lt;link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /&gt; </code></pre> <p>So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version.</p> <p><strong><em>OR</em></strong> if you know where to find good documentation for the mercurial <strong>python module</strong>, that would also be helpful. I can't seem to find it anywhere.</p> <h3>My Solution</h3> <p>I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:</p> <pre><code>import subprocess def get_hg_rev(file_path): pipe = subprocess.Popen( ["hg", "log", "-l", "1", "--template", "{node}", file_path], stdout=subprocess.PIPE ) return pipe.stdout.read() </code></pre> <p>example use:</p> <pre><code>&gt; path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css" &gt; get_hg_rev(path_to_file) '0ed525cf38a7b7f4f1321763d964a39327db97c4' </code></pre>
28
2009-07-20T13:08:01Z
13,568,616
<p>I wanted to do the same thing the OP wanted to do, get <code>hg id -i</code> from a script (get tip revision of the whole REPOSITORY, not of a single FILE in that repo) but I did not want to use popen, and the code from <code>brendan</code> got me started, but wasn't what I wanted. </p> <p>So I wrote this... Comments/criticism welcome. This gets the tip rev in hex as a string.</p> <pre><code>from mercurial import ui, hg, revlog # from mercurial.node import hex # should I have used this? def getrepohex(reporoot): repo = hg.repository(ui.ui(), reporoot) revs = repo.revs('tip') if len(revs)==1: return str(repo.changectx(revs[0])) else: raise Exception("Internal failure in getrepohex") </code></pre>
0
2012-11-26T16:08:18Z
[ "python", "documentation", "mercurial", "revision" ]
Mercurial scripting with python
1,153,469
<p>I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.</p> <p>The reason is that I want to add it to the css/js files on our website like so:</p> <pre><code>&lt;link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /&gt; </code></pre> <p>So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version.</p> <p><strong><em>OR</em></strong> if you know where to find good documentation for the mercurial <strong>python module</strong>, that would also be helpful. I can't seem to find it anywhere.</p> <h3>My Solution</h3> <p>I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:</p> <pre><code>import subprocess def get_hg_rev(file_path): pipe = subprocess.Popen( ["hg", "log", "-l", "1", "--template", "{node}", file_path], stdout=subprocess.PIPE ) return pipe.stdout.read() </code></pre> <p>example use:</p> <pre><code>&gt; path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css" &gt; get_hg_rev(path_to_file) '0ed525cf38a7b7f4f1321763d964a39327db97c4' </code></pre>
28
2009-07-20T13:08:01Z
13,568,980
<p>FWIW to avoid fetching that value on every page/view render, I just have my deploy put it into the <code>settings.py</code> file. Then I can reference <code>settings.REVISION</code> without all the overhead of accessing mercurial and/or another process. Do you ever have this value change w/o reloading your server?</p>
1
2012-11-26T16:28:54Z
[ "python", "documentation", "mercurial", "revision" ]
Mercurial scripting with python
1,153,469
<p>I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.</p> <p>The reason is that I want to add it to the css/js files on our website like so:</p> <pre><code>&lt;link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /&gt; </code></pre> <p>So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version.</p> <p><strong><em>OR</em></strong> if you know where to find good documentation for the mercurial <strong>python module</strong>, that would also be helpful. I can't seem to find it anywhere.</p> <h3>My Solution</h3> <p>I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:</p> <pre><code>import subprocess def get_hg_rev(file_path): pipe = subprocess.Popen( ["hg", "log", "-l", "1", "--template", "{node}", file_path], stdout=subprocess.PIPE ) return pipe.stdout.read() </code></pre> <p>example use:</p> <pre><code>&gt; path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css" &gt; get_hg_rev(path_to_file) '0ed525cf38a7b7f4f1321763d964a39327db97c4' </code></pre>
28
2009-07-20T13:08:01Z
22,000,832
<p>An updated, cleaner subprocess version (uses <code>.check_output()</code>, added in Python 2.7/3.1) that I use in my Django settings file for a crude end-to-end deployment check (I dump it into an HTML comment):</p> <pre><code>import subprocess HG_REV = subprocess.check_output(['hg', 'id', '--id']).strip() </code></pre> <p>You could wrap it in a <code>try</code> if you don't want some strange hiccup to prevent startup:</p> <pre><code>try: HG_REV = subprocess.check_output(['hg', 'id', '--id']).strip() except OSError: HG_REV = "? (Couldn't find HG)" except subprocess.CalledProcessError as e: HG_REV = "? (Error {})".format(e.returncode) except: # should never have to deal with a hangup HG_REV = "???" </code></pre>
3
2014-02-24T22:50:00Z
[ "python", "documentation", "mercurial", "revision" ]
Mercurial scripting with python
1,153,469
<p>I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.</p> <p>The reason is that I want to add it to the css/js files on our website like so:</p> <pre><code>&lt;link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /&gt; </code></pre> <p>So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version.</p> <p><strong><em>OR</em></strong> if you know where to find good documentation for the mercurial <strong>python module</strong>, that would also be helpful. I can't seem to find it anywhere.</p> <h3>My Solution</h3> <p>I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:</p> <pre><code>import subprocess def get_hg_rev(file_path): pipe = subprocess.Popen( ["hg", "log", "-l", "1", "--template", "{node}", file_path], stdout=subprocess.PIPE ) return pipe.stdout.read() </code></pre> <p>example use:</p> <pre><code>&gt; path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css" &gt; get_hg_rev(path_to_file) '0ed525cf38a7b7f4f1321763d964a39327db97c4' </code></pre>
28
2009-07-20T13:08:01Z
28,800,428
<p> <strong>If you are using Python 2, you want to use <a href="http://mercurial.selenic.com/wiki/pythonhglib" rel="nofollow"><code>hglib</code></a>.</strong> </p> <p>I don't know what to use if you're using Python 3, sorry. Probably <a href="https://pypi.python.org/pypi/hgapi/1.7.2" rel="nofollow"><code>hgapi</code></a>.</p> <h2>Contents of this answer</h2> <ul> <li>Mercurial's APIs</li> <li>How to use hglib</li> <li>Why hglib is the best choice for Python 2 users</li> <li>If you're writing a hook, that discouraged internal interface is awfully convenient</li> </ul> <h2>Mercurial's APIs</h2> <p>Mercurial has two official APIs.</p> <ol> <li>The Mercurial command server. You can talk to it from Python 2 using the <code>hglib</code> (<a href="http://mercurial.selenic.com/wiki/pythonhglib" rel="nofollow">wiki</a>, <a href="https://pypi.python.org/pypi/python-hglib/" rel="nofollow">PyPI</a>) package, which is maintained by the Mercurial team.</li> <li>Mercurial's command-line interface. You can talk to it via <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow"><code>subprocess</code></a>, or <a href="https://pypi.python.org/pypi/hgapi/1.7.2" rel="nofollow"><code>hgapi</code></a>, or somesuch.</li> </ol> <h2>How to use hglib</h2> <p>Installation:</p> <pre><code>pip install python-hglib </code></pre> <p>Usage:</p> <pre><code>import hglib client = hglib.open("/path/to/repo") commit = client.log("tip") print commit.author </code></pre> <p>More usage information on the <a href="http://mercurial.selenic.com/wiki/pythonhglib#basic_usage" rel="nofollow">hglib wiki page</a>.</p> <h2>Why hglib is the best choice for Python 2 users</h2> <p>Because it is maintained by the Mercurial team, and it is what the Mercurial team recommend for interfacing with Mercurial. </p> <p><a href="http://mercurial.selenic.com/wiki/mercurialapi#why_you_shouldn.27t_use_mercurial.27s_internal_api" rel="nofollow">From Mercurial's wiki</a>, the following statement on interfacing with Mercurial:</p> <blockquote> <p>For the vast majority of third party code, the best approach is to use Mercurial's published, documented, and stable API: the command line interface. Alternately, use the <a href="http://mercurial.selenic.com/wiki/commandserver" rel="nofollow">CommandServer</a> or the libraries which are based on it to get a fast, stable, language-neutral interface. </p> </blockquote> <p>From the command server page:</p> <blockquote> <p>[The command server allows] third-party applications and libraries to communicate with Mercurial over a pipe that eliminates the per-command start-up overhead. Libraries can then encapsulate the command generation and parsing to present a language-appropriate API to these commands.</p> </blockquote> <p>The Python interface to the Mercurial command-server, as said, is <code>hglib</code>.</p> <p>The per-command overhead of the command line interface is no joke, by the way. I once built a very small test suite (only about 5 tests) that used <code>hg</code> via <code>subprocess</code> to create, commit by commit, a handful of repos with e.g. merge situations. Throughout the project, the runtime of suite stayed between 5 to 30 seconds, with nearly all time spent in the <code>hg</code> calls.</p> <h2>If you're writing a hook, that discouraged internal interface is awfully convenient</h2> <p>The signature of a Python hook function is like so:</p> <pre><code># In the hgrc: # [hooks] # preupdate.my_hook = python:/path/to/file.py:my_hook def my_hook( ui, repo, hooktype, ... hook-specific args, find them in `hg help config` ..., **kwargs) </code></pre> <p><code>ui</code> and <code>repo</code> are part of the aforementioned discouraged unofficial <a href="http://mercurial.selenic.com/wiki/mercurialapi" rel="nofollow">internal API</a>. The fact that they are right there in your function args makes them terribly convenient to use, such as in this example of a <code>preupdate</code> hook that disallows merges between certain branches.</p> <pre><code>def check_if_merge_is_allowed(ui, repo, hooktype, parent1, parent2, **kwargs): from_ = repo[parent2].branch() to_ = repo[parent1].branch() ... # return True if the hook fails and the merge should not proceed. </code></pre> <p>If your hook code is not so important, and you're not publishing it, you might choose to use the discouraged unofficial internal API. If your hook is part of an extension that you're publishing, better use <code>hglib</code>.</p>
3
2015-03-01T23:12:55Z
[ "python", "documentation", "mercurial", "revision" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
1,153,591
<p>You can write <a href="http://www.python.org/doc/2.5.2/ext/intro.html" rel="nofollow">python extensions</a> in C++. Basically python itself is written in C and you can use that to call into your C code. You have full access to your python objects. Also check out <a href="http://www.boost.org/doc/libs/1%5F39%5F0/libs/python/doc/index.html" rel="nofollow">Boost.Python</a>.</p>
1
2009-07-20T13:30:06Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
1,153,604
<p>Yes, it is possible, encouraged and <a href="http://docs.python.org/extending/extending.html" rel="nofollow">documented</a>. I have done it myself and found it to be very easy.</p>
7
2009-07-20T13:31:37Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
1,153,605
<p><a href="http://docs.python.org/c-api/index.html" rel="nofollow">Python/C API Reference Manual</a> - the API used by C and C++ programmers who want to write extension modules or embed Python.</p> <p><a href="http://docs.python.org/extending/index.html#extending-index" rel="nofollow">Extending and Embedding the Python Interpreter</a></p> <blockquote> <p>describes how to write modules in C or C++ to extend the Python interpreter with new modules. Those modules can define new functions but also new object types and their methods. The document also describes how to embed the Python interpreter in another application, for use as an extension language. Finally, it shows how to compile and link extension modules so that they can be loaded dynamically (at run time) into the interpreter, if the underlying operating system supports this feature.</p> </blockquote>
3
2009-07-20T13:31:48Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
1,153,606
<p>Try <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a>. Makes writing C++ extensions for Python easier.</p>
3
2009-07-20T13:31:53Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
1,153,623
<p>See this:</p> <p>Extending Python with C or C++ </p> <p>"It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls. </p> <p>To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header "Python.h". "</p> <p><a href="http://www.python.org/doc/2.5.2/ext/intro.html" rel="nofollow">http://www.python.org/doc/2.5.2/ext/intro.html</a></p> <p>PS It's spelt "integrate" :)</p>
1
2009-07-20T13:33:47Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
1,153,635
<p>Interfacing Python with C/C++ is not an easy task.</p> <p>Here I copy/paste a <a href="http://stackoverflow.com/questions/456884/extending-python-to-swig-or-not-to-swig/456949#456949">previous answer</a> on a previous question for the different methods to write a python extension. Featuring Boost.Python, SWIG, Pybindgen...</p> <ul> <li><p>You can write an extension yourself in C or C++ with the <a href="http://docs.python.org/extending/index.html">Python C-API</a>.</p> <p>In a word: don't do that except for learning how to do it. It's very difficult to do it correctly. You will have to increment and decrement references by hand and write a lot of code just to expose one function, with very few benefits.</p></li> <li><p><a href="http://www.swig.org/">Swig</a>:</p> <p>pro: you can generate bindings for many scripting languages.</p> <p>cons: I don't like the way the parser works. I don't know if they've made some progress but two years ago the C++ parser was quite limited. Most of the time I had to copy/paste my .h headers to add some <code>%</code> characters and to give extra hints to the swig parser.</p> <p>I also needed to deal with the Python C-API from time to time for (not so) complicated type conversions. </p> <p>I'm not using it anymore. </p></li> <li><p><a href="http://www.boost.org/doc/libs/1_39_0/libs/python/doc/index.html">Boost.Python</a>:</p> <p>pro: It's a very complete library. It allows you to do almost everything that is possible with the C-API, but in C++. I never had to write a C-API code with this library. I also never encountered a bug due to the library. Code for bindings either works like a charm or refuses to compile.</p> <p>It's probably one of the best solutions currently available if you already have some C++ library to bind. But if you only have a small C function to rewrite, I would probably try with Cython.</p> <p>cons: if you don't have a precompiled Boost.Python library you're going to use Bjam (sort of a replacement of make). I really hate Bjam and its syntax.</p> <p>Python libraries created with B.P tend to become obese. It also takes a <strong>lot</strong> of time to compile them.</p></li> <li><p><a href="http://sourceforge.net/projects/pygccxml/?source=dlp">Py++</a>: it's Boost.Python made easy. Py++ uses a C++ parser to read your code and then generates Boost.Python code automatically. You also have a great support from its author (no it's not me ;-) ).</p> <p>cons: only the problems due to Boost.Python itself.</p> <p><strong>Edit</strong> this project looks discontinued. While probably still working it may be better to consider switching.</p></li> <li><p><a href="http://code.google.com/p/pybindgen/">Pybindgen</a>:</p> <p>It generates the code dealing with the C-API. You can either describe functions and classes in a Python file, or let Pybindgen read your headers and generate bindings automatically (for this it uses pygccxml, a python library wrote by the author of Py++).</p> <p>cons: it's a young project, with a smaller team than Boost.Python. There are still some limitations: you cannot expose your own C++ exceptions, you cannot use multiple inheritance for your C++ classes. </p> <p>Anyway it's worth trying!</p></li> <li><p>Pyrex and <a href="http://www.cython.org/">Cython</a>:</p> <p>Here you don't write real C/C++ but a mix between Python and C. This intermediate code will generate a regular Python module. </p></li> </ul> <p><strong>Edit Jul 22 2013:</strong> Now Py++ looks discontinued, I'm now looking for a good alternative. I'm currently experimenting with Cython for my C++ library. This language is a mix between Python and C. Within a Cython function you can use either Python or C/C++ entities (functions, variables, objects, ...). </p> <p>Cython is quite easy to learn, has very good performance, and you can even avoid C/C++ completely if you don't have to interface legacy C++ libraries.</p> <p>However for C++ it comes with some problems. It is less "automagic" than Py++ was, so it's probably better for stable C++ API (which is now the case of my library). The biggest problem I see with Cython is with C++ polymorphism. With Py++/boost:python I was able to define a virtual method in C++, override it in Python, and have the Python version called within C++. With Cython it's still doable but you need to explicitly use the C-Python API.</p> <p><strong>Edit 2015-12-14:</strong></p> <p>There is a new one, <a href="https://github.com/wjakob/pybind11">pybind11</a>, similar to Boost.Python but with some potential advantages. For example it uses C++11 language features to make it simpler to create new bindings. Also it is a header-only library, so there is nothing to compile before using it, and no library to link. </p> <p>I played with it a little bit and it was indeed quite simple and pleasant to use. My only fear is that like Boot.Python it could lead to long compilation time and large libraries. I haven't done any benchmark yet.</p>
53
2009-07-20T13:35:54Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
1,153,884
<p>I've used PyCxx <a href="http://cxx.sourceforge.net/" rel="nofollow">http://cxx.sourceforge.net/</a> in the past and i found that it was very good. </p> <p>It wraps the python c API in a very elegant manner and makes it very simple to use. It is very easy to write python extension in c++. It is provided with clear examples so it is easy to get started.</p> <p>I've really enjoyed using this library and I do recommend it. </p>
2
2009-07-20T14:19:57Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
1,154,056
<p>We use <a href="http://www.swig.org/" rel="nofollow">swig</a> very successfully in our product.</p> <p>Basically swig takes your C++ code and generates a python wrapper around it.</p>
3
2009-07-20T14:52:10Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
9,513,677
<p>It depends on your portability requirements. I've been struggling with this for a while, and I ended up wrapping my C++ using the <a href="http://docs.python.org/extending/index.html" rel="nofollow">python API</a> directly because I need something that works on systems where the admin has only hacked together a mostly-working gcc and python installation. </p> <p>In theory Boost.Python should be a very good option, since Boost is available (almost) everywhere. Unfortunately, if you end up on a OS with an older <em>default</em> python installation (our collaboration is stuck with 2.4), you'll run into problems if you try to run Boost.Python with a newer version (we all use Python 2.6). Since your admin likely didn't bother to install a version of Boost corresponding to every python version, you'll have to build it yourself. </p> <p>So if you don't mind possibly requiring some Boost setup on every system your code runs on, use Boost.Python. If you want code that will definitely work on any system with Python and a C++ compiler, use the Python API. </p>
2
2012-03-01T09:31:20Z
[ "c++", "python", "integration" ]
Integrate Python And C++
1,153,577
<p>I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.</p> <p>Is it possible to integrate C++ and Python in the same project?</p>
29
2009-07-20T13:28:04Z
18,262,313
<p>Another interesting way to do is python code generation by running python itself to parse c++ header files. <a href="http://answers.opencv.org/question/6618/how-python-api-is-generated/" rel="nofollow">OpenCV team successfully took this approach</a> and now they have done exact same thing to make java wrapper for OpenCV library. I found this created cleaner Python API without limitation caused by a certain library.</p>
1
2013-08-15T21:37:47Z
[ "c++", "python", "integration" ]
How do I debug a py2exe 'application failed to initialize properly' error?
1,153,643
<p>I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an exe, but when I actually try to run that it barks some cryptic error message. At first they were simple messages saying it couldn't find certain DLLs, but even after giving it all the DLLs it wanted, it now returns this:</p> <pre><code>The application failed to initialize properly (0xc0000142). Click OK to terminate the application. </code></pre> <p>So I broke things down and just made a very, very simple application utilizing wxPython just to see if that would work, or if some of the more complicated features of my original app were getting in the way. But even my simple test returned the same error. Here's the code for the simple test script:</p> <pre><code>import wx class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX) panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE) main_sizer = wx.BoxSizer(wx.VERTICAL) testtxt = wx.StaticText(panel, -1, label='This is a test!') main_sizer.Add(testtxt, 0, wx.ALIGN_CENTER) panel.SetSizerAndFit(main_sizer) self.Show(1) return app = wx.PySimpleApp() frame = MainWindow(None, -1, 'Test App') app.MainLoop() </code></pre> <p>And here's the py2exe setup script I used:</p> <pre><code>#!/usr/bin/python from distutils.core import setup import py2exe manifest = """ &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;assemblyIdentity version="0.64.1.0" processorArchitecture="x86" name="Controls" type="win32" /&gt; &lt;description&gt;Test Program&lt;/description&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;/assembly&gt; """ setup( windows = [ { "script": "testme.py", "icon_resources": [(1, "testme.ico")], "other_resources": [(24,1, manifest)] } ], data_files=["testme.ico"] </code></pre> <p>)</p> <p>Then I run <code>python setup.py py2exe</code>, it generates the EXE file, warns about some DLL files (which I subsequently copy into the dist directory), but then when I try to run the EXE, I get the error I quoted above immediately.</p>
7
2009-07-20T13:37:08Z
1,153,721
<p>I've used py2exe before and I've never run across a situation like this....</p> <p>However, it sounds like missing dependencies are your problem.....</p> <p>Does the packaged program work on your machine but not on others?</p> <p>If so, run the packaged application within DEPENDS (dependency walker) on both machines and compare to hopefully discern which packages didn't get included. </p> <p>Good Luck</p>
0
2009-07-20T13:54:20Z
[ "python", "wxpython", "py2exe" ]
How do I debug a py2exe 'application failed to initialize properly' error?
1,153,643
<p>I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an exe, but when I actually try to run that it barks some cryptic error message. At first they were simple messages saying it couldn't find certain DLLs, but even after giving it all the DLLs it wanted, it now returns this:</p> <pre><code>The application failed to initialize properly (0xc0000142). Click OK to terminate the application. </code></pre> <p>So I broke things down and just made a very, very simple application utilizing wxPython just to see if that would work, or if some of the more complicated features of my original app were getting in the way. But even my simple test returned the same error. Here's the code for the simple test script:</p> <pre><code>import wx class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX) panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE) main_sizer = wx.BoxSizer(wx.VERTICAL) testtxt = wx.StaticText(panel, -1, label='This is a test!') main_sizer.Add(testtxt, 0, wx.ALIGN_CENTER) panel.SetSizerAndFit(main_sizer) self.Show(1) return app = wx.PySimpleApp() frame = MainWindow(None, -1, 'Test App') app.MainLoop() </code></pre> <p>And here's the py2exe setup script I used:</p> <pre><code>#!/usr/bin/python from distutils.core import setup import py2exe manifest = """ &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;assemblyIdentity version="0.64.1.0" processorArchitecture="x86" name="Controls" type="win32" /&gt; &lt;description&gt;Test Program&lt;/description&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;/assembly&gt; """ setup( windows = [ { "script": "testme.py", "icon_resources": [(1, "testme.ico")], "other_resources": [(24,1, manifest)] } ], data_files=["testme.ico"] </code></pre> <p>)</p> <p>Then I run <code>python setup.py py2exe</code>, it generates the EXE file, warns about some DLL files (which I subsequently copy into the dist directory), but then when I try to run the EXE, I get the error I quoted above immediately.</p>
7
2009-07-20T13:37:08Z
1,153,867
<p>You are not supposed to copy ALL of the .dlls it complains about! Some of them are Windows system files, and they are present in the correct places on the system. If you copy them into the dist folder, things won't work correctly.</p> <p>In general, you only want to copy .dlls which are specific to your application. Not system .dlls. In some situations you may need to ship vcredist_xx.exe in your installer to get the MSVC runtime on the system. You should never try to ship those .dlls files "raw" by yourself. Use the redist package, it will save you time and frustration.</p> <p>Have you tried following the directions here: <a href="http://wiki.wxpython.org/SmallApp" rel="nofollow">http://wiki.wxpython.org/SmallApp</a> ?</p>
0
2009-07-20T14:17:17Z
[ "python", "wxpython", "py2exe" ]
How do I debug a py2exe 'application failed to initialize properly' error?
1,153,643
<p>I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an exe, but when I actually try to run that it barks some cryptic error message. At first they were simple messages saying it couldn't find certain DLLs, but even after giving it all the DLLs it wanted, it now returns this:</p> <pre><code>The application failed to initialize properly (0xc0000142). Click OK to terminate the application. </code></pre> <p>So I broke things down and just made a very, very simple application utilizing wxPython just to see if that would work, or if some of the more complicated features of my original app were getting in the way. But even my simple test returned the same error. Here's the code for the simple test script:</p> <pre><code>import wx class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX) panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE) main_sizer = wx.BoxSizer(wx.VERTICAL) testtxt = wx.StaticText(panel, -1, label='This is a test!') main_sizer.Add(testtxt, 0, wx.ALIGN_CENTER) panel.SetSizerAndFit(main_sizer) self.Show(1) return app = wx.PySimpleApp() frame = MainWindow(None, -1, 'Test App') app.MainLoop() </code></pre> <p>And here's the py2exe setup script I used:</p> <pre><code>#!/usr/bin/python from distutils.core import setup import py2exe manifest = """ &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;assemblyIdentity version="0.64.1.0" processorArchitecture="x86" name="Controls" type="win32" /&gt; &lt;description&gt;Test Program&lt;/description&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;/assembly&gt; """ setup( windows = [ { "script": "testme.py", "icon_resources": [(1, "testme.ico")], "other_resources": [(24,1, manifest)] } ], data_files=["testme.ico"] </code></pre> <p>)</p> <p>Then I run <code>python setup.py py2exe</code>, it generates the EXE file, warns about some DLL files (which I subsequently copy into the dist directory), but then when I try to run the EXE, I get the error I quoted above immediately.</p>
7
2009-07-20T13:37:08Z
1,154,115
<p>Are you sure that you give the same dlls that the one used by wxPython.</p> <p>The vc++ dlls used by wxpython can be downloaded from the wxpython download page. Did you try these one?</p>
0
2009-07-20T15:04:14Z
[ "python", "wxpython", "py2exe" ]
How do I debug a py2exe 'application failed to initialize properly' error?
1,153,643
<p>I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an exe, but when I actually try to run that it barks some cryptic error message. At first they were simple messages saying it couldn't find certain DLLs, but even after giving it all the DLLs it wanted, it now returns this:</p> <pre><code>The application failed to initialize properly (0xc0000142). Click OK to terminate the application. </code></pre> <p>So I broke things down and just made a very, very simple application utilizing wxPython just to see if that would work, or if some of the more complicated features of my original app were getting in the way. But even my simple test returned the same error. Here's the code for the simple test script:</p> <pre><code>import wx class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX) panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE) main_sizer = wx.BoxSizer(wx.VERTICAL) testtxt = wx.StaticText(panel, -1, label='This is a test!') main_sizer.Add(testtxt, 0, wx.ALIGN_CENTER) panel.SetSizerAndFit(main_sizer) self.Show(1) return app = wx.PySimpleApp() frame = MainWindow(None, -1, 'Test App') app.MainLoop() </code></pre> <p>And here's the py2exe setup script I used:</p> <pre><code>#!/usr/bin/python from distutils.core import setup import py2exe manifest = """ &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;assemblyIdentity version="0.64.1.0" processorArchitecture="x86" name="Controls" type="win32" /&gt; &lt;description&gt;Test Program&lt;/description&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;/assembly&gt; """ setup( windows = [ { "script": "testme.py", "icon_resources": [(1, "testme.ico")], "other_resources": [(24,1, manifest)] } ], data_files=["testme.ico"] </code></pre> <p>)</p> <p>Then I run <code>python setup.py py2exe</code>, it generates the EXE file, warns about some DLL files (which I subsequently copy into the dist directory), but then when I try to run the EXE, I get the error I quoted above immediately.</p>
7
2009-07-20T13:37:08Z
1,154,736
<p>Note that there is a later version of the Visual C++ 2008 Redistributable package: <a href="http://www.microsoft.com/downloads/info.aspx?na=47&amp;p=2&amp;SrcDisplayLang=en&amp;SrcCategoryId=&amp;SrcFamilyId=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&amp;u=details.aspx%3ffamilyid%3dA5C84275-3B97-4AB7-A40D-3802B2AF5FC2%26displaylang%3den">SP1</a>. However, both the SP1 and the earlier release don't install the DLLs into the path. As the download page says (my emphasis):</p> <blockquote> <p>This package installs runtime components of C Runtime (CRT), Standard C++, ATL, MFC, OpenMP and MSDIA libraries. For libraries that support side-by-side deployment model (CRT, SCL, ATL, MFC, OpenMP) they are installed <strong>into the native assembly cache, also called WinSxS folder</strong>, on versions of Windows operating system that support side-by-side assemblies.</p> </blockquote> <p>You will probably find these files in the <code>%WINDIR%\WinSxS</code> folder and not in the path.What I think you need to do is incorporate the manifest information for the relevant DLLs (found in <code>%WINDIR%\WinSxS\Manifests</code>) into your <code>setup.py</code>. I added the following section:</p> <pre><code>&lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.30729.4918" processorArchitecture="X86" publicKeyToken="1fc8b3b9a1e18e3b" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; </code></pre> <p>immediately after the existing <code>&lt;dependency&gt;</code> section, and rebuilt the exe: it ran without problems. <strong>Note:</strong> depending on exactly what version of the Visual C++ files you installed, the above info may not be exactly correct. Look at the manifests on your system and use the correct <code>version</code>, <code>publicKeyToken</code> etc.</p> <p>Alternatively, look at <a href="http://stackoverflow.com/questions/1145662/py2exe-compiled-python-windows-application-wont-run-because-of-dll">this answer</a> for how to deploy the DLLs with your application (as opposed to assuming they already exist on the target system). Oh ... I see you asked that original question ;-)</p>
9
2009-07-20T17:11:13Z
[ "python", "wxpython", "py2exe" ]
How do I debug a py2exe 'application failed to initialize properly' error?
1,153,643
<p>I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an exe, but when I actually try to run that it barks some cryptic error message. At first they were simple messages saying it couldn't find certain DLLs, but even after giving it all the DLLs it wanted, it now returns this:</p> <pre><code>The application failed to initialize properly (0xc0000142). Click OK to terminate the application. </code></pre> <p>So I broke things down and just made a very, very simple application utilizing wxPython just to see if that would work, or if some of the more complicated features of my original app were getting in the way. But even my simple test returned the same error. Here's the code for the simple test script:</p> <pre><code>import wx class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX) panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE) main_sizer = wx.BoxSizer(wx.VERTICAL) testtxt = wx.StaticText(panel, -1, label='This is a test!') main_sizer.Add(testtxt, 0, wx.ALIGN_CENTER) panel.SetSizerAndFit(main_sizer) self.Show(1) return app = wx.PySimpleApp() frame = MainWindow(None, -1, 'Test App') app.MainLoop() </code></pre> <p>And here's the py2exe setup script I used:</p> <pre><code>#!/usr/bin/python from distutils.core import setup import py2exe manifest = """ &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;assemblyIdentity version="0.64.1.0" processorArchitecture="x86" name="Controls" type="win32" /&gt; &lt;description&gt;Test Program&lt;/description&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;/assembly&gt; """ setup( windows = [ { "script": "testme.py", "icon_resources": [(1, "testme.ico")], "other_resources": [(24,1, manifest)] } ], data_files=["testme.ico"] </code></pre> <p>)</p> <p>Then I run <code>python setup.py py2exe</code>, it generates the EXE file, warns about some DLL files (which I subsequently copy into the dist directory), but then when I try to run the EXE, I get the error I quoted above immediately.</p>
7
2009-07-20T13:37:08Z
1,573,757
<p>Your question was: How do I debug py2exe</p> <p>Here is a tip:</p> <ul> <li>Use <a href="http://www.dependencywalker.com" rel="nofollow">dependency walker</a></li> </ul> <p>As for your specific problem, I expect that you will find a solution on this more complete thread dealing with the same problem:</p> <p><a href="http://stackoverflow.com/questions/323424">py2exe fails to generate an executable</a></p>
1
2009-10-15T17:07:57Z
[ "python", "wxpython", "py2exe" ]
Listing builtin functions and methods (Python)
1,153,690
<p>I have came up with this:</p> <pre><code>[a for a in dir(__builtins__) if str(type(getattr(__builtins__,a))) == "&lt;type 'builtin_function_or_method'&gt;"] </code></pre> <p>I know its ugly. Can you show me a better/more pythonic way of doing this?</p>
3
2009-07-20T13:47:57Z
1,153,722
<p>There is the <a href="http://docs.python.org/library/inspect.html" rel="nofollow"><code>inspect</code> module</a>:</p> <pre><code>import inspect filter(inspect.isbuiltin, (member for name, member in inspect.getmembers(__builtins__))) </code></pre> <p>Edit: reading the documentation a little more closely, I came up with this variant that doesn't use <code>__getattr__</code></p> <pre><code>import inspect members = (member for name, member in inspect.getmembers(__builtins__)) filter(inspect.isbuiltin, members) </code></pre>
6
2009-07-20T13:54:31Z
[ "python", "module", "introspection", "inspect" ]
Listing builtin functions and methods (Python)
1,153,690
<p>I have came up with this:</p> <pre><code>[a for a in dir(__builtins__) if str(type(getattr(__builtins__,a))) == "&lt;type 'builtin_function_or_method'&gt;"] </code></pre> <p>I know its ugly. Can you show me a better/more pythonic way of doing this?</p>
3
2009-07-20T13:47:57Z
1,153,803
<p>Here's a variation without getattr:</p> <pre><code>import inspect [n.__name__ for n in __builtins__.__dict__.values() if inspect.isbuiltin(n)] </code></pre> <p>And if you want the actual function pointers:</p> <pre><code>import inspect [n for n in __builtins__.__dict__.values() if inspect.isbuiltin(n)] </code></pre>
2
2009-07-20T14:08:05Z
[ "python", "module", "introspection", "inspect" ]
PyQt: how to handle auto-resize of widgets when their content changes
1,153,714
<p>I am having some issues with the size of qt4 widgets when their content changes.</p> <p>I will illustrate my problems with two simple scenarios:</p> <p>Scenario 1:</p> <p>I have a QLineEdit widget. Sometimes, when I'm changing its content using QLineEdit.setText(), the one-line string doesn't fit into the widget at its current size anymore. I must select the widget and use the arrow keys to scroll the string in both directions in order to see it all.</p> <p>Scenario 2:</p> <p>I have a QTextEdit widget. Sometimes, when I'm changing its content using QTextEdit.setHtml(), the rendered HTML content doesn't fit into the widget at its current size anymore. The widget starts displaying horizontal and/or vertical scroll bars and I can use them to scroll the HTML content.</p> <p>What I would want in such scenarios is to have some logic that decides if after a content change, the new content won't fit anymore into the widget and automatically increase the widget size so everything would fit.</p> <p>How are these scenarios handled? I'm using PyQt4.</p> <p>Edit: after reading both the comment and the first answer (which mentions typing content into the widget), I went over the question one more time. I was unpleasantly surprised to find out a horrible typo. I meant QTextBrowser when I wrote QTextEdit, my apologies for misleading you. That is: I have a widget which renders HTML code that I'm changing and I would want the widget to grow enough to display everything without having scrollbars.</p> <p>As for QLineEdit instead of QLabel - I went for QLineEdit since I've noticed I can't select text from a QLabel with the mouse for copying it. With QLineEdit it is possible.</p>
9
2009-07-20T13:53:55Z
1,166,388
<p>I'm answering in C++ here, since that's what I'm most familiar with, and your problem isn't specific to PyQt.</p> <p>Normally, you just need to call <code>QWidget::updateGeometry()</code> when the <code>sizeHint()</code> may have changed, just like you need to call <code>QWidget::update()</code> when the contents may have changed.</p> <p>Your problem, however, is that the <code>sizeHint()</code> doesn't change when text is added to <code>QLineEdit</code> and <code>QTextEdit</code>. For a reason: People don't expect their dialogs to grow-as-they-type :)</p> <p>That said, if you really want grow-as-you-type behaviour in those widgets you need to inherit from them and reimplement <code>sizeHint()</code> and <code>minimumSizeHint()</code> to return the larger size, and potentially <code>setText()</code>, <code>append()</code> etc. to call <code>updateGeometry()</code> so the sizehint change is noticed.</p> <p>The sizehint calculation won't be entirely trivial, and will be way easier for <code>QLineEdit</code> than for <code>QTextEdit</code> (which is secretly a <code>QAbstractScrollArea</code>), but you can look at the <code>sizeHint()</code> and <code>minimumSizeHint()</code> implementations for inspiration (also the one for <code>QComboBox</code>, which has a mode to do exactly what you want: <code>QComboBox::AdjustToContents</code>.</p> <p>EDIT: Your two usecases (QTextBrowser w/o scrollbars and QLineEdit instead of QLabel just for selecting the text in there) can be solved by using a QLabel and a recent enough Qt. QLabel has gained both link-clicking notification and so-called "text-interaction flags" (one of which is TextSelectableByMouse) in Qt 4.2. The only difference that I was able to make out is that loading new content isn't automatic, there's no history, and there's no micro focus hinting (ie. tabbing from link to link) in QLabel.</p>
7
2009-07-22T16:08:31Z
[ "c++", "python", "qt", "qt4", "pyqt4" ]
PyQt: how to handle auto-resize of widgets when their content changes
1,153,714
<p>I am having some issues with the size of qt4 widgets when their content changes.</p> <p>I will illustrate my problems with two simple scenarios:</p> <p>Scenario 1:</p> <p>I have a QLineEdit widget. Sometimes, when I'm changing its content using QLineEdit.setText(), the one-line string doesn't fit into the widget at its current size anymore. I must select the widget and use the arrow keys to scroll the string in both directions in order to see it all.</p> <p>Scenario 2:</p> <p>I have a QTextEdit widget. Sometimes, when I'm changing its content using QTextEdit.setHtml(), the rendered HTML content doesn't fit into the widget at its current size anymore. The widget starts displaying horizontal and/or vertical scroll bars and I can use them to scroll the HTML content.</p> <p>What I would want in such scenarios is to have some logic that decides if after a content change, the new content won't fit anymore into the widget and automatically increase the widget size so everything would fit.</p> <p>How are these scenarios handled? I'm using PyQt4.</p> <p>Edit: after reading both the comment and the first answer (which mentions typing content into the widget), I went over the question one more time. I was unpleasantly surprised to find out a horrible typo. I meant QTextBrowser when I wrote QTextEdit, my apologies for misleading you. That is: I have a widget which renders HTML code that I'm changing and I would want the widget to grow enough to display everything without having scrollbars.</p> <p>As for QLineEdit instead of QLabel - I went for QLineEdit since I've noticed I can't select text from a QLabel with the mouse for copying it. With QLineEdit it is possible.</p>
9
2009-07-20T13:53:55Z
1,188,257
<p>For the QTextBrowser case you should be able to get the size of the document using</p> <pre><code>QTextBrowser::document()-&gt;size(); </code></pre> <p>after setting the html, and then resizing it the QTextBrowser afterwards. </p>
2
2009-07-27T13:49:41Z
[ "c++", "python", "qt", "qt4", "pyqt4" ]
PyQt: how to handle auto-resize of widgets when their content changes
1,153,714
<p>I am having some issues with the size of qt4 widgets when their content changes.</p> <p>I will illustrate my problems with two simple scenarios:</p> <p>Scenario 1:</p> <p>I have a QLineEdit widget. Sometimes, when I'm changing its content using QLineEdit.setText(), the one-line string doesn't fit into the widget at its current size anymore. I must select the widget and use the arrow keys to scroll the string in both directions in order to see it all.</p> <p>Scenario 2:</p> <p>I have a QTextEdit widget. Sometimes, when I'm changing its content using QTextEdit.setHtml(), the rendered HTML content doesn't fit into the widget at its current size anymore. The widget starts displaying horizontal and/or vertical scroll bars and I can use them to scroll the HTML content.</p> <p>What I would want in such scenarios is to have some logic that decides if after a content change, the new content won't fit anymore into the widget and automatically increase the widget size so everything would fit.</p> <p>How are these scenarios handled? I'm using PyQt4.</p> <p>Edit: after reading both the comment and the first answer (which mentions typing content into the widget), I went over the question one more time. I was unpleasantly surprised to find out a horrible typo. I meant QTextBrowser when I wrote QTextEdit, my apologies for misleading you. That is: I have a widget which renders HTML code that I'm changing and I would want the widget to grow enough to display everything without having scrollbars.</p> <p>As for QLineEdit instead of QLabel - I went for QLineEdit since I've noticed I can't select text from a QLabel with the mouse for copying it. With QLineEdit it is possible.</p>
9
2009-07-20T13:53:55Z
1,813,475
<p>Ok implement <code>sizeHint()</code> method. And every time your content change size call <code>updateGeometry()</code> When content change without changing size use <code>update()</code>. (<code>updateGeometry()</code> automatically call <code>update()</code>).</p>
0
2009-11-28T19:18:00Z
[ "c++", "python", "qt", "qt4", "pyqt4" ]
PyQt: how to handle auto-resize of widgets when their content changes
1,153,714
<p>I am having some issues with the size of qt4 widgets when their content changes.</p> <p>I will illustrate my problems with two simple scenarios:</p> <p>Scenario 1:</p> <p>I have a QLineEdit widget. Sometimes, when I'm changing its content using QLineEdit.setText(), the one-line string doesn't fit into the widget at its current size anymore. I must select the widget and use the arrow keys to scroll the string in both directions in order to see it all.</p> <p>Scenario 2:</p> <p>I have a QTextEdit widget. Sometimes, when I'm changing its content using QTextEdit.setHtml(), the rendered HTML content doesn't fit into the widget at its current size anymore. The widget starts displaying horizontal and/or vertical scroll bars and I can use them to scroll the HTML content.</p> <p>What I would want in such scenarios is to have some logic that decides if after a content change, the new content won't fit anymore into the widget and automatically increase the widget size so everything would fit.</p> <p>How are these scenarios handled? I'm using PyQt4.</p> <p>Edit: after reading both the comment and the first answer (which mentions typing content into the widget), I went over the question one more time. I was unpleasantly surprised to find out a horrible typo. I meant QTextBrowser when I wrote QTextEdit, my apologies for misleading you. That is: I have a widget which renders HTML code that I'm changing and I would want the widget to grow enough to display everything without having scrollbars.</p> <p>As for QLineEdit instead of QLabel - I went for QLineEdit since I've noticed I can't select text from a QLabel with the mouse for copying it. With QLineEdit it is possible.</p>
9
2009-07-20T13:53:55Z
1,817,169
<p>i achieve a similar effect by using the following C++ class:</p> <h2>textedit.h</h2> <pre><code>#ifndef TEXTEDIT_H #define TEXTEDIT_H #include &lt;QTextEdit&gt; class TextEdit : public QTextEdit { Q_DISABLE_COPY( TextEdit ) public: TextEdit( QWidget* parent = NULL ); TextEdit( const QString&amp; text, QWidget* parent = NULL ); virtual ~TextEdit(); void fitToDocument( Qt::Orientations orientations ); virtual QSize sizeHint() const; private: int fittedHeight_; Qt::Orientations fittedOrientations_; int fittedWidth_; }; #include "textedit-inl.h" #endif // TEXTEDIT_H </code></pre> <h2>textedit-inl.h</h2> <pre><code>#ifndef TEXTEDITINL_H #define TEXTEDITINL_H #include "textedit.h" inline TextEdit::TextEdit( QWidget* parent ) : QTextEdit( parent ), fittedOrientations_( 0 ) { } inline TextEdit::TextEdit( const QString&amp; text, QWidget* parent ) : QTextEdit( text, parent ), fittedOrientations_( 0 ) { } inline TextEdit::~TextEdit() { } inline QSize TextEdit::sizeHint() const { QSize sizeHint = QTextEdit::sizeHint(); if( fittedOrientations_ &amp; Qt::Horizontal ) sizeHint.setWidth( fittedWidth_ ); if( fittedOrientations_ &amp; Qt::Vertical ) sizeHint.setHeight( fittedHeight_ ); return sizeHint; } #endif // TEXTEDITINL_H </code></pre> <h2>textedit.cpp</h2> <pre><code>#include "textedit.h" void TextEdit::fitToDocument( Qt::Orientations orientations ) { QSize documentSize( document()-&gt;size().toSize() ); QSizePolicy sizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ); if( orientations &amp; Qt::Horizontal ) { fittedWidth_ = documentSize.width() + (width() - viewport()-&gt;width()); sizePolicy.setHorizontalPolicy( QSizePolicy::Fixed ); } if( orientations &amp; Qt::Vertical ) { fittedHeight_ = documentSize.height() + (width() - viewport()-&gt;width()); sizePolicy.setVerticalPolicy( QSizePolicy::Fixed ); } fittedOrientations_ = orientations; setSizePolicy( sizePolicy ); updateGeometry(); } </code></pre> <p>for example, calling <code>TextEdit::fitToDocument( Qt::Horizontal )</code> will set the widget's width to a fixed width exactly large enough to fit the document and its surroundings (e.g. a vertical scrollbar, if there is one). if your goal is to have this happen whenever the contents change, connect the <code>QTextEdit::textChanged()</code> signal to a slot which calls <code>TextEdit::fitToDocument()</code>.</p> <p>as for your issue with <code>QLabel</code>, the solution is simple: call <code>QLabel::setTextInteractionFlags( Qt::LinksAccessibleByMouse | Qt::TextSelectableByMouse )</code>.</p>
1
2009-11-29T23:39:50Z
[ "c++", "python", "qt", "qt4", "pyqt4" ]
PyQt: how to handle auto-resize of widgets when their content changes
1,153,714
<p>I am having some issues with the size of qt4 widgets when their content changes.</p> <p>I will illustrate my problems with two simple scenarios:</p> <p>Scenario 1:</p> <p>I have a QLineEdit widget. Sometimes, when I'm changing its content using QLineEdit.setText(), the one-line string doesn't fit into the widget at its current size anymore. I must select the widget and use the arrow keys to scroll the string in both directions in order to see it all.</p> <p>Scenario 2:</p> <p>I have a QTextEdit widget. Sometimes, when I'm changing its content using QTextEdit.setHtml(), the rendered HTML content doesn't fit into the widget at its current size anymore. The widget starts displaying horizontal and/or vertical scroll bars and I can use them to scroll the HTML content.</p> <p>What I would want in such scenarios is to have some logic that decides if after a content change, the new content won't fit anymore into the widget and automatically increase the widget size so everything would fit.</p> <p>How are these scenarios handled? I'm using PyQt4.</p> <p>Edit: after reading both the comment and the first answer (which mentions typing content into the widget), I went over the question one more time. I was unpleasantly surprised to find out a horrible typo. I meant QTextBrowser when I wrote QTextEdit, my apologies for misleading you. That is: I have a widget which renders HTML code that I'm changing and I would want the widget to grow enough to display everything without having scrollbars.</p> <p>As for QLineEdit instead of QLabel - I went for QLineEdit since I've noticed I can't select text from a QLabel with the mouse for copying it. With QLineEdit it is possible.</p>
9
2009-07-20T13:53:55Z
4,453,797
<p>Maybe take a look at <a href="https://sourceforge.net/project/stats/?group_id=384208&amp;ugn=pyqtresize" rel="nofollow">Python QT Automatic Widget Resizer</a>. It's written in python though but it may give you some ideas on how to go about doing what you need.</p>
2
2010-12-15T19:05:33Z
[ "c++", "python", "qt", "qt4", "pyqt4" ]
SQLAlchemy and django, is it production ready?
1,154,331
<p>Has anyone used <code>SQLAlchemy</code> in addition to <code>Django</code>'s ORM?</p> <p>I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins). </p> <p>Is it possible?</p> <p>Note: I'm aware about <code>django-sqlalchemy</code> but the project doesn't seem to be production ready. </p>
21
2009-07-20T15:44:44Z
1,154,949
<p>I don't think it's good practice to use both. You should either:</p> <ol> <li>Use Django's ORM and use custom SQL where Django's built-in SQL generation doesn't meet your needs, or</li> <li>Use SQLAlchemy (which gives you finer control at the price of added complexity) and, if needed, use a declarative layer such as <a href="http://elixir.ematia.de/">Elixir</a> to make life a little easier.</li> </ol> <p>Of course, if you need Django's admin, then the first of these approaches is recommended.</p>
6
2009-07-20T17:54:00Z
[ "python", "database", "django", "sqlalchemy" ]
SQLAlchemy and django, is it production ready?
1,154,331
<p>Has anyone used <code>SQLAlchemy</code> in addition to <code>Django</code>'s ORM?</p> <p>I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins). </p> <p>Is it possible?</p> <p>Note: I'm aware about <code>django-sqlalchemy</code> but the project doesn't seem to be production ready. </p>
21
2009-07-20T15:44:44Z
1,155,407
<p>What I would do,</p> <ol> <li><p>Define the schema in Django orm, let it write the db via syncdb. You get the admin interface.</p></li> <li><p>In view1 you need a complex join</p></li> </ol> <pre> <code> def view1(request): import sqlalchemy data = sqlalchemy.complex_join_magic(...) ... payload = {'data': data, ...} return render_to_response('template', payload, ...) </code> </pre>
17
2009-07-20T19:21:06Z
[ "python", "database", "django", "sqlalchemy" ]
SQLAlchemy and django, is it production ready?
1,154,331
<p>Has anyone used <code>SQLAlchemy</code> in addition to <code>Django</code>'s ORM?</p> <p>I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins). </p> <p>Is it possible?</p> <p>Note: I'm aware about <code>django-sqlalchemy</code> but the project doesn't seem to be production ready. </p>
21
2009-07-20T15:44:44Z
1,308,718
<p>Jacob Kaplan-Moss admitted to typing "import sqlalchemy" from time to time. I may write a queryset adapter for sqlalchemy results in the not too distant future.</p>
4
2009-08-20T20:47:20Z
[ "python", "database", "django", "sqlalchemy" ]
SQLAlchemy and django, is it production ready?
1,154,331
<p>Has anyone used <code>SQLAlchemy</code> in addition to <code>Django</code>'s ORM?</p> <p>I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins). </p> <p>Is it possible?</p> <p>Note: I'm aware about <code>django-sqlalchemy</code> but the project doesn't seem to be production ready. </p>
21
2009-07-20T15:44:44Z
3,555,602
<p>I've done it before and it's fine. Use the SQLAlchemy feature where it can read in the schema so you don't need to declare your fields twice.</p> <p>You can grab the connection settings from the settings, the only problem is stuff like the different flavours of postgres driver (e.g. with psyco and without).</p> <p>It's worth it as the SQLAlchemy stuff is just so much nicer for stuff like joins.</p>
6
2010-08-24T10:45:36Z
[ "python", "database", "django", "sqlalchemy" ]
SQLAlchemy and django, is it production ready?
1,154,331
<p>Has anyone used <code>SQLAlchemy</code> in addition to <code>Django</code>'s ORM?</p> <p>I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins). </p> <p>Is it possible?</p> <p>Note: I'm aware about <code>django-sqlalchemy</code> but the project doesn't seem to be production ready. </p>
21
2009-07-20T15:44:44Z
27,579,527
<p>Nowadays you can use <a href="https://pypi.python.org/pypi/aldjemy/0.3.10" rel="nofollow">Aldjemy</a>. Consider using this <a href="http://rodic.fr/blog/sqlalchemy-django/" rel="nofollow">tutorial</a>.</p>
2
2014-12-20T10:59:47Z
[ "python", "database", "django", "sqlalchemy" ]
Python write to line flow
1,154,373
<p>Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:</p> <pre><code>for linesplit in fileList: for i in range (0, len(linesplit)): t.write (linesplit[i]+'\t') </code></pre> <p>I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:</p> <pre><code>value1 value2 value3 value1 value2 value3 value1 value2 value3 </code></pre> <p>Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...</p>
1
2009-07-20T15:54:50Z
1,154,387
<p>I'm sorry... After I hit submit it dawned on me. My last value already has a \n in it which causes the newline.</p>
1
2009-07-20T15:57:40Z
[ "python", "file-io" ]
Python write to line flow
1,154,373
<p>Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:</p> <pre><code>for linesplit in fileList: for i in range (0, len(linesplit)): t.write (linesplit[i]+'\t') </code></pre> <p>I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:</p> <pre><code>value1 value2 value3 value1 value2 value3 value1 value2 value3 </code></pre> <p>Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...</p>
1
2009-07-20T15:54:50Z
1,154,391
<p>it doesn't produce what you want because original lines (<code>linesplit</code>) contain end of line character (<code>\n</code>) that you're not stripping. insert the following before your second for loop:</p> <pre><code>linesplit = linesplit.strip('\n') </code></pre> <p>That should do the job.</p>
6
2009-07-20T15:58:04Z
[ "python", "file-io" ]
Python write to line flow
1,154,373
<p>Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:</p> <pre><code>for linesplit in fileList: for i in range (0, len(linesplit)): t.write (linesplit[i]+'\t') </code></pre> <p>I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:</p> <pre><code>value1 value2 value3 value1 value2 value3 value1 value2 value3 </code></pre> <p>Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...</p>
1
2009-07-20T15:54:50Z
1,154,396
<p>Your last value must have a "\n" which causes both problems: The first problem because it outputs '\t' after the newline, the second problem should be obvious - the mystery newlines are coming from your last value.</p>
1
2009-07-20T15:59:23Z
[ "python", "file-io" ]
Python write to line flow
1,154,373
<p>Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:</p> <pre><code>for linesplit in fileList: for i in range (0, len(linesplit)): t.write (linesplit[i]+'\t') </code></pre> <p>I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:</p> <pre><code>value1 value2 value3 value1 value2 value3 value1 value2 value3 </code></pre> <p>Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...</p>
1
2009-07-20T15:54:50Z
1,154,398
<p>you linesplit variable could have newlines. just use strip() to remove it. </p>
1
2009-07-20T15:59:34Z
[ "python", "file-io" ]
Python write to line flow
1,154,373
<p>Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:</p> <pre><code>for linesplit in fileList: for i in range (0, len(linesplit)): t.write (linesplit[i]+'\t') </code></pre> <p>I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:</p> <pre><code>value1 value2 value3 value1 value2 value3 value1 value2 value3 </code></pre> <p>Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...</p>
1
2009-07-20T15:54:50Z
1,154,399
<p>Your <code>"value3"</code> strings are really <code>"value3\n"</code>, which explains the magical newlines and the extraneous tabs on all but the first line.</p>
1
2009-07-20T16:00:00Z
[ "python", "file-io" ]
Python write to line flow
1,154,373
<p>Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:</p> <pre><code>for linesplit in fileList: for i in range (0, len(linesplit)): t.write (linesplit[i]+'\t') </code></pre> <p>I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:</p> <pre><code>value1 value2 value3 value1 value2 value3 value1 value2 value3 </code></pre> <p>Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...</p>
1
2009-07-20T15:54:50Z
1,154,401
<p>The inner loop isn't required. Perhaps you meant to use:</p> <pre><code>t.write('\t'.join(linesplit)) </code></pre>
0
2009-07-20T16:00:24Z
[ "python", "file-io" ]
How to run statistics Cumulative Distribution Function and Probablity Density Function using SciPy?
1,154,378
<p>I am new to Python and new to SciPy libraries. I wanted to take some ques from the experts here on the list before dive into SciPy world.</p> <p>I was wondering if some one could provide a rough guide about how to run two stats functions: Cumulative Distribution Function (CDF) and Probability Distribution Function (PDF).</p> <p>My use case is the following: I have a sampleSpaceList [] which have 1000 floating point values. When a new floating point value is generated in my program, I would like to run both CDF and PDF on the sampleList for it and get the probabilty of value less or equal for CDF and probablity distribution for PDF.</p> <p>Many thanks in advance!</p> <p>Omer</p> <p>=== some more information ===</p> <p>Basically, in my program there are events which can either succeed or fail. If they succeed, then I calculate a event-ratio for that event and add to my sampleSpaceList until it reaches a threshold of 1000. Once the threshold is achieved, then for any next event-ratio; I would like to get a probability that whether that event-ratio would succeed or not in my system. </p> <p>What I basically would like to get is the probability of success for a particular event ratio. </p> <p>I am not very sure whether CDF or PDF will be relative to my problem so that 's why I wanted to learn how to use both but at any given moment, I will be only using either CDF or PDF to get a probability of event-ratio being successful.</p>
4
2009-07-20T15:55:52Z
1,154,859
<p>See this article: <a href="http://www.johndcook.com/blog/2009/07/20/probability-distributions-scipy/">Probability distributions in SciPy</a>.</p>
8
2009-07-20T17:35:06Z
[ "python", "statistics", "scipy", "probability" ]
Python: List initialization differences
1,154,494
<p>I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about?</p> <pre><code>list_1 = [0] * 10 list_2 = [0 for i in range(10)] </code></pre> <p>Are there any better ways to do this same task?</p> <p>Thanks in advance.</p>
3
2009-07-20T16:17:33Z
1,154,512
<p>I personally would advice to use the first method, since it is most likely the best performing one, since the system knows in advance the size of the list and the contents.</p> <p>In the second form, it must first evaluate the generator and collect all the values. Most likely by building up the list incrementally -- what is costly because of resizing.</p> <p>The first method should also be the best way at all.</p>
3
2009-07-20T16:22:50Z
[ "python", "list" ]
Python: List initialization differences
1,154,494
<p>I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about?</p> <pre><code>list_1 = [0] * 10 list_2 = [0 for i in range(10)] </code></pre> <p>Are there any better ways to do this same task?</p> <p>Thanks in advance.</p>
3
2009-07-20T16:17:33Z
1,154,521
<p>It depends on whether your list elements are mutable, if they are, there'll be a difference:</p> <pre><code>&gt;&gt;&gt; l = [[]] * 10 &gt;&gt;&gt; l [[], [], [], [], [], [], [], [], [], []] &gt;&gt;&gt; l[0].append(1) &gt;&gt;&gt; l [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] &gt;&gt;&gt; l = [[] for i in range(10)] &gt;&gt;&gt; l[0].append(1) &gt;&gt;&gt; l [[1], [], [], [], [], [], [], [], [], []] </code></pre> <p>For immutable elements, the behavior of the two is the same. There might be a performance difference between them, but I'm not sure which one would perform faster.</p>
15
2009-07-20T16:24:26Z
[ "python", "list" ]
Python: List initialization differences
1,154,494
<p>I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about?</p> <pre><code>list_1 = [0] * 10 list_2 = [0 for i in range(10)] </code></pre> <p>Are there any better ways to do this same task?</p> <p>Thanks in advance.</p>
3
2009-07-20T16:17:33Z
1,155,237
<p>The first one is not only faster, but is also more readable: just by a quick look, you immediately understand what's into that list, while in the second case you have to stop and see the iteration. </p> <p>Since source code is written once and read many times, for immutable elements I definitely vote for the first option.</p>
1
2009-07-20T18:49:24Z
[ "python", "list" ]
python distutils / setuptools: how to exclude a module, or honor svn:ignore flag
1,154,586
<p>I have a python project, 'myproject', that contains several packages. one of those packages, 'myproject.settings', contains a module 'myproject.settings.local' that is excluded from version control via 'svn:ignore' property.</p> <p>I would like setuptools to ignore this file when making a bdist or bdist_egg target.</p> <p>I have experimented with find_packages(exclude..) to no avail. Ideally I was hoping that only files that are not ignored by svn would be included.</p> <p>Is there a way to achieve the exclusion of my module? (I am on a patched (<a href="http://bugs.python.org/setuptools/issue64" rel="nofollow">http://bugs.python.org/setuptools/issue64</a>) version of setuptools trunk, with subversion 1.6.)</p> <p>thanks for any insight you might have</p> <p>-frank</p>
4
2009-07-20T16:36:17Z
1,155,321
<p>I don't know if there is a regular way to do that but you you try a workaround like proposed in the <a href="http://stackoverflow.com/questions/1129180/how-can-i-make-setuptools-ignore-subversion-inventory">http://stackoverflow.com/questions/1129180/how-can-i-make-setuptools-ignore-subversion-inventory</a></p> <p>svn export your package to a temporary directory, run the setup.py from there</p>
2
2009-07-20T19:07:25Z
[ "python", "setuptools", "distutils" ]
Using Cheetah Templating system with windows and python 2.6.1 (namemapper problem)
1,155,065
<p>So I am trying to use the Cheetah templating engine in conjunction with the Django web framework, and that is actually working fine. I did some simple tests with that and I was able to render pages and whatnot.</p> <p>However, problems arise whenever doing anything other than using very simple variable/attribute/methods in the Cheetah templates. It gets mad and says: You don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with the compiled C version of NameMapper. "\nYou don't have the C version of NameMapper installed! "</p> <p>And then it will be unable to find whatever attribute or method I was trying to call inside the Cheetah template.</p> <p>I attempted to download the C version of Namemapper and install it, but I wasn't sure how to 'install' a .pyd file (when I looked up '.pyd' files on the web it said they are just dynamic python modules that can be used with an import statement). Additionally, the Cheetah website only has C versions of Namemapper for python 2.4 and 2.5, while I am using python 2.6.1, so that is probably an issue as well.</p> <p>Does anyone have a solution for this? Thanks.</p>
5
2009-07-20T18:17:16Z
1,248,643
<p>I have compiled the PYD file for Python 2.6 as well as Windows installers that have it bundled in, so that users don't have to figure out where to drop the PYD on Windows.</p> <p>Installers: <a href="http://feisley.com/python/cheetah/" rel="nofollow">http://feisley.com/python/cheetah/</a> (pyd files are in the /pyd folder)</p> <p>Hope this helps!</p>
6
2009-08-08T11:41:28Z
[ "python", "windows", "django", "template-engine", "cheetah" ]
Are there any libraries for generating Python source?
1,155,186
<p>I'd like to write a code generation tool that will allow me to create sourcefiles for dynamically generated classes. I can create the class and use it in code, but it would be nice to have a sourcefile both for documentation and to allow something to import.</p> <p>Does such a thing exist? I've seen <a href="http://pypi.python.org/pypi/sourcecodegen/0.6.11" rel="nofollow">sourcecodegen</a>, but I'd rather avoid messing with the ast trees as they're not portable.</p>
0
2009-07-20T18:41:42Z
1,155,229
<p>I'm not aware of any off-the-shelf library, but have a look at the Python templating engines <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a> and <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a>. They can both generate Python source behind the scenes (they convert text templates to Python code and then to Python bytecode).</p>
2
2009-07-20T18:48:21Z
[ "python", "code-generation" ]
Prevent opening a second instance
1,155,315
<p>What's the easiest way to check if my program is already running with WxPython under Windows? Ideally, if the user tries to launch the program a second time, the focus should return to the first instance (even if the window is minimized).</p> <p>This <a href="http://stackoverflow.com/questions/94274/return-to-an-already-open-application-when-a-user-tries-to-open-a-new-instance">question</a> is similar but the answer is for VB.NET.</p>
2
2009-07-20T19:05:52Z
1,155,368
<p>You should use <a href="http://www.wxpython.org/docs/api/wx.SingleInstanceChecker-class.html" rel="nofollow">wx.SingleInstanceChecker</a>. See <a href="http://wiki.wxpython.org/OneInstanceRunning" rel="nofollow">here</a> for more information on how to use it, and <a href="http://aspn.activestate.com/ASPN/Mail/Message/wxPython-users/3707388" rel="nofollow">this post</a> tells about finding the running instance (you have to use pywin32 functions for this, there's nothing built into wxPython AFAIK).</p>
3
2009-07-20T19:14:50Z
[ "python", "windows", "user-interface", "wxpython" ]
How do I access an inherited class's inner class and modify it?
1,155,351
<p>So I have a class, specifically, this:</p> <pre><code>class ProductVariantForm_PRE(ModelForm): class Meta: model = ProductVariant exclude = ("productowner","status") def clean_meta(self): if len(self.cleaned_data['meta']) == 0: raise forms.ValidationError(_(u'You have to select at least 1 meta attribute.')) for m in self.cleaned_data['meta']: for n in self.cleaned_data['meta']: if m != n: if m.name == n.name: raise forms.ValidationError(_(u'You can only select 1 meta data of each type. IE: You cannot select 2 COLOR DATA (Red and Blue). You can however select 2 different data such as Shape and Size.')) return self.cleaned_data['meta'] </code></pre> <p>I wish to extend this class (a ModelForm), and so I have a class B. </p> <p>Class B will look like this:</p> <pre><code>class B(ProductVariantForm_PRE): </code></pre> <p>How can I access the inner class "Meta" in class B and modify the exclude field?</p> <p>Thanks!</p>
1
2009-07-20T19:12:33Z
1,155,448
<p>Take a look at the Django documentation for model inheritance <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#meta-inheritance" rel="nofollow">here</a>. From that page:</p> <blockquote> <p>When an abstract base class is created, Django makes any Meta inner class you declared in the base class available as an attribute. If a child class does not declare its own Meta class, it will inherit the parent's Meta. If the child wants to extend the parent's Meta class, it can subclass it. For example:</p> </blockquote> <pre><code>class CommonInfo(models.Model): ... class Meta: abstract = True ordering = ['name'] class Student(CommonInfo): ... class Meta(CommonInfo.Meta): db_table = 'student_info' </code></pre>
4
2009-07-20T19:26:07Z
[ "python", "django" ]
Python: re..find longest sequence
1,155,376
<p>I have a string that is randomly generated:</p> <pre><code>polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" </code></pre> <p>I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3.</p> <p>How would I go about doing this using python's re module?</p> <p>Thanks in advance.</p> <p>EDIT: <br> I mean the longest number of repeats of a given string. So the longest string with "diNCO diamine" is 3: <br> diol <b>diNCO diamine diNCO diamine diNCO diamine</b> diNCO diol diNCO diamine</p>
0
2009-07-20T19:15:36Z
1,155,442
<p>One was is to use <code>findall</code>:</p> <pre><code>polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" len(re.findall("diNCO diamine", polymer_str)) # returns 4. </code></pre>
0
2009-07-20T19:25:40Z
[ "python", "regex" ]
Python: re..find longest sequence
1,155,376
<p>I have a string that is randomly generated:</p> <pre><code>polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" </code></pre> <p>I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3.</p> <p>How would I go about doing this using python's re module?</p> <p>Thanks in advance.</p> <p>EDIT: <br> I mean the longest number of repeats of a given string. So the longest string with "diNCO diamine" is 3: <br> diol <b>diNCO diamine diNCO diamine diNCO diamine</b> diNCO diol diNCO diamine</p>
0
2009-07-20T19:15:36Z
1,155,466
<p>Using re:</p> <pre><code> m = re.search(r"(\bdiNCO diamine\b\s?)+", polymer_str) len(m.group(0)) / len("bdiNCO diamine") </code></pre>
0
2009-07-20T19:29:42Z
[ "python", "regex" ]
Python: re..find longest sequence
1,155,376
<p>I have a string that is randomly generated:</p> <pre><code>polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" </code></pre> <p>I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3.</p> <p>How would I go about doing this using python's re module?</p> <p>Thanks in advance.</p> <p>EDIT: <br> I mean the longest number of repeats of a given string. So the longest string with "diNCO diamine" is 3: <br> diol <b>diNCO diamine diNCO diamine diNCO diamine</b> diNCO diol diNCO diamine</p>
0
2009-07-20T19:15:36Z
1,155,508
<p>I think the op wants the longest contiguous sequence. You can get all contiguous sequences like: seqs = re.findall("(?:diNCO diamine)+", polymer_str) </p> <p>and then find the longest.</p>
3
2009-07-20T19:37:33Z
[ "python", "regex" ]
Python: re..find longest sequence
1,155,376
<p>I have a string that is randomly generated:</p> <pre><code>polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" </code></pre> <p>I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3.</p> <p>How would I go about doing this using python's re module?</p> <p>Thanks in advance.</p> <p>EDIT: <br> I mean the longest number of repeats of a given string. So the longest string with "diNCO diamine" is 3: <br> diol <b>diNCO diamine diNCO diamine diNCO diamine</b> diNCO diol diNCO diamine</p>
0
2009-07-20T19:15:36Z
1,155,805
<p>Expanding on <a href="http://stackoverflow.com/users/90354/ealdwulf">Ealdwulf</a>'s <a href="http://stackoverflow.com/questions/1155376/python-re-find-longest-sequence/1155508#1155508">answer</a>:</p> <p>Documentation on <code>re.findall</code> can be found <a href="http://docs.python.org/library/re.html#re.findall" rel="nofollow">here</a>.</p> <pre><code>def getLongestSequenceSize(search_str, polymer_str): matches = re.findall(r'(?:\b%s\b\s?)+' % search_str, polymer_str) longest_match = max(matches) return longest_match.count(search_str) </code></pre> <p>This could be written as one line, but it becomes less readable in that form.</p> <p><strong>Alternative:</strong></p> <p>If <code>polymer_str</code> is huge, it will be more memory efficient to use <code>re.finditer</code>. Here's how you might go about it:</p> <pre><code>def getLongestSequenceSize(search_str, polymer_str): longest_match = '' for match in re.finditer(r'(?:\b%s\b\s?)+' % search_str, polymer_str): if len(match.group(0)) &gt; len(longest_match): longest_match = match.group(0) return longest_match.count(search_str) </code></pre> <p>The biggest difference between <code>findall</code> and <code>finditer</code> is that the first returns a list object, while the second iterates over Match objects. Also, the <code>finditer</code> approach will be somewhat slower.</p>
5
2009-07-20T20:31:51Z
[ "python", "regex" ]
Python: re..find longest sequence
1,155,376
<p>I have a string that is randomly generated:</p> <pre><code>polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" </code></pre> <p>I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3.</p> <p>How would I go about doing this using python's re module?</p> <p>Thanks in advance.</p> <p>EDIT: <br> I mean the longest number of repeats of a given string. So the longest string with "diNCO diamine" is 3: <br> diol <b>diNCO diamine diNCO diamine diNCO diamine</b> diNCO diol diNCO diamine</p>
0
2009-07-20T19:15:36Z
1,156,704
<pre><code>import re pat = re.compile("[^|]+") p = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine".replace("diNCO diamine","|").replace(" ","") print max(map(len,pat.split(p))) </code></pre>
2
2009-07-21T00:25:54Z
[ "python", "regex" ]
Python accessing multiple webpages at once
1,155,404
<p>I have a tkinter GUI that downloads data from multiple websites at once. I run a seperate thread for each download (about 28). Is that too much threads for one GUI process? because it's really slow, each individual page should take about 1 to 2 seconds but when all are run at once it takes over 40 seconds. Is there any way I can shorten the time it takes to download all the pages? Any help is appreciated, thanks.</p>
0
2009-07-20T19:20:13Z
1,155,473
<p>It's probably the GIL (global interpreter lock) that gets in your way. Python has some performance problems with many threads.</p> <p>You could try twisted.web.getPage (see <a href="http://twistedmatrix.com/projects/core/documentation/howto/async.html" rel="nofollow">http://twistedmatrix.com/projects/core/documentation/howto/async.html</a> a bit down the page). I don't have benchmarks for that. But taking the example on that page and adding 28 deferreds to see how fast it is will give you a comparable result pretty fast. Keep in mind, that you'd have to use the gtk reactor and get into twisteds programming style, though.</p>
2
2009-07-20T19:31:22Z
[ "python", "user-interface", "multithreading", "download", "tkinter" ]
Python accessing multiple webpages at once
1,155,404
<p>I have a tkinter GUI that downloads data from multiple websites at once. I run a seperate thread for each download (about 28). Is that too much threads for one GUI process? because it's really slow, each individual page should take about 1 to 2 seconds but when all are run at once it takes over 40 seconds. Is there any way I can shorten the time it takes to download all the pages? Any help is appreciated, thanks.</p>
0
2009-07-20T19:20:13Z
1,155,479
<p>You can try using processes instead of threads. Python has GIL which might cause some delays in your situation.</p>
0
2009-07-20T19:31:59Z
[ "python", "user-interface", "multithreading", "download", "tkinter" ]
Python accessing multiple webpages at once
1,155,404
<p>I have a tkinter GUI that downloads data from multiple websites at once. I run a seperate thread for each download (about 28). Is that too much threads for one GUI process? because it's really slow, each individual page should take about 1 to 2 seconds but when all are run at once it takes over 40 seconds. Is there any way I can shorten the time it takes to download all the pages? Any help is appreciated, thanks.</p>
0
2009-07-20T19:20:13Z
1,155,498
<p>A process can have hundreds of threads on any modern OS without any problem.</p> <p>If you're bandwidth-limited, 1 to 2 seconds times 28 means 40 seconds is about right. If you're latency limited, it should be faster, but with no information, all I can suggest is:</p> <ul> <li>add logging to your code to make sure it's actually running in parallel, and that you're not accidentally serializing your threads somehow;</li> <li>use a network monitor to make sure that network requests are actually going out in parallel.</li> </ul> <p>It's hard to give anything better without more information.</p>
1
2009-07-20T19:35:07Z
[ "python", "user-interface", "multithreading", "download", "tkinter" ]
Django, how to make a view atomic?
1,155,513
<p>I have a simple django app to simulate a stock market, users come in and buy/sell. When they choose to trade, </p> <ol> <li>the market price is read, and</li> <li>based on the buy/sell order the market price is increased/decreased.</li> </ol> <p>I'm not sure how this works in django, but is there a way to make the view atomic? i.e. I'm concerned that user A's actions may read the price but before it's updated because of his order, user B's action reads the price.</p> <p>Couldn't find a simple, clean solution for this online. Thanks.</p>
1
2009-07-20T19:38:26Z
1,155,531
<p>Wrap the DB queries that read and the ones that update in a transaction. The syntax depends on what ORM you are using.</p>
-1
2009-07-20T19:43:43Z
[ "python", "database", "django", "locking", "atomic" ]
Django, how to make a view atomic?
1,155,513
<p>I have a simple django app to simulate a stock market, users come in and buy/sell. When they choose to trade, </p> <ol> <li>the market price is read, and</li> <li>based on the buy/sell order the market price is increased/decreased.</li> </ol> <p>I'm not sure how this works in django, but is there a way to make the view atomic? i.e. I'm concerned that user A's actions may read the price but before it's updated because of his order, user B's action reads the price.</p> <p>Couldn't find a simple, clean solution for this online. Thanks.</p>
1
2009-07-20T19:38:26Z
1,155,591
<p>This is database transactions, with some notes. All notes for Postgresql; all databases have locking mechanisms but the details are different.</p> <p>Many databases don't do this level of locking by default, even if you're in a transaction. You need to get an explicit lock on the data.</p> <p>In Postgresql, you probably want SELECT ... FOR UPDATE, which will lock the returned rows. You need to use FOR UPDATE on every SELECT that wants to block if another user is about to update them.</p> <p>Unfortunately, there's no way to do a FOR UPDATE in Django's ORM. You'd eitiher need to hack the ORM a bit or use raw SQL, as far as I know. If this is low-performance code and you can afford to serialize <em>all</em> access to the table, you can use a table-level LOCK IN EXCLUSIVE MODE, which will serialize the whole table.</p> <p><a href="http://www.postgresql.org/docs/current/static/explicit-locking.html" rel="nofollow">http://www.postgresql.org/docs/current/static/explicit-locking.html</a></p> <p><a href="http://www.postgresql.org/docs/current/static/sql-lock.html" rel="nofollow">http://www.postgresql.org/docs/current/static/sql-lock.html</a></p> <p><a href="http://www.postgresql.org/docs/current/static/sql-select.html" rel="nofollow">http://www.postgresql.org/docs/current/static/sql-select.html</a></p>
1
2009-07-20T19:57:18Z
[ "python", "database", "django", "locking", "atomic" ]
Django, how to make a view atomic?
1,155,513
<p>I have a simple django app to simulate a stock market, users come in and buy/sell. When they choose to trade, </p> <ol> <li>the market price is read, and</li> <li>based on the buy/sell order the market price is increased/decreased.</li> </ol> <p>I'm not sure how this works in django, but is there a way to make the view atomic? i.e. I'm concerned that user A's actions may read the price but before it's updated because of his order, user B's action reads the price.</p> <p>Couldn't find a simple, clean solution for this online. Thanks.</p>
1
2009-07-20T19:38:26Z
24,523,421
<p>Pretty old question, but since <a href="https://docs.djangoproject.com/en/dev/topics/db/transactions/" rel="nofollow">1.6</a> you can use <code>transaction.atomic()</code> as decorator.</p> <p><strong>views.py</strong></p> <pre><code>@transaction.atomic() def stock_action(request): #trade here </code></pre>
0
2014-07-02T05:23:12Z
[ "python", "database", "django", "locking", "atomic" ]
Getting rows from XML using XPath and Python
1,155,566
<p>I'd like to get some rows (<strong>z:row</strong> rows) from XML using:</p> <pre><code>&lt;rs:data&gt; &lt;z:row Attribute1="1" Attribute2="1" /&gt; &lt;z:row Attribute1="2" Attribute2="2" /&gt; &lt;z:row Attribute1="3" Attribute2="3" /&gt; &lt;z:row Attribute1="4" Attribute2="4" /&gt; &lt;z:row Attribute1="5" Attribute2="5" /&gt; &lt;z:row Attribute1="6" Attribute2="6" /&gt; &lt;/rs:data&gt; </code></pre> <p>I'm having trouble using (<strong>Python</strong>):</p> <pre><code>ElementTree.parse('myxmlfile.xml').getroot().findall('//z:row') </code></pre> <p>I think that two points are invalid in that case.</p> <p>Anyone knows how can I do that?</p>
0
2009-07-20T19:50:51Z
1,155,581
<p>If you don't want to figure out setting up namespaces properly, you can ignore them like this:</p> <pre><code>XPathGet("//*[local-name() = 'row']") </code></pre> <p>Which selects every node whose name (without namespace) is <code>row</code>.</p>
1
2009-07-20T19:54:53Z
[ "python", "xml", "xpath" ]
Getting rows from XML using XPath and Python
1,155,566
<p>I'd like to get some rows (<strong>z:row</strong> rows) from XML using:</p> <pre><code>&lt;rs:data&gt; &lt;z:row Attribute1="1" Attribute2="1" /&gt; &lt;z:row Attribute1="2" Attribute2="2" /&gt; &lt;z:row Attribute1="3" Attribute2="3" /&gt; &lt;z:row Attribute1="4" Attribute2="4" /&gt; &lt;z:row Attribute1="5" Attribute2="5" /&gt; &lt;z:row Attribute1="6" Attribute2="6" /&gt; &lt;/rs:data&gt; </code></pre> <p>I'm having trouble using (<strong>Python</strong>):</p> <pre><code>ElementTree.parse('myxmlfile.xml').getroot().findall('//z:row') </code></pre> <p>I think that two points are invalid in that case.</p> <p>Anyone knows how can I do that?</p>
0
2009-07-20T19:50:51Z
1,155,584
<p>The "z:" prefixes represent an XML namespace. you'll need to find out what that namespace is, and do the following:</p> <pre><code>XmlDocument doc = new XmlDocument(); doc.Load(@"File.xml"); XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); ns.AddNamespace("z", @"http://thenamespace.com"); XmlNodeList nodes = doc.SelectNodes(@"//z:row", ns); </code></pre>
1
2009-07-20T19:55:31Z
[ "python", "xml", "xpath" ]
Getting rows from XML using XPath and Python
1,155,566
<p>I'd like to get some rows (<strong>z:row</strong> rows) from XML using:</p> <pre><code>&lt;rs:data&gt; &lt;z:row Attribute1="1" Attribute2="1" /&gt; &lt;z:row Attribute1="2" Attribute2="2" /&gt; &lt;z:row Attribute1="3" Attribute2="3" /&gt; &lt;z:row Attribute1="4" Attribute2="4" /&gt; &lt;z:row Attribute1="5" Attribute2="5" /&gt; &lt;z:row Attribute1="6" Attribute2="6" /&gt; &lt;/rs:data&gt; </code></pre> <p>I'm having trouble using (<strong>Python</strong>):</p> <pre><code>ElementTree.parse('myxmlfile.xml').getroot().findall('//z:row') </code></pre> <p>I think that two points are invalid in that case.</p> <p>Anyone knows how can I do that?</p>
0
2009-07-20T19:50:51Z
1,155,892
<p>If I define the namespaces like this: </p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;rs:data xmlns="http://example.com" xmlns:rs="http://example.com/rs" xmlns:z="http://example.com/z"&gt; &lt;z:row Attribute1="1" Attribute2="1" /&gt; &lt;z:row Attribute1="2" Attribute2="2" /&gt; &lt;z:row Attribute1="3" Attribute2="3" /&gt; &lt;z:row Attribute1="4" Attribute2="4" /&gt; &lt;z:row Attribute1="5" Attribute2="5" /&gt; &lt;z:row Attribute1="6" Attribute2="6" /&gt; &lt;/rs:data&gt; </code></pre> <p>the Python <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">ElementTree</a>-API can be used like this:</p> <pre><code>ElementTree.parse("r.xml").getroot().findall('{http://example.com/z}row') # =&gt; [&lt;Element {http://example.com/z}row at 551ee0&gt;, &lt;Element {http://example.com/z}row at 551c60&gt;, &lt;Element {http://example.com/z}row at 551f08&gt;, &lt;Element {http://example.com/z}row at 551be8&gt;, &lt;Element {http://example.com/z}row at 551eb8&gt;, &lt;Element {http://example.com/z}row at 551f30&gt;] </code></pre> <p>See also <a href="http://effbot.org/zone/element.htm#xml-namespaces" rel="nofollow">http://effbot.org/zone/element.htm#xml-namespaces</a></p>
1
2009-07-20T20:49:24Z
[ "python", "xml", "xpath" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
1,155,636
<p>Regular expressions maybe?</p> <pre><code>import re my_string = "Mary had a little lamb" len(re.findall("a", my_string)) </code></pre>
31
2009-07-20T20:03:19Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
1,155,647
<blockquote> <p><a href="https://docs.python.org/2/library/stdtypes.html#str.count" rel="nofollow">str.count(sub[, start[, end]])</a></p> <p>Return the number of non-overlapping occurrences of substring <code>sub</code> in the range <code>[start, end]</code>. Optional arguments <code>start</code> and <code>end</code> are interpreted as in slice notation.</p> </blockquote> <pre><code>&gt;&gt;&gt; sentence = 'Mary had a little lamb' &gt;&gt;&gt; sentence.count('a') 4 </code></pre> <p>Or:</p> <pre><code>from collections import Counter sentence = 'Mary had a little lamb' print(Counter(list(sentence))['a']) </code></pre>
617
2009-07-20T20:04:26Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
1,155,648
<p>You can use <a href="https://docs.python.org/2/library/string.html#string.count" rel="nofollow">count()</a> :</p> <pre><code>&gt;&gt;&gt; 'Mary had a little lamb'.count('a') 4 </code></pre>
76
2009-07-20T20:04:45Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
1,155,649
<pre><code>myString.count('a'); </code></pre> <p>more info <a href="http://docs.python.org/library/stdtypes.html">here</a></p>
20
2009-07-20T20:04:47Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
1,155,652
<pre><code>"aabc".count("a") </code></pre>
13
2009-07-20T20:05:03Z
[ "python", "string", "count" ]