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 |
|---|---|---|---|---|---|---|---|---|---|
Is there a wiki processor for Trac to format and colour Python tracebacks? | 1,275,401 | <p>Understandably many of the tickets we file in Trac contain tracebacks. It would be excellent if these were nicely formatted and syntax highlighted.</p>
<p>I've conducted a cursory Google search for a Python traceback wiki processor and have not found any quick hits.</p>
<p>I'm happy to roll my own if anyone can recommend a traceback formatter (stand alone or embedded in an open source project) that outputs HTML/reStructuredText/etc.</p>
| 4 | 2009-08-14T00:21:37Z | 1,275,531 | <p><a href="http://pygments.org/languages/" rel="nofollow">Pygments</a> has support for syntax-coloring Python tracebacks, and there's a <a href="http://trac-hacks.org/wiki/TracPygmentsPlugin" rel="nofollow">trac plugin</a>, but the wiki page claims Trac 0.11 supports Pygments natively.</p>
| 2 | 2009-08-14T01:04:39Z | [
"python",
"syntax",
"trac"
] |
Is there a wiki processor for Trac to format and colour Python tracebacks? | 1,275,401 | <p>Understandably many of the tickets we file in Trac contain tracebacks. It would be excellent if these were nicely formatted and syntax highlighted.</p>
<p>I've conducted a cursory Google search for a Python traceback wiki processor and have not found any quick hits.</p>
<p>I'm happy to roll my own if anyone can recommend a traceback formatter (stand alone or embedded in an open source project) that outputs HTML/reStructuredText/etc.</p>
| 4 | 2009-08-14T00:21:37Z | 1,320,590 | <p>Trac 0.11 supports Pygments but doesn't expose the pytb formatting type. Here's a patch against Trac 0.11.3 to add support for Python tracebacks.</p>
<pre><code>diff -r 5a0c5e3255b4 mimeview/api.py
--- a/mimeview/api.py Tue Aug 11 11:33:45 2009 +1000
+++ b/mimeview/api.py Mon Aug 24 15:13:34 2009 +1000
@@ -348,6 +348,7 @@
'text/x-perl': ['pl', 'pm', 'PL', 'perl'],
'text/x-php': ['php', 'php3', 'php4'],
'text/x-python': ['py', 'python'],
+ 'text/x-python-traceback':['pytb'],
'text/x-pyrex': ['pyx'],
'text/x-ruby': ['rb', 'ruby'],
'text/x-scheme': ['scm'],
</code></pre>
| 2 | 2009-08-24T05:16:58Z | [
"python",
"syntax",
"trac"
] |
Is there a wiki processor for Trac to format and colour Python tracebacks? | 1,275,401 | <p>Understandably many of the tickets we file in Trac contain tracebacks. It would be excellent if these were nicely formatted and syntax highlighted.</p>
<p>I've conducted a cursory Google search for a Python traceback wiki processor and have not found any quick hits.</p>
<p>I'm happy to roll my own if anyone can recommend a traceback formatter (stand alone or embedded in an open source project) that outputs HTML/reStructuredText/etc.</p>
| 4 | 2009-08-14T00:21:37Z | 7,014,002 | <p>I don't believe you need that patch. You could specify the shortcode mapping in the <a href="http://trac.edgewall.org/wiki/TracIni#mimeviewer-section" rel="nofollow">trac.ini</a>, but you can also (at least in trac 0.12) just use the mime type directly:</p>
<pre><code>{{{
#!text/x-python-traceback
<traceback>
}}}
</code></pre>
<p>See more at <a href="http://trac.edgewall.org/wiki/TracSyntaxColoring" rel="nofollow">http://trac.edgewall.org/wiki/TracSyntaxColoring</a>. x-python-traceback isn't in the list there, but you'll get an error previewing if trac can't handle it and it WorkedForMe.</p>
| 4 | 2011-08-10T16:03:37Z | [
"python",
"syntax",
"trac"
] |
What is the best way to handle rotating sprites for a top-down view game | 1,275,482 | <p>I am working on a top-down view 2d game at the moment and I am learning a ton about sprites and sprite handling. My question is how to handle a set of sprites that can be rotated in as many as 32 directions.</p>
<p>At the moment a given object has its sprite sheet with all of the animations oriented with the object pointing at 0 degrees at all times. Now, since the object can rotate in as many as 32 directions, what is the best way to work with that original sprite sheet. My current best guess is to have the program basically dynamically create 32 more sprite sheets when the object is first loaded into the game, and then all subsequent instances of that type of object will share those sprite sheets.</p>
<p>Anyways, any advice in this regard would be helpful. Let me know if I need to rephrase the question, I know its kindof an odd one. Thanks</p>
<p>Edit: I guess for more clarification. If I have, for instance an object that has 2 animations of 5 frames a peice, that is a pretty easy sprite sheet to create and organize, its a simple 2x5 grid (or 5x2 depending on how you lay it out). But the problem is that now those 2 animations have to be rotated in 32 directions. This means that in the end there will be 320 individual sprites. I am going to say that (and correct me if im wrong) since I'm concerned about performance and frame-rate, rotating the sprites on the fly every single frame is not an option. So, how should these 320 sprites that make up these 2 animations be organized? Would it be better to</p>
<ul>
<li>Think of it as 32 2x5 sprite sheets</li>
<li>split the sprite sheet up into individual frames, and then have an array the 32 different directions per frame (so 10 arrays of 32 directional sprites)</li>
<li>Other....?</li>
<li>Doesn't matter?</li>
</ul>
<p>Thanks</p>
| 2 | 2009-08-14T00:47:42Z | 1,275,490 | <p>You can just rotate the sprites directly by setting the rotate portion of the sprite's transform.</p>
<p>For some sample code, check out the Chimp sprite in this <a href="http://www.pygame.org/docs/tut/chimp/ChimpLineByLine.html" rel="nofollow">pygame tutorial</a>. It rotates the sprites when the Chimp is "dizzy".</p>
| 2 | 2009-08-14T00:51:48Z | [
"python",
"pygame",
"sprite"
] |
What is the best way to handle rotating sprites for a top-down view game | 1,275,482 | <p>I am working on a top-down view 2d game at the moment and I am learning a ton about sprites and sprite handling. My question is how to handle a set of sprites that can be rotated in as many as 32 directions.</p>
<p>At the moment a given object has its sprite sheet with all of the animations oriented with the object pointing at 0 degrees at all times. Now, since the object can rotate in as many as 32 directions, what is the best way to work with that original sprite sheet. My current best guess is to have the program basically dynamically create 32 more sprite sheets when the object is first loaded into the game, and then all subsequent instances of that type of object will share those sprite sheets.</p>
<p>Anyways, any advice in this regard would be helpful. Let me know if I need to rephrase the question, I know its kindof an odd one. Thanks</p>
<p>Edit: I guess for more clarification. If I have, for instance an object that has 2 animations of 5 frames a peice, that is a pretty easy sprite sheet to create and organize, its a simple 2x5 grid (or 5x2 depending on how you lay it out). But the problem is that now those 2 animations have to be rotated in 32 directions. This means that in the end there will be 320 individual sprites. I am going to say that (and correct me if im wrong) since I'm concerned about performance and frame-rate, rotating the sprites on the fly every single frame is not an option. So, how should these 320 sprites that make up these 2 animations be organized? Would it be better to</p>
<ul>
<li>Think of it as 32 2x5 sprite sheets</li>
<li>split the sprite sheet up into individual frames, and then have an array the 32 different directions per frame (so 10 arrays of 32 directional sprites)</li>
<li>Other....?</li>
<li>Doesn't matter?</li>
</ul>
<p>Thanks</p>
| 2 | 2009-08-14T00:47:42Z | 1,277,181 | <p>The 32 directions for the sprite translate into 32 rotations by 11.25 degrees. </p>
<p>You can reduce the number of precalculated images to 8 you only calculate the first 90 degrees (<code>11.25, 22.5, 33.75, 45.0, 56.25, 67.5, 78.75, 90.0</code>) and use the flip operations dynamically. Flips are much faster because they essentially only change the order an image is copied from the buffer. </p>
<p>For example, when you display an image that is rotated by 101.25 degrees, load the precalculated image of 67.5 degrees and flip it vertically.</p>
<p>I just realized that this only works if your graphic is symmetrical ;-)</p>
<p>When talking about a modern computer, you might not need to optimize anything. The memory used by precalculating the sprites is certainly negligible, and the cpu usage when rotating the image probably too. When you are programming for a embedded device however, it does matter.</p>
| 4 | 2009-08-14T10:35:40Z | [
"python",
"pygame",
"sprite"
] |
What is the best way to handle rotating sprites for a top-down view game | 1,275,482 | <p>I am working on a top-down view 2d game at the moment and I am learning a ton about sprites and sprite handling. My question is how to handle a set of sprites that can be rotated in as many as 32 directions.</p>
<p>At the moment a given object has its sprite sheet with all of the animations oriented with the object pointing at 0 degrees at all times. Now, since the object can rotate in as many as 32 directions, what is the best way to work with that original sprite sheet. My current best guess is to have the program basically dynamically create 32 more sprite sheets when the object is first loaded into the game, and then all subsequent instances of that type of object will share those sprite sheets.</p>
<p>Anyways, any advice in this regard would be helpful. Let me know if I need to rephrase the question, I know its kindof an odd one. Thanks</p>
<p>Edit: I guess for more clarification. If I have, for instance an object that has 2 animations of 5 frames a peice, that is a pretty easy sprite sheet to create and organize, its a simple 2x5 grid (or 5x2 depending on how you lay it out). But the problem is that now those 2 animations have to be rotated in 32 directions. This means that in the end there will be 320 individual sprites. I am going to say that (and correct me if im wrong) since I'm concerned about performance and frame-rate, rotating the sprites on the fly every single frame is not an option. So, how should these 320 sprites that make up these 2 animations be organized? Would it be better to</p>
<ul>
<li>Think of it as 32 2x5 sprite sheets</li>
<li>split the sprite sheet up into individual frames, and then have an array the 32 different directions per frame (so 10 arrays of 32 directional sprites)</li>
<li>Other....?</li>
<li>Doesn't matter?</li>
</ul>
<p>Thanks</p>
| 2 | 2009-08-14T00:47:42Z | 1,296,881 | <p>Typically you will sacrifice either processor time or memory, and you need to balance between the two. Unless you've got some great limit to your processor or you're computing a lot of expensive stuff, there's no real reason to put all that into the memory. Rotating a few sprites with a transform is cheap enough that it is definitely not worth it to store 32x as much information in memory - especially because that information is a bunch of images, and images use up a lot of memory, relatively speaking.</p>
| 1 | 2009-08-18T22:18:49Z | [
"python",
"pygame",
"sprite"
] |
Python 3 and static typing | 1,275,646 | <p>I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from <a href="http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927">this SO answer</a> function parameter annotation:</p>
<pre><code>def digits(x:'nonnegative number') -> "yields number's digits":
# ...
</code></pre>
<p>Not knowing anything about this, I thought it could maybe be used for implementing static typing in Python!</p>
<p>After some searching, there seemed to be a lot discussion regarding (entirely optional) static typing in Python, such as that mentioned in <a href="http://www.python.org/dev/peps/pep-3107/">PEP 3107</a>, and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=85551">"Adding Optional Static Typing to Python"</a> (and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=86641">part 2</a>)</p>
<p>..but, I'm not clear how far this has progressed. Are there any implementations of static typing, using the parameter-annotation? Did any of the parameterised-type ideas make it into Python 3?</p>
| 52 | 2009-08-14T01:47:26Z | 1,275,658 | <p>As mentioned in that PEP, static type checking is one of the possible applications that function annotations can be used for, but they're leaving it up to third-party libraries to decide how to do it. That is, there isn't going to be an official implementation in core python.</p>
<p>As far as third-party implementations are concerned, there are some snippets (such as <a href="http://code.activestate.com/recipes/572161/">http://code.activestate.com/recipes/572161/</a>), which seem to do the job pretty well.</p>
<p>EDIT:</p>
<p>As a note, I want to mention that checking behavior is preferable to checking type, therefore I think static typechecking is not so great an idea. My answer above is aimed at answering the question, not because I would do typechecking myself in such a way.</p>
| 14 | 2009-08-14T01:53:23Z | [
"python",
"python-3.x",
"static-typing"
] |
Python 3 and static typing | 1,275,646 | <p>I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from <a href="http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927">this SO answer</a> function parameter annotation:</p>
<pre><code>def digits(x:'nonnegative number') -> "yields number's digits":
# ...
</code></pre>
<p>Not knowing anything about this, I thought it could maybe be used for implementing static typing in Python!</p>
<p>After some searching, there seemed to be a lot discussion regarding (entirely optional) static typing in Python, such as that mentioned in <a href="http://www.python.org/dev/peps/pep-3107/">PEP 3107</a>, and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=85551">"Adding Optional Static Typing to Python"</a> (and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=86641">part 2</a>)</p>
<p>..but, I'm not clear how far this has progressed. Are there any implementations of static typing, using the parameter-annotation? Did any of the parameterised-type ideas make it into Python 3?</p>
| 52 | 2009-08-14T01:47:26Z | 1,276,121 | <p>"Static typing" in Python can only be implemented so that the type checking is done in run-time, which means it slows down the application. Therefore you don't want that as a generality. Instead you want some of your methods to check it's inputs. This can be easily done with plain asserts, or with decorators if you (mistakenly) think you need it a lot.</p>
<p>There is also an alternative to static type checking, and that is to use an aspect oriented component architecture like The Zope Component Architecture. Instead of checking the type, you adapt it. So instead of:</p>
<pre><code>assert isinstance(theobject, myclass)
</code></pre>
<p>you do this:</p>
<pre><code>theobject = IMyClass(theobject)
</code></pre>
<p>If theobject already implements IMyClass nothing happens. If it doesn't, an adapter that wraps whatever theobject is to IMyClass will be looked up, and used instead of theobject. If no adapter is found, you get an error.</p>
<p>This combined the dynamicism of Python with the desire to have a specific type in a specific way.</p>
| 13 | 2009-08-14T05:01:33Z | [
"python",
"python-3.x",
"static-typing"
] |
Python 3 and static typing | 1,275,646 | <p>I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from <a href="http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927">this SO answer</a> function parameter annotation:</p>
<pre><code>def digits(x:'nonnegative number') -> "yields number's digits":
# ...
</code></pre>
<p>Not knowing anything about this, I thought it could maybe be used for implementing static typing in Python!</p>
<p>After some searching, there seemed to be a lot discussion regarding (entirely optional) static typing in Python, such as that mentioned in <a href="http://www.python.org/dev/peps/pep-3107/">PEP 3107</a>, and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=85551">"Adding Optional Static Typing to Python"</a> (and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=86641">part 2</a>)</p>
<p>..but, I'm not clear how far this has progressed. Are there any implementations of static typing, using the parameter-annotation? Did any of the parameterised-type ideas make it into Python 3?</p>
| 52 | 2009-08-14T01:47:26Z | 1,276,582 | <p>Thanks for reading my code!</p>
<p>Indeed, it's not hard to create a generic annotation enforcer in Python. Here's my take:</p>
<pre><code>'''Very simple enforcer of type annotations.
This toy super-decorator can decorate all functions in a given module that have
annotations so that the type of input and output is enforced; an AssertionError is
raised on mismatch.
This module also has a test function func() which should fail and logging facility
log which defaults to print.
Since this is a test module, I cut corners by only checking *keyword* arguments.
'''
import sys
log = print
def func(x:'int' = 0) -> 'str':
'''An example function that fails type checking.'''
return x
# For simplicity, I only do keyword args.
def check_type(*args):
param, value, assert_type = args
log('Checking {0} = {1} of {2}.'.format(*args))
if not isinstance(value, assert_type):
raise AssertionError(
'Check failed - parameter {0} = {1} not {2}.'
.format(*args))
return value
def decorate_func(func):
def newf(*args, **kwargs):
for k, v in kwargs.items():
check_type(k, v, ann[k])
return check_type('<return_value>', func(*args, **kwargs), ann['return'])
ann = {k: eval(v) for k, v in func.__annotations__.items()}
newf.__doc__ = func.__doc__
newf.__type_checked = True
return newf
def decorate_module(module = '__main__'):
'''Enforces type from annotation for all functions in module.'''
d = sys.modules[module].__dict__
for k, f in d.items():
if getattr(f, '__annotations__', {}) and not getattr(f, '__type_checked', False):
log('Decorated {0!r}.'.format(f.__name__))
d[k] = decorate_func(f)
if __name__ == '__main__':
decorate_module()
# This will raise AssertionError.
func(x = 5)
</code></pre>
<p>Given this simplicity, it's strange at the first sight that this thing is not mainstream. However, I believe there are good reasons why it's <strong>not as useful as it might seem</strong>. Generally, type checking helps because if you add integer and dictionary, chances are you made some obvious mistake (and if you meant something reasonable, it's still <em>better to be explicit than implicit</em>).</p>
<p>But in real life you often mix quantities of the same <strong>computer type</strong> as seen by compiler but clearly different <strong>human type</strong>, for example the following snippet contains an obvious mistake:</p>
<pre><code>height = 1.75 # Bob's height in meters.
length = len(sys.modules) # Number of modules imported by program.
area = height * length # What's that supposed to mean???
</code></pre>
<p>Any human should immediately see a mistake in the above line provided it knows the 'human type' of variables <code>height</code> and <code>length</code> even though it looks to computer as <strong>perfectly legal</strong> multiplication of <code>int</code> and <code>float</code>.</p>
<p>There's more that can be said about possible solutions to this problem, but enforcing 'computer types' is apparently a half-solution, so, at least in my opinion, it's <em>worse than no solution at all</em>. It's the same reason why <strong>Systems Hungarian</strong> is a terrible idea while <strong>Apps Hungarian</strong> is a great one. There's more at the very informative <strong><a href="http://www.joelonsoftware.com/articles/Wrong.html">post of Joel Spolsky</a></strong>.</p>
<p>Now if somebody was to implement some kind of Pythonic third-party library that would automatically assign to real-world data its <strong>human type</strong> and then took care to transform that type like <code>width * height -> area</code> and enforce that check with function annotations, I think that would be a type checking people could really use!</p>
| 31 | 2009-08-14T07:53:55Z | [
"python",
"python-3.x",
"static-typing"
] |
Python 3 and static typing | 1,275,646 | <p>I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from <a href="http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927">this SO answer</a> function parameter annotation:</p>
<pre><code>def digits(x:'nonnegative number') -> "yields number's digits":
# ...
</code></pre>
<p>Not knowing anything about this, I thought it could maybe be used for implementing static typing in Python!</p>
<p>After some searching, there seemed to be a lot discussion regarding (entirely optional) static typing in Python, such as that mentioned in <a href="http://www.python.org/dev/peps/pep-3107/">PEP 3107</a>, and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=85551">"Adding Optional Static Typing to Python"</a> (and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=86641">part 2</a>)</p>
<p>..but, I'm not clear how far this has progressed. Are there any implementations of static typing, using the parameter-annotation? Did any of the parameterised-type ideas make it into Python 3?</p>
| 52 | 2009-08-14T01:47:26Z | 14,814,818 | <p>This is not an answer to question directly, but I found out a Python fork that adds static typing: <a href="http://www.mypy-lang.org/">mypy-lang.org</a>, of course one can't rely on it as it's still small endeavor, but interesting.</p>
| 12 | 2013-02-11T15:05:33Z | [
"python",
"python-3.x",
"static-typing"
] |
Python 3 and static typing | 1,275,646 | <p>I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from <a href="http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927">this SO answer</a> function parameter annotation:</p>
<pre><code>def digits(x:'nonnegative number') -> "yields number's digits":
# ...
</code></pre>
<p>Not knowing anything about this, I thought it could maybe be used for implementing static typing in Python!</p>
<p>After some searching, there seemed to be a lot discussion regarding (entirely optional) static typing in Python, such as that mentioned in <a href="http://www.python.org/dev/peps/pep-3107/">PEP 3107</a>, and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=85551">"Adding Optional Static Typing to Python"</a> (and <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=86641">part 2</a>)</p>
<p>..but, I'm not clear how far this has progressed. Are there any implementations of static typing, using the parameter-annotation? Did any of the parameterised-type ideas make it into Python 3?</p>
| 52 | 2009-08-14T01:47:26Z | 39,145,690 | <p>Sure, static typing seems a bit "unpythonic" and I don't use it all the time. But there are cases (e.g. nested classes, as in domain specific language parsing) where it can really speed up your development. </p>
<p>Then I prefer using <a href="https://gist.github.com/leycec/3d48cc60e7d5fe8860b077acb067dc54" rel="nofollow">beartype</a> explained in this <a href="http://stackoverflow.com/a/37961120/4680402">post</a>*. It comes with a git repo, tests and an explanation what it can and what it can't do ... and I like the name ;) </p>
<p>* Please don't pay attention to Cecil's rant about why Python doesn't come with batteries included in this case.</p>
| 0 | 2016-08-25T12:44:30Z | [
"python",
"python-3.x",
"static-typing"
] |
JQuery "get" failure (using Google App Engine on the back-end) | 1,275,708 | <p>What I am trying to do is pretty simple: yet something has clearly gone awry.</p>
<p>On the Front-End:</p>
<pre><code>function eval() {
var x = 'Unchanged X'
$.get("/", { entry: document.getElementById('entry').value },
function(data){
x = data;
}
);
$("#result").html(x);
}
</code></pre>
<p>On the Back-End:</p>
<pre><code>class MainHandler(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'index.html')
if self.request.get('entry') != '':
#self.response.out.write({'evalresult': self.request.get('entry')})
self.response.out.write(request.get('entry'))
else:
self.response.out.write(template.render(path, {'result': 'Welcome!!'}))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
</code></pre>
<p>Yet, apparently the function is never being called and #result gets set to 'Unchanged X'. What am I missing?</p>
<p><strong>NOTE: The callback is NOT being called. I have verified this by placing an alert("Test") within the callback function. Any ideas anyone?</strong></p>
| 1 | 2009-08-14T02:12:46Z | 1,275,713 | <p><code>$("#result").html(x);</code> goes in the <code>get()</code> callback</p>
| 2 | 2009-08-14T02:16:25Z | [
"javascript",
"jquery",
"python",
"google-app-engine"
] |
JQuery "get" failure (using Google App Engine on the back-end) | 1,275,708 | <p>What I am trying to do is pretty simple: yet something has clearly gone awry.</p>
<p>On the Front-End:</p>
<pre><code>function eval() {
var x = 'Unchanged X'
$.get("/", { entry: document.getElementById('entry').value },
function(data){
x = data;
}
);
$("#result").html(x);
}
</code></pre>
<p>On the Back-End:</p>
<pre><code>class MainHandler(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'index.html')
if self.request.get('entry') != '':
#self.response.out.write({'evalresult': self.request.get('entry')})
self.response.out.write(request.get('entry'))
else:
self.response.out.write(template.render(path, {'result': 'Welcome!!'}))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
</code></pre>
<p>Yet, apparently the function is never being called and #result gets set to 'Unchanged X'. What am I missing?</p>
<p><strong>NOTE: The callback is NOT being called. I have verified this by placing an alert("Test") within the callback function. Any ideas anyone?</strong></p>
| 1 | 2009-08-14T02:12:46Z | 1,275,809 | <p>If the callback is not running you can try changing the $.get into a $.ajax() call, and adding an error callback, to see if the server is returning an error.</p>
<p>Or better yet, check in the "net" panel in firebug to see what the server response is, which might help you track down what the issue is on the back end.</p>
<p>Also once the issue is fixed, you might want to replace the $.get with a simple $().load which would take the data and place it into the div automatically:</p>
<pre><code>$('#result').load('/', { entry: document.getElementById('entry').value });
</code></pre>
<p>EDIT: I suppose the following would be a more jQueryish way of writing it:</p>
<pre><code>$('#result').load('/', { entry: $('#entry').val() });
</code></pre>
| 2 | 2009-08-14T02:48:31Z | [
"javascript",
"jquery",
"python",
"google-app-engine"
] |
JQuery "get" failure (using Google App Engine on the back-end) | 1,275,708 | <p>What I am trying to do is pretty simple: yet something has clearly gone awry.</p>
<p>On the Front-End:</p>
<pre><code>function eval() {
var x = 'Unchanged X'
$.get("/", { entry: document.getElementById('entry').value },
function(data){
x = data;
}
);
$("#result").html(x);
}
</code></pre>
<p>On the Back-End:</p>
<pre><code>class MainHandler(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'index.html')
if self.request.get('entry') != '':
#self.response.out.write({'evalresult': self.request.get('entry')})
self.response.out.write(request.get('entry'))
else:
self.response.out.write(template.render(path, {'result': 'Welcome!!'}))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
</code></pre>
<p>Yet, apparently the function is never being called and #result gets set to 'Unchanged X'. What am I missing?</p>
<p><strong>NOTE: The callback is NOT being called. I have verified this by placing an alert("Test") within the callback function. Any ideas anyone?</strong></p>
| 1 | 2009-08-14T02:12:46Z | 1,276,473 | <p>First we have the silly mistake:</p>
<pre><code><font size="3" face="Trebuchet MS">Speak Your Mind:&nbsp;&nbsp;</font><input type="text"
size="60" id="entry"/> <img valign="bottom" src='/assets/cognifyup.png'
onMouseOver="over()" onMouseOut="out()" onMouseDown="out(); evaluate();"
onMouseUp="over()"><br><br>
</code></pre>
<p>Semicolons are required after the calls to <code>over()</code> and <code>out()</code> (roger that? <em>--- sorry couldn't resist</em>)</p>
<p>Secondly (the much more subtle problem):</p>
<p>If we ever need intend to translate the <code>get()</code> into a <code>getJSON()</code> call, (which you might have noted was my original intent from the commented python code that returns a dict), then we need to wrap a <code>str()</code> call around <code>self.request.get('entry')</code>. Hence, </p>
<p><code>self.response.out.write({'evalresult': self.request.get('entry')})</code> </p>
<p>becomes: </p>
<p><code>self.response.out.write({'evalresult': str(self.request.get('entry'))})</code> </p>
<p>As strings from an HTML field translate to unicode text in Python, at the back-end, we apparently need to convert it to a Python string (as <code>getJSON()</code> apparently doesn't like Python's representation of a unicode string -- any ideas why this this is the case anyone?).</p>
<p>At any rate, the original problem has been solved. In conclusion: any JSON object with a Python unicode string will <em>not</em> be accepted as a valid JSON object and will fail silently -- a nasty gotcha that I can see biting anyone using JQuery with Python on the server-side.</p>
| 1 | 2009-08-14T07:20:48Z | [
"javascript",
"jquery",
"python",
"google-app-engine"
] |
how to access dictionary element in django template? | 1,275,735 | <p>I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.</p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
</code></pre>
<p>it raises an exception with this message "Could not parse the remainder"</p>
| 110 | 2009-08-14T02:24:58Z | 1,275,751 | <p>You need to find (or define) a 'get' template tag, for example, <a href="http://push.cx/2007/django-template-tag-for-dictionary-access">here</a>.</p>
| 9 | 2009-08-14T02:30:39Z | [
"python",
"django"
] |
how to access dictionary element in django template? | 1,275,735 | <p>I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.</p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
</code></pre>
<p>it raises an exception with this message "Could not parse the remainder"</p>
| 110 | 2009-08-14T02:24:58Z | 1,275,805 | <p>Ideally, you would create a method on the choice object that found itself in votes, or create a relationship between the models. A template tag that performed the dictionary lookup would work, too.</p>
| 3 | 2009-08-14T02:46:44Z | [
"python",
"django"
] |
how to access dictionary element in django template? | 1,275,735 | <p>I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.</p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
</code></pre>
<p>it raises an exception with this message "Could not parse the remainder"</p>
| 110 | 2009-08-14T02:24:58Z | 1,275,999 | <p>To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object: </p>
<pre><code> class Choice(models.Model):
text = models.CharField(max_length=200)
def calculateVotes(self):
return Vote.objects.filter(choice = self).count()
votes = property(calculateVotes)
</code></pre>
<p>And then in your template, you can do:</p>
<pre><code> {% for choice in choices %}
{{choice.choice}} - {{choice.votes}} <br />
{% endfor %}
</code></pre>
<p>The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa. </p>
<p>I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.</p>
| 40 | 2009-08-14T04:07:47Z | [
"python",
"django"
] |
how to access dictionary element in django template? | 1,275,735 | <p>I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.</p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
</code></pre>
<p>it raises an exception with this message "Could not parse the remainder"</p>
| 110 | 2009-08-14T02:24:58Z | 1,724,201 | <p>you can use the dot notation:</p>
<blockquote>
<p>Dot lookups can be summarized like
this: when the template system
encounters a dot in a variable name,
it tries the following lookups, in
this order:</p>
<ul>
<li>Dictionary lookup (e.g., foo["bar"])</li>
<li>Attribute lookup (e.g., foo.bar)</li>
<li>Method call (e.g., foo.bar())</li>
<li>List-index lookup (e.g., foo[2])</li>
</ul>
<p>The system uses the first lookup type
that works. Itâs short-circuit logic.</p>
</blockquote>
| 121 | 2009-11-12T18:01:40Z | [
"python",
"django"
] |
how to access dictionary element in django template? | 1,275,735 | <p>I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.</p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
</code></pre>
<p>it raises an exception with this message "Could not parse the remainder"</p>
| 110 | 2009-08-14T02:24:58Z | 6,285,769 | <pre><code>choices = {'key1':'val1', 'key2':'val2'}
</code></pre>
<p>Here's the template:</p>
<pre>
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
</pre>
<p>Basically, <code>.items</code> is a Django keyword that splits a dictionary into a list of (key, value) pairs. This enables iteration over a dictionary in a Django template.</p>
| 180 | 2011-06-08T21:59:02Z | [
"python",
"django"
] |
how to access dictionary element in django template? | 1,275,735 | <p>I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.</p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
</code></pre>
<p>it raises an exception with this message "Could not parse the remainder"</p>
| 110 | 2009-08-14T02:24:58Z | 37,053,330 | <p><a href="https://github.com/telminov/sw-django-utils/blob/master/djutils/templatetags/djutils.py" rel="nofollow">django_template_filter</a>
filter name get_value_from_dict</p>
<pre><code>{{ your_dict|get_value_from_dict:your_key }}
</code></pre>
| 0 | 2016-05-05T14:32:36Z | [
"python",
"django"
] |
how to access dictionary element in django template? | 1,275,735 | <p>I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.</p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
</code></pre>
<p>it raises an exception with this message "Could not parse the remainder"</p>
| 110 | 2009-08-14T02:24:58Z | 38,530,067 | <p>Similar to the answer by @russian_spy :</p>
<pre><code><ul>
{% for choice in choices.items %}
<li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}
</ul>
</code></pre>
<p>This might be suitable for breaking down more complex dictionaries.</p>
| 0 | 2016-07-22T15:19:35Z | [
"python",
"django"
] |
Executes Fine In Jail Shell but not in Browser | 1,276,497 | <p>My python script executes fine in Jail shell, putting out html which I can pipe to an html file. When I look at the file, it's exactly what I want. However when I try to run the file from a browser I get a 500 error. According to the instructions at <a href="http://imgseekweb.sourceforge.net/install.html" rel="nofollow">http://imgseekweb.sourceforge.net/install.html</a> the cgi-bin should be in suEXEC mode. My hosting company changed the cgi-script handler to allow .py files and he made a little test script that works fine, but mine still does not.</p>
<p>I tried to make suEXEC a custom Apache file handler of .py files in cPanel, but this did not seem to help, it just made the Python script print out as text in the browser without executing.</p>
<p>Any ideas for resolution. I'm so close now that script at least works in Jail Shell. I even try to fake out Apache by making the test file launch a system execution of the python script but that also caused a 500 error, although it too spit out the correct html in Jail Shell even doing some Lynx like display of the html this time.</p>
<p>Whatever machinations I did also caused the test.py to stop working. It now gives a 500 error too even with all the code I added removed.</p>
| 0 | 2009-08-14T07:27:40Z | 1,280,412 | <p>My hoster resolved the issue. It turns out I'm working in a Windows environment with Microsoft Expression 2.0 HTML editor. The code needed to be converted to a UNIX environment with dos2unix which is installed in the hoster environment and can be accessed from the shell...Thanks for reading this thread to any who read it.</p>
| 0 | 2009-08-14T21:54:01Z | [
"python",
"browser",
"scripting"
] |
Take screenshots **quickly** from python | 1,276,616 | <p>A <code>PIL.Image.grab() </code> takes about 0.5 seconds. That's just to get data from the screen to my app, without any processing on my part. <a href="http://www.fraps.com/" rel="nofollow">FRAPS</a>, on the other hand, can take screenshots up to 30 FPS. Is there any way for me to do the same from a Python program? If not, how about from a C program? (I could interface it w/ the Python program, potentially...)</p>
| 4 | 2009-08-14T08:08:31Z | 1,276,664 | <p>If you want fast screenshots, you must use a lower level API, like DirectX or GTK. There are Python wrappers for those, like <a href="http://directpython.sourceforge.net/" rel="nofollow">DirectPython</a> and <a href="http://www.pygtk.org/" rel="nofollow">PyGTK</a>. Some samples I've found follow:</p>
<ul>
<li><p><a href="http://www.reddit.com/r/programming/comments/8qe1t/fast%5Fx11%5Fscreenshots%5Fin%5Fpython%5Fsee%5Fcomment/" rel="nofollow">PyGTK sample</a> </p></li>
<li><p><a href="http://www.codeproject.com/KB/dialog/screencap.aspx" rel="nofollow">Windows and DirectX samples</a></p></li>
</ul>
| 1 | 2009-08-14T08:25:02Z | [
"python",
"image",
"optimization",
"performance",
"screen-scraping"
] |
Stripping everything but alphanumeric chars from a string in Python | 1,276,764 | <p>What is the best way to strip all non alphanumeric characters from a string, using Python?</p>
<p>The solutions presented in the <a href="http://stackoverflow.com/questions/840948">PHP variant of this question</a> will probably work with some minor adjustments, but don't seem very 'pythonic' to me.</p>
<p>For the record, I don't just want to strip periods and commas (and other punctuation), but also quotes, brackets, etc.</p>
| 142 | 2009-08-14T08:54:47Z | 1,276,774 | <p>Regular expressions to the rescue:</p>
<pre><code>import re
re.sub(r'\W+', '', your_string)
</code></pre>
| 116 | 2009-08-14T08:57:37Z | [
"python",
"string"
] |
Stripping everything but alphanumeric chars from a string in Python | 1,276,764 | <p>What is the best way to strip all non alphanumeric characters from a string, using Python?</p>
<p>The solutions presented in the <a href="http://stackoverflow.com/questions/840948">PHP variant of this question</a> will probably work with some minor adjustments, but don't seem very 'pythonic' to me.</p>
<p>For the record, I don't just want to strip periods and commas (and other punctuation), but also quotes, brackets, etc.</p>
| 142 | 2009-08-14T08:54:47Z | 1,276,782 | <p>How about:</p>
<pre><code>def ExtractAlphanumeric(InputString):
from string import ascii_letters, digits
return "".join([ch for ch in InputString if ch in (ascii_letters + digits)])
</code></pre>
<p>This works by using list comprehension to produce a list of the characters in <code>InputString</code> if they are present in the combined <code>ascii_letters</code> and <code>digits</code> strings. It then joins the list together into a string.</p>
| 8 | 2009-08-14T08:58:39Z | [
"python",
"string"
] |
Stripping everything but alphanumeric chars from a string in Python | 1,276,764 | <p>What is the best way to strip all non alphanumeric characters from a string, using Python?</p>
<p>The solutions presented in the <a href="http://stackoverflow.com/questions/840948">PHP variant of this question</a> will probably work with some minor adjustments, but don't seem very 'pythonic' to me.</p>
<p>For the record, I don't just want to strip periods and commas (and other punctuation), but also quotes, brackets, etc.</p>
| 142 | 2009-08-14T08:54:47Z | 1,276,804 | <pre><code>>>> import re
>>> string = "Kl13@£$%[};'\""
>>> pattern = re.compile('\W')
>>> string = re.sub(pattern, '', string)
>>> print string
Kl13
</code></pre>
| 6 | 2009-08-14T09:01:22Z | [
"python",
"string"
] |
Stripping everything but alphanumeric chars from a string in Python | 1,276,764 | <p>What is the best way to strip all non alphanumeric characters from a string, using Python?</p>
<p>The solutions presented in the <a href="http://stackoverflow.com/questions/840948">PHP variant of this question</a> will probably work with some minor adjustments, but don't seem very 'pythonic' to me.</p>
<p>For the record, I don't just want to strip periods and commas (and other punctuation), but also quotes, brackets, etc.</p>
| 142 | 2009-08-14T08:54:47Z | 1,276,811 | <p>You could try:</p>
<pre><code>print ''.join(ch for ch in some_string if ch.isalnum())
</code></pre>
| 14 | 2009-08-14T09:02:28Z | [
"python",
"string"
] |
Stripping everything but alphanumeric chars from a string in Python | 1,276,764 | <p>What is the best way to strip all non alphanumeric characters from a string, using Python?</p>
<p>The solutions presented in the <a href="http://stackoverflow.com/questions/840948">PHP variant of this question</a> will probably work with some minor adjustments, but don't seem very 'pythonic' to me.</p>
<p>For the record, I don't just want to strip periods and commas (and other punctuation), but also quotes, brackets, etc.</p>
| 142 | 2009-08-14T08:54:47Z | 1,277,047 | <p>I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string <code>string.printable</code> (part of the built-in <code>string</code> module).</p>
<pre><code>$ python -m timeit -s \
"import string" \
"''.join(ch for ch in string.printable if ch.isalnum())"
10000 loops, best of 3: 57.6 usec per loop
$ python -m timeit -s \
"import string" \
"filter(str.isalnum, string.printable)"
10000 loops, best of 3: 37.9 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]', '', string.printable)"
10000 loops, best of 3: 27.5 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]+', '', string.printable)"
100000 loops, best of 3: 15 usec per loop
$ python -m timeit -s \
"import re, string; pattern = re.compile('[\W_]+')" \
"pattern.sub('', string.printable)"
100000 loops, best of 3: 11.2 usec per loop
</code></pre>
| 160 | 2009-08-14T10:03:32Z | [
"python",
"string"
] |
Stripping everything but alphanumeric chars from a string in Python | 1,276,764 | <p>What is the best way to strip all non alphanumeric characters from a string, using Python?</p>
<p>The solutions presented in the <a href="http://stackoverflow.com/questions/840948">PHP variant of this question</a> will probably work with some minor adjustments, but don't seem very 'pythonic' to me.</p>
<p>For the record, I don't just want to strip periods and commas (and other punctuation), but also quotes, brackets, etc.</p>
| 142 | 2009-08-14T08:54:47Z | 1,280,823 | <p>Use the <strong>str.translate()</strong> method.</p>
<p>Presuming you will be doing this often:</p>
<p>(1) Once, create a string containing all the characters you wish to delete:</p>
<pre><code>delchars = ''.join(c for c in map(chr, range(256)) if not c.isalnum())
</code></pre>
<p>(2) Whenever you want to scrunch a string:</p>
<pre><code>scrunched = s.translate(None, delchars)
</code></pre>
<p>The setup cost probably compares favourably with re.compile; the marginal cost is way lower:</p>
<pre><code>C:\junk>\python26\python -mtimeit -s"import string;d=''.join(c for c in map(chr,range(256)) if not c.isalnum());s=string.printable" "s.translate(None,d)"
100000 loops, best of 3: 2.04 usec per loop
C:\junk>\python26\python -mtimeit -s"import re,string;s=string.printable;r=re.compile(r'[\W_]+')" "r.sub('',s)"
100000 loops, best of 3: 7.34 usec per loop
</code></pre>
<p>Note: <strong>Using string.printable as benchmark data gives the pattern '[\W_]+' an unfair advantage</strong>; all the non-alphanumeric characters are in one bunch ... in typical data there would be more than one substitution to do:</p>
<pre><code>C:\junk>\python26\python -c "import string; s = string.printable; print len(s),repr(s)"
100 '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
</code></pre>
<p>Here's what happens if you give re.sub a bit more work to do:</p>
<pre><code>C:\junk>\python26\python -mtimeit -s"d=''.join(c for c in map(chr,range(256)) if not c.isalnum());s='foo-'*25" "s.translate(None,d)"
1000000 loops, best of 3: 1.97 usec per loop
C:\junk>\python26\python -mtimeit -s"import re;s='foo-'*25;r=re.compile(r'[\W_]+')" "r.sub('',s)"
10000 loops, best of 3: 26.4 usec per loop
</code></pre>
| 52 | 2009-08-15T00:33:48Z | [
"python",
"string"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 1,277,175 | <p>I compile it in <code>/usr/local</code> without any issues whatsoever.</p>
<p>Install Python, libxml2, libxslt and then lxml. You might need setuptools installed too.</p>
| -4 | 2009-08-14T10:33:46Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 1,277,258 | <p>Have you tried with easy_install? </p>
<ul>
<li><a href="http://peak.telecommunity.com/DevCenter/EasyInstall" rel="nofollow">http://peak.telecommunity.com/DevCenter/EasyInstall</a></li>
</ul>
<p>I don't own a Mac so I can't test it, but easy_install is almost considered the standard way to install python modules, so if you don't know it you should have a look at it.</p>
| -2 | 2009-08-14T10:57:49Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 1,277,326 | <p>Try installing Cython and installing from source, easy_install does fail. I haven't tried on my mac yet though.</p>
<p>Failing that the ports version isn't that ancient. You can see the dependencies, some of which had to be updated for my Linux build of lxml.</p>
<p>info py25-lxml
py25-lxml @2.1.5 (python, devel)</p>
<p>lxml is a Pythonic binding for the libxml2 and libxslt libraries. It is unique
in that it combines the speed and feature completeness of these libraries with
the simplicity of a native Python API, mostly compatible but superior to the
well-known ElementTree API.
Homepage: <a href="http://codespeak.net/lxml/" rel="nofollow">http://codespeak.net/lxml/</a></p>
<p>Library Dependencies: python25, libxml2, libxslt, py25-hashlib, py25-setuptools,
py25-zlib
Platforms: darwin
Maintainers: akitada@macports.org openmaintainer@macports.org</p>
| 0 | 2009-08-14T11:15:46Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 1,277,327 | <p>This is quite up to date - march 2009: <a href="http://lsimons.wordpress.com/2008/08/31/how-to-install-lxml-python-module-on-mac-os-105-leopard/" rel="nofollow">http://lsimons.wordpress.com/2008/08/31/how-to-install-lxml-python-module-on-mac-os-105-leopard/</a></p>
| 0 | 2009-08-14T11:15:50Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 1,277,421 | <p>Thanks to @jessenoller on Twitter I have an answer that fits my needs - you can compile lxml with static dependencies, hence avoiding messing with the libxml2 that ships with OS X. Here's what worked for me:</p>
<pre><code>cd /tmp
curl -O http://lxml.de/files/lxml-3.6.0.tgz
tar -xzvf lxml-3.6.0.tgz
cd lxml-3.6.0
python setup.py build --static-deps --libxml2-version=2.7.3 --libxslt-version=1.1.24
sudo python setup.py install
</code></pre>
| 33 | 2009-08-14T11:40:39Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 1,277,425 | <p>This worked for me in the past <a href="http://muffinresearch.co.uk/archives/2009/03/05/install-lxml-on-osx/" rel="nofollow">install lxml on osx</a></p>
| 1 | 2009-08-14T11:41:46Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 1,333,631 | <p>Easy_install <em>can</em> work using this:</p>
<p>STATIC_DEPS=true easy_install 'lxml>=2.2beta4'</p>
<p>you may <em>then</em> need to run, depending on permissions;</p>
<p>STATIC_DEPS=true sudo easy_install 'lxml>=2.2beta4'</p>
<p>see
<a href="http://muffinresearch.co.uk/archives/2009/03/05/install-lxml-on-osx/">http://muffinresearch.co.uk/archives/2009/03/05/install-lxml-on-osx/</a></p>
| 5 | 2009-08-26T10:05:27Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 1,542,110 | <p>lxml is <a href="http://code.activestate.com/pypm/lxml/" rel="nofollow">included</a> in the <a href="http://docs.activestate.com/activepython/2.7/pypm.html" rel="nofollow">pypm</a> repository:</p>
<pre><code>$ pypm install lxml
</code></pre>
| 0 | 2009-10-09T06:27:38Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 5,785,013 | <p>I've had excellent luck with <a href="http://mxcl.github.com/homebrew/">Homebrew</a> to install the <code>libxml2</code> dependency:</p>
<pre><code>brew install libxml2
</code></pre>
<p>Homebrew doesn't seem to have <code>libxslt</code> available, but I've not yet had a need for XSLT. YMMV.</p>
<p>Once you have the dependency(s), then the usual methods work just fine:</p>
<pre><code>pip install lxml
</code></pre>
<p>or</p>
<pre><code>easy_install lxml
</code></pre>
| 16 | 2011-04-26T01:32:08Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 6,545,556 | <p>This worked for me (10.6.8):</p>
<pre><code>sudo env ARCHFLAGS="-arch i386 -arch x86_64" easy_install lxml
</code></pre>
| 30 | 2011-07-01T08:38:34Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 7,850,559 | <p>I had this working fine with Snow Lepoard but after I upgraded to Lion I had to symlink gcc-4.2 to gcc. Running sudo env ARCHFLAGS="-arch i386 -arch x86_64" easy_install lxml was looking for gcc-4.2 instead of gcc.</p>
| 1 | 2011-10-21T14:06:12Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 10,323,988 | <p>To install with up to date versions of libxml2 and libxslt: </p>
<pre><code>ARCHFLAGS="-arch i386 -arch x86_64" STATIC_DEPS=true pip install lxml
</code></pre>
<p>To install with specific versions of libraries:</p>
<pre><code>ARCHFLAGS="-arch i386 -arch x86_64" STATIC_DEPS=true LIBXML2_VERSION=2.7.3 LIBXSLT_VERSION=1.1.24 pip install lxml
</code></pre>
<p>CentOS 64 bit (a bit off question, but hard won): </p>
<pre><code>CFLAGS=-fPIC STATIC_DEPS=true pip install lxml
</code></pre>
<p>or </p>
<pre><code>CFLAGS=-fPIC STATIC_DEPS=true LIBXML2_VERSION=2.7.3 LIBXSLT_VERSION=1.1.24 pip install lxml
</code></pre>
| 0 | 2012-04-25T21:21:11Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 19,303,920 | <p>This worked for me on 10.8.5</p>
<ol>
<li>Install Xcode from Mac App Store</li>
<li>Xcode -> Preferences -> Downloads -> Command Line Tools</li>
<li>Install homebrew using</li>
<li><code>ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"</code></li>
<li><code>brew install libxml2</code></li>
<li><code>sudo easy_install lxml</code></li>
</ol>
<p>This comprises suggestions from:</p>
<ul>
<li><a href="http://stackoverflow.com/a/6545556/300224">http://stackoverflow.com/a/6545556/300224</a></li>
<li><a href="http://stackoverflow.com/a/5785013/300224">http://stackoverflow.com/a/5785013/300224</a></li>
<li><a href="http://stackoverflow.com/a/9403589">http://stackoverflow.com/a/9403589</a></li>
</ul>
<p>But I wanted to compile it into one answer rather than leave comments everywhere</p>
| 2 | 2013-10-10T18:52:08Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 21,501,469 | <p>On <strong>OS X 10.9.1</strong> the suggested answer above errors out during install -- following changes had to be made:</p>
<pre><code>cd /tmp
curl -o lxml-3.3.0.tgz http://lxml.de/files/lxml-3.3.0.tgz
tar -xzvf lxml-3.3.0.tgz
cd lxml-3.3.0
python setup.py build --static-deps --libxml2-version=2.8.0 --libxslt-version=1.1.24
sudo python setup.py install
</code></pre>
| 3 | 2014-02-01T17:54:12Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 24,543,380 | <p>A lot of pain went into this for an outdated 10.6.8 os x but here it goes for anyone running Snow Leopard! </p>
<p>First you have to install a different version of libxml2 from homebrew and install --with-python. You can do this by typing in the following commands.</p>
<pre><code>brew update
brew edit libxml2
</code></pre>
<p>Then find the line that says "--without-python" and change to "--with-python". </p>
<pre><code>system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--with-python"
</code></pre>
<p>Now you can install libxml2.</p>
<pre><code>brew install libxml2
</code></pre>
<p><strong>Next check your new install of libxml2 in the default homebrew location. You want to find the libxml2 config.</strong></p>
<p><strong>YOURS MAY BE DIFFERENT:</strong></p>
<p><strong>"/usr/local/Cellar/libxml2/<em>VERSION_</em>/bin/xml2-config"</strong></p>
<p>Now use the following command to install lxml with pip using the newly installed libxml2 config and not the Mac OS X version. </p>
<pre><code>ARCHFLAGS="-arch i386 -arch x86_64" pip install lxml --install-option="--with-xml2-config=/usr/local/Cellar/libxml2/2.9.1/bin/xml2-config"
</code></pre>
<p>Worked for me on my 10.6.8 Python 2.6. Thanks. </p>
<p>Credit goes to this page for showing me pip --install-option ... </p>
<p><a href="http://natanyellin.com/page/4/" rel="nofollow"><a href="http://natanyellin.com/page/4/" rel="nofollow">http://natanyellin.com/page/4/</a></a></p>
| 0 | 2014-07-03T00:55:04Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 33,181,756 | <p>I'm using OSX 10.11 El Capitan and Homebrew. Using <code>pip install lxml</code> would give me "fatal error: 'libxml/xmlversion.h' file not found" and "failed with error code 1" blah blah.</p>
<p>According to the <a href="http://lxml.de/installation.html" rel="nofollow">official website</a>, I should use <code>STATIC_DEPS=true pip install lxml</code> (add sudo before pip if you need that), and that solved my problem.</p>
<p>I ran <code>brew install libxml2</code> and <code>brew install libxslt</code> to install the dependencies while troubleshooting. I'm not sure if those two commands are necessary.</p>
| 1 | 2015-10-17T01:24:15Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
How do you install lxml on OS X Leopard without using MacPorts or Fink? | 1,277,124 | <p>I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works?</p>
<p>Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.</p>
| 34 | 2009-08-14T10:22:27Z | 34,777,511 | <p>using homebrew (0.9.5) on el capitan (10.11.1) the following worked for me:</p>
<pre><code>brew install libxml2
LD_FLAGS=-L/usr/local/opt/libxml2/lib CPPFLAGS=-I/usr/local/opt/libxml2/include/libxml2 pip install lxml
</code></pre>
| 2 | 2016-01-13T21:36:49Z | [
"python",
"osx",
"shell",
"lxml",
"osx-leopard"
] |
Python: zip-like function that pads to longest length? | 1,277,278 | <p>Is there a built-in function that works like <code>zip()</code> but that will pad the results so that the length of the resultant list is the length of the <em>longest</em> input rather than the <em>shortest</em> input?</p>
<pre><code>>>> a=['a1']
>>> b=['b1','b2','b3']
>>> c=['c1','c2']
>>> zip(a,b,c)
[('a1', 'b1', 'c1')]
>>> What command goes here?
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
</code></pre>
| 70 | 2009-08-14T11:04:09Z | 1,277,286 | <p>For Python 2.6x use <code>itertools</code> module's <a href="http://docs.python.org/library/itertools.html#itertools.izip_longest"><code>izip_longest</code></a>.</p>
<p>For Python 3 use <a href="http://docs.python.org/3.1/library/itertools.html#itertools.zip_longest"><code>zip_longest</code></a> instead (no leading <code>i</code>).</p>
<pre><code>>>> list(itertools.izip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
</code></pre>
| 41 | 2009-08-14T11:06:13Z | [
"python",
"list",
"zip"
] |
Python: zip-like function that pads to longest length? | 1,277,278 | <p>Is there a built-in function that works like <code>zip()</code> but that will pad the results so that the length of the resultant list is the length of the <em>longest</em> input rather than the <em>shortest</em> input?</p>
<pre><code>>>> a=['a1']
>>> b=['b1','b2','b3']
>>> c=['c1','c2']
>>> zip(a,b,c)
[('a1', 'b1', 'c1')]
>>> What command goes here?
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
</code></pre>
| 70 | 2009-08-14T11:04:09Z | 1,277,311 | <p>You can either use <a href="https://docs.python.org/2/library/itertools.html#itertools.izip_longest"><code>itertools.izip_longest</code></a> (Python 2.6+), or you can use <code>map</code> with <code>None</code>. It is a little known <a href="https://docs.python.org/2/library/functions.html#map">feature of <code>map</code></a> (but <code>map</code> changed in Python 3.x, so this only works in Python 2.x).</p>
<pre><code>>>> map(None, a, b, c)
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
</code></pre>
| 98 | 2009-08-14T11:10:44Z | [
"python",
"list",
"zip"
] |
How can I pass my locals and access the variables directly from another function? | 1,277,519 | <p>Let's say I have this :</p>
<pre><code>
def a(dict):
locals().update(dict)
print size
def b():
size = 20
f(locals())
</code></pre>
<p>What do I have to do to access the <code>size</code> variable directly from the <code>a</code> function? I know of :</p>
<pre><code>
size = dict["size"]
</code></pre>
<p>but I think there should be a more direct way. I tried using <code>locals().update(dict)</code> but it didn't work. Is there a betteer way ?</p>
| 3 | 2009-08-14T12:08:57Z | 1,277,538 | <pre><code>print size
</code></pre>
<p>cannot work, because "size" is not known when the code is compiled. Your code will work if you change it like this:</p>
<pre><code>def a(dict):
locals().update(dict)
print locals()["size"]
def b():
size = 20
a(locals())
</code></pre>
<p>But as the comment to your question already suggests: This is very strange code. I'm very sure that there are better solutions, if you explain what you really want to do.</p>
| 0 | 2009-08-14T12:18:27Z | [
"python",
"variables",
"function",
"language-features"
] |
How can I pass my locals and access the variables directly from another function? | 1,277,519 | <p>Let's say I have this :</p>
<pre><code>
def a(dict):
locals().update(dict)
print size
def b():
size = 20
f(locals())
</code></pre>
<p>What do I have to do to access the <code>size</code> variable directly from the <code>a</code> function? I know of :</p>
<pre><code>
size = dict["size"]
</code></pre>
<p>but I think there should be a more direct way. I tried using <code>locals().update(dict)</code> but it didn't work. Is there a betteer way ?</p>
| 3 | 2009-08-14T12:08:57Z | 1,277,564 | <p>Is this helping you somehow?</p>
<pre><code>def print_size(size=None):
print(size)
dict = {'size': 'XXL'}
print_size(**dict)
</code></pre>
| 0 | 2009-08-14T12:23:42Z | [
"python",
"variables",
"function",
"language-features"
] |
How can I pass my locals and access the variables directly from another function? | 1,277,519 | <p>Let's say I have this :</p>
<pre><code>
def a(dict):
locals().update(dict)
print size
def b():
size = 20
f(locals())
</code></pre>
<p>What do I have to do to access the <code>size</code> variable directly from the <code>a</code> function? I know of :</p>
<pre><code>
size = dict["size"]
</code></pre>
<p>but I think there should be a more direct way. I tried using <code>locals().update(dict)</code> but it didn't work. Is there a betteer way ?</p>
| 3 | 2009-08-14T12:08:57Z | 1,277,683 | <p>You can use closures to access the scope of another function:</p>
<pre><code>def b():
def a():
print size
size = 20
a()
</code></pre>
<p>The trick is to stack functions which belongs together in each other. This way the inner function a can access the local variables of the outer function b.</p>
<p>But I don't know what you're really up to so I'm not sure if this helps.</p>
| 1 | 2009-08-14T12:51:38Z | [
"python",
"variables",
"function",
"language-features"
] |
How can I pass my locals and access the variables directly from another function? | 1,277,519 | <p>Let's say I have this :</p>
<pre><code>
def a(dict):
locals().update(dict)
print size
def b():
size = 20
f(locals())
</code></pre>
<p>What do I have to do to access the <code>size</code> variable directly from the <code>a</code> function? I know of :</p>
<pre><code>
size = dict["size"]
</code></pre>
<p>but I think there should be a more direct way. I tried using <code>locals().update(dict)</code> but it didn't work. Is there a betteer way ?</p>
| 3 | 2009-08-14T12:08:57Z | 1,278,351 | <p>The Python compiler optimizes access to local variables by recognizing at compile time whether the barenames a function is accessing are local (i.e., barenames assigned or otherwise bound within the function). So if you code:</p>
<pre><code>def lv1(d):
locals().update(d)
print zap
</code></pre>
<p>the compiler "knows" that barename <code>zap</code> is NOT local (not assigned in function <code>lv1</code>) and so it compiles code to access it as a global instead -- whatever <code>d</code> contains won't matter.</p>
<p>If you prefer slow and bloated code, you can defeat the optimization by using an <code>exec</code> inside the function -- when the compiler sees the keyword <code>exec</code>, it KNOWS you're trying to make your code as slow, bloated and buggy as possible, and so it cooperates by not optimizing in any way, just about.</p>
<p>So, the following code works as you desire:</p>
<pre><code>def lv1(d):
exec ""
locals().update(d)
print zap
lv1({'zap': 23})
</code></pre>
<p>it emits <code>23</code> as you want.</p>
<p>I hope it's clear from the above "deadpan humor" that the technique is not recommended, but I'd better spell it out very explicitly: for the dubious syntactic pleasure of writing <code>print zap</code> in lieu of <code>print locals()['zap']</code>, you ARE paying a hefty price in terms of performance. Still, like all sorts of dangerous tools that can be useful in rare use cases for really experienced guru-level programmers who really truly know what they're doing and why, <code>exec</code> is there, available for you to use (or mis-use) at your whim: Python does NOT stand in your way!-)</p>
| 9 | 2009-08-14T14:54:55Z | [
"python",
"variables",
"function",
"language-features"
] |
python subprocess module: looping over stdout of child process | 1,277,866 | <p>I have some commands which I am running using the subprocess module. I then want to loop over the lines of the output. The documentation says do not do data_stream.stdout.read which I am not but I may be doing something which calls that. I am looping over the output like this:</p>
<pre><code>for line in data_stream.stdout:
#do stuff here
.
.
.
</code></pre>
<p>Can this cause deadlocks like reading from data_stream.stdout or are the Popen modules set up for this kind of looping such that it uses the communicate code but handles all the callings of it for you?</p>
| 4 | 2009-08-14T13:34:20Z | 1,277,980 | <p><code>data_stream.stdout</code> is a standard output <strong>handle</strong>. you shouldn't be looping over it. <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow"><code>communicate</code></a> returns tuple of <code>(stdoutdata, stderr)</code>. this <code>stdoutdata</code> you should be using to do your stuff.</p>
| 0 | 2009-08-14T13:54:15Z | [
"python",
"subprocess"
] |
python subprocess module: looping over stdout of child process | 1,277,866 | <p>I have some commands which I am running using the subprocess module. I then want to loop over the lines of the output. The documentation says do not do data_stream.stdout.read which I am not but I may be doing something which calls that. I am looping over the output like this:</p>
<pre><code>for line in data_stream.stdout:
#do stuff here
.
.
.
</code></pre>
<p>Can this cause deadlocks like reading from data_stream.stdout or are the Popen modules set up for this kind of looping such that it uses the communicate code but handles all the callings of it for you?</p>
| 4 | 2009-08-14T13:34:20Z | 1,278,000 | <p>You have to worry about deadlocks if you're <strong>communicating</strong> with your subprocess, i.e. if you're writing to stdin as well as reading from stdout. Because these pipes may be cached, doing this kind of two-way communication is very much a no-no:</p>
<pre><code>data_stream = Popen(mycmd, stdin=PIPE, stdout=PIPE)
data_stream.stdin.write("do something\n")
for line in data_stream:
... # BAD!
</code></pre>
<p>However, if you've not set up stdin (or stderr) when constructing data_stream, you should be fine.</p>
<pre><code>data_stream = Popen(mycmd, stdout=PIPE)
for line in data_stream.stdout:
... # Fine
</code></pre>
<p>If you need two-way communication, use <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate">communicate</a>.</p>
| 6 | 2009-08-14T13:57:35Z | [
"python",
"subprocess"
] |
python subprocess module: looping over stdout of child process | 1,277,866 | <p>I have some commands which I am running using the subprocess module. I then want to loop over the lines of the output. The documentation says do not do data_stream.stdout.read which I am not but I may be doing something which calls that. I am looping over the output like this:</p>
<pre><code>for line in data_stream.stdout:
#do stuff here
.
.
.
</code></pre>
<p>Can this cause deadlocks like reading from data_stream.stdout or are the Popen modules set up for this kind of looping such that it uses the communicate code but handles all the callings of it for you?</p>
| 4 | 2009-08-14T13:34:20Z | 1,278,211 | <p>SilentGhost's/chrispy's answers are OK if you have a small to moderate amount of output from your subprocess. Sometimes, though, there may be a lot of output - too much to comfortably buffer in memory. In such a case, the thing to do is <code>start()</code> the process, and spawn a couple of threads - one to read <code>child.stdout</code> and one to read <code>child.stderr</code> where <code>child</code> is the subprocess. You then need to <code>wait()</code> for the subprocess to terminate.</p>
<p>This is actually how <code>communicate()</code> works; the advantage of using your own threads is that you can process the output from the subprocess as it is generated. For example, in my project <a href="http://code.google.com/p/python-gnupg/" rel="nofollow"><code>python-gnupg</code></a> I use this technique to read status output from the GnuPG executable as it is generated, rather than waiting for all of it by calling <code>communicate()</code>. You are welcome to inspect the source of this project - the relevant stuff is in the module <code>gnupg.py</code>.</p>
| 3 | 2009-08-14T14:33:29Z | [
"python",
"subprocess"
] |
python subprocess module: looping over stdout of child process | 1,277,866 | <p>I have some commands which I am running using the subprocess module. I then want to loop over the lines of the output. The documentation says do not do data_stream.stdout.read which I am not but I may be doing something which calls that. I am looping over the output like this:</p>
<pre><code>for line in data_stream.stdout:
#do stuff here
.
.
.
</code></pre>
<p>Can this cause deadlocks like reading from data_stream.stdout or are the Popen modules set up for this kind of looping such that it uses the communicate code but handles all the callings of it for you?</p>
| 4 | 2009-08-14T13:34:20Z | 1,278,245 | <p>The two answer have caught the gist of the issue pretty well: don't mix writing something to the subprocess, reading something from it, writing again, etc -- the pipe's buffering means you're at risk of a deadlock. If you can, write everything you need to write to the subprocess FIRST, close that pipe, and only THEN read everything the subprocess has to say; <code>communicate</code> is nice for the purpose, IF the amount of data is not too large to fit in memory (if it is, you can still achieve the same effect "manually").</p>
<p>If you need finer-grain interaction, look instead at <a href="http://pexpect.sourceforge.net/pexpect.html">pexpect</a> or, if you're on Windows, <a href="http://code.google.com/p/wexpect/">wexpect</a>.</p>
| 6 | 2009-08-14T14:38:51Z | [
"python",
"subprocess"
] |
Python and dictionary like object | 1,277,881 | <p>I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).</p>
<p>But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using <strong><code>isinstance</code></strong> and <strong><code>type</code></strong> (because they are considered bad, as I can read on almost every Pythonista's blog).</p>
<p>But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?</p>
<p>Thanks!</p>
<p>Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : <a href="http://blog.cafeaumiel.com/public/python/dict_deep_update.py" rel="nofollow">http://blog.cafeaumiel.com/public/python/dict_deep_update.py</a></p>
| 10 | 2009-08-14T13:37:53Z | 1,277,918 | <p>use <code>isinstance</code>, there is nothing wrong with it and it's routinely used in code requiring recursion.</p>
<p>If by dictionary-like you mean the object's class inherit from the <code>dict</code>, <code>isinstance</code> will also return <code>True</code>.</p>
<pre><code>>>> class A(dict):
pass
>>> a = A()
>>> isinstance(a, dict)
True
</code></pre>
| 1 | 2009-08-14T13:43:29Z | [
"python",
"dictionary",
"duck-typing"
] |
Python and dictionary like object | 1,277,881 | <p>I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).</p>
<p>But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using <strong><code>isinstance</code></strong> and <strong><code>type</code></strong> (because they are considered bad, as I can read on almost every Pythonista's blog).</p>
<p>But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?</p>
<p>Thanks!</p>
<p>Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : <a href="http://blog.cafeaumiel.com/public/python/dict_deep_update.py" rel="nofollow">http://blog.cafeaumiel.com/public/python/dict_deep_update.py</a></p>
| 10 | 2009-08-14T13:37:53Z | 1,277,936 | <p>Duck typing is where you do what you want to do, and deal with the fallout if your objects don't behave the way you expected them to.</p>
<p>You want to check if something is dict-like, and update it if it is, right? Just call the object's update method, and handle the Exception you get if there is no such method.</p>
<p>Of course, this will fall flat if you deal with custom class objects which have update methods that do something else entirely -- I'm not quite sure how to deal with that.</p>
| 1 | 2009-08-14T13:45:06Z | [
"python",
"dictionary",
"duck-typing"
] |
Python and dictionary like object | 1,277,881 | <p>I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).</p>
<p>But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using <strong><code>isinstance</code></strong> and <strong><code>type</code></strong> (because they are considered bad, as I can read on almost every Pythonista's blog).</p>
<p>But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?</p>
<p>Thanks!</p>
<p>Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : <a href="http://blog.cafeaumiel.com/public/python/dict_deep_update.py" rel="nofollow">http://blog.cafeaumiel.com/public/python/dict_deep_update.py</a></p>
| 10 | 2009-08-14T13:37:53Z | 1,278,070 | <p>Check out the (new in 3.x) abstract base classes (ABC's) in the collections module:</p>
<p><a href="http://docs.python.org/3.1/library/collections.html">http://docs.python.org/3.1/library/collections.html</a></p>
<p>I would consider checking with isinstance against Mapping like in the following:</p>
<pre><code>>>> import collections
>>> isinstance({},collections.Mapping)
True
</code></pre>
<p>Then, if you make your own dict-like class, make collections.Mapping one of its bases.</p>
<p>The other route is trying and catching whatever exceptions for the dictionary operations, - but with the recursion you're talking about, I'd rather check against the base type first than handle figuring out what dict or subdict or other dict member was or was not there to throw an exception.</p>
<p>Editing to add: The benefit of checking against the Mapping ABC instead of against dict is that the same test will work for dict-like classes regardless of whether or not they subclass dict, so it's more flexible, just in case.</p>
| 11 | 2009-08-14T14:08:58Z | [
"python",
"dictionary",
"duck-typing"
] |
Python and dictionary like object | 1,277,881 | <p>I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).</p>
<p>But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using <strong><code>isinstance</code></strong> and <strong><code>type</code></strong> (because they are considered bad, as I can read on almost every Pythonista's blog).</p>
<p>But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?</p>
<p>Thanks!</p>
<p>Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : <a href="http://blog.cafeaumiel.com/public/python/dict_deep_update.py" rel="nofollow">http://blog.cafeaumiel.com/public/python/dict_deep_update.py</a></p>
| 10 | 2009-08-14T13:37:53Z | 1,278,292 | <p>If you also have to handle custom classes that behave like dictionaries but aren't subclassed from dict, you can use getattr to get the function you require.</p>
<pre><code># loop
# ... more code
someObject = getObject(..)
try:
getattr(someObject, "update")("someValue")
except AttributeError:
# Wasn't a type we can handle
</code></pre>
| 0 | 2009-08-14T14:45:47Z | [
"python",
"dictionary",
"duck-typing"
] |
Python and dictionary like object | 1,277,881 | <p>I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).</p>
<p>But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using <strong><code>isinstance</code></strong> and <strong><code>type</code></strong> (because they are considered bad, as I can read on almost every Pythonista's blog).</p>
<p>But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?</p>
<p>Thanks!</p>
<p>Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : <a href="http://blog.cafeaumiel.com/public/python/dict_deep_update.py" rel="nofollow">http://blog.cafeaumiel.com/public/python/dict_deep_update.py</a></p>
| 10 | 2009-08-14T13:37:53Z | 1,279,829 | <p>Well, to update recursively a dictionary, you must call the 'items' method to iterate on it.</p>
<p>So I suggest, you just do :</p>
<pre><code>try :
for key, value in data.items() :
# recursive call
except AttributeError :
# handling the trouble
</code></pre>
| 1 | 2009-08-14T19:47:54Z | [
"python",
"dictionary",
"duck-typing"
] |
Python and dictionary like object | 1,277,881 | <p>I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).</p>
<p>But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using <strong><code>isinstance</code></strong> and <strong><code>type</code></strong> (because they are considered bad, as I can read on almost every Pythonista's blog).</p>
<p>But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?</p>
<p>Thanks!</p>
<p>Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : <a href="http://blog.cafeaumiel.com/public/python/dict_deep_update.py" rel="nofollow">http://blog.cafeaumiel.com/public/python/dict_deep_update.py</a></p>
| 10 | 2009-08-14T13:37:53Z | 24,437,844 | <p>I like to check for the '<strong>__setitem__</strong>' magic method... this that is what allows the foo['bar'] = baz behavior.</p>
<pre><code>if getattr(obj, '__setattr__'):
obj[key] = val
</code></pre>
<p>Here is the <a href="https://docs.python.org/2/reference/datamodel.html#emulating-container-types" rel="nofollow">python 2.7 docs</a></p>
| 0 | 2014-06-26T18:40:42Z | [
"python",
"dictionary",
"duck-typing"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 1,277,937 | <pre><code>filter(lambda n: isinstance(n, int), [1,2,"three"])
</code></pre>
| 0 | 2009-08-14T13:45:28Z | [
"python"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 1,277,940 | <p>List comprehensions.</p>
<pre><code>list_2 = [num for num in list_1 if isinstance(num, (int,float))]
</code></pre>
| 12 | 2009-08-14T13:46:19Z | [
"python"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 1,277,943 | <pre><code>list_2 = [i for i in list_1 if isinstance(i, (int, float))]
</code></pre>
| 0 | 2009-08-14T13:46:51Z | [
"python"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 1,277,949 | <pre><code>list_2 = [i for i in list_1 if isinstance(i, (int, float))]
</code></pre>
| 2 | 2009-08-14T13:47:54Z | [
"python"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 1,277,966 | <pre><code>>>> [ i for i in list_1 if not str(i).replace(" ","").isalpha() ]
[1, 123131.13099999999, 9.9999999999999995e-07, 34.124512352650001]
</code></pre>
| -1 | 2009-08-14T13:51:54Z | [
"python"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 1,277,993 | <p>This should be the most efficent and shortest:</p>
<pre><code>import operator
filter(operator.isNumberType, list_1)
</code></pre>
<p>Edit: this in python 3000:</p>
<pre><code>import numbers
[x for x in list_1 if isinstance(x, numbers.Number)]
</code></pre>
| 13 | 2009-08-14T13:56:52Z | [
"python"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 1,281,993 | <p>for short of SilentGhost way</p>
<pre><code>list_2 = [i for i in list_1 if isinstance(i, (int, float))]
</code></pre>
<p>to</p>
<pre><code>list_2 = [i for i in list_1 if not isinstance(i, str)]
</code></pre>
| -1 | 2009-08-15T14:20:37Z | [
"python"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 34,065,821 | <p>I think the easiest way is:</p>
<pre><code>[s for s in myList if s.isdigit()]
</code></pre>
<p>Hope it helps!</p>
| 0 | 2015-12-03T12:14:45Z | [
"python"
] |
Is there a way to output the numbers only from a python list? | 1,277,914 | <p>Simple Question:</p>
<pre><code>list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
</code></pre>
<p>I want to create a <code>list_2</code> such that it only contains the numbers:</p>
<pre><code>list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]
</code></pre>
<p>Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?</p>
| 5 | 2009-08-14T13:42:47Z | 39,723,833 | <p>All solutions proposed work only if the numbers inside the list are already converted to the appropriate type (<code>int</code>, <code>float</code>).</p>
<p>I found myself with a list coming from the <code>fetchall</code> function of <code>sqlite3</code>. All elements there were formated as <code>str</code>, even if some of those elements were actually integers.</p>
<pre><code>cur.execute('SELECT column1 FROM table1 WHERE column2 = ?', (some_condition, ))
list_of_tuples = cur.fetchall()
</code></pre>
<p>The equivalent from the question would be having something like:</p>
<pre><code>list_1 = [ 'asdada', '1', '123131', 'blaa adaraerada', '0', '34', 'stackoverflow is awesome' ]
</code></pre>
<p>For such a case, in order to get a list with the integers only, this is the alternative I found:</p>
<pre><code>list_of_numbers = []
for tup in list_of_tuples:
try:
list_of_numbers.append(int(tup[0]))
except ValueError:
pass
</code></pre>
<p><strong>list_of_numbers</strong> will contain only all integers from the initial list.</p>
| 0 | 2016-09-27T11:45:53Z | [
"python"
] |
Updating profile with python-twitter | 1,278,192 | <p>I am trying to update my Profile info via <a href="http://code.google.com/p/python-twitter/" rel="nofollow">python-twitter module</a>.</p>
<pre><code>>>> api = twitter.Api(username="username", password="password")
>>> user = api.GetUser(user="username")
>>> user.SetLocation('New Location')
</code></pre>
<p>The problem is that it is not getting updated and the documentation is unclear if there's another step I need to do - is there a "save" that I need to call or something like that?</p>
| 0 | 2009-08-14T14:31:48Z | 1,278,284 | <p>I don't believe that the python-twitter module currently supports updating a profile. SetLocation will only update your local user object that GetUser has returned.</p>
<p>It would be relatively trivial to add support for this to the module though. Have a look at this method:</p>
<p><a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0update%5Fprofile" rel="nofollow">account/update_profile</a> </p>
<p>and then add a new method to the Api class that calls <strong>account/update_profile</strong> with the updated user data.</p>
| 1 | 2009-08-14T14:45:15Z | [
"python",
"api",
"twitter"
] |
Updating profile with python-twitter | 1,278,192 | <p>I am trying to update my Profile info via <a href="http://code.google.com/p/python-twitter/" rel="nofollow">python-twitter module</a>.</p>
<pre><code>>>> api = twitter.Api(username="username", password="password")
>>> user = api.GetUser(user="username")
>>> user.SetLocation('New Location')
</code></pre>
<p>The problem is that it is not getting updated and the documentation is unclear if there's another step I need to do - is there a "save" that I need to call or something like that?</p>
| 0 | 2009-08-14T14:31:48Z | 2,266,068 | <p>This are the set*profile* methods from User:</p>
<pre><code>SetProfileBackgroundColor(self, profile_background_color)
SetProfileBackgroundImageUrl(self, profile_background_image_url)
SetProfileBackgroundTile(self, profile_background_tile)
Set the boolean flag for whether to tile the profile background image.
Args:
profile_background_tile: Boolean flag for whether to tile or not.
SetProfileImageUrl(self, profile_image_url)
Set the url of the thumbnail of this user.
Args:
profile_image_url: The url of the thumbnail of this user
SetProfileLinkColor(self, profile_link_color)
SetProfileSidebarFillColor(self, profile_sidebar_fill_color)
SetProfileTextColor(self, profile_text_color)
</code></pre>
<p>You can see a list of available methods at <a href="http://static.unto.net/python-twitter/0.6/doc/twitter.html" rel="nofollow">http://static.unto.net/python-twitter/0.6/doc/twitter.html</a></p>
| 0 | 2010-02-15T13:05:00Z | [
"python",
"api",
"twitter"
] |
How to eliminate last digit from each of the top lines | 1,278,664 | <pre><code>>Sequence 1.1.1 ATGCGCGCGATAAGGCGCTA
ATATTATAGCGCGCGCGCGGATATATATATATATATATATT
>Sequence 1.2.2 ATATGCGCGCGCGCGCGGCG
ACCCCGCGCGCGCGCGGCGCGATATATATATATATATATATT
>Sequence 2.1.1 ATTCGCGCGAGTATAGCGGCG
</code></pre>
<p>NOW,I would like to remove the last digit from each of the line that starts with '>'. For example, in this first line, i would like to remove '.1' (rightmost) and in second instance i would like to remove '.2' and then write the rest of the file to a new file. Thanks,</p>
| 1 | 2009-08-14T15:52:28Z | 1,278,687 | <pre><code>if line.startswith('>Sequence'):
line = line[:-2] # trim 2 characters from the end of the string
</code></pre>
<p>or if there could be more than one digit after the period:</p>
<pre><code>if line.startswith('>Sequence'):
dot_pos = line.rfind('.') # find position of rightmost period
line = line[:dot_pos] # truncate upto but not including the dot
</code></pre>
<p><strong>Edit for if the sequence occurs on the same line as >Sequence</strong></p>
<p>If we know that there will always be only 1 digit to remove we can cut out the period and the digit with:</p>
<pre><code>line = line[:13] + line[15:]
</code></pre>
<p>This is using a feature of Python called <em>slices</em>. The indexes are zero-based and exclusive for the end of the range so <code>line[0:13]</code> will give us the first 13 characters of <code>line</code>. Except that if we want to start at the beginning the 0 is optional so <code>line[:13]</code> does the same thing. Similarly <code>line[15:]</code> gives us the substring starting at character 15 to the end of the string.</p>
| 4 | 2009-08-14T15:57:51Z | [
"python",
"file"
] |
How to eliminate last digit from each of the top lines | 1,278,664 | <pre><code>>Sequence 1.1.1 ATGCGCGCGATAAGGCGCTA
ATATTATAGCGCGCGCGCGGATATATATATATATATATATT
>Sequence 1.2.2 ATATGCGCGCGCGCGCGGCG
ACCCCGCGCGCGCGCGGCGCGATATATATATATATATATATT
>Sequence 2.1.1 ATTCGCGCGAGTATAGCGGCG
</code></pre>
<p>NOW,I would like to remove the last digit from each of the line that starts with '>'. For example, in this first line, i would like to remove '.1' (rightmost) and in second instance i would like to remove '.2' and then write the rest of the file to a new file. Thanks,</p>
| 1 | 2009-08-14T15:52:28Z | 1,278,690 | <p>map <code>"".join(line.split('.')[:-1])</code> to each line of the file.</p>
| 2 | 2009-08-14T15:58:11Z | [
"python",
"file"
] |
How to eliminate last digit from each of the top lines | 1,278,664 | <pre><code>>Sequence 1.1.1 ATGCGCGCGATAAGGCGCTA
ATATTATAGCGCGCGCGCGGATATATATATATATATATATT
>Sequence 1.2.2 ATATGCGCGCGCGCGCGGCG
ACCCCGCGCGCGCGCGGCGCGATATATATATATATATATATT
>Sequence 2.1.1 ATTCGCGCGAGTATAGCGGCG
</code></pre>
<p>NOW,I would like to remove the last digit from each of the line that starts with '>'. For example, in this first line, i would like to remove '.1' (rightmost) and in second instance i would like to remove '.2' and then write the rest of the file to a new file. Thanks,</p>
| 1 | 2009-08-14T15:52:28Z | 1,278,691 | <pre><code>import fileinput
import re
for line in fileinput.input(inplace=True, backup='.bak'):
line = line.rstrip()
if line.startswith('>'):
line = re.sub(r'\.\d$', '', line)
print line
</code></pre>
<p>many details can be changed depending on details of the processing you want, which you have not clearly communicated, but this is the general idea.</p>
| 7 | 2009-08-14T15:58:29Z | [
"python",
"file"
] |
How to eliminate last digit from each of the top lines | 1,278,664 | <pre><code>>Sequence 1.1.1 ATGCGCGCGATAAGGCGCTA
ATATTATAGCGCGCGCGCGGATATATATATATATATATATT
>Sequence 1.2.2 ATATGCGCGCGCGCGCGGCG
ACCCCGCGCGCGCGCGGCGCGATATATATATATATATATATT
>Sequence 2.1.1 ATTCGCGCGAGTATAGCGGCG
</code></pre>
<p>NOW,I would like to remove the last digit from each of the line that starts with '>'. For example, in this first line, i would like to remove '.1' (rightmost) and in second instance i would like to remove '.2' and then write the rest of the file to a new file. Thanks,</p>
| 1 | 2009-08-14T15:52:28Z | 1,278,695 | <pre><code>import re
trimmedtext = re.sub(r'(\d+\.\d+)\.\d', '$1', text)
</code></pre>
<p>Should do it. Somewhat simpler than searching for start characters (and it won't effect your DNA chains)</p>
| 4 | 2009-08-14T15:59:03Z | [
"python",
"file"
] |
How to eliminate last digit from each of the top lines | 1,278,664 | <pre><code>>Sequence 1.1.1 ATGCGCGCGATAAGGCGCTA
ATATTATAGCGCGCGCGCGGATATATATATATATATATATT
>Sequence 1.2.2 ATATGCGCGCGCGCGCGGCG
ACCCCGCGCGCGCGCGGCGCGATATATATATATATATATATT
>Sequence 2.1.1 ATTCGCGCGAGTATAGCGGCG
</code></pre>
<p>NOW,I would like to remove the last digit from each of the line that starts with '>'. For example, in this first line, i would like to remove '.1' (rightmost) and in second instance i would like to remove '.2' and then write the rest of the file to a new file. Thanks,</p>
| 1 | 2009-08-14T15:52:28Z | 1,278,764 | <p>Here's a short script. Run it like: <code>script [filename to clean]</code>. Lots of error handling omitted.</p>
<p>It operates using generators, so it should work fine on huge files as well.</p>
<pre><code>import sys
import os
def clean_line(line):
if line.startswith(">"):
return line.rstrip()[:-2]
else:
return line.rstrip()
def clean(input):
for line in input:
yield clean_line(line)
if __name__ == "__main__":
filename = sys.argv[1]
print "Cleaning %s; output to %s.." % (filename, filename + ".clean")
input = None
output = None
try:
input = open(filename, "r")
output = open(filename + ".clean", "w")
for line in clean(input):
output.write(line + os.linesep)
print ": " + line
except:
input.close()
if output != None:
output.close()
</code></pre>
| 1 | 2009-08-14T16:13:19Z | [
"python",
"file"
] |
How to eliminate last digit from each of the top lines | 1,278,664 | <pre><code>>Sequence 1.1.1 ATGCGCGCGATAAGGCGCTA
ATATTATAGCGCGCGCGCGGATATATATATATATATATATT
>Sequence 1.2.2 ATATGCGCGCGCGCGCGGCG
ACCCCGCGCGCGCGCGGCGCGATATATATATATATATATATT
>Sequence 2.1.1 ATTCGCGCGAGTATAGCGGCG
</code></pre>
<p>NOW,I would like to remove the last digit from each of the line that starts with '>'. For example, in this first line, i would like to remove '.1' (rightmost) and in second instance i would like to remove '.2' and then write the rest of the file to a new file. Thanks,</p>
| 1 | 2009-08-14T15:52:28Z | 1,278,956 | <pre><code>import re
input_file = open('in')
output_file = open('out', 'w')
for line in input_file:
line = re.sub(r'(\d+[.]\d+)[.]\d+', r'\1', line)
output_file.write(line)
</code></pre>
| 0 | 2009-08-14T16:54:01Z | [
"python",
"file"
] |
Python When I catch an exception, how do I get the type, file, and line number? | 1,278,705 | <p>Catching an exception that would print like this:</p>
<pre><code>Traceback (most recent call last):
File "c:/tmp.py", line 1, in <module>
4 / 0
ZeroDivisionError: integer division or modulo by zero
</code></pre>
<p>I want to format it into:</p>
<pre><code>ZeroDivisonError, tmp.py, 1
</code></pre>
| 115 | 2009-08-14T16:02:14Z | 1,278,740 | <pre><code>import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
</code></pre>
| 161 | 2009-08-14T16:09:05Z | [
"python",
"exception",
"exception-handling",
"stack-trace"
] |
Python When I catch an exception, how do I get the type, file, and line number? | 1,278,705 | <p>Catching an exception that would print like this:</p>
<pre><code>Traceback (most recent call last):
File "c:/tmp.py", line 1, in <module>
4 / 0
ZeroDivisionError: integer division or modulo by zero
</code></pre>
<p>I want to format it into:</p>
<pre><code>ZeroDivisonError, tmp.py, 1
</code></pre>
| 115 | 2009-08-14T16:02:14Z | 16,046,900 | <p><a href="http://jserv.sayya.org/misc/use_source_luke.png">Source</a> (Py v2.7.3) for <a href="http://hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l130">traceback.format_exception()</a> and called/related functions helps greatly. Embarrassingly, I always forget to <a href="http://catb.org/jargon/html/U/UTSL.html">Read the Source</a>. I only did so for this after searching for similar details in vain. A simple question, "How to recreate the same output as Python for an exception, with all the same details?" This would get anybody 90+% to whatever they're looking for. Frustrated, I came up with this example. I hope it helps others. (It sure helped me! ;-)</p>
<pre><code>import sys, traceback
traceback_template = '''Traceback (most recent call last):
File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n''' # Skipping the "actual line" item
# Also note: we don't walk all the way through the frame stack in this example
# see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
# (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)
try:
1/0
except:
# http://docs.python.org/2/library/sys.html#sys.exc_info
exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default
'''
Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
or if we do not delete the labels on (not much) older versions of Py, the
reference we created can linger.
traceback.format_exc/print_exc do this very thing, BUT note this creates a
temp scope within the function.
'''
traceback_details = {
'filename': exc_traceback.tb_frame.f_code.co_filename,
'lineno' : exc_traceback.tb_lineno,
'name' : exc_traceback.tb_frame.f_code.co_name,
'type' : exc_type.__name__,
'message' : exc_value.message, # or see traceback._some_str()
}
del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
# This still isn't "completely safe", though!
# "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
# with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
print
print traceback.format_exc()
print
print traceback_template % traceback_details
print
</code></pre>
<p>In specific answer to this query:</p>
<pre><code>sys.exc_info()[0].__name__, os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), sys.exc_info()[2].tb_lineno
</code></pre>
| 22 | 2013-04-16T20:55:32Z | [
"python",
"exception",
"exception-handling",
"stack-trace"
] |
How do I detect missing fields in a CSV file in a Pythonic way? | 1,278,749 | <p>I'm trying to parse a CSV file using Python's <code>csv</code> module (specifically, the <code>DictReader</code> class). Is there a Pythonic way to detect empty or missing fields and throw an error?</p>
<p>Here's a sample file using the following headers: NAME, LABEL, VALUE</p>
<pre><code>foo,bar,baz
yes,no
x,y,z
</code></pre>
<p>When parsing, I'd like the second line to throw an error since it's missing the VALUE field.</p>
<p>Here's a code snippet which shows how I'm approaching this (disregard the hard-coded strings...they're only present for brevity):</p>
<pre><code>import csv
HEADERS = ["name", "label", "value" ]
fileH = open('configFile')
reader = csv.DictReader(fileH, HEADERS)
for row in reader:
if row["name"] is None or row["name"] == "":
# raise Error
if row["label"] is None or row["label"] == "":
# raise Error
...
fileH.close()
</code></pre>
<p>Is there a cleaner way of checking for fields in the CSV file w/out having a bunch of <code>if</code> statements? If I need to add more fields, I'll also need more conditionals, which I would like to avoid if possible.</p>
| 7 | 2009-08-14T16:10:36Z | 1,278,779 | <p>Something like this?</p>
<pre><code>...
for row in reader:
for column, value in row.items():
if value is None or value == "":
# raise Error, using value of column to say which field is missing
</code></pre>
<p>You may be able to use 'if not value:' as your test instead of the more explicit test you gave.</p>
| 1 | 2009-08-14T16:15:11Z | [
"python",
"error-handling",
"csv"
] |
How do I detect missing fields in a CSV file in a Pythonic way? | 1,278,749 | <p>I'm trying to parse a CSV file using Python's <code>csv</code> module (specifically, the <code>DictReader</code> class). Is there a Pythonic way to detect empty or missing fields and throw an error?</p>
<p>Here's a sample file using the following headers: NAME, LABEL, VALUE</p>
<pre><code>foo,bar,baz
yes,no
x,y,z
</code></pre>
<p>When parsing, I'd like the second line to throw an error since it's missing the VALUE field.</p>
<p>Here's a code snippet which shows how I'm approaching this (disregard the hard-coded strings...they're only present for brevity):</p>
<pre><code>import csv
HEADERS = ["name", "label", "value" ]
fileH = open('configFile')
reader = csv.DictReader(fileH, HEADERS)
for row in reader:
if row["name"] is None or row["name"] == "":
# raise Error
if row["label"] is None or row["label"] == "":
# raise Error
...
fileH.close()
</code></pre>
<p>Is there a cleaner way of checking for fields in the CSV file w/out having a bunch of <code>if</code> statements? If I need to add more fields, I'll also need more conditionals, which I would like to avoid if possible.</p>
| 7 | 2009-08-14T16:10:36Z | 1,278,792 | <pre><code>if any(row[key] in (None, "") for key in row):
# raise error
</code></pre>
<p><strong>Edit</strong>: Even better:</p>
<pre><code>if any(val in (None, "") for val in row.itervalues()):
# raise error
</code></pre>
| 13 | 2009-08-14T16:17:55Z | [
"python",
"error-handling",
"csv"
] |
How do I detect missing fields in a CSV file in a Pythonic way? | 1,278,749 | <p>I'm trying to parse a CSV file using Python's <code>csv</code> module (specifically, the <code>DictReader</code> class). Is there a Pythonic way to detect empty or missing fields and throw an error?</p>
<p>Here's a sample file using the following headers: NAME, LABEL, VALUE</p>
<pre><code>foo,bar,baz
yes,no
x,y,z
</code></pre>
<p>When parsing, I'd like the second line to throw an error since it's missing the VALUE field.</p>
<p>Here's a code snippet which shows how I'm approaching this (disregard the hard-coded strings...they're only present for brevity):</p>
<pre><code>import csv
HEADERS = ["name", "label", "value" ]
fileH = open('configFile')
reader = csv.DictReader(fileH, HEADERS)
for row in reader:
if row["name"] is None or row["name"] == "":
# raise Error
if row["label"] is None or row["label"] == "":
# raise Error
...
fileH.close()
</code></pre>
<p>Is there a cleaner way of checking for fields in the CSV file w/out having a bunch of <code>if</code> statements? If I need to add more fields, I'll also need more conditionals, which I would like to avoid if possible.</p>
| 7 | 2009-08-14T16:10:36Z | 1,278,797 | <p>Since <code>None</code> and empty strings both evaluate to <code>False</code>, you should consider this:</p>
<pre><code>for row in reader:
for header in HEADERS:
if not row[header]:
# raise error
</code></pre>
<p>Note that, unlike some other answers, you will still have the option of raising an informative, header-specific error.</p>
| 2 | 2009-08-14T16:18:38Z | [
"python",
"error-handling",
"csv"
] |
How do I detect missing fields in a CSV file in a Pythonic way? | 1,278,749 | <p>I'm trying to parse a CSV file using Python's <code>csv</code> module (specifically, the <code>DictReader</code> class). Is there a Pythonic way to detect empty or missing fields and throw an error?</p>
<p>Here's a sample file using the following headers: NAME, LABEL, VALUE</p>
<pre><code>foo,bar,baz
yes,no
x,y,z
</code></pre>
<p>When parsing, I'd like the second line to throw an error since it's missing the VALUE field.</p>
<p>Here's a code snippet which shows how I'm approaching this (disregard the hard-coded strings...they're only present for brevity):</p>
<pre><code>import csv
HEADERS = ["name", "label", "value" ]
fileH = open('configFile')
reader = csv.DictReader(fileH, HEADERS)
for row in reader:
if row["name"] is None or row["name"] == "":
# raise Error
if row["label"] is None or row["label"] == "":
# raise Error
...
fileH.close()
</code></pre>
<p>Is there a cleaner way of checking for fields in the CSV file w/out having a bunch of <code>if</code> statements? If I need to add more fields, I'll also need more conditionals, which I would like to avoid if possible.</p>
| 7 | 2009-08-14T16:10:36Z | 1,278,896 | <p>This code will provide, for each row, a list of field names which are not present (or are empty) for that row. You could then provide a more detailed exception, such as "Missing fields: foo, baz".</p>
<pre><code>def missing(row):
return [h for h in HEADERS if not row.get(h)]
for row in reader:
m = missing(row)
if missing:
# raise exception with list of missing field names
</code></pre>
| 1 | 2009-08-14T16:39:14Z | [
"python",
"error-handling",
"csv"
] |
How do I detect missing fields in a CSV file in a Pythonic way? | 1,278,749 | <p>I'm trying to parse a CSV file using Python's <code>csv</code> module (specifically, the <code>DictReader</code> class). Is there a Pythonic way to detect empty or missing fields and throw an error?</p>
<p>Here's a sample file using the following headers: NAME, LABEL, VALUE</p>
<pre><code>foo,bar,baz
yes,no
x,y,z
</code></pre>
<p>When parsing, I'd like the second line to throw an error since it's missing the VALUE field.</p>
<p>Here's a code snippet which shows how I'm approaching this (disregard the hard-coded strings...they're only present for brevity):</p>
<pre><code>import csv
HEADERS = ["name", "label", "value" ]
fileH = open('configFile')
reader = csv.DictReader(fileH, HEADERS)
for row in reader:
if row["name"] is None or row["name"] == "":
# raise Error
if row["label"] is None or row["label"] == "":
# raise Error
...
fileH.close()
</code></pre>
<p>Is there a cleaner way of checking for fields in the CSV file w/out having a bunch of <code>if</code> statements? If I need to add more fields, I'll also need more conditionals, which I would like to avoid if possible.</p>
| 7 | 2009-08-14T16:10:36Z | 1,278,903 | <p>If you use matplotlib.mlab.csv2rec, it already saves the content of the file into an array and raise an error if one of the values is missing.</p>
<pre><code>>>> from matplotlib.mlab import csv2rec
>>> content_array = csv2rec('file.txt')
IndexError: list index out of range
</code></pre>
<p>The problem is that there is not a simple way to customize this behaviour, or to supply a default value in case of missing rows. Moreover, the error message is not very explainatory (could be useful to post a bug report here).</p>
<p>p.s. since csv2rec saves the content of the file into a numpy record, it will be easier to get the values equal to None.</p>
| 0 | 2009-08-14T16:39:56Z | [
"python",
"error-handling",
"csv"
] |
How do unit tests work in django-tagging, because I want mine to run like that? | 1,279,032 | <p>Few times while browsing <code>tests</code> dir in various Django apps I stumbled across <code>models.py</code> and <code>settings.py</code> files (in <code>django-tagging</code> for example). </p>
<p>But there's no code to be found that syncs test models or applies custom test settings - but tests make use of them just as if django would auto-magically load them. However if I try to run <code>django-tagging</code>'s tests: <code>manage.py test tagging</code>, it doesn't do even a single test. </p>
<p>This is exactly what I need right now to test my app, but don't really know how.</p>
<p>So, how does it work?</p>
| 0 | 2009-08-14T17:13:45Z | 1,279,096 | <p>You mean, "How do I write unit tests in Django?" Check the <a href="http://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">documentation on testing</a>.</p>
<p>When I've done it, I wrote unit tests in a test/ subdirectory. Make sure the directory has an empty __init__.py file. You may also need a models.py file. Add unit tests that derive from unittest.TestCase (in module unittest). Add the module 'xxxx.test' to your INSTALLED_APPS in settings.py (where 'xxxx' is the base name of your application).</p>
<p>Here's some sample code of mine to get you started:</p>
<pre><code>#!/usr/bin/env python
# http://docs.djangoproject.com/en/dev/topics/testing/
from sys import stderr
import unittest
from django.test.client import Client
from expenses.etl.loader import load_all, load_init
class TestCase(unittest.TestCase):
def setUp(self):
print "setUp"
def testLoading(self):
print "Calling load_init()"
load_init()
print "Calling load_all()"
load_all()
print "Done"
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>If you mean, "How do I get data loaded into my unit tests?", then use fixtures, described on the same documentation page.</p>
| 0 | 2009-08-14T17:26:25Z | [
"python",
"django",
"unit-testing"
] |
How do unit tests work in django-tagging, because I want mine to run like that? | 1,279,032 | <p>Few times while browsing <code>tests</code> dir in various Django apps I stumbled across <code>models.py</code> and <code>settings.py</code> files (in <code>django-tagging</code> for example). </p>
<p>But there's no code to be found that syncs test models or applies custom test settings - but tests make use of them just as if django would auto-magically load them. However if I try to run <code>django-tagging</code>'s tests: <code>manage.py test tagging</code>, it doesn't do even a single test. </p>
<p>This is exactly what I need right now to test my app, but don't really know how.</p>
<p>So, how does it work?</p>
| 0 | 2009-08-14T17:13:45Z | 1,283,400 | <p>If you want to run the tests in <code>django-tagging</code>, you can try:</p>
<blockquote>
<p>django-admin.py test --settings=tagging.tests.settings</p>
</blockquote>
<p>Basically, it uses doctests which are in the <code>tests.py</code> file inside the <code>tests</code> package/directory. The tests use the settings file in that same directory (and specified in the command line to django-admin). For more information see the django documentation on <a href="http://docs.djangoproject.com/en/dev/topics/testing/#writing-doctests" rel="nofollow">writing doctests</a>.</p>
| 1 | 2009-08-16T03:29:26Z | [
"python",
"django",
"unit-testing"
] |
Python and regex | 1,279,087 | <p>i have to parse need string.
Here is command I execute in Linux console:</p>
<pre><code>amixer get Master |grep Mono:
</code></pre>
<p>And get, for example, </p>
<pre><code>Mono: Playback 61 [95%] [-3.00dB] [on]
</code></pre>
<p>Then i test it from python-console:</p>
<pre><code>import re,os
print re.search( ur"(?<=\[)[0-9]{1,3}", u" Mono: Playback 61 [95%] [-3.00dB] [on]" ).group()[0]
</code></pre>
<p>And get result: 95. It's that, what i need. But if I'll change my script to this:</p>
<pre><code>print re.search( ur"(?<=\[)[0-9]{1,3}", str(os.system("amixer get Master |grep Mono:")) ).group()[0]
</code></pre>
<p>It'll returns None-object. Why?</p>
| 0 | 2009-08-14T17:25:01Z | 1,279,095 | <p><code>os.system()</code> returns the exit code from the application, not the text output of the application.</p>
<p>You should read up on the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code></a> Python module; it will do what you need.</p>
| 7 | 2009-08-14T17:26:25Z | [
"python",
"regex"
] |
Python and regex | 1,279,087 | <p>i have to parse need string.
Here is command I execute in Linux console:</p>
<pre><code>amixer get Master |grep Mono:
</code></pre>
<p>And get, for example, </p>
<pre><code>Mono: Playback 61 [95%] [-3.00dB] [on]
</code></pre>
<p>Then i test it from python-console:</p>
<pre><code>import re,os
print re.search( ur"(?<=\[)[0-9]{1,3}", u" Mono: Playback 61 [95%] [-3.00dB] [on]" ).group()[0]
</code></pre>
<p>And get result: 95. It's that, what i need. But if I'll change my script to this:</p>
<pre><code>print re.search( ur"(?<=\[)[0-9]{1,3}", str(os.system("amixer get Master |grep Mono:")) ).group()[0]
</code></pre>
<p>It'll returns None-object. Why?</p>
| 0 | 2009-08-14T17:25:01Z | 1,279,107 | <p>How to run a process and get the output:</p>
<p><a href="http://docs.python.org/library/popen2.html" rel="nofollow">http://docs.python.org/library/popen2.html</a></p>
| 0 | 2009-08-14T17:28:02Z | [
"python",
"regex"
] |
Python and regex | 1,279,087 | <p>i have to parse need string.
Here is command I execute in Linux console:</p>
<pre><code>amixer get Master |grep Mono:
</code></pre>
<p>And get, for example, </p>
<pre><code>Mono: Playback 61 [95%] [-3.00dB] [on]
</code></pre>
<p>Then i test it from python-console:</p>
<pre><code>import re,os
print re.search( ur"(?<=\[)[0-9]{1,3}", u" Mono: Playback 61 [95%] [-3.00dB] [on]" ).group()[0]
</code></pre>
<p>And get result: 95. It's that, what i need. But if I'll change my script to this:</p>
<pre><code>print re.search( ur"(?<=\[)[0-9]{1,3}", str(os.system("amixer get Master |grep Mono:")) ).group()[0]
</code></pre>
<p>It'll returns None-object. Why?</p>
| 0 | 2009-08-14T17:25:01Z | 1,279,115 | <p>Instead of using <code>os.system()</code>, use the <code>subprocess</code> module:</p>
<pre><code>from subprocess import Popen, PIPE
p = Popen("amixer get Master | grep Mono:", shell = True, stdout = PIPE)
stdout = p.stdout.read()
print re.search( ur"(?<=\[)[0-9]{1,3}", stdout).group()
</code></pre>
| 1 | 2009-08-14T17:30:24Z | [
"python",
"regex"
] |
What's the regex for removing dots in acronyms but not in domain names? | 1,279,110 | <p>I want to remove dots in acronyms but not in domain names in a python string. For example,
I want the string</p>
<pre><code>'a.b.c. test@test.com http://www.test.com'
</code></pre>
<p>to become</p>
<pre><code>'abc test@test.com http://www.test.com'
</code></pre>
<p>The closest regex I made so far is</p>
<pre><code>re.sub('(?:\s|\A).{1}\.',lambda s: s.group()[0:2], s)
</code></pre>
<p>which results to</p>
<pre><code>'ab.c. test@test.com http://www.test.com'
</code></pre>
<p>It seems that for the above regex to work, I need to change the regex to</p>
<pre><code>(?:\s|\A|\G).{1}\.
</code></pre>
<p>but there is no end of match marker (\G) in python.</p>
<p>EDIT: As I have mentioned in my comment, the strings have no specific formatting. These strings contain informal human conversations and so may contain zero, one or several acronyms or domain names. A few errors is fine by me if it would save me from coding a "real" parser.</p>
| 1 | 2009-08-14T17:28:58Z | 1,279,152 | <p>I suggest you split the string at '@' (or whatever character makes sense), do the substitution on the first part, then put the string back together. I think that will show the intent of the code better than a complex regexp. Something like this, perhaps:</p>
<pre><code>string='a.b.c. test@test.com http://www.test.com'
left, rest = string.split("@",1)
left = left.replace(".","")
result="%s@%s" % (left, rest)
</code></pre>
| 2 | 2009-08-14T17:37:46Z | [
"python",
"regex"
] |
What's the regex for removing dots in acronyms but not in domain names? | 1,279,110 | <p>I want to remove dots in acronyms but not in domain names in a python string. For example,
I want the string</p>
<pre><code>'a.b.c. test@test.com http://www.test.com'
</code></pre>
<p>to become</p>
<pre><code>'abc test@test.com http://www.test.com'
</code></pre>
<p>The closest regex I made so far is</p>
<pre><code>re.sub('(?:\s|\A).{1}\.',lambda s: s.group()[0:2], s)
</code></pre>
<p>which results to</p>
<pre><code>'ab.c. test@test.com http://www.test.com'
</code></pre>
<p>It seems that for the above regex to work, I need to change the regex to</p>
<pre><code>(?:\s|\A|\G).{1}\.
</code></pre>
<p>but there is no end of match marker (\G) in python.</p>
<p>EDIT: As I have mentioned in my comment, the strings have no specific formatting. These strings contain informal human conversations and so may contain zero, one or several acronyms or domain names. A few errors is fine by me if it would save me from coding a "real" parser.</p>
| 1 | 2009-08-14T17:28:58Z | 1,279,162 | <p>You could simply remove DOTS that don't have two [a-z] letters (or more) ahead of them:</p>
<pre><code>\.(?![a-zA-Z]{2})
</code></pre>
<p>But that will of course also remove the first DOT from the following address:</p>
<p>name.i@foo.bar</p>
<p>You could fix that by doing:</p>
<pre><code>\.(?![a-zA-Z]{2}|[^\s@]*+@)
</code></pre>
<p>but I'm sure there will be many more such corner cases.</p>
| 2 | 2009-08-14T17:39:49Z | [
"python",
"regex"
] |
What's the regex for removing dots in acronyms but not in domain names? | 1,279,110 | <p>I want to remove dots in acronyms but not in domain names in a python string. For example,
I want the string</p>
<pre><code>'a.b.c. test@test.com http://www.test.com'
</code></pre>
<p>to become</p>
<pre><code>'abc test@test.com http://www.test.com'
</code></pre>
<p>The closest regex I made so far is</p>
<pre><code>re.sub('(?:\s|\A).{1}\.',lambda s: s.group()[0:2], s)
</code></pre>
<p>which results to</p>
<pre><code>'ab.c. test@test.com http://www.test.com'
</code></pre>
<p>It seems that for the above regex to work, I need to change the regex to</p>
<pre><code>(?:\s|\A|\G).{1}\.
</code></pre>
<p>but there is no end of match marker (\G) in python.</p>
<p>EDIT: As I have mentioned in my comment, the strings have no specific formatting. These strings contain informal human conversations and so may contain zero, one or several acronyms or domain names. A few errors is fine by me if it would save me from coding a "real" parser.</p>
| 1 | 2009-08-14T17:28:58Z | 1,279,163 | <p>If your data is always formatted like this then why not split your data into 3 parts by splitting on the space.</p>
<p>Then it's pretty trivial to remove the periods from the first element and use join to remerge the parts.</p>
| 5 | 2009-08-14T17:40:06Z | [
"python",
"regex"
] |
What's the regex for removing dots in acronyms but not in domain names? | 1,279,110 | <p>I want to remove dots in acronyms but not in domain names in a python string. For example,
I want the string</p>
<pre><code>'a.b.c. test@test.com http://www.test.com'
</code></pre>
<p>to become</p>
<pre><code>'abc test@test.com http://www.test.com'
</code></pre>
<p>The closest regex I made so far is</p>
<pre><code>re.sub('(?:\s|\A).{1}\.',lambda s: s.group()[0:2], s)
</code></pre>
<p>which results to</p>
<pre><code>'ab.c. test@test.com http://www.test.com'
</code></pre>
<p>It seems that for the above regex to work, I need to change the regex to</p>
<pre><code>(?:\s|\A|\G).{1}\.
</code></pre>
<p>but there is no end of match marker (\G) in python.</p>
<p>EDIT: As I have mentioned in my comment, the strings have no specific formatting. These strings contain informal human conversations and so may contain zero, one or several acronyms or domain names. A few errors is fine by me if it would save me from coding a "real" parser.</p>
| 1 | 2009-08-14T17:28:58Z | 1,279,417 | <p>Not as elegant as a simple <code>re.sub()</code>, but try this:</p>
<pre><code>import re
s='a.b.c. test@test.com http://www.test.com'
m=re.search('(.*?)(([a-zA-Z]\.){2,})(.*)', s)
if m:
replacement=''.join(m.group(2).split('.'))
s=m.group(1)+replacement+m.group(4)
print s
</code></pre>
<p>It assumes that there's no more than one acronym per string, but you could always run it repeatedly.</p>
| 0 | 2009-08-14T18:30:24Z | [
"python",
"regex"
] |
What's the regex for removing dots in acronyms but not in domain names? | 1,279,110 | <p>I want to remove dots in acronyms but not in domain names in a python string. For example,
I want the string</p>
<pre><code>'a.b.c. test@test.com http://www.test.com'
</code></pre>
<p>to become</p>
<pre><code>'abc test@test.com http://www.test.com'
</code></pre>
<p>The closest regex I made so far is</p>
<pre><code>re.sub('(?:\s|\A).{1}\.',lambda s: s.group()[0:2], s)
</code></pre>
<p>which results to</p>
<pre><code>'ab.c. test@test.com http://www.test.com'
</code></pre>
<p>It seems that for the above regex to work, I need to change the regex to</p>
<pre><code>(?:\s|\A|\G).{1}\.
</code></pre>
<p>but there is no end of match marker (\G) in python.</p>
<p>EDIT: As I have mentioned in my comment, the strings have no specific formatting. These strings contain informal human conversations and so may contain zero, one or several acronyms or domain names. A few errors is fine by me if it would save me from coding a "real" parser.</p>
| 1 | 2009-08-14T17:28:58Z | 1,280,397 | <p>The following worked for me (with thanks to Bart for his answer):</p>
<pre><code>re.sub('\.(?!(\S[^. ])|\d)', '', s)
</code></pre>
<p>This will not remove a dot if it is the first character in a word or acronym. </p>
| 1 | 2009-08-14T21:49:47Z | [
"python",
"regex"
] |
What's the regex for removing dots in acronyms but not in domain names? | 1,279,110 | <p>I want to remove dots in acronyms but not in domain names in a python string. For example,
I want the string</p>
<pre><code>'a.b.c. test@test.com http://www.test.com'
</code></pre>
<p>to become</p>
<pre><code>'abc test@test.com http://www.test.com'
</code></pre>
<p>The closest regex I made so far is</p>
<pre><code>re.sub('(?:\s|\A).{1}\.',lambda s: s.group()[0:2], s)
</code></pre>
<p>which results to</p>
<pre><code>'ab.c. test@test.com http://www.test.com'
</code></pre>
<p>It seems that for the above regex to work, I need to change the regex to</p>
<pre><code>(?:\s|\A|\G).{1}\.
</code></pre>
<p>but there is no end of match marker (\G) in python.</p>
<p>EDIT: As I have mentioned in my comment, the strings have no specific formatting. These strings contain informal human conversations and so may contain zero, one or several acronyms or domain names. A few errors is fine by me if it would save me from coding a "real" parser.</p>
| 1 | 2009-08-14T17:28:58Z | 1,280,754 | <p>A non-regex way:</p>
<pre><code>>>> S = 'a.b.c. test@test.com http://www.test.com'
>>> ' '.join(w if '@' in w or ':' in w else w.replace('.', '') for w in S.split())
'abc test@test.com http://www.test.com'
</code></pre>
<p>(Requires spaces to split on, though - so if you had something like commas with no spaces it could miss some.)</p>
| 1 | 2009-08-15T00:00:57Z | [
"python",
"regex"
] |
Controlling Django ModelForm output | 1,279,221 | <p>I've got a Model in Django, example code below (not my actual code):</p>
<pre><code>class Department(models.Model):
name = models.CharField(max_length=100)
abbreviation = models.CharField(max_length=4)
</code></pre>
<p>Let's say I do the following in the Django shell:</p>
<pre><code>>>> Department(name='Computer Science',abbreviation='C S ').save()
>>> Department(name='Mathematics',abbreviation='MATH').save()
>>> Department(name='Anthropology',abbreviation='ANTH').save()
</code></pre>
<p>I now have those four departments stored in my database. Say we have another class, <code>Course</code>, which belongs to a <code>Department</code>:</p>
<pre><code>class Course(models.Model):
department = models.ForeignKey('Department')
number = models.IntegerField()
class CourseForm(ModelForm):
class Meta:
model = Course
</code></pre>
<p>If I render the <code>ModelForm</code> object directly in a template by just referncing a variable, say <code>form</code>, which got passed down, the Departments appear in a drop-down box (an HTML select box). So far so good.</p>
<p>The problem is: the items in the select box are sorted by ID. So they appear as:</p>
<ol><li>Computer Science</li><li>Mathematics</li><li>Anthropology</li></ol>
<p>But, I want them sorted alphabetically, i.e.</p>
<ol><li>Anthropology</li><li>Computer Science</li><li>Mathematics</li></ol>
<p>How can I change the way these items are sorted in the <code>ModelForm</code> code, or in the <code>Model</code> code, rather than in the template?</p>
<p>And in general, how can I customize the way a particular field or widget works when generated by a <code>ModelForm</code>?</p>
| 6 | 2009-08-14T17:49:06Z | 1,279,291 | <blockquote>
<p>How can I change the way these items are sorted in the ModelForm code, or in the Model code, rather than in the template?</p>
</blockquote>
<p>One thing you can do is add an <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#ordering"><code>ordering</code></a> <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#ref-models-options">meta option</a>. You do this by adding a <code>Meta</code> inner class to a class, with the <code>ordering</code> attribute specified:</p>
<pre><code>class Department(models.Model):
name = models.CharField(max_length=100)
abbreviation = models.CharField(max_length=4)
class Meta:
ordering = ["name"]
</code></pre>
<p>Note that this changes default ordering for <code>Department</code> models (not just when used in a form).</p>
<blockquote>
<p>And in general, how can I customize the way a particular field or widget works when generated by a ModelForm?</p>
</blockquote>
<p>You'll want to read the Django docs about <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#topics-forms-modelforms"><code>ModelForm</code></a> and <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#ref-forms-fields">built-in form fields</a>. In particular, pay attention to the optional <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#widget"><code>widget</code></a> attribute, which allows you to change a form field's widget. The difference types of widgets are described <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#ref-forms-widgets">here</a>.</p>
| 9 | 2009-08-14T18:04:31Z | [
"python",
"django",
"django-templates",
"django-forms"
] |
Controlling Django ModelForm output | 1,279,221 | <p>I've got a Model in Django, example code below (not my actual code):</p>
<pre><code>class Department(models.Model):
name = models.CharField(max_length=100)
abbreviation = models.CharField(max_length=4)
</code></pre>
<p>Let's say I do the following in the Django shell:</p>
<pre><code>>>> Department(name='Computer Science',abbreviation='C S ').save()
>>> Department(name='Mathematics',abbreviation='MATH').save()
>>> Department(name='Anthropology',abbreviation='ANTH').save()
</code></pre>
<p>I now have those four departments stored in my database. Say we have another class, <code>Course</code>, which belongs to a <code>Department</code>:</p>
<pre><code>class Course(models.Model):
department = models.ForeignKey('Department')
number = models.IntegerField()
class CourseForm(ModelForm):
class Meta:
model = Course
</code></pre>
<p>If I render the <code>ModelForm</code> object directly in a template by just referncing a variable, say <code>form</code>, which got passed down, the Departments appear in a drop-down box (an HTML select box). So far so good.</p>
<p>The problem is: the items in the select box are sorted by ID. So they appear as:</p>
<ol><li>Computer Science</li><li>Mathematics</li><li>Anthropology</li></ol>
<p>But, I want them sorted alphabetically, i.e.</p>
<ol><li>Anthropology</li><li>Computer Science</li><li>Mathematics</li></ol>
<p>How can I change the way these items are sorted in the <code>ModelForm</code> code, or in the <code>Model</code> code, rather than in the template?</p>
<p>And in general, how can I customize the way a particular field or widget works when generated by a <code>ModelForm</code>?</p>
| 6 | 2009-08-14T17:49:06Z | 1,280,441 | <p>mipadi has shown you how to modify the ordering for your Department model, and this is reflected in the form widget.</p>
<p>However, if you only wanted to change the ordering for that widget, and leave the model's default ordering as something else, you could do this:</p>
<pre><code>class CourseForm(ModelForm):
department = forms.ModelChoiceField(
queryset=Department.objects.order_by('name'))
class Meta:
model = Course
</code></pre>
| 1 | 2009-08-14T22:04:06Z | [
"python",
"django",
"django-templates",
"django-forms"
] |
BytesIO with python v2.5 | 1,279,244 | <p><strong>Question:</strong></p>
<p>How do I get a byte stream that works like StringIO for Python 2.5?</p>
<p><strong>Application:</strong></p>
<p>I'm converting a PDF to text, but don't want to save a file to the hard disk.</p>
<p><strong>Other Thoughts:</strong></p>
<p>I figured I could use StringIO, but there's no mode parameter (I guess "String" implies text mode). </p>
<p>Apparently the io.BytesIO class is new in v2.6, so that doesn't work for me either.</p>
<p>I've got a solution with the tempfile module, but I'd like to avoid any reads/writes to/from the hard disk.</p>
| 1 | 2009-08-14T17:54:01Z | 1,279,251 | <p>In Python 2.x, "string" means "bytes", and "unicode" means "string". You should use the <code>StringIO</code> or <code>cStringIO</code> modules. The mode will depend on which kind of data you pass in as the buffer parameter.</p>
| 4 | 2009-08-14T17:55:49Z | [
"python",
"stringio",
"bytesio"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.