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
list |
|---|---|---|---|---|---|---|---|---|---|
Is there a HAML implementation for use with Python and Django
| 519,671
|
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p>
<p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
| 68
|
2009-02-06T09:30:01Z
| 3,497,256
|
<p>I just made this <a href="http://github.com/fitoria/django-haml" rel="nofollow">http://github.com/fitoria/django-haml</a> it's still in very early stage but it works.</p>
| 2
|
2010-08-16T20:55:55Z
|
[
"python",
"django",
"django-templates",
"haml"
] |
Is there a HAML implementation for use with Python and Django
| 519,671
|
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p>
<p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
| 68
|
2009-02-06T09:30:01Z
| 5,171,915
|
<p>Daniel Skinner's project (mentioned above) seems to have been renamed to DMSL. It seems very powerful, emulates HAML but allows you to use python functions, lambdas, comprehensions etc in it's syntax: <a href="https://github.com/dasacc22/dmsl" rel="nofollow">https://github.com/dasacc22/dmsl</a></p>
| 2
|
2011-03-02T18:46:17Z
|
[
"python",
"django",
"django-templates",
"haml"
] |
Is there a HAML implementation for use with Python and Django
| 519,671
|
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p>
<p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
| 68
|
2009-02-06T09:30:01Z
| 10,713,234
|
<p>My project, <a href="https://github.com/mikeboers/PyHAML" rel="nofollow">PyHAML</a>, is a Mako preprocessor that gives you very HAML-like syntax. Some of the Ruby doesn't translate very well to Python, so there are some differences, but the spirit is the same.</p>
| 3
|
2012-05-23T03:57:01Z
|
[
"python",
"django",
"django-templates",
"haml"
] |
Is there a HAML implementation for use with Python and Django
| 519,671
|
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p>
<p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
| 68
|
2009-02-06T09:30:01Z
| 16,259,000
|
<p>I ran across jade doing some node.js work and when returning to Django was looking for something similar. I found <a href="https://github.com/SyrusAkbary/pyjade" rel="nofollow" title="PyJade">Pyjade</a> and while it's nearly exactly what I'm looking for it handles errors and debugging rather poorly within Django.</p>
| 3
|
2013-04-28T02:41:06Z
|
[
"python",
"django",
"django-templates",
"haml"
] |
Is there a HAML implementation for use with Python and Django
| 519,671
|
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p>
<p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
| 68
|
2009-02-06T09:30:01Z
| 17,970,159
|
<p>You may be interested in <a href="https://github.com/2nd/Plim">Plim</a>. It's a mature python port of <a href="http://slim-lang.com/">Slim</a>.</p>
| 5
|
2013-07-31T12:16:42Z
|
[
"python",
"django",
"django-templates",
"haml"
] |
Good Sound processing/Analysis/Capturing Modules
| 519,851
|
<p>We are working on Sound processing and Analysis where we need to extract frequencies, pitches, octaves and other parameters of sound including dBPowerSpectrum Analysis. </p>
<p>We also need to do this irrespective of the file formats or do the conversion between quite a file format(though conversion is not a very critical requirement if those parameters can be analyzed on most file formats).<br>
We also need to capture/record sound from Mic. We found a Python module called Snack which does almost everything we need, but the whole problem is that it requires tkinter to be installed.<br>
Since we are planning to write a Web client for this program, I feel installing tkinter and initializing and passing its object to Sound Processing module is an overhead.<br>
Can you please suggest us few good Sound Processing Module. We don't expect an all in one module. Its OK even if these functionalities are spread over several modules. </p>
<p>Kindly suggest.</p>
<p>Thanks in Advance</p>
| 1
|
2009-02-06T10:48:24Z
| 519,908
|
<p>See <a href="http://www.csounds.com/node/188" rel="nofollow">http://www.csounds.com/node/188</a> for a package that does much of this.</p>
| 2
|
2009-02-06T11:09:36Z
|
[
"python",
"audio",
"music"
] |
Good Sound processing/Analysis/Capturing Modules
| 519,851
|
<p>We are working on Sound processing and Analysis where we need to extract frequencies, pitches, octaves and other parameters of sound including dBPowerSpectrum Analysis. </p>
<p>We also need to do this irrespective of the file formats or do the conversion between quite a file format(though conversion is not a very critical requirement if those parameters can be analyzed on most file formats).<br>
We also need to capture/record sound from Mic. We found a Python module called Snack which does almost everything we need, but the whole problem is that it requires tkinter to be installed.<br>
Since we are planning to write a Web client for this program, I feel installing tkinter and initializing and passing its object to Sound Processing module is an overhead.<br>
Can you please suggest us few good Sound Processing Module. We don't expect an all in one module. Its OK even if these functionalities are spread over several modules. </p>
<p>Kindly suggest.</p>
<p>Thanks in Advance</p>
| 1
|
2009-02-06T10:48:24Z
| 1,390,270
|
<p>You can use <a href="http://cournape.github.com/audiolab/" rel="nofollow">scikits audiolab</a> to read in any file supported by <a href="http://www.mega-nerd.com/libsndfile/" rel="nofollow">libsndfile</a>, and then use <a href="http://www.scipy.org/PyLab" rel="nofollow">PyLab</a> (<a href="http://www.scipy.org/" rel="nofollow">NumPy and SciPy</a>) to do the processing.</p>
<p>I don't know of a way to read in live audio from the mic, though, which is why I was just looking at Snack myself. If there's a way to convert Snack sounds into numpy arrays, then that would work.</p>
<p>If you use <code>padsp ipython</code> in Ubuntu, you can read in data from /dev/dsp, and it will actually be coming from PulseAudio's input. You can use the <a href="http://docs.python.org/library/ossaudiodev.html" rel="nofollow">ossaudiodev</a> module, though I haven't gotten this to work, or you can do some kind of ugly construction like:</p>
<pre><code>audio = numpy.fromfile('/dev/dsp'...
</code></pre>
<p>but I guess you still need to use ossaudiodev to set up the sampling rate, format, etc. first.</p>
| 1
|
2009-09-07T17:20:31Z
|
[
"python",
"audio",
"music"
] |
Good Sound processing/Analysis/Capturing Modules
| 519,851
|
<p>We are working on Sound processing and Analysis where we need to extract frequencies, pitches, octaves and other parameters of sound including dBPowerSpectrum Analysis. </p>
<p>We also need to do this irrespective of the file formats or do the conversion between quite a file format(though conversion is not a very critical requirement if those parameters can be analyzed on most file formats).<br>
We also need to capture/record sound from Mic. We found a Python module called Snack which does almost everything we need, but the whole problem is that it requires tkinter to be installed.<br>
Since we are planning to write a Web client for this program, I feel installing tkinter and initializing and passing its object to Sound Processing module is an overhead.<br>
Can you please suggest us few good Sound Processing Module. We don't expect an all in one module. Its OK even if these functionalities are spread over several modules. </p>
<p>Kindly suggest.</p>
<p>Thanks in Advance</p>
| 1
|
2009-02-06T10:48:24Z
| 2,463,496
|
<p>For audio capture and playback I've liked <a href="http://people.csail.mit.edu/hubert/pyaudio/" rel="nofollow">PyAudio</a>. It's cross-platform and pretty easy to use.</p>
| 2
|
2010-03-17T15:22:02Z
|
[
"python",
"audio",
"music"
] |
Cross-platform gui toolkit for deploying Python applications
| 520,015
|
<p>Building on:
<a href="http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/">http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/</a></p>
<h1>Merits:</h1>
<p>1 - ease of design / integration - learning curve</p>
<p>2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web</p>
<p>3 - pythonic API</p>
<p>4 - quality of documentation - I want to do something a bit more complicated, now what?</p>
<p>5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file)</p>
<p>6 - licensing</p>
<p>7 - others? (specify)
<hr /></p>
<h1>Contenders:</h1>
<p>1 - tkinter, as currently supported (as of 2.6, 3.0)</p>
<p>2 - pyttk library</p>
<p>3 - pyGTK</p>
<p>4 - pyQt</p>
<p>5 - wxPython</p>
<p>6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste</p>
<p>7 - others? (specify)</p>
| 45
|
2009-02-06T11:43:30Z
| 520,055
|
<p>Please don't hesitate to expand this answer.</p>
<h1><a href="http://wiki.python.org/moin/TkInter">Tkinter</a></h1>
<p>Tkinter is the toolkit that comes with python. That means you already have everything you need to write a GUI. What that also means is that if you choose to distribute your program, most likely everyone else already has what they need to run your program.</p>
<p>Tkinter is mature and stable, and is (at least arguably) quite easy to use.I found it easier to use than wxPython, but obviously that's somewhat subjective. </p>
<p>Tkinter gets a bad rap for looking ugly and out of date. While it's true that it's easy to create ugly GUIs with Tkinter, it's also pretty easy to create nice looking GUIs. Tkinter doesn't hold your hand, but it doesn't much get in the way, either. Tkinter looks best on the Mac and Windows since it uses native widgets there, but it looks OK on linux, too. </p>
<p>The other point about the look of Tkinter is that, for the most part, look isn't as important as people make it out to be. Most applications written with toolkits such as Tkinter, wxPython, PyQT, etc are special-purpose applications. For the types of applications these toolkits are used for, usability trumps looks. If the look of the application is important, it's easy enough to polish up a Tkinter application.</p>
<p>Tkinter has some features that other toolkits don't come close to matching. Variable traces, named fonts, geometry (layout) managers, and the way Tkinter processes events are still the standard to which other toolkits should be judged. </p>
<p>On the downside, Tkinter is a wrapper around a Tcl interpreter that runs inside python. This is mostly invisible to anyone developing with Tkinter, but it sometimes results in error messages that expose this architecture. You'll get an error complaining about a widget with a name like ".1245485.67345" which will make almost no sense to anyone unless you're also familiar with how Tcl/tk works.</p>
<p>Another downside is that Tkinter doesn't have as many pre-built widgets as wxPython. The hierarchical tree widget in Tkinter is a little weak, for example, and there's no built-in table widget. On the other hand, Tkinter's canvas and text widgets are extremely powerful and easy to use. For most types of applications you will write, however, you'll have everything you need. Just don't expect to replicate Microsoft Word or Photoshop with Tkinter. </p>
<p>I don't know what the license is for Tkinter, I assume the same as for python as a whole. Tcl/tk has a BSD-style license. </p>
<h1><a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro">PyQt</a></h1>
<p>It's build on top of <a href="http://qt.nokia.com/">Qt</a>, a C++ framework. It's quite advanced and has some good tools like the Qt Designer to design your applications. You should be aware though, that it doesn't feel like Python 100%, but close to it. The <a href="http://doc.qt.nokia.com/4.5/index.html">documentation</a> is excellent</p>
<p>This framework is really good. It's being actively developed by Trolltech, who is owned by Nokia. The bindings for Python are developed by Riverbank.</p>
<p>PyQt is available under the GPL license or a commercial one. The price of a riverbank PyQt license is about 400 euro per developer.</p>
<p>Qt is not only a GUI-framework but has a lot of other classes too, one can create an application by just using Qt classes. (Like SQL, networking, scripting, â¦)</p>
<p>Qt used to emulate GUI elements on every platform but now uses native styles of the platforms (although not native GUI toolkits): see <a href="http://doc.qt.nokia.com/4.4/qtmac-as-native.html">the documentation for Mac OS X</a> and <a href="http://doc.qt.nokia.com/4.5/qwindowsxpstyle.html#details">the windows XP style</a></p>
<p>Packaging is as simple as running py2exe or pyInstaller. The content of my PyQt app looks like this on windows (I have used InnoSetup on top of it for proper installation):</p>
<pre>
pyticroque.exe PyQt4.QtGui.pyd unicodedata.pyd
MSVCP71.dll PyQt4._qt.pyd unins000.dat
MSVCR71.dll python25.dll unins000.exe
PyQt4.QtCore.pyd sip.pyd _socket.pyd
</pre>
<p>QT comes with a widget designer and even in recent versions with an <a href="http://qt.nokia.com/products/developer-tools">IDE</a> to help design Qt software.</p>
<h1><a href="http://pyside.org">PySide</a></h1>
<p>PySide is a LGPL binding to Qt. It's developed by nokia as a replacement for the GPL PyQt.</p>
<blockquote>
<p>Although based on a different
technology than the existing
GPL-licensed PyQt bindings, PySide
will initially aim to be
API-compatible with them. In addition
to the PyQt-compatible API, a more
Pythonic API will be provided in the
future.</p>
</blockquote>
<h1><a href="http://www.wxpython.org/">wxPython</a></h1>
<p>wxPython is a binding for Python using the <a href="http://www.wxwidgets.org/">wxWidgets</a>-Framework. This framework is under the LGPL licence and is developed by the open source community.</p>
<p>What I'm really missing is a good tool to design the interface, they have about 3 but none of them is usable.</p>
<p>One thing I should mention is that I found a bug in the tab-view despite the fact that I didn't use anything advanced. (Only on Mac OS X) I think <a href="http://www.wxwidgets.org/">wxWidgets</a> isn't as polished as <a href="http://qt.nokia.com/">Qt</a>.</p>
<p>wxPython is really only about the GUI-classes, there isn't much else.</p>
<p>wxWidgets uses native GUI elements.</p>
<p>An advantage wxPython has over Tkinter is that wxPython has a much larger library of widgets from which to choose from. </p>
<h1>Others</h1>
<p>I haven't got any experience with other GUI frameworks, maybe someone else has.</p>
| 42
|
2009-02-06T12:06:10Z
|
[
"python",
"user-interface",
"cross-platform"
] |
Cross-platform gui toolkit for deploying Python applications
| 520,015
|
<p>Building on:
<a href="http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/">http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/</a></p>
<h1>Merits:</h1>
<p>1 - ease of design / integration - learning curve</p>
<p>2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web</p>
<p>3 - pythonic API</p>
<p>4 - quality of documentation - I want to do something a bit more complicated, now what?</p>
<p>5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file)</p>
<p>6 - licensing</p>
<p>7 - others? (specify)
<hr /></p>
<h1>Contenders:</h1>
<p>1 - tkinter, as currently supported (as of 2.6, 3.0)</p>
<p>2 - pyttk library</p>
<p>3 - pyGTK</p>
<p>4 - pyQt</p>
<p>5 - wxPython</p>
<p>6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste</p>
<p>7 - others? (specify)</p>
| 45
|
2009-02-06T11:43:30Z
| 520,961
|
<p>Pro wxPython</p>
<ul>
<li>Lots of tutorials</li>
<li>wxGlade as an Editor: not perfect yet, but usable.</li>
</ul>
| 0
|
2009-02-06T16:21:04Z
|
[
"python",
"user-interface",
"cross-platform"
] |
Cross-platform gui toolkit for deploying Python applications
| 520,015
|
<p>Building on:
<a href="http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/">http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/</a></p>
<h1>Merits:</h1>
<p>1 - ease of design / integration - learning curve</p>
<p>2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web</p>
<p>3 - pythonic API</p>
<p>4 - quality of documentation - I want to do something a bit more complicated, now what?</p>
<p>5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file)</p>
<p>6 - licensing</p>
<p>7 - others? (specify)
<hr /></p>
<h1>Contenders:</h1>
<p>1 - tkinter, as currently supported (as of 2.6, 3.0)</p>
<p>2 - pyttk library</p>
<p>3 - pyGTK</p>
<p>4 - pyQt</p>
<p>5 - wxPython</p>
<p>6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste</p>
<p>7 - others? (specify)</p>
| 45
|
2009-02-06T11:43:30Z
| 694,187
|
<p>I would definitely appreciate it if anyone knows of something better than what's commonly discussed; I see to have headaches finding something appropriate...</p>
<p>Qt is great, but PyQt doesn't seem to have the same development resources. It seems to have some clever way to generate bindings, but isn't complete (e.g. PyKDE terminal kpart) and there is a dearth of documentation (as the developers admit). Compatibility with Qt's UI designer is nice.</p>
<p>wxpython - controls aren't as nice looking, widget library isn't as large as KDE.</p>
<p>OpenGL - doesn't even support fonts by default... pygame is okay, but opengl being a state machine is too annoying (object oriented models prevent making the a call in the wrong state).</p>
<p>XUL - neat idea, I wish it worked. The <a href="http://pyxpcomext.mozdev.org/no%5Fwrap/tutorials/pyxulrunner/python%5Fxulrunner%5Fabout.html" rel="nofollow">pyxulrunner</a> tutorial didn't work for me, though -- first I had to add the xulrunner /usr/lib path to LD_LIBRARY_PATH, then it still had problems with "from xpcom import components"...</p>
<p>my wishlist for a ui library would be</p>
<ul>
<li>Python integration (i.e. uses builtins like unicode, modules like threading, and language features like closures)</li>
<li>good intermediate representation (like XUL instead of generating hundreds of lines looking like "listbox91.addChild(label28)")</li>
<li><em>simple</em> mutlithreaded support (automatic locks or event posting so e.g. elt.setText can be called from any thread; let the designer manage locking with Python locks if necessary)</li>
<li>user-centric features as well - scripting of a sequence of UI events, ability to keybind anything (KDE has dcop, but afaik binding isn't done automatically by the UI library), and intercept events.</li>
<li>potential for a large, easy-to-contribute standard library.</li>
<li>documentation, though if the library was well designed and generated enough interest, this would be a given.</li>
</ul>
<p>In my experience, html is so much easier to get something good-looking up than UI libraries.</p>
<p><strong>edit</strong> - after working with PyQt 4 for a while, it gets the job done for simple UI's. I'm currently not developing for end users, so looks don't matter. The QTextBrowser is very useful for displaying basic HTML tables and generating HTML links.</p>
| 5
|
2009-03-29T06:03:47Z
|
[
"python",
"user-interface",
"cross-platform"
] |
Cross-platform gui toolkit for deploying Python applications
| 520,015
|
<p>Building on:
<a href="http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/">http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/</a></p>
<h1>Merits:</h1>
<p>1 - ease of design / integration - learning curve</p>
<p>2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web</p>
<p>3 - pythonic API</p>
<p>4 - quality of documentation - I want to do something a bit more complicated, now what?</p>
<p>5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file)</p>
<p>6 - licensing</p>
<p>7 - others? (specify)
<hr /></p>
<h1>Contenders:</h1>
<p>1 - tkinter, as currently supported (as of 2.6, 3.0)</p>
<p>2 - pyttk library</p>
<p>3 - pyGTK</p>
<p>4 - pyQt</p>
<p>5 - wxPython</p>
<p>6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste</p>
<p>7 - others? (specify)</p>
| 45
|
2009-02-06T11:43:30Z
| 881,659
|
<p><a href="http://www.jython.org/Project/" rel="nofollow">Jython</a>.</p>
<blockquote>
<p>Jython is an implementation of the
high-level, dynamic, object-oriented
language Python written in 100% Pure
Java, and seamlessly integrated with
the Java platform. It thus allows you
to run Python on any Java platform.</p>
</blockquote>
<p>You can use either Swing, Applet, or other GUI frameworks available to Java platform. See <a href="http://java.sun.com/docs/books/tutorial/" rel="nofollow">Java Tutorials</a> for <a href="http://java.sun.com/docs/books/tutorial/ui/index.html" rel="nofollow">Graphical User Interfaces</a> and <a href="http://java.sun.com/docs/books/tutorial/2d/index.html" rel="nofollow">2D Graphics</a>. There are plenty of books and <a href="http://java.sun.com/javase/6/docs/" rel="nofollow">documentation</a> such as <a href="http://java.sun.com/javase/6/docs/api/index.html" rel="nofollow">API reference</a>.</p>
<p>Here's a Hello world Swing application from <a href="http://www.javalobby.org/articles/jython/" rel="nofollow">An Introduction to Jython</a>.</p>
<pre><code>from javax.swing import *
frame = JFrame("Hello Jython")
label = JLabel("Hello Jython!", JLabel.CENTER)
frame.add(label)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(300, 300)
frame.show()
</code></pre>
<p>Here's a Jython <a href="http://replay.waybackmachine.org/20080724075253/http://www.ditchnet.org/wp/2005/05/10/mulit-threaded-jython-applet/" rel="nofollow">applet by Todd Ditchendorf that demonstrates multi-threaded particle drawing</a> (60 lines).</p>
<pre><code>from __future__ import nested_scopes
import java.lang as lang
import java.util as util
import java.awt as awt
import javax.swing as swing
class Particle:
def __init__(self,initX,initY):
self.x = initX
self.y = initY
self.rng = util.Random()
def move(self):
self.x += self.rng.nextInt(10) - 5
self.y += self.rng.nextInt(20) - 10
def draw(self,g2):
g2.drawRect(self.x,self.y,10,10)
class ParticleCanvas(awt.Canvas):
def __init__(self,newSize):
awt.Canvas.__init__(self,size=(newSize,newSize))
def paint(self,g2):
for p in self.particles:
p.draw(g2)
class ParticleApplet(swing.JApplet):
def init(self):
self.canvas = ParticleCanvas(self.getWidth())
self.contentPane.add(self.canvas)
def start(self):
n = 10
particles = []
for i in range(n):
particles.append(Particle(150,150))
self.canvas.particles = particles
self.threads = []
for i in range(n):
self.threads.append(self.makeThread(particles[i]))
self.threads[i].start()
def makeThread(self,p):
class MyRunnable(lang.Runnable):
def run(this):
try:
while 1:
p.move()
self.canvas.repaint()
lang.Thread.sleep(100)
except lang.InterruptedException:
return
return lang.Thread(MyRunnable())
</code></pre>
<p>If you are just interested in drawing lines and circles you can probably cut it down to half.</p>
| 5
|
2009-05-19T08:55:42Z
|
[
"python",
"user-interface",
"cross-platform"
] |
Cross-platform gui toolkit for deploying Python applications
| 520,015
|
<p>Building on:
<a href="http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/">http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/</a></p>
<h1>Merits:</h1>
<p>1 - ease of design / integration - learning curve</p>
<p>2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web</p>
<p>3 - pythonic API</p>
<p>4 - quality of documentation - I want to do something a bit more complicated, now what?</p>
<p>5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file)</p>
<p>6 - licensing</p>
<p>7 - others? (specify)
<hr /></p>
<h1>Contenders:</h1>
<p>1 - tkinter, as currently supported (as of 2.6, 3.0)</p>
<p>2 - pyttk library</p>
<p>3 - pyGTK</p>
<p>4 - pyQt</p>
<p>5 - wxPython</p>
<p>6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste</p>
<p>7 - others? (specify)</p>
| 45
|
2009-02-06T11:43:30Z
| 881,684
|
<p>I'm just weighing in to say that TKinter sucks. It sadly seems that it is packed with Python because of backwards compatibility. </p>
<p>The documentation is horrible. It looks horrible. I have run into some bizarre bugs that will actually crash Python.</p>
| 4
|
2009-05-19T09:01:32Z
|
[
"python",
"user-interface",
"cross-platform"
] |
What's the cleanest way to extract URLs from a string using Python?
| 520,031
|
<p>Although I know I could use some hugeass regex such as the one posted <a href="http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx">here</a> I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?</p>
<p>Simple question, but nothing jumped out on Google (or Stackoverflow).</p>
<p>Look forward to seeing how y'all do this!</p>
| 18
|
2009-02-06T11:51:57Z
| 520,036
|
<p>Use a regular expression.</p>
<p>Reply to comment from the OP: I know this is not helpful. I am telling you the correct way to solve the problem as you stated it is to use a regular expression.</p>
| 8
|
2009-02-06T11:54:44Z
|
[
"python",
"regex",
"url"
] |
What's the cleanest way to extract URLs from a string using Python?
| 520,031
|
<p>Although I know I could use some hugeass regex such as the one posted <a href="http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx">here</a> I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?</p>
<p>Simple question, but nothing jumped out on Google (or Stackoverflow).</p>
<p>Look forward to seeing how y'all do this!</p>
| 18
|
2009-02-06T11:51:57Z
| 520,056
|
<p>if you know that there is a URL following a space in the string you can do something like this:</p>
<p>s is the string containg the url</p>
<pre><code>>>> t = s[s.find("http://"):]
>>> t = t[:t.find(" ")]
</code></pre>
<p>otherwise you need to check if find returns -1 or not.</p>
| 5
|
2009-02-06T12:06:16Z
|
[
"python",
"regex",
"url"
] |
What's the cleanest way to extract URLs from a string using Python?
| 520,031
|
<p>Although I know I could use some hugeass regex such as the one posted <a href="http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx">here</a> I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?</p>
<p>Simple question, but nothing jumped out on Google (or Stackoverflow).</p>
<p>Look forward to seeing how y'all do this!</p>
| 18
|
2009-02-06T11:51:57Z
| 520,078
|
<p>You can use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>.</p>
<pre><code>def extractlinks(html):
soup = BeautifulSoup(html)
anchors = soup.findAll('a')
links = []
for a in anchors:
links.append(a['href'])
return links
</code></pre>
<p>Note that the solution with regexes is faster, although will not be as accurate. </p>
| 4
|
2009-02-06T12:12:58Z
|
[
"python",
"regex",
"url"
] |
What's the cleanest way to extract URLs from a string using Python?
| 520,031
|
<p>Although I know I could use some hugeass regex such as the one posted <a href="http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx">here</a> I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?</p>
<p>Simple question, but nothing jumped out on Google (or Stackoverflow).</p>
<p>Look forward to seeing how y'all do this!</p>
| 18
|
2009-02-06T11:51:57Z
| 1,855,891
|
<p>Look at Django's approach here: <a href="https://github.com/django/django/blob/98c5370ef673bc83deaf24c197e0bb22a75071e3/django/utils/html.py#L257" rel="nofollow"><code>django.utils.urlize()</code></a>. Regexps are too limited for the job and you have to use heuristics to get results that are mostly right.</p>
| 10
|
2009-12-06T17:03:32Z
|
[
"python",
"regex",
"url"
] |
What's the cleanest way to extract URLs from a string using Python?
| 520,031
|
<p>Although I know I could use some hugeass regex such as the one posted <a href="http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx">here</a> I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?</p>
<p>Simple question, but nothing jumped out on Google (or Stackoverflow).</p>
<p>Look forward to seeing how y'all do this!</p>
| 18
|
2009-02-06T11:51:57Z
| 14,055,143
|
<p>You can use this library I wrote:</p>
<p><a href="https://github.com/imranghory/urlextractor">https://github.com/imranghory/urlextractor</a></p>
<p>It's extremely hacky, but it doesn't rely upon "http://" like many other techniques, rather it uses the Mozilla TLD list (via the tldextract library) to search for TLDs (i.e ".co.uk", ".com", etc.) in the text and then attempts to construct urls around the TLD.</p>
<p>It doesn't aim to be RFC compliant but rather accurate for how urls are used in practice in the real world. So for example it will reject the technically valid domain "com" (you can actually use a TLD as a domain; although it's rare in practice) and will strip trail full-stops or commas from urls.</p>
| 5
|
2012-12-27T12:59:34Z
|
[
"python",
"regex",
"url"
] |
What's the cleanest way to extract URLs from a string using Python?
| 520,031
|
<p>Although I know I could use some hugeass regex such as the one posted <a href="http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx">here</a> I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?</p>
<p>Simple question, but nothing jumped out on Google (or Stackoverflow).</p>
<p>Look forward to seeing how y'all do this!</p>
| 18
|
2009-02-06T11:51:57Z
| 28,552,670
|
<p>I know that it's exactly what you do not want but here's a file with a huge regex:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
the web url matching regex used by markdown
http://daringfireball.net/2010/07/improved_regex_for_matching_urls
https://gist.github.com/gruber/8891611
"""
URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»ââââ])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))"""
</code></pre>
<p>I call that file <code>urlmarker.py</code> and when I need it I just import it, eg.</p>
<pre><code>import urlmarker
import re
re.findall(urlmarker.URL_REGEX,'some text news.yahoo.com more text')
</code></pre>
<p>cf. <a href="http://daringfireball.net/2010/07/improved_regex_for_matching_urls" rel="nofollow">http://daringfireball.net/2010/07/improved_regex_for_matching_urls</a></p>
<p>Also, here is what Django (1.6) uses to validate <code>URLField</code>s:</p>
<pre><code>regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
</code></pre>
<p>cf. <a href="https://github.com/django/django/blob/1.6/django/core/validators.py#L43-50" rel="nofollow">https://github.com/django/django/blob/1.6/django/core/validators.py#L43-50</a></p>
<p>Django 1.9 has that logic split across a few classes</p>
| 6
|
2015-02-17T00:20:26Z
|
[
"python",
"regex",
"url"
] |
What's the cleanest way to extract URLs from a string using Python?
| 520,031
|
<p>Although I know I could use some hugeass regex such as the one posted <a href="http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx">here</a> I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?</p>
<p>Simple question, but nothing jumped out on Google (or Stackoverflow).</p>
<p>Look forward to seeing how y'all do this!</p>
| 18
|
2009-02-06T11:51:57Z
| 30,408,189
|
<h2>There is an excellent comparison of 13 different regex approaches</h2>
<p>...which can be found at this page: <a href="https://mathiasbynens.be/demo/url-regex"><strong>In search of the perfect URL validation regex</strong></a>. </p>
<p>The Diego Perini regex, which passed all the tests, is <strong>very</strong> long but is available at his gist <a href="https://gist.github.com/dperini/729294">here</a>.<br>
Note that you will have to convert his PHP version to python regex (there are slight differences).</p>
<p>I ended up using the <a href="https://gist.github.com/731338/810d83626a6d79f40a251f250ed4625cac0e731f">Imme Emosol</a> version which passes the vast majority of tests and is a fraction of the size of Diego Perini's.</p>
<p>Here is a python-compatible version of the Imme Emosol regex:</p>
<pre><code>r'^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$'
</code></pre>
| 6
|
2015-05-23T02:08:49Z
|
[
"python",
"regex",
"url"
] |
Python "property object has no attribute" Exception
| 520,152
|
<pre><code>confirmation = property(_get_confirmation, _set_confirmation)
confirmation.short_description = "Confirmation"
</code></pre>
<p>When I try the above I get an Exception I don't quite understand:</p>
<pre><code>AttributeError: 'property' object has no attribute 'short_description'
</code></pre>
<p>This was an <a href="http://stackoverflow.com/questions/435544/django-custom-virtual-model-field-with-companion-stored-field/435580#435580">answer</a> to another question on here but I couldn't comment on it as I don't have enough points or something. :-(</p>
<p>In other tests I've also got this error under similar circumstances:</p>
<pre><code>TypeError: 'property' object has only read-only attributes (assign to .short_description)
</code></pre>
<p>Any ideas anybody?</p>
| 4
|
2009-02-06T12:45:09Z
| 520,180
|
<p>The result of property() is an object where you can't add new fields or methods. It's immutable which is why you get the error.</p>
<p><a href="http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/" rel="nofollow">Example how to use property()</a>.</p>
<p>[EDIT] As for the <a href="http://stackoverflow.com/questions/435544/django-custom-virtual-model-field-with-companion-stored-field/435580#435580">answer</a>, you refer to: I think the indentation of the example was completely wrong when you looked at it. This has been fixed, now.</p>
| 3
|
2009-02-06T13:01:53Z
|
[
"python",
"django",
"properties"
] |
Where is Python used? I read about it a lot on Reddit
| 520,210
|
<p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
| 8
|
2009-02-06T13:08:13Z
| 520,230
|
<p>Everywhere. It's used <a href="http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm">extensively by google</a> for one.</p>
<p>See <a href="http://en.wikipedia.org/wiki/Python_software">list of python software</a> for more info, and also <a href="http://www.python.org/doc/essays/ppt/www8-py-www/sld010.htm">who uses python on the web?</a></p>
| 17
|
2009-02-06T13:12:56Z
|
[
"python"
] |
Where is Python used? I read about it a lot on Reddit
| 520,210
|
<p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
| 8
|
2009-02-06T13:08:13Z
| 520,233
|
<p>Not sure about India, but you can get a decent overview of available Python jobs on the python.org jobs page <a href="http://www.python.org/community/jobs/" rel="nofollow">here</a>. </p>
| 1
|
2009-02-06T13:13:10Z
|
[
"python"
] |
Where is Python used? I read about it a lot on Reddit
| 520,210
|
<p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
| 8
|
2009-02-06T13:08:13Z
| 520,239
|
<p>It definitely has job value. For instance Google requires it. Have a look at <a href="http://www.google.co.in/support/jobs/bin/topic.py?dep_id=1054&loc_id=1100&topic=1054" rel="nofollow">Google openings in India</a>:</p>
<blockquote>
<p>Excellent programming skills in at
least one of the following languages:
C, C++, Java or Python (C++/Python
preferred)</p>
</blockquote>
| 4
|
2009-02-06T13:14:47Z
|
[
"python"
] |
Where is Python used? I read about it a lot on Reddit
| 520,210
|
<p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
| 8
|
2009-02-06T13:08:13Z
| 520,246
|
<p>Try looking at Mark Pilgrim's excellent book "<a href="http://www.diveintopython.org/" rel="nofollow">Dive Into Python</a>" which is available for download under GNU Free Documentation License.</p>
<p>HTH</p>
<p>cheers,</p>
<p>Rob</p>
| 1
|
2009-02-06T13:16:35Z
|
[
"python"
] |
Where is Python used? I read about it a lot on Reddit
| 520,210
|
<p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
| 8
|
2009-02-06T13:08:13Z
| 520,247
|
<p>In many large companies it is a primary scripting language.
Google is using it along with Java and C++ and almost nothing else.
Also many web pages are built on top of python and Django.
Another place is game development. Many games have their engines written in C++ but all the logic in Python.</p>
<p>In other words it is one of the most valuable tools.</p>
<p>This might be of interest for you as well:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/35753/is-python-good-for-big-software-projects-not-web-based">Is Python good for big software projects (not web based)?</a></li>
<li><a href="http://stackoverflow.com/questions/371966/are-there-any-good-reasons-why-i-should-not-use-python">Are there any good reasons why I should not use Python?</a></li>
<li><a href="http://stackoverflow.com/questions/111857/what-did-you-use-to-teach-yourself-python">What did you use to teach yourself python?</a></li>
</ul>
| 10
|
2009-02-06T13:16:37Z
|
[
"python"
] |
Where is Python used? I read about it a lot on Reddit
| 520,210
|
<p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
| 8
|
2009-02-06T13:08:13Z
| 520,257
|
<p>In 10 years of web development I've had 1 client have me write an email parsing app with it. Not that it doesn't get used, but I've seen Ruby/php/.net way more often in the wild.</p>
<p>Edit:
From the other posts if you plan on working at Google, it sounds like the language to learn - LOL!</p>
| 1
|
2009-02-06T13:20:40Z
|
[
"python"
] |
Where is Python used? I read about it a lot on Reddit
| 520,210
|
<p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
| 8
|
2009-02-06T13:08:13Z
| 520,369
|
<p>It's juste one example but I know it is widely used in large scientific institutions with high tech machinery where non-programmers (typically physicists) need quick prototypes or tools to cover their data collection/processing needs. The easy-to access scripting language aspect clearly plays its role here. So I don't know about building a career out of that only but I'd definitely say that knowing Python is a very valuable asset on your resume, it'll strengthen your "smell of usefulness".</p>
| 1
|
2009-02-06T13:58:54Z
|
[
"python"
] |
Where is Python used? I read about it a lot on Reddit
| 520,210
|
<p>I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.</p>
| 8
|
2009-02-06T13:08:13Z
| 1,380,233
|
<p>The google app engine lets you use python (or Java). I HIGHLY recommend that you check it out. If you want to have a FREE website with a database (actually a datastore but it works much like a database) using python, THIS IS IT. It scales up too. If you start to get enough traffic you would have to start paying for the usage it requires.</p>
<p><a href="http://code.google.com/appengine/docs/python/overview.html" rel="nofollow">http://code.google.com/appengine/docs/python/overview.html</a></p>
<p>You could make your own python based site and run some ads. Voila, make some money. Also, I'm sure google could be impressed by some good python because I hear they use it for much of their own sites.</p>
| 0
|
2009-09-04T16:18:16Z
|
[
"python"
] |
Search Files& Dirs on Website
| 520,362
|
<p>Hi im coding to code a Tool that searchs for Dirs and files.</p>
<p>have done so the tool searchs for dirs, but need help to make it search for files on websites.</p>
<p>Any idea how it can be in python?</p>
| 0
|
2009-02-06T13:55:31Z
| 520,373
|
<p>Is this tool scanning the directories of your own website (in which the tool is running), or external sites?</p>
| 1
|
2009-02-06T14:00:58Z
|
[
"python"
] |
Search Files& Dirs on Website
| 520,362
|
<p>Hi im coding to code a Tool that searchs for Dirs and files.</p>
<p>have done so the tool searchs for dirs, but need help to make it search for files on websites.</p>
<p>Any idea how it can be in python?</p>
| 0
|
2009-02-06T13:55:31Z
| 520,397
|
<p>You can only do this if you have permission to browse directories on the site and no default page exists.</p>
| 1
|
2009-02-06T14:10:02Z
|
[
"python"
] |
Search Files& Dirs on Website
| 520,362
|
<p>Hi im coding to code a Tool that searchs for Dirs and files.</p>
<p>have done so the tool searchs for dirs, but need help to make it search for files on websites.</p>
<p>Any idea how it can be in python?</p>
| 0
|
2009-02-06T13:55:31Z
| 520,423
|
<p>You cannot get a directory listing on a website.</p>
<p>Pedantically, HTTP has no notion of directory.</p>
<p>Pratically, WebDAV provides a directory listing verb, so you can use that if WebDAV is enabled.</p>
<p>Otherwise, the closest thing you can do is similar to what recursive wget does: get a page, parse the HTML, look for hyperlinks (<code>a/@href</code> in xpath), filter out hyperlinks that do not point to URL below the current page, recurse into the remaining urls.</p>
<p>You can do further filtering, depending on your use case, such as removing the query part of the URL (anything after the first <code>?</code>).</p>
<p>When the server has a directory listing feature enabled, this gives you something usable. This also gives you something usable if the website has no directory listing but is organized in a sensible way.</p>
| 1
|
2009-02-06T14:17:46Z
|
[
"python"
] |
Search Files& Dirs on Website
| 520,362
|
<p>Hi im coding to code a Tool that searchs for Dirs and files.</p>
<p>have done so the tool searchs for dirs, but need help to make it search for files on websites.</p>
<p>Any idea how it can be in python?</p>
| 0
|
2009-02-06T13:55:31Z
| 520,575
|
<p>If you're getting information on your own website for presentation in your own web application, you should use os.walk.</p>
<p>See <a href="http://www.python.org/doc/2.5.2/lib/os-file-dir.html" rel="nofollow">http://www.python.org/doc/2.5.2/lib/os-file-dir.html</a> for more information.</p>
| 0
|
2009-02-06T14:55:31Z
|
[
"python"
] |
Event handling with Jython & Swing
| 520,615
|
<p>I'm making a GUI by using Swing from Jython. Event handling seems to be particularly elegant from Jython, just set</p>
<pre><code>JButton("Push me", actionPerformed = nameOfFunctionToCall)
</code></pre>
<p>However, trying same thing inside a class gets difficult. Naively trying</p>
<pre><code>JButton("Push me", actionPerformed = nameOfMethodToCall)
</code></pre>
<p>or</p>
<pre><code>JButton("Push me", actionPerformed = nameOfMethodToCall(self))
</code></pre>
<p>from a GUI-construction method of the class doesn't work, because the first argument of a method to be called should be <em>self</em>, in order to access the data members of the class, and on the other hand, it's not possible to pass any arguments to the event handler through AWT event queue. The only option seems to be using lambda (as advised at <a href="http://www.javalobby.org/articles/jython/" rel="nofollow">http://www.javalobby.org/articles/jython/</a>) which results in something like this:</p>
<pre><code>JButton("Push me", actionPerformed = lambda evt : ClassName.nameOfMethodToCall(self))
</code></pre>
<p>It works, but the elegance is gone. All this just because the method being called needs a <em>self</em> reference from somewhere. Is there any other way around this?</p>
| 8
|
2009-02-06T15:09:13Z
| 523,456
|
<pre><code>JButton("Push me", actionPerformed=self.nameOfMethodToCall)
</code></pre>
<p>Here's a modified example from the article you cited:</p>
<pre><code>from javax.swing import JButton, JFrame
class MyFrame(JFrame):
def __init__(self):
JFrame.__init__(self, "Hello Jython")
button = JButton("Hello", actionPerformed=self.hello)
self.add(button)
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setSize(300, 300)
self.show()
def hello(self, event):
print "Hello, world!"
if __name__=="__main__":
MyFrame()
</code></pre>
| 11
|
2009-02-07T08:35:51Z
|
[
"java",
"python",
"user-interface",
"swing",
"jython"
] |
Has anyone installed MySQLdb for Python on Cygwin?
| 520,865
|
<p>I'm trying to install MySQLdb for python on Cygwin. Unfortunately, when I run <code>python setup.py build</code>, I get the following error:</p>
<pre><code>$ python setup.py build
/bin/sh: /usr/local/bin/mysql_config: No such file or directory
Traceback (most recent call last):
File "setup.py", line 16, in <module>
metadata, options = get_config()
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
raise EnvironmentError, "%s not found" % mysql_config.path
EnvironmentError: /usr/local/bin/mysql_config not found
</code></pre>
<p>Clearly I don't have <code>mysql_config</code> installed, which I guess is the problem. This is mentioned in the README for MySQLdb, but it doesn't explain how to either get around it or how to install mysql_config.</p>
<p>So maybe this is as easy as: How can I install <code>mysql_config</code> for Cygwin?</p>
<p>Or maybe it's harder than that.</p>
<p>FYI: I have python 2.5.2 and MySQL 5.1.30, running under Cygwin.</p>
| 10
|
2009-02-06T16:01:35Z
| 521,081
|
<p>You'll need mysql-devel, if it's available for cygwin, or you'll need to build mysql from source.</p>
<p>Your best bet is probably to just compile the MySQL client yourself in order to get the necessary headers to compile MySQLdb. See <a href="http://cpansearch.perl.org/src/CAPTTOFU/DBD-mysql-3.0000/INSTALL.html#windows_cygwin" rel="nofollow">this note</a> on the similar Perl DB driver.</p>
| 2
|
2009-02-06T16:48:26Z
|
[
"python",
"mysql",
"cygwin"
] |
Has anyone installed MySQLdb for Python on Cygwin?
| 520,865
|
<p>I'm trying to install MySQLdb for python on Cygwin. Unfortunately, when I run <code>python setup.py build</code>, I get the following error:</p>
<pre><code>$ python setup.py build
/bin/sh: /usr/local/bin/mysql_config: No such file or directory
Traceback (most recent call last):
File "setup.py", line 16, in <module>
metadata, options = get_config()
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
raise EnvironmentError, "%s not found" % mysql_config.path
EnvironmentError: /usr/local/bin/mysql_config not found
</code></pre>
<p>Clearly I don't have <code>mysql_config</code> installed, which I guess is the problem. This is mentioned in the README for MySQLdb, but it doesn't explain how to either get around it or how to install mysql_config.</p>
<p>So maybe this is as easy as: How can I install <code>mysql_config</code> for Cygwin?</p>
<p>Or maybe it's harder than that.</p>
<p>FYI: I have python 2.5.2 and MySQL 5.1.30, running under Cygwin.</p>
| 10
|
2009-02-06T16:01:35Z
| 1,785,355
|
<p>I followed the directions on <a href="http://phaseshiftllc.com/archives/2008/10/26/installing-mysql-gem-on-windows-cygwin-for-rails#comment-86" rel="nofollow">this comment</a> to get MySQL installed on Cygwin. I had to use version 5.1.35, which can be downloaded from <a href="http://downloads.mysql.com/archives.php?p=mysql-5.1&o=other" rel="nofollow">here</a>, as the latest (5.1.41) failed to build.</p>
<p>Here is the command line I used:</p>
<p>./configure âwithout-libedit âwithout-readline âwithout-server CFLAGS=-O2`</p>
| 1
|
2009-11-23T19:19:45Z
|
[
"python",
"mysql",
"cygwin"
] |
Has anyone installed MySQLdb for Python on Cygwin?
| 520,865
|
<p>I'm trying to install MySQLdb for python on Cygwin. Unfortunately, when I run <code>python setup.py build</code>, I get the following error:</p>
<pre><code>$ python setup.py build
/bin/sh: /usr/local/bin/mysql_config: No such file or directory
Traceback (most recent call last):
File "setup.py", line 16, in <module>
metadata, options = get_config()
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
raise EnvironmentError, "%s not found" % mysql_config.path
EnvironmentError: /usr/local/bin/mysql_config not found
</code></pre>
<p>Clearly I don't have <code>mysql_config</code> installed, which I guess is the problem. This is mentioned in the README for MySQLdb, but it doesn't explain how to either get around it or how to install mysql_config.</p>
<p>So maybe this is as easy as: How can I install <code>mysql_config</code> for Cygwin?</p>
<p>Or maybe it's harder than that.</p>
<p>FYI: I have python 2.5.2 and MySQL 5.1.30, running under Cygwin.</p>
| 10
|
2009-02-06T16:01:35Z
| 8,440,154
|
<p>After building MySQL using the instructions above, you'll need to do the following to build and install MySQLdb:</p>
<ol>
<li>Download the Python 'setuptools' package <a href="http://pypi.python.org/pypi/setuptools#files" rel="nofollow">here</a> (example: setuptools-0.6c11-py2.6.egg). You'll need this to run setup.py which comes with MySQL-python.</li>
<li>Install setuptools using the instructions on the same page (you just run it as if it was a shell script).</li>
<li>Download MySQL-python <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">here</a> (example: MySQL-python-1.2.3.tar.gz).</li>
<li>Expand the archive and you'll find installation instructions in the README file.</li>
<li>Build and install MySQL-python using the instructions in the README file.</li>
</ol>
| 2
|
2011-12-09T01:52:00Z
|
[
"python",
"mysql",
"cygwin"
] |
Has anyone installed MySQLdb for Python on Cygwin?
| 520,865
|
<p>I'm trying to install MySQLdb for python on Cygwin. Unfortunately, when I run <code>python setup.py build</code>, I get the following error:</p>
<pre><code>$ python setup.py build
/bin/sh: /usr/local/bin/mysql_config: No such file or directory
Traceback (most recent call last):
File "setup.py", line 16, in <module>
metadata, options = get_config()
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
raise EnvironmentError, "%s not found" % mysql_config.path
EnvironmentError: /usr/local/bin/mysql_config not found
</code></pre>
<p>Clearly I don't have <code>mysql_config</code> installed, which I guess is the problem. This is mentioned in the README for MySQLdb, but it doesn't explain how to either get around it or how to install mysql_config.</p>
<p>So maybe this is as easy as: How can I install <code>mysql_config</code> for Cygwin?</p>
<p>Or maybe it's harder than that.</p>
<p>FYI: I have python 2.5.2 and MySQL 5.1.30, running under Cygwin.</p>
| 10
|
2009-02-06T16:01:35Z
| 17,468,646
|
<p>How I did it:</p>
<p>First I installed <a href="https://github.com/transcode-open/apt-cyg" rel="nofollow"><code>apt-cyg</code></a>. With that:</p>
<pre><code># apt-cyg install gcc # older name
apt-cyg install gcc-core # as of 2015
apt-cyg install python-setuptools
easy_install pip
pip install -U mysql-python
</code></pre>
| 3
|
2013-07-04T11:03:46Z
|
[
"python",
"mysql",
"cygwin"
] |
Has anyone installed MySQLdb for Python on Cygwin?
| 520,865
|
<p>I'm trying to install MySQLdb for python on Cygwin. Unfortunately, when I run <code>python setup.py build</code>, I get the following error:</p>
<pre><code>$ python setup.py build
/bin/sh: /usr/local/bin/mysql_config: No such file or directory
Traceback (most recent call last):
File "setup.py", line 16, in <module>
metadata, options = get_config()
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
raise EnvironmentError, "%s not found" % mysql_config.path
EnvironmentError: /usr/local/bin/mysql_config not found
</code></pre>
<p>Clearly I don't have <code>mysql_config</code> installed, which I guess is the problem. This is mentioned in the README for MySQLdb, but it doesn't explain how to either get around it or how to install mysql_config.</p>
<p>So maybe this is as easy as: How can I install <code>mysql_config</code> for Cygwin?</p>
<p>Or maybe it's harder than that.</p>
<p>FYI: I have python 2.5.2 and MySQL 5.1.30, running under Cygwin.</p>
| 10
|
2009-02-06T16:01:35Z
| 19,615,174
|
<p>Got the same error after trying <code>pip install mysql-python</code>. I have Win7 x64 + Cygwin x86 2.830 + Django 1.5.5 + Python 2.7.</p>
<p>So I ran Cygwin setup and downloaded the <code>libmysqlclient-devel</code>: MySQL database client library (development) and that did it!!</p>
| 2
|
2013-10-27T06:06:41Z
|
[
"python",
"mysql",
"cygwin"
] |
Has anyone installed MySQLdb for Python on Cygwin?
| 520,865
|
<p>I'm trying to install MySQLdb for python on Cygwin. Unfortunately, when I run <code>python setup.py build</code>, I get the following error:</p>
<pre><code>$ python setup.py build
/bin/sh: /usr/local/bin/mysql_config: No such file or directory
Traceback (most recent call last):
File "setup.py", line 16, in <module>
metadata, options = get_config()
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
raise EnvironmentError, "%s not found" % mysql_config.path
EnvironmentError: /usr/local/bin/mysql_config not found
</code></pre>
<p>Clearly I don't have <code>mysql_config</code> installed, which I guess is the problem. This is mentioned in the README for MySQLdb, but it doesn't explain how to either get around it or how to install mysql_config.</p>
<p>So maybe this is as easy as: How can I install <code>mysql_config</code> for Cygwin?</p>
<p>Or maybe it's harder than that.</p>
<p>FYI: I have python 2.5.2 and MySQL 5.1.30, running under Cygwin.</p>
| 10
|
2009-02-06T16:01:35Z
| 30,419,348
|
<p>First, install apt-cyg:</p>
<pre><code>lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg`
install apt-cyg /bin
</code></pre>
<p>Now, use apt-cyg to install mysql-devel:</p>
<pre><code>apt-cyg install libmysqlclient-devel
</code></pre>
| 2
|
2015-05-24T01:54:37Z
|
[
"python",
"mysql",
"cygwin"
] |
How to convert a list of number to html in Python?
| 520,881
|
<p>hey guys, my last problem ^^ say i have a string which contains html, like</p>
<pre><code>html = '<td class="p11_666699"><strong>100</strong></td>'
</code></pre>
<p>and a list like</p>
<pre><code>numbers = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150]
</code></pre>
<p>basically i want to do something like this:</p>
<pre><code>html = '<td class="p11_666699"><strong>' + numbers + '</strong></td>'
</code></pre>
<p>edit: for some reason the code tags add curly brackets when i post this, so it messes up, sorry.</p>
| 0
|
2009-02-06T16:05:16Z
| 520,923
|
<p>Are you looking for a way to join a list of numbers into a string? This will work:</p>
<pre><code>' '.join(map(str, [10, 20, 30]))
</code></pre>
<p>Resulting in:</p>
<pre><code>'10 20 30'
</code></pre>
<p>The second argument of <code>map</code> is a list, so you can place your 'numbers' list there.</p>
<p>This is in no way HTML specific, of course.</p>
| 1
|
2009-02-06T16:14:01Z
|
[
"python"
] |
How to convert a list of number to html in Python?
| 520,881
|
<p>hey guys, my last problem ^^ say i have a string which contains html, like</p>
<pre><code>html = '<td class="p11_666699"><strong>100</strong></td>'
</code></pre>
<p>and a list like</p>
<pre><code>numbers = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150]
</code></pre>
<p>basically i want to do something like this:</p>
<pre><code>html = '<td class="p11_666699"><strong>' + numbers + '</strong></td>'
</code></pre>
<p>edit: for some reason the code tags add curly brackets when i post this, so it messes up, sorry.</p>
| 0
|
2009-02-06T16:05:16Z
| 520,936
|
<p>I think you either want this:</p>
<pre><code>numbers = [100, 101, 102, 103]
output = "<td>" + ", ".join(map(str, numbers)) + "</td>"
</code></pre>
<p>or</p>
<pre><code>output = ""
for number in numbers:
output += "<td>" + str(number) + "</td>"
</code></pre>
| 2
|
2009-02-06T16:16:28Z
|
[
"python"
] |
How to convert a list of number to html in Python?
| 520,881
|
<p>hey guys, my last problem ^^ say i have a string which contains html, like</p>
<pre><code>html = '<td class="p11_666699"><strong>100</strong></td>'
</code></pre>
<p>and a list like</p>
<pre><code>numbers = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150]
</code></pre>
<p>basically i want to do something like this:</p>
<pre><code>html = '<td class="p11_666699"><strong>' + numbers + '</strong></td>'
</code></pre>
<p>edit: for some reason the code tags add curly brackets when i post this, so it messes up, sorry.</p>
| 0
|
2009-02-06T16:05:16Z
| 520,938
|
<p>As pointed out in the comments, it's really hard to understand your question... but if you want to generate a bunch of table cells, each containing one of the numbers, use something like this:</p>
<pre><code>html = ''.join('<td>%d</td>' % n for n in numbers)
</code></pre>
<p>Of course you can add in a <code>class</code> or other attribute to be applied to the table cells if you want.</p>
| 4
|
2009-02-06T16:17:03Z
|
[
"python"
] |
How to convert a list of number to html in Python?
| 520,881
|
<p>hey guys, my last problem ^^ say i have a string which contains html, like</p>
<pre><code>html = '<td class="p11_666699"><strong>100</strong></td>'
</code></pre>
<p>and a list like</p>
<pre><code>numbers = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150]
</code></pre>
<p>basically i want to do something like this:</p>
<pre><code>html = '<td class="p11_666699"><strong>' + numbers + '</strong></td>'
</code></pre>
<p>edit: for some reason the code tags add curly brackets when i post this, so it messes up, sorry.</p>
| 0
|
2009-02-06T16:05:16Z
| 520,947
|
<pre><code>html = ['<td class="p11_666699"><strong>%d</strong></td>' % number for number in numbers]
</code></pre>
<p>And I see David just suggested this (but joined). </p>
| 1
|
2009-02-06T16:18:40Z
|
[
"python"
] |
pagination with the python cmd module
| 520,963
|
<p>I'm prototyping a Python app with the <a href="http://docs.python.org/library/cmd.html">cmd</a> module.</p>
<p>Some messages to the user will be quite long and I'd like to paginate them.
The first 10 (or a configurable number) lines of the message would appear, and pressing the SPACE bar would display the next page, until the end of the message.</p>
<p>I don't want to reinvent something here, is there a simple mean to implement this feature?</p>
| 8
|
2009-02-06T16:21:16Z
| 521,054
|
<p>The simple thing would just be to pipe your script through "less" or a similar command at runtime.</p>
<p>Here's a simple method that does approximately what you want, though:</p>
<pre><code>def print_and_wait(some_long_message):
lines = some_long_message.split('\n')
i=0
while i < len(lines):
print '\n'.join(lines[i:i+10])
raw_input("press enter to read more...")
i += 10
</code></pre>
<p>You could also look into using curses.</p>
| 4
|
2009-02-06T16:42:32Z
|
[
"python",
"pagination",
"cmd"
] |
pagination with the python cmd module
| 520,963
|
<p>I'm prototyping a Python app with the <a href="http://docs.python.org/library/cmd.html">cmd</a> module.</p>
<p>Some messages to the user will be quite long and I'd like to paginate them.
The first 10 (or a configurable number) lines of the message would appear, and pressing the SPACE bar would display the next page, until the end of the message.</p>
<p>I don't want to reinvent something here, is there a simple mean to implement this feature?</p>
| 8
|
2009-02-06T16:21:16Z
| 699,021
|
<p>As Yoni said above the right way to do this is to provide a print method that pages automatically inside your running cmd instance. The constructor of Cmd takes stdin and stdout arguments. So simple provide an object that works like stdout and supports your paging print method.</p>
<pre><code>class PagingStdOut(object):
def write(self, buffer, lines_before_pause=40):
# do magic paging here...
</code></pre>
| 3
|
2009-03-30T21:07:16Z
|
[
"python",
"pagination",
"cmd"
] |
pagination with the python cmd module
| 520,963
|
<p>I'm prototyping a Python app with the <a href="http://docs.python.org/library/cmd.html">cmd</a> module.</p>
<p>Some messages to the user will be quite long and I'd like to paginate them.
The first 10 (or a configurable number) lines of the message would appear, and pressing the SPACE bar would display the next page, until the end of the message.</p>
<p>I don't want to reinvent something here, is there a simple mean to implement this feature?</p>
| 8
|
2009-02-06T16:21:16Z
| 708,681
|
<p>Paging subroutines can be found in the <a href="http://bazaar.launchpad.net/~ipython-dev/ipython/trunk/annotate/head%3A/IPython/genutils.py" rel="nofollow">genutils.py</a> file of <a href="http://ipython.scipy.org/" rel="nofollow">IPython</a> (see <code>page</code>, or <code>page_dumb</code> for a simpler one). The code is a little complicated, but that's probably unavoidable if you are trying to be portable to systems including Windows and the various kinds of terminal emulators.</p>
| 0
|
2009-04-02T07:37:36Z
|
[
"python",
"pagination",
"cmd"
] |
pagination with the python cmd module
| 520,963
|
<p>I'm prototyping a Python app with the <a href="http://docs.python.org/library/cmd.html">cmd</a> module.</p>
<p>Some messages to the user will be quite long and I'd like to paginate them.
The first 10 (or a configurable number) lines of the message would appear, and pressing the SPACE bar would display the next page, until the end of the message.</p>
<p>I don't want to reinvent something here, is there a simple mean to implement this feature?</p>
| 8
|
2009-02-06T16:21:16Z
| 1,380,570
|
<p>I had the same question. There is a pager built in to the <a href="http://docs.python.org/library/pydoc" rel="nofollow"><strong>pydoc</strong> module</a>. I incorporated it thusly (which I find hackish and unsatisfying... I'm open to better ideas though).</p>
<p>I like the idea that it would autopage if there are more than <em>x</em> results and paging is on, which is possible to implement, but not done here. </p>
<pre><code>import cmd
from pydoc import pager
from cStringIO import StringIO
import sys
PAGER = True
class Commander(cmd.Cmd):
prompt = "> "
def do_pager(self,line):
global PAGER
line = line + " 1"
tokens = line.lower().split()
if tokens[0] in ("on","true","t", "1"):
PAGER = True
print "# setting PAGER True"
elif tokens[0] in ("off","false","f","0"):
PAGER = False
print "# setting PAGER False"
else:
print "# can't set pager: don't know -> %s" % tokens[0]
def do_demo(self,line):
results = dict(a=1,b=2,c=3)
self.format_commandline_results(results)
def format_commandline_results(self,results):
if PAGER:
ofh = StringIO()
else:
ofh = sys.stdout
for (k,v) in sorted(results.items()):
print >> ofh, "%s -> %s" % (k,v)
if PAGER:
ofh.seek(0)
pager(ofh.read())
return None
def do_EOF(self,line):
print "",
return True
if __name__ == "__main__":
Commander().cmdloop("# try: \n> pager off \n> demo \n> pager on \n> demo \n\n")
</code></pre>
| 1
|
2009-09-04T17:31:11Z
|
[
"python",
"pagination",
"cmd"
] |
Further Processing of Output of Undefined Methods (Python)
| 521,111
|
<p>How do I write a Python class that handles calls on undefined methods by first, getting the output of a function of the same name from a given module, and then, doing something further with that output?</p>
<p>For example, given add(x, y), doublerInstance.add(1, 1) should return 4.</p>
<p>I know _ _ getattr _ _() intercepts calls on undefined methods, and getattr() can retrieve a function object. But I don't know how get the arguments passed to the undefined call caught by _ _ getattr _ _() to the function retrieved by getattr().</p>
<pre><code>EXAMPLE
Module functions.py:
def add(x, y):
return x +
Module doubler.py:
class Doubler:
def __init__(self, source):
self.source = source
def __getattr__(self, attrname):
fnc = getattr(self.source, attrname)
return fnc() * 2
Session:
>import functions as f
>import doubler as d
>doublerInstance = d.Doubler(f)
>doublerInstance.add(1, 2)
<snip> TypeError: add() takes exactly 2 arguments, (0 given)
END
</code></pre>
<p>I do understand the error -- getattr() returns a function to be run, and the call fnc() doesn't pass any arguments to that function -- here, add(). But how do I get the arguments passed in to the call dblr.add(1, 2) and pass those to the function returned by the getattr() call? </p>
<p>I'm looking for the right way to do this, not some usage of _ _ getattr _ _. I realize that decorator functions using @ might be a better tool here, but I don't yet understand those well enough to see whether they could be applied here.</p>
<p>ALSO -- what resource should I have looked at to figure this out for myself? I haven't found it in the Lutz books, the Cookbook, or the Python Library Reference.</p>
| 2
|
2009-02-06T16:55:56Z
| 521,194
|
<p><code>__getattr__</code> has to return the function - not the result from calling it:</p>
<pre><code>class Doubler:
def __init__(self, source):
self.source = source
def __getattr__(self, attrname):
fnc = getattr(self.source, attrname)
return lambda x,y : fnc(x,y) * 2
</code></pre>
<p>This uses a lambda expression; it returns a new function that doubles the output on fnc</p>
<p>Perhaps this test code will make it clearer:</p>
<pre><code>import functions as f
import doubler as d
doublerInstance = d.Doubler(f)
print doublerInstance.add(1, 2)
doubleadd = doublerInstance.add
print doubleadd(1,2)
print doubleadd(2,3)
</code></pre>
| 2
|
2009-02-06T17:14:28Z
|
[
"python"
] |
Further Processing of Output of Undefined Methods (Python)
| 521,111
|
<p>How do I write a Python class that handles calls on undefined methods by first, getting the output of a function of the same name from a given module, and then, doing something further with that output?</p>
<p>For example, given add(x, y), doublerInstance.add(1, 1) should return 4.</p>
<p>I know _ _ getattr _ _() intercepts calls on undefined methods, and getattr() can retrieve a function object. But I don't know how get the arguments passed to the undefined call caught by _ _ getattr _ _() to the function retrieved by getattr().</p>
<pre><code>EXAMPLE
Module functions.py:
def add(x, y):
return x +
Module doubler.py:
class Doubler:
def __init__(self, source):
self.source = source
def __getattr__(self, attrname):
fnc = getattr(self.source, attrname)
return fnc() * 2
Session:
>import functions as f
>import doubler as d
>doublerInstance = d.Doubler(f)
>doublerInstance.add(1, 2)
<snip> TypeError: add() takes exactly 2 arguments, (0 given)
END
</code></pre>
<p>I do understand the error -- getattr() returns a function to be run, and the call fnc() doesn't pass any arguments to that function -- here, add(). But how do I get the arguments passed in to the call dblr.add(1, 2) and pass those to the function returned by the getattr() call? </p>
<p>I'm looking for the right way to do this, not some usage of _ _ getattr _ _. I realize that decorator functions using @ might be a better tool here, but I don't yet understand those well enough to see whether they could be applied here.</p>
<p>ALSO -- what resource should I have looked at to figure this out for myself? I haven't found it in the Lutz books, the Cookbook, or the Python Library Reference.</p>
| 2
|
2009-02-06T16:55:56Z
| 521,197
|
<p>When you call <code>doublerInstance.add(1, 2)</code>, you're getting an attribute <code>add</code> from it, and then you're <em>calling</em> it. But inside your getattr, you're returning a value. You have to return a function.</p>
<p>Anyway, for this particular case to work, you need this:</p>
<pre><code>def __getattr__(self, attrname) :
fnc = getattr(self.source, attrname)
def doubled(*args, **kwargs) :
return 2 * fnc(*args, **kwargs)
return doubled
</code></pre>
| 2
|
2009-02-06T17:15:11Z
|
[
"python"
] |
Further Processing of Output of Undefined Methods (Python)
| 521,111
|
<p>How do I write a Python class that handles calls on undefined methods by first, getting the output of a function of the same name from a given module, and then, doing something further with that output?</p>
<p>For example, given add(x, y), doublerInstance.add(1, 1) should return 4.</p>
<p>I know _ _ getattr _ _() intercepts calls on undefined methods, and getattr() can retrieve a function object. But I don't know how get the arguments passed to the undefined call caught by _ _ getattr _ _() to the function retrieved by getattr().</p>
<pre><code>EXAMPLE
Module functions.py:
def add(x, y):
return x +
Module doubler.py:
class Doubler:
def __init__(self, source):
self.source = source
def __getattr__(self, attrname):
fnc = getattr(self.source, attrname)
return fnc() * 2
Session:
>import functions as f
>import doubler as d
>doublerInstance = d.Doubler(f)
>doublerInstance.add(1, 2)
<snip> TypeError: add() takes exactly 2 arguments, (0 given)
END
</code></pre>
<p>I do understand the error -- getattr() returns a function to be run, and the call fnc() doesn't pass any arguments to that function -- here, add(). But how do I get the arguments passed in to the call dblr.add(1, 2) and pass those to the function returned by the getattr() call? </p>
<p>I'm looking for the right way to do this, not some usage of _ _ getattr _ _. I realize that decorator functions using @ might be a better tool here, but I don't yet understand those well enough to see whether they could be applied here.</p>
<p>ALSO -- what resource should I have looked at to figure this out for myself? I haven't found it in the Lutz books, the Cookbook, or the Python Library Reference.</p>
| 2
|
2009-02-06T16:55:56Z
| 521,208
|
<p>Try this:</p>
<pre><code>class Doubler:
def __init__(self, source):
self.source = source
def __getattr__(self, attrname):
def tmp_func(*args):
fnc = getattr(self.source, attrname)
return fnc(*args) * 2
return tmp_func
</code></pre>
<p>Hint:
<strong>getattr</strong> must return a function, not the result of the function call.</p>
| 0
|
2009-02-06T17:17:45Z
|
[
"python"
] |
Python loops with multiple lists?
| 521,321
|
<p><strong><edit></strong>
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:</p>
<pre><code>zip(range(len(files)), files, directories)
</code></pre>
<p><strong></edit></strong></p>
<p>Hi,</p>
<p>I'm in the process of learning Python, but I come from a background where the following pseudocode is typical:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for(i = 0; i < directories.length; i++) {
print (i + 1) + '. ' + directories[i] + '/' + files[i] + '\n'
}
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
</code></pre>
<p>In Python, the way I would write the above right now, would be like this:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for i in range(len(directories)):
print '%s. %s/%s' % ((i + 1), directories[i], files[i]
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
</code></pre>
<p>While reading Dive into Python, Mark Pilgrim says that using for loops for counters is "Visual Basic-style thinking" (<a href="http://diveintopython.net/file_handling/for_loops.html#fileinfo.for.counter">Simple Counters</a>). He goes on to show how to use loops with dictionaries, but never really addresses a python solution in regards to how for loop counters are typically used in other languages.</p>
<p>I was hoping somebody could show me how to properly write the above scenario in Python. Is it possible to do it a different way? </p>
<p>If I took out the incrementing line count, is it possible to just match the two lists together using some kind of list comprehension?</p>
<p>For example, if all I wanted from the output was this (no counters, is that possible with list comprehension):</p>
<pre><code># Output:
# directory_0/file_a
# directory_1/file_b
# directory_2/file_c
</code></pre>
<p>Thanks in advance for any help.</p>
| 15
|
2009-02-06T17:42:27Z
| 521,345
|
<p>Try this:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for file, dir in zip(files, directories):
print dir + '/' + file
</code></pre>
<p>To explain, the <code>zip()</code> function takes lists as input and returns a list of "zipped" tuples. so <code>zip([1,2,3,4,5],[a,b,c,d,e])</code> would return <code>[(1,a),(2,b)</code> and so on. </p>
<p>You can then assign the members of the tuples to variables with the python <code>for <var> in <list></code> syntax. </p>
<p>There are a million different ways to do what you are asking, but the above uses some more "pythonic" constructs to make the code a lot more readable (IMHO, anyway). </p>
| 10
|
2009-02-06T17:46:38Z
|
[
"python",
"arrays",
"loops",
"list"
] |
Python loops with multiple lists?
| 521,321
|
<p><strong><edit></strong>
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:</p>
<pre><code>zip(range(len(files)), files, directories)
</code></pre>
<p><strong></edit></strong></p>
<p>Hi,</p>
<p>I'm in the process of learning Python, but I come from a background where the following pseudocode is typical:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for(i = 0; i < directories.length; i++) {
print (i + 1) + '. ' + directories[i] + '/' + files[i] + '\n'
}
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
</code></pre>
<p>In Python, the way I would write the above right now, would be like this:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for i in range(len(directories)):
print '%s. %s/%s' % ((i + 1), directories[i], files[i]
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
</code></pre>
<p>While reading Dive into Python, Mark Pilgrim says that using for loops for counters is "Visual Basic-style thinking" (<a href="http://diveintopython.net/file_handling/for_loops.html#fileinfo.for.counter">Simple Counters</a>). He goes on to show how to use loops with dictionaries, but never really addresses a python solution in regards to how for loop counters are typically used in other languages.</p>
<p>I was hoping somebody could show me how to properly write the above scenario in Python. Is it possible to do it a different way? </p>
<p>If I took out the incrementing line count, is it possible to just match the two lists together using some kind of list comprehension?</p>
<p>For example, if all I wanted from the output was this (no counters, is that possible with list comprehension):</p>
<pre><code># Output:
# directory_0/file_a
# directory_1/file_b
# directory_2/file_c
</code></pre>
<p>Thanks in advance for any help.</p>
| 15
|
2009-02-06T17:42:27Z
| 521,361
|
<pre><code>import os.path
for dir, file in zip(directories, files):
print(os.path.join(dir, file)) # for directories, files
</code></pre>
<p>you can have it as a list comprehension as well, creating list of string with print going after that]</p>
<p>with counter:</p>
<pre><code>for i, (dir, file) in enumerate(zip(directories, files)):
print(i, os.path.join(dir, file))
</code></pre>
| 35
|
2009-02-06T17:49:07Z
|
[
"python",
"arrays",
"loops",
"list"
] |
Python loops with multiple lists?
| 521,321
|
<p><strong><edit></strong>
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:</p>
<pre><code>zip(range(len(files)), files, directories)
</code></pre>
<p><strong></edit></strong></p>
<p>Hi,</p>
<p>I'm in the process of learning Python, but I come from a background where the following pseudocode is typical:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for(i = 0; i < directories.length; i++) {
print (i + 1) + '. ' + directories[i] + '/' + files[i] + '\n'
}
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
</code></pre>
<p>In Python, the way I would write the above right now, would be like this:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for i in range(len(directories)):
print '%s. %s/%s' % ((i + 1), directories[i], files[i]
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
</code></pre>
<p>While reading Dive into Python, Mark Pilgrim says that using for loops for counters is "Visual Basic-style thinking" (<a href="http://diveintopython.net/file_handling/for_loops.html#fileinfo.for.counter">Simple Counters</a>). He goes on to show how to use loops with dictionaries, but never really addresses a python solution in regards to how for loop counters are typically used in other languages.</p>
<p>I was hoping somebody could show me how to properly write the above scenario in Python. Is it possible to do it a different way? </p>
<p>If I took out the incrementing line count, is it possible to just match the two lists together using some kind of list comprehension?</p>
<p>For example, if all I wanted from the output was this (no counters, is that possible with list comprehension):</p>
<pre><code># Output:
# directory_0/file_a
# directory_1/file_b
# directory_2/file_c
</code></pre>
<p>Thanks in advance for any help.</p>
| 15
|
2009-02-06T17:42:27Z
| 521,380
|
<p>Building on Ryan's answer, you can do:</p>
<pre><code>for fileDir in [dir + '/' + file for dir in directories for file in files]:
print(fileDir)
</code></pre>
| -1
|
2009-02-06T17:51:54Z
|
[
"python",
"arrays",
"loops",
"list"
] |
Python loops with multiple lists?
| 521,321
|
<p><strong><edit></strong>
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:</p>
<pre><code>zip(range(len(files)), files, directories)
</code></pre>
<p><strong></edit></strong></p>
<p>Hi,</p>
<p>I'm in the process of learning Python, but I come from a background where the following pseudocode is typical:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for(i = 0; i < directories.length; i++) {
print (i + 1) + '. ' + directories[i] + '/' + files[i] + '\n'
}
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
</code></pre>
<p>In Python, the way I would write the above right now, would be like this:</p>
<pre><code>directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for i in range(len(directories)):
print '%s. %s/%s' % ((i + 1), directories[i], files[i]
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
</code></pre>
<p>While reading Dive into Python, Mark Pilgrim says that using for loops for counters is "Visual Basic-style thinking" (<a href="http://diveintopython.net/file_handling/for_loops.html#fileinfo.for.counter">Simple Counters</a>). He goes on to show how to use loops with dictionaries, but never really addresses a python solution in regards to how for loop counters are typically used in other languages.</p>
<p>I was hoping somebody could show me how to properly write the above scenario in Python. Is it possible to do it a different way? </p>
<p>If I took out the incrementing line count, is it possible to just match the two lists together using some kind of list comprehension?</p>
<p>For example, if all I wanted from the output was this (no counters, is that possible with list comprehension):</p>
<pre><code># Output:
# directory_0/file_a
# directory_1/file_b
# directory_2/file_c
</code></pre>
<p>Thanks in advance for any help.</p>
| 15
|
2009-02-06T17:42:27Z
| 1,626,201
|
<p>If you want to add a counter to any for loop in Python you can use the enumerate() function:</p>
<pre><code>listA = ["A", "B", "C", "D", "E"]
listB = ["a", "b", "c", "d", "e"]
for i, (a, b) in enumerate(zip(listA, listB)):
print "%d) %s, %s" % (i, a, b)
</code></pre>
<p>gives the output:</p>
<pre><code>0) A, a
1) B, b
2) C, c
3) D, d
4) E, e
</code></pre>
| 0
|
2009-10-26T17:37:45Z
|
[
"python",
"arrays",
"loops",
"list"
] |
How does one parse simple inline markup (i.e. *bold*), in Python?
| 521,326
|
<p>How does one implement a parser (in Python) for a subset of wikitext that modifies text, namely:</p>
<pre><code>*bold*, /italics/, _underline_
</code></pre>
<p>I'm converting it to LaTeX, so the conversion is from:</p>
<pre><code>Hello, *world*! Let's /go/.
</code></pre>
<p>to:</p>
<pre><code>Hello \textbf{world}! Let's \textit{go}.
</code></pre>
<p>Though there's nothing specific about it being a conversion to LaTeX (notably except nested cases like "*bold /italics* whatami/" => "textbf{bold \textit{italics} whatami}").</p>
<p>I've looked at <a href="http://stackoverflow.com/questions/154592">existing markup libraries</a>, but they're (a) not quite the wiki language I'd like, and (b) seemingly overpowered for this problem.</p>
<p>I've considered reverse engineering <a href="http://creoleparser.googlecode.com/svn/docs/index.html" rel="nofollow">Creoleparser</a>, but I'd like to know what suggestions others have before I undertake that effort.</p>
<p>Thanks!</p>
| 3
|
2009-02-06T17:43:21Z
| 521,367
|
<p>If your language is small, regular expressions might be the least painful solution:</p>
<pre><code>>>> import re
>>> str = "Hello, *world*! Let's /go/."
>>> str = re.sub(r"\*([^\*]*)\*", r"\textbf{\1}", str)
>>> str = re.sub(r"/([^/]*)/", r"\textit{\1}", str)
>>> str
"Hello, \textbf{world}! Let's \textit{go}."
</code></pre>
| 4
|
2009-02-06T17:50:33Z
|
[
"python",
"parsing",
"wikitext",
"creole"
] |
Why True/False is capitalized in Python?
| 521,476
|
<p>All members are camel case, right? Why True/False but not true/false, which is more relaxed?</p>
| 34
|
2009-02-06T18:13:04Z
| 521,508
|
<p>From <a href="http://www.python.org/dev/peps/pep-0285/">Pep 285</a>:</p>
<blockquote>
<p>Should the constants be called 'True'
and 'False' (similar to
None) or 'true' and 'false' (as in C++, Java and C99)?</p>
<p>=> True and False.</p>
<p>Most reviewers agree that consistency within Python is more
important than consistency with other languages.</p>
</blockquote>
<p>This, as Andrew points out, is probably because <a href="http://docs.python.org/library/constants.html">all (most)? built-in constants are capitalized</a>.</p>
| 49
|
2009-02-06T18:20:10Z
|
[
"python",
"camelcasing"
] |
Why True/False is capitalized in Python?
| 521,476
|
<p>All members are camel case, right? Why True/False but not true/false, which is more relaxed?</p>
| 34
|
2009-02-06T18:13:04Z
| 521,509
|
<p>Here's a <a href="http://mail.python.org/pipermail/python-list/2007-May/440165.html" rel="nofollow">possible explaination</a>:</p>
<blockquote>
<blockquote>
<p>I see that naming conventions are such that classes usually get named
CamelCase. So why are the built-in types named all lowercase (like
list, dict, set, bool, etc.)?</p>
</blockquote>
<p>Because most of them originally were
types and factory functions, not<br />
classes - and a naming convention is
not a strong reason to make backwards
incompatible changes. A different
example: the new builtin type <code>set</code> is
based on (altough not exactly equal
to) the Set class from the sets module</p>
</blockquote>
| 3
|
2009-02-06T18:20:14Z
|
[
"python",
"camelcasing"
] |
Why True/False is capitalized in Python?
| 521,476
|
<p>All members are camel case, right? Why True/False but not true/false, which is more relaxed?</p>
| 34
|
2009-02-06T18:13:04Z
| 521,515
|
<p>All of python's <a href="http://docs.python.org/library/constants.html">built-in constants</a> are capitalized or [upper] CamelCase:</p>
| 10
|
2009-02-06T18:21:40Z
|
[
"python",
"camelcasing"
] |
Why True/False is capitalized in Python?
| 521,476
|
<p>All members are camel case, right? Why True/False but not true/false, which is more relaxed?</p>
| 34
|
2009-02-06T18:13:04Z
| 718,323
|
<p><code>True</code> and <code>False</code> are capitalized in Haskell, the other language which uses indentation as syntax.</p>
| -6
|
2009-04-05T04:11:42Z
|
[
"python",
"camelcasing"
] |
Why True/False is capitalized in Python?
| 521,476
|
<p>All members are camel case, right? Why True/False but not true/false, which is more relaxed?</p>
| 34
|
2009-02-06T18:13:04Z
| 1,656,406
|
<p>I'd say that they're called <code>True</code> and <code>False</code> because they're singletons.</p>
| 0
|
2009-11-01T04:38:33Z
|
[
"python",
"camelcasing"
] |
Comparison function in Python using Lambdas
| 521,505
|
<p>I am trying to understand lambdas and I get the idea but how do I define multiple conditions for a Point2 [x,y] comparison, so something like:</p>
<pre><code>if x1 < x2: -1
if x1 == x2: 0
if x1 > x2: 1
</code></pre>
| 1
|
2009-02-06T18:19:26Z
| 521,517
|
<p>EDIT: Updated to be real Python according to <a href="http://www.python.org/dev/peps/pep-0308/" rel="nofollow">PEP308</a> :) Note that the PEP has interesting information about how this should be parenthesized depending on which version of Python you're using. I won't attempt to reproduce it here - just read the PEP!</p>
<p>How about:</p>
<pre><code>-1 if x1 < x2 else (0 if x1 == x2 else 1)
</code></pre>
<p>(That's without any knowledge of Python lambda expressions, but it's a fairly common way of expressing this logic in a single expression, which I guess is what you're after.)</p>
<p>EDIT: Others have suggested using <code>cmp</code> - I've been assuming that the questioner actually wants more complicated logic, such as providing their own comparisons, but wants the general form of "choose from a few conditions in a single expression".</p>
| 3
|
2009-02-06T18:22:11Z
|
[
"python",
"sorting",
"lambda"
] |
Comparison function in Python using Lambdas
| 521,505
|
<p>I am trying to understand lambdas and I get the idea but how do I define multiple conditions for a Point2 [x,y] comparison, so something like:</p>
<pre><code>if x1 < x2: -1
if x1 == x2: 0
if x1 > x2: 1
</code></pre>
| 1
|
2009-02-06T18:19:26Z
| 521,529
|
<p>The code above is equivalent to:</p>
<pre><code>cmp(x1,x2)
</code></pre>
<p>or in a (ugly) lambda expression:</p>
<pre><code>lambda x1,x2: 1 if x1>x2 else (0 if x1==x2 else -1)
</code></pre>
<p>(works only in Python 2.6 and above).</p>
<p>Normally you should use lambda expressions only for functions like</p>
<pre><code>def fun(...):
return ...
</code></pre>
| 5
|
2009-02-06T18:25:40Z
|
[
"python",
"sorting",
"lambda"
] |
Comparison function in Python using Lambdas
| 521,505
|
<p>I am trying to understand lambdas and I get the idea but how do I define multiple conditions for a Point2 [x,y] comparison, so something like:</p>
<pre><code>if x1 < x2: -1
if x1 == x2: 0
if x1 > x2: 1
</code></pre>
| 1
|
2009-02-06T18:19:26Z
| 521,539
|
<pre><code>my_compare = lambda x1,x2 : cmp(x1, x2)
my_compare( -100, 100 )
</code></pre>
| 4
|
2009-02-06T18:27:04Z
|
[
"python",
"sorting",
"lambda"
] |
Comparison function in Python using Lambdas
| 521,505
|
<p>I am trying to understand lambdas and I get the idea but how do I define multiple conditions for a Point2 [x,y] comparison, so something like:</p>
<pre><code>if x1 < x2: -1
if x1 == x2: 0
if x1 > x2: 1
</code></pre>
| 1
|
2009-02-06T18:19:26Z
| 521,541
|
<p>In such a case, lambda expressions aren't usually the best thing. As Jon Skeet mentioned, you're gonna end with multiple if-else expressions:</p>
<pre><code>lambda x1, x2: -1 if x1 < x2 else (0 if x1 == x2 else -1)
</code></pre>
<p>For your specific problem:</p>
<pre><code>lambda x1, x2: cmp(x1, x2)
</code></pre>
<p>is the way to go.</p>
| 4
|
2009-02-06T18:27:22Z
|
[
"python",
"sorting",
"lambda"
] |
How do i get python's pprint to return a string instead of printing?
| 521,532
|
<p>In other words, what's the sprintf equivalent to pprint? </p>
| 76
|
2009-02-06T18:25:53Z
| 521,545
|
<p>The <a href="http://docs.python.org/library/pprint.html">pprint</a> module has a command named <a href="http://docs.python.org/library/pprint.html#pprint.pformat">pformat</a>, for just that purpose.</p>
<p>From the documentation:</p>
<blockquote>
<p>Return the formatted representation of object as a string. indent,
width and depth will be passed to the PrettyPrinter constructor as
formatting parameters.</p>
</blockquote>
<p>Example:</p>
<pre><code>>>> import pprint
>>> people = [
... {"first": "Brian", "last": "Kernighan"},
... {"first": "Dennis", "last": "Richie"},
... ]
>>> pprint.pformat(people, indent=4)
"[ { 'first': 'Brian', 'last': 'Kernighan'},\n { 'first': 'Dennis', 'last': 'Richie'}]"
</code></pre>
| 123
|
2009-02-06T18:28:30Z
|
[
"python"
] |
How do i get python's pprint to return a string instead of printing?
| 521,532
|
<p>In other words, what's the sprintf equivalent to pprint? </p>
| 76
|
2009-02-06T18:25:53Z
| 521,546
|
<p>Are you looking for <code>pprint.pformat</code>?</p>
| 7
|
2009-02-06T18:29:14Z
|
[
"python"
] |
How do i get python's pprint to return a string instead of printing?
| 521,532
|
<p>In other words, what's the sprintf equivalent to pprint? </p>
| 76
|
2009-02-06T18:25:53Z
| 521,550
|
<p>Assuming you really do mean <code>pprint</code> from the <a href="http://docs.python.org/library/pprint.html">pretty-print library</a>, then you want
the <code>pprint.pformat</code> method.</p>
<p>If you just mean <code>print</code>, then you want <code>str()</code></p>
| 10
|
2009-02-06T18:29:47Z
|
[
"python"
] |
How do i get python's pprint to return a string instead of printing?
| 521,532
|
<p>In other words, what's the sprintf equivalent to pprint? </p>
| 76
|
2009-02-06T18:25:53Z
| 521,553
|
<p>Something like this:</p>
<pre><code>import pprint, StringIO
s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string
</code></pre>
| 0
|
2009-02-06T18:30:04Z
|
[
"python"
] |
How do i get python's pprint to return a string instead of printing?
| 521,532
|
<p>In other words, what's the sprintf equivalent to pprint? </p>
| 76
|
2009-02-06T18:25:53Z
| 6,472,848
|
<pre><code>>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>
</code></pre>
| 8
|
2011-06-24T19:30:38Z
|
[
"python"
] |
How can I get only class variables?
| 521,710
|
<p>I have this class definition:</p>
<pre><code>class cols:
name = 'name'
size = 'size'
date = 'date'
@classmethod
def foo(cls):
print "This is a class method"
</code></pre>
<p>With __dict__ I get all class attributes (members and variables). Also there are the "Internal attributes" too (like __main__). How can I get only the class variables without instantiation?</p>
| 4
|
2009-02-06T19:06:37Z
| 521,728
|
<pre><code>import inspect
inspect.getmembers(cols)
</code></pre>
<p>There are a lot if things you can do with the inspect module: <a href="http://lfw.org/python/inspect.html" rel="nofollow">http://lfw.org/python/inspect.html</a></p>
| 1
|
2009-02-06T19:11:10Z
|
[
"python"
] |
How can I get only class variables?
| 521,710
|
<p>I have this class definition:</p>
<pre><code>class cols:
name = 'name'
size = 'size'
date = 'date'
@classmethod
def foo(cls):
print "This is a class method"
</code></pre>
<p>With __dict__ I get all class attributes (members and variables). Also there are the "Internal attributes" too (like __main__). How can I get only the class variables without instantiation?</p>
| 4
|
2009-02-06T19:06:37Z
| 521,772
|
<p>I wouldn't know a straightforward way, especially since from the interpreter's POV, there is not that much of a difference between a method of a class and any other variable (methods have descriptors, but that's it...).</p>
<p>So when you only want non-callable class members, you have to fiddle around a little:</p>
<pre><code>>>> class cols:
... name = "name"
... @classmethod
... def foo(cls): pass
>>> import inspect
>>> def get_vars(cls):
... return [name for name, obj in cls.__dict__.iteritems()
if not name.startswith("__") and not inspect.isroutine(obj)]
>>> get_vars(cols)
['name']
</code></pre>
| 5
|
2009-02-06T19:20:51Z
|
[
"python"
] |
Is there a way to decode numerical COM error-codes in pywin32
| 521,759
|
<p>Here is part of a stack-trace from a recent run of an unreliable application written in Python which controls another application written in Excel:</p>
<pre><code>pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
</code></pre>
<p>Obviously something has gone wrong ... but what?[1] These COM error codes seem to be excessively cryptic. </p>
<p>How can I decode this error message? Is there a table somewhere that allows me to convert this numerical error code into something more meaningful? </p>
<p>[1] I actually know what went wrong in this case, it was attempting to access a Name prperty on a Range object which did not have a Name property... not all bugs are this easy to find!</p>
| 24
|
2009-02-06T19:18:01Z
| 521,814
|
<p>Yes try the win32api module:</p>
<pre><code>import win32api
e_msg = win32api.FormatMessage(-2147352567)
</code></pre>
<p>You can grab any codes returned from the exception and pass them to FormatMessage. Your example had 2 error codes.</p>
| 5
|
2009-02-06T19:31:24Z
|
[
"python",
"windows",
"excel",
"com",
"pywin32"
] |
Is there a way to decode numerical COM error-codes in pywin32
| 521,759
|
<p>Here is part of a stack-trace from a recent run of an unreliable application written in Python which controls another application written in Excel:</p>
<pre><code>pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
</code></pre>
<p>Obviously something has gone wrong ... but what?[1] These COM error codes seem to be excessively cryptic. </p>
<p>How can I decode this error message? Is there a table somewhere that allows me to convert this numerical error code into something more meaningful? </p>
<p>[1] I actually know what went wrong in this case, it was attempting to access a Name prperty on a Range object which did not have a Name property... not all bugs are this easy to find!</p>
| 24
|
2009-02-06T19:18:01Z
| 531,105
|
<p>You are not doing anything wrong. The first item in your stack trace (the number) is the error code returned by the COM object. The second item is the description associated with the error code which in this case is "Exception Occurred". pywintypes.com_error already called the equivalent of win32api.FormatMessage(errCode) for you. We'll look at the second number in a minute.</p>
<p><em>By the way, you can use the "Error Lookup" utility that comes in Visual Studio (C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\ErrLook.exe) as a quick launching pad to check COM error codes. That utility also calls FormatMessage for you and displays the result. Not all error codes will work with this mechanism, but many will. That's usually my first stop.</em></p>
<p>Error handling and reporting in COM is a bit messy. I'll try to give you some background.</p>
<p>All COM method calls will return a numeric code called an HRESULT that can indicate success or failure. All forms of error reporting in COM build on top of that.</p>
<p>The codes are commonly expressed in hex, although sometimes you will see them as large 32-bit numbers, like in your stack trace. There are all kinds of predefined return codes for common results and problems, or the object can return custom numeric codes for special situations. For example, the value 0 (called S_OK) universally means "No error" and 0x80000002 is E_OUTOFMEMORY. Sometimes the HRESULT codes are returned by the object, sometimes by the COM infrastructure.</p>
<p>A COM object can also choose to provide much richer error information by implementing an interface called IErrorInfo. When an object implements IErrorInfo, it can provide all kinds of detail about what happened, such as a detailed custom error message and even the name of a help file that describes the problem. In VB6 and VBA. the <code>Err</code> object allows you to access all that information (<code>Err.Description</code>, etc).</p>
<p>To complicate matters, late bound COM objects (which use a mechanism called COM Automation or IDispatch) add some layers that need to be peeled off to get information out. Excel is usually manipulated via late binding.</p>
<p>Now let's look at your situation again. What you are getting as the first number is a fairly generic error code: DISP_E_EXCEPTION. <em>Note: you can usually figure out the official name of an HRESULT by googling the number, although sometimes you will have to use the hex version to find anything useful.</em></p>
<p>Errors that begin with DISP_ are IDISPATCH error codes. The error loosely means "There was a COM exception thrown by the object", with more information packed elsewhere (although I don't quite know where; I'll have to look it up).</p>
<p>From what I understand of pywintypes.com_error, the last number in your message is the actual error code that was returned by the object during the exception. It's the actual numeric code that you would get out of VBA's <code>Err.Number</code>.</p>
<p>Unfortunately, that second code -2146788248 (0x800A9C68) is in the range reserved for custom application-defined error messages (in VBA: <code>VbObjectError + someCustomErrorNumber</code>), so there is no centralized meaning. The same number can mean entirely different things for different programs.</p>
<p>In this case, we have reached a dead end:</p>
<blockquote>
<p>The error code is "custom", and the application needs to document what it is, except that Excel doesn't. Also, Excel (or the actual source of the error) doesn't seem to be providing any more information via IErrorInfo.</p>
</blockquote>
<p>Excel is notorious (to me at least) for cryptic error codes from automation and obscure situations that cause them. This is especially so for errors that one could consider "design-time errors" ("you should have known better than calling a method that doesn't exist in the object"). Instead of a nice "Could not read the Name property", you get "<strong><em>Run-time error '1004': Application defined or object-defined error</em></strong>" (which I just got by trying to access a Name property on a Range, from VBA in Excel). That is NOT very helpful.</p>
<p>The problem is not routed on Python or it's interface to Excel. Excel itself doesn't explain what happened, even to VBA.</p>
<p>However, the general procedure above remains valid. If you get an error from Excel in the future, you might get a better error message that you can track the same way.</p>
<p>Good luck!</p>
| 33
|
2009-02-10T05:01:04Z
|
[
"python",
"windows",
"excel",
"com",
"pywin32"
] |
Is there a way to decode numerical COM error-codes in pywin32
| 521,759
|
<p>Here is part of a stack-trace from a recent run of an unreliable application written in Python which controls another application written in Excel:</p>
<pre><code>pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
</code></pre>
<p>Obviously something has gone wrong ... but what?[1] These COM error codes seem to be excessively cryptic. </p>
<p>How can I decode this error message? Is there a table somewhere that allows me to convert this numerical error code into something more meaningful? </p>
<p>[1] I actually know what went wrong in this case, it was attempting to access a Name prperty on a Range object which did not have a Name property... not all bugs are this easy to find!</p>
| 24
|
2009-02-06T19:18:01Z
| 5,326,994
|
<p>Do it like this:</p>
<pre><code>try:
[whatever code]
except pythoncom.com_error as error:
print(win32api.FormatMessage(error.excepinfo[5]))
</code></pre>
<p>More information on digesting the pythoncom.com_error object here: <a href="http://docs.activestate.com/activepython/3.2/pywin32/com_error.html" rel="nofollow">http://docs.activestate.com/activepython/3.2/pywin32/com_error.html</a></p>
| 5
|
2011-03-16T14:49:34Z
|
[
"python",
"windows",
"excel",
"com",
"pywin32"
] |
Is there a way to decode numerical COM error-codes in pywin32
| 521,759
|
<p>Here is part of a stack-trace from a recent run of an unreliable application written in Python which controls another application written in Excel:</p>
<pre><code>pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
</code></pre>
<p>Obviously something has gone wrong ... but what?[1] These COM error codes seem to be excessively cryptic. </p>
<p>How can I decode this error message? Is there a table somewhere that allows me to convert this numerical error code into something more meaningful? </p>
<p>[1] I actually know what went wrong in this case, it was attempting to access a Name prperty on a Range object which did not have a Name property... not all bugs are this easy to find!</p>
| 24
|
2009-02-06T19:18:01Z
| 10,641,263
|
<p>Specifically for pythoncom, the errors codes that result are more than cryptic. This is because pythoncom represents them internally as a 32bit signed integer, when the correct representation is a 32bit <em>unsigned</em> integer. As a result, the conversion that you end up seeing in the stack trace is incorrect.</p>
<p>In particular, your exception, according to pythoncom, is -2147352567, and your (for lack of a better word) Err.Number is -2146788248.</p>
<p>This however causes some issues when watching for specific errors, like below:</p>
<pre><code>DISP_E_EXCEPTION = 0x80020009
#...
#except pywintypes.com_error as e:
# print repr(e)
# #pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
# hr = e.hresult
hr = -2147352567
if hr == DISP_E_EXCEPTION:
pass #This never occurs
else:
raise
</code></pre>
<p>To see why this has issues, lets look into these error codes:</p>
<pre><code>>>> DISP_E_EXCEPTION = 0x80020009
>>> DISP_E_EXCEPTION
2147614729L
>>> my_hr = -2147352567
>>> my_hr == DISP_E_EXCEPTION
False
</code></pre>
<p>Again, this is because python sees the constant declared as positive, and pythoncom's incorrect declaration interpreted it as negative. Of course, the most obvious solution fails:</p>
<pre><code>>>> hex(my_hr)
'-0x7ffdfff7'
</code></pre>
<p>The solution is to properly interpret the number. Luckily, pythoncom's representation is reversible. We need to interpret the negative number as a 32 bit signed integer, then interpret <em>that</em> as an unsigned integer:</p>
<pre><code>def fix_com_hresult(hr):
import struct
return struct.unpack("L", struct.pack("l", hr))[0]
>>> DISP_E_EXCEPTION = 0x80020009
>>> my_hr = -2147352567
>>> my_hr == DISP_E_EXCEPTION
False
>>> fixed_hr = fix_com_hresult(my_hr)
>>> fixed_hr
2147614729L
>>> fixed_hr == DISP_E_EXCEPTION
True
</code></pre>
<p>So, putting it all together, you need to run fix_com_hresult() on that result from pythoncom, essentially all the time.</p>
<p>Since normally you need to do this when checking for exceptions, I created these functions:</p>
<pre><code>def fix_com_exception(e):
e.hresult = fix_com_hresult(e.hresult)
e.args = [e.hresult] + list(e.args[1:])
return e
def fix_com_hresult(hr):
import struct
return struct.unpack("L", struct.pack("l", hr))[0]
</code></pre>
<p>which can then be used how you expect:</p>
<pre><code>DISP_E_EXCEPTION = 0x80020009
try:
#failing call
except pywintypes.com_error as e:
print repr(e)
#pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
fix_com_exception(e)
print repr(e)
#pywintypes.com_error: (2147614729L, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
if e.hresult == DISP_E_EXCEPTION:
print "Got expected failure"
else:
raise
</code></pre>
<p>I was unable to find a MSDN document listing all HRESULTs, but I found this: <a href="http://www.megos.ch/support/doserrors_e.txt" rel="nofollow">http://www.megos.ch/support/doserrors_e.txt</a></p>
<p>Also, since you have it, fix_com_hresult() should also be run on your extended error code (-2146788248), but as Euro Micelli said, it doesn't help you in this particular instance :)</p>
| 0
|
2012-05-17T18:15:44Z
|
[
"python",
"windows",
"excel",
"com",
"pywin32"
] |
Is there a way to decode numerical COM error-codes in pywin32
| 521,759
|
<p>Here is part of a stack-trace from a recent run of an unreliable application written in Python which controls another application written in Excel:</p>
<pre><code>pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
</code></pre>
<p>Obviously something has gone wrong ... but what?[1] These COM error codes seem to be excessively cryptic. </p>
<p>How can I decode this error message? Is there a table somewhere that allows me to convert this numerical error code into something more meaningful? </p>
<p>[1] I actually know what went wrong in this case, it was attempting to access a Name prperty on a Range object which did not have a Name property... not all bugs are this easy to find!</p>
| 24
|
2009-02-06T19:18:01Z
| 29,101,263
|
<p>No-one has yet mentioned the <code>strerror</code> attribute of the <a href="http://timgolden.me.uk/pywin32-docs/com_error.html" rel="nofollow"><code>pywintypes.com_error</code> Exception</a>. This returns the result of <code>FormatMessage</code> for the error code. So instead of doing it yourself like this</p>
<pre><code>try:
[whatever code]
except pythoncom.com_error as error:
print(win32api.FormatMessage(error.excepinfo[5]))
</code></pre>
<p>You can just do this:</p>
<pre><code>try:
[whatever code]
except pythoncom.com_error as error:
print(error.strerror)
</code></pre>
<p>Note it will return <code>None</code> if you have a non-standard <code>HRESULT</code> :(</p>
| 1
|
2015-03-17T14:09:05Z
|
[
"python",
"windows",
"excel",
"com",
"pywin32"
] |
How to use storeHtmlSource in python code (Selenium RC)
| 522,229
|
<p>I found storeHtmlSource method description in <a href="http://seleniumhq.org/projects/core/reference.html" rel="nofollow">Selenium reference</a>, but can't figure out how to use it in python code I generated by exporting recording of my actions from the Selenium IDE.</p>
<p>I need to pass the html source code of the current page into a function for processing. How to do that? Can anyone show example of code for calling this method? Could it at all to be called from python?</p>
| 0
|
2009-02-06T21:23:49Z
| 557,371
|
<p>I can't speak for Python, but check out the getHtmlSource method for the Java API of the <a href="http://release.seleniumhq.org/selenium-remote-control/1.0-beta-2/doc/java/com/thoughtworks/selenium/Selenium.html" rel="nofollow">Selenium interface</a>. It explains what it does pretty clearly.</p>
| 1
|
2009-02-17T15:29:53Z
|
[
"python",
"html",
"selenium"
] |
Finding first and last index of some value in a list in Python
| 522,372
|
<p>Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:</p>
<pre><code>verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
</code></pre>
| 23
|
2009-02-06T22:00:00Z
| 522,401
|
<p>Sequences have a method <code>index(value)</code> which returns index of first occurrence.<br>
You can run it on <code>verts[::-1]</code> to find out the last index.</p>
| 39
|
2009-02-06T22:05:06Z
|
[
"python",
"list",
"search"
] |
Finding first and last index of some value in a list in Python
| 522,372
|
<p>Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:</p>
<pre><code>verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
</code></pre>
| 23
|
2009-02-06T22:00:00Z
| 6,194,807
|
<p>Use <code>i1 = yourlist.index(yourvalue)</code> and <code>i2 = yourlist.rindex(yourvalue).</code> </p>
| 10
|
2011-05-31T23:48:50Z
|
[
"python",
"list",
"search"
] |
Finding first and last index of some value in a list in Python
| 522,372
|
<p>Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:</p>
<pre><code>verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
</code></pre>
| 23
|
2009-02-06T22:00:00Z
| 18,157,104
|
<p>if you are searching for the index of the last occurance of myvalue in mylist:</p>
<pre><code>len(mylist) - mylist[::-1].index(myvalue) - 1
</code></pre>
| 7
|
2013-08-09T23:23:39Z
|
[
"python",
"list",
"search"
] |
Finding first and last index of some value in a list in Python
| 522,372
|
<p>Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:</p>
<pre><code>verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
</code></pre>
| 23
|
2009-02-06T22:00:00Z
| 29,525,218
|
<p>As a small helper function:</p>
<pre><code>def rindex(mylist, myvalue):
return len(mylist) - mylist[::-1].index(myvalue) - 1
</code></pre>
| 4
|
2015-04-08T20:57:56Z
|
[
"python",
"list",
"search"
] |
Is there a way to loop through a sub section of a list in Python
| 522,430
|
<p>So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it?</p>
<p>I don't see a way by using the for each and for range techniques.</p>
| 3
|
2009-02-06T22:15:20Z
| 522,439
|
<pre><code>for element in allElements[400:501]:
# do something
</code></pre>
<p>These are <a href="http://docs.python.org/reference/expressions.html#id8" rel="nofollow">slices</a> and generate a sublist of the whole list. They are one of the main elements of Python.</p>
| 7
|
2009-02-06T22:16:58Z
|
[
"python",
"loops",
"list"
] |
Is there a way to loop through a sub section of a list in Python
| 522,430
|
<p>So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it?</p>
<p>I don't see a way by using the for each and for range techniques.</p>
| 3
|
2009-02-06T22:15:20Z
| 522,442
|
<pre><code>for x in thousand[400:500]:
pass
</code></pre>
<p>If you are working with an iterable instead of a list, you should use <a href="http://docs.python.org/library/itertools">itertools</a>:</p>
<pre><code>import itertools
for x in itertools.islice(thousand, 400, 500):
pass
</code></pre>
<p>If you need to loop over <code>thousand[500]</code>, then use 501 as the latter index. This will work even if <code>thousand[501]</code> is not a valid index.</p>
| 22
|
2009-02-06T22:17:21Z
|
[
"python",
"loops",
"list"
] |
Is there a way to loop through a sub section of a list in Python
| 522,430
|
<p>So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it?</p>
<p>I don't see a way by using the for each and for range techniques.</p>
| 3
|
2009-02-06T22:15:20Z
| 524,254
|
<p>Using </p>
<pre><code>for element in allElements[400:501]:
doSomething(element)
</code></pre>
<p>makes Python create new object, and might have some impact on memory usage.</p>
<p>Instead I'd use:</p>
<pre><code>for index in xrange(400, 501):
doSomething(allElements[index])
</code></pre>
<p>This way also enables you to manipulate list indexes during iteration.</p>
<p>EDIT: In Python 3.0 you can use <code>range()</code> instead of <code>xrange()</code>, but in 2.5 and earlier versions <code>range()</code> creates a list while <code>xrange()</code> creates a generator, which eats less of your precious RAM.</p>
| 2
|
2009-02-07T18:08:58Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 522,569
|
<pre><code>for i in range(len(ints)):
print i, ints[i]
</code></pre>
| 37
|
2009-02-06T22:49:23Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 522,576
|
<p>Old fashioned way:</p>
<pre><code>for ix in range(len(ints)):
print ints[ix]
</code></pre>
<p>List comprehension:</p>
<pre><code>[ (ix, ints[ix]) for ix in range(len(ints))]
>>> ints
[1, 2, 3, 4, 5]
>>> for ix in range(len(ints)): print ints[ix]
...
1
2
3
4
5
>>> [ (ix, ints[ix]) for ix in range(len(ints))]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> lc = [ (ix, ints[ix]) for ix in range(len(ints))]
>>> for tup in lc:
... print tup
...
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
>>>
</code></pre>
| 6
|
2009-02-06T22:52:06Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 522,578
|
<p>Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.</p>
<p>The better option is to use the built-in function <a href="https://docs.python.org/3/library/functions.html#enumerate"><code>enumerate()</code></a>, available in both Python 2 and 3:</p>
<pre><code>for idx, val in enumerate(ints):
print(idx, val)
</code></pre>
<p>Check out <a href="https://www.python.org/dev/peps/pep-0279/">PEP 279</a> for more.</p>
| 2,666
|
2009-02-06T22:52:36Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 10,459,739
|
<p>According to this discussion: <a href="http://bytes.com/topic/python/answers/464012-objects-list-index">http://bytes.com/topic/python/answers/464012-objects-list-index</a></p>
<p>Loop counter iteration</p>
<p>The current idiom for looping over the indices makes use of the built-in 'range' function:</p>
<pre><code>for i in range(len(sequence)):
# work with index i
</code></pre>
<p>Looping over both elements and indices can be achieved either by the old idiom or by using the new 'zip' built-in function[2]:</p>
<pre><code>for i in range(len(sequence)):
e = sequence[i]
# work with index i and element e
</code></pre>
<p>or</p>
<pre><code>for i, e in zip(range(len(sequence)), sequence):
# work with index i and element e
</code></pre>
<p>via <a href="http://www.python.org/dev/peps/pep-0212/">http://www.python.org/dev/peps/pep-0212/</a></p>
| 5
|
2012-05-05T07:10:07Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 19,642,174
|
<p>I don't know if the following is pythonic or not, but it uses the Python function <code>enumerate</code> and prints the enumerator and the value.</p>
<pre><code>int_list = [8, 23, 45, 12, 78]
for index in enumerate(int_list):
print index
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)
</code></pre>
| 5
|
2013-10-28T18:17:06Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 23,886,515
|
<p>It's pretty simple to start it from <code>1</code> other than <code>0</code>:</p>
<pre><code>for index in enumerate(iterable, start=1):
print index
</code></pre>
<h2>Note</h2>
<p>Important hint, though a little misleading, since <code>index</code> will be a <code>tuple</code> <code>(idx, item)</code> here.
Good to go.</p>
| 64
|
2014-05-27T10:04:52Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 26,350,953
|
<p>The better way to get the index of each element of the sequence:</p>
<pre><code>for indx , value in enumerate(arraySquence):
print (indx , value )
</code></pre>
| -6
|
2014-10-14T00:32:03Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 28,072,982
|
<blockquote>
<h1>Using a for loop, how do I access the loop index, from 1 to 5 in this case?</h1>
</blockquote>
<p>Use <code>enumerate</code>:</p>
<pre><code>for index, item in enumerate(items):
print(index, item)
</code></pre>
<p>And note that indexes start at zero, so you would get 0 to 4 with this. If you want the count, I explain that below.</p>
<h1>Unidiomatic control flow</h1>
<p>What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:</p>
<blockquote>
<pre><code>index = 0 # Python's indexing starts at zero
for item in items: # Python's for loops are a "for each" loop
print(index, item)
index += 1
</code></pre>
</blockquote>
<p>Or in languages that do not have a for-each loop:</p>
<blockquote>
<pre><code>index = 0
while index < len(items):
print(index, items[index])
index += 1
</code></pre>
</blockquote>
<p>or sometimes more commonly (but unidiomatically) found in Python:</p>
<blockquote>
<pre><code>for index in range(len(items)):
print(index, items[index])
</code></pre>
</blockquote>
<h1>Use the Enumerate Function</h1>
<p>Python's <a href="https://docs.python.org/2/library/functions.html#enumerate"><code>enumerate</code> function</a> reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an <code>enumerate</code> object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:</p>
<pre><code>for index, item in enumerate(items, start=0): # default is zero
print(index, item)
</code></pre>
<p>This code sample is fairly well the <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#index-item-2-enumerate">canonical</a> example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.</p>
<h2>Getting a count</h2>
<p>Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with <code>1</code> and the final number will be your count.</p>
<pre><code>for count, item in enumerate(items, start=1): # default is zero
print(item)
print('there were {0} items printed'.format(count))
</code></pre>
<p>The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.</p>
<hr>
<h2>Breaking it down - a step by step explanation</h2>
<p>To break these examples down, say we have a list of items that we want to iterate over with an index:</p>
<pre><code>items = ['a', 'b', 'c', 'd', 'e']
</code></pre>
<p>Now we pass this iterable to enumerate, creating an enumerate object:</p>
<pre><code>enumerate_object = enumerate(items) # the enumerate object
</code></pre>
<p>We can pull the first item out of this iterable that we would get in a loop with the <code>next</code> function:</p>
<pre><code>iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)
</code></pre>
<p>And we see we get a tuple of <code>0</code>, the first index, and <code>'a'</code>, the first item:</p>
<pre><code>(0, 'a')
</code></pre>
<p>we can use what is referred to as "<a href="https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences">sequence unpacking</a>" to extract the elements from this two-tuple:</p>
<pre><code>index, item = iteration
# 0, 'a' = (0, 'a') # essentially this.
</code></pre>
<p>and when we inspect <code>index</code>, we find it refers to the first index, 0, and <code>item</code> refers to the first item, <code>'a'</code>.</p>
<pre><code>>>> print(index)
0
>>> print(item)
a
</code></pre>
<h1>Conclusion</h1>
<ul>
<li>Python indexes start at zero</li>
<li>To get these indexes from an iterable as you iterate over it, use the enumerate function</li>
<li>Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:</li>
</ul>
<p>So do this:</p>
<pre><code>for index, item in enumerate(items, start=0): # Python indexes start at zero
print(index, item)
</code></pre>
| 155
|
2015-01-21T17:11:49Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 28,350,332
|
<pre><code>ints = [9, 23, 45, 12, 78]
ints.extend([1,2,3,4,5,6,7,8])
for idx, val in enumerate(ints):
print(idx,val)
</code></pre>
<p>This way you can extend a list. Extend means you can add multiple values at a time.</p>
<p>To append this list you have to write the code given below:</p>
<pre><code>ints = [9, 23, 45, 12, 78]
ints.append([1])
for idx, val in enumerate(ints):
print(idx,val)
</code></pre>
<p>This way you can add a single value at a time. If you write <code>ints.append([1])</code> so this will create a sub list for this element.</p>
| 6
|
2015-02-05T17:28:25Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 30,441,272
|
<p>First of all, the indexes will be from 0 to 4. Programming languages start counting from 0; don't forget that or you will come across an index out of bounds exception. All you need in the for loop is a variable counting from 0 to 4 like so:</p>
<pre><code>for x in range(0, 5):
</code></pre>
<p>Keep in mind that I wrote 0 to 5 because the loop stops one number before the max. :)</p>
<p>To get the value of an index use</p>
<pre><code>list[index]
</code></pre>
| 4
|
2015-05-25T15:08:34Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 30,441,543
|
<p>You can do it with this code:</p>
<pre><code>ints = [8, 23, 45, 12, 78]
index = 0
for value in (ints):
index +=1
print index, value
</code></pre>
<p>Use this code if you need to reset the index value at the end of the loop:</p>
<pre><code>ints = [8, 23, 45, 12, 78]
index = 0
for value in (ints):
index +=1
print index, value
if index >= len(ints)-1:
index = 0
</code></pre>
| 1
|
2015-05-25T15:26:58Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 33,332,541
|
<p>May be cleaner sometimes:</p>
<pre><code>index_i = 0
for i in R
...
index_i += 1
</code></pre>
| -2
|
2015-10-25T17:12:47Z
|
[
"python",
"loops",
"list"
] |
Accessing the index in Python 'for' loops
| 522,563
|
<p>How do I access the index itself for a list like the following?</p>
<pre><code>ints = [8, 23, 45, 12, 78]
</code></pre>
<p>When I loop through it using a <code>for</code> loop, how do I access the loop index, from 1 to 5 in this case?</p>
| 1,512
|
2009-02-06T22:47:54Z
| 38,764,000
|
<p>The fastest way to access indexes of list within loop in <strong>Python 2.7</strong> is to use the <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow">range method</a> for small lists and <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow">enumerate method</a> for medium and huge size lists.</p>
<p>Please see <strong>different approaches</strong> which can be used to iterate over list and access index value and <strong>their performance metrics</strong> (which I suppose would be useful for you) in code samples below:</p>
<pre><code>from timeit import timeit
# Using range
def range_loop(iterable):
for i in range(len(iterable)):
1 + iterable[i]
# Using xrange
def xrange_loop(iterable):
for i in xrange(len(iterable)):
1 + iterable[i]
# Using enumerate
def enumerate_loop(iterable):
for i, val in enumerate(iterable):
1 + val
# Manual indexing
def manual_indexing_loop(iterable):
index = 0
for item in iterable:
1 + item
index += 1
</code></pre>
<p>See performance metrics for each method below:</p>
<pre><code>from timeit import timeit
def measure(l, number=10000):
print "Measure speed for list with %d items" % len(l)
print "xrange: ", timeit(lambda :xrange_loop(l), number=number)
print "range: ", timeit(lambda :range_loop(l), number=number)
print "enumerate: ", timeit(lambda :enumerate_loop(l), number=number)
print "manual_indexing: ", timeit(lambda :manual_indexing_loop(l), number=number)
measure(range(1000))
# Measure speed for list with 1000 items
# xrange: 0.758321046829
# range: 0.701184988022
# enumerate: 0.724966049194
# manual_indexing: 0.894635915756
measure(range(10000))
# Measure speed for list with 100000 items
# xrange: 81.4756360054
# range: 75.0172479153
# enumerate: 74.687623024
# manual_indexing: 91.6308541298
measure(range(10000000), number=100)
# Measure speed for list with 10000000 items
# xrange: 82.267786026
# range: 84.0493988991
# enumerate: 78.0344707966
# manual_indexing: 95.0491430759
</code></pre>
<p>As the result, using <code>range</code> method is the fastest one up to list with 1000 items. For list with size > 10 000 items <code>enumerate</code> is the winner.</p>
<p>Adding some useful links below:</p>
<ul>
<li><p><em><a href="http://stackoverflow.com/questions/94935/what-is-the-difference-between-range-and-xrange-functions-in-python-2-x">What is the difference between range and xrange functions in Python 2.X?</a></em></p></li>
<li><p><em><a href="http://stackoverflow.com/questions/4852944/what-is-faster-for-loop-using-enumerate-or-for-loop-using-xrange-in-python">What is faster for loop using enumerate or for loop using xrange in Python?</a></em></p></li>
<li><p><em><a href="http://stackoverflow.com/questions/11990105/rangelenlist-or-enumeratelist">range(len(list)) or enumerate(list)?</a></em></p></li>
</ul>
| 4
|
2016-08-04T09:49:50Z
|
[
"python",
"loops",
"list"
] |
AppEngine: Maintaining DataStore Consistency When Creating Records
| 522,586
|
<p>I've hit a small dilemma! I have a handler called vote; when it is invoked it sets a user's vote to whatever they have picked. To remember what options they previously picked, I store a VoteRecord options which details what their current vote is set to.</p>
<p>Of course, the first time they vote, I have to create the object and store it. But successive votes should just change the value of the existing VoteRecord. But he comes the problem: under some circumstances two VoteRecords can be created. It's rare (only happened once in all 500 votes we've seen so far) but still bad when it does.</p>
<p>The issue happens because two separate handlers both do essentially this:</p>
<pre><code>query = VoteRecord.all().filter('user =', session.user).filter('poll =', poll)
if query.count(1) > 0:
vote = query[0]
poll.votes[vote.option] -= 1
poll.votes[option] += 1
poll.put()
vote.option = option
vote.updated = datetime.now()
vote.put()
else:
vote = VoteRecord()
vote.user = session.user
vote.poll = poll
vote.option = option
vote.put()
poll.votes[option] += 1
poll.put()
session.user.votes += 1
session.user.xp += 3
session.user.put()
incr('votes')
</code></pre>
<p>My question is: what is the most effective and fastest way to handle these requests while ensuring that no request is lost and no request creates two VoteRecord objects?</p>
| 3
|
2009-02-06T22:55:04Z
| 523,057
|
<p>The issue is this part: </p>
<pre><code>if vote.count(1) == 0:
obj = VoteRecord()
obj.user = user
obj.option = option
obj.put()
</code></pre>
<p>Without a transaction, your code could run in this order in two interpreter instances:</p>
<pre><code>if vote.count(1) == 0:
obj = VoteRecord()
obj.user = user
if vote.count(1) == 0:
obj = VoteRecord()
obj.user = user
obj.option = option
obj.put()
obj.option = option
obj.put()
</code></pre>
<p>Or any weird combination thereof. The problem is the count test runs again before the put has occured, so the second thread goes through the first part of the conditional instead of the second.</p>
<p>You can fix this by putting the code in a function and then using</p>
<pre><code>db.run_in_transaction()
</code></pre>
<p>to run the function.</p>
<p>Problem is you seem to be relying on the count of objects returned by a query for your decision logic that needs to be put in the transaction. If you read the Google I/O talks or look at the group you'll see that this is not recommended. That's because you can't transactionalize a query. Instead, you should store the count as an entity value somewhere, query for it <em>outside</em> of the transaction function, and then pass the key for that entity to your transaction function.</p>
<p>Here's an example of a transaction function that checks an entity property. It's passed the key as a parameter:</p>
<pre><code>def checkAndLockPage(pageKey):
page = db.get(pageKey)
if page.locked:
return False
else:
page.locked = True
page.put()
return True
</code></pre>
<p>Only one user at a time can lock this entity, and there will never be any duplicate locks.</p>
| 1
|
2009-02-07T03:19:59Z
|
[
"python",
"google-app-engine",
"gae-datastore",
"consistency",
"gae-ds-transactions"
] |
AppEngine: Maintaining DataStore Consistency When Creating Records
| 522,586
|
<p>I've hit a small dilemma! I have a handler called vote; when it is invoked it sets a user's vote to whatever they have picked. To remember what options they previously picked, I store a VoteRecord options which details what their current vote is set to.</p>
<p>Of course, the first time they vote, I have to create the object and store it. But successive votes should just change the value of the existing VoteRecord. But he comes the problem: under some circumstances two VoteRecords can be created. It's rare (only happened once in all 500 votes we've seen so far) but still bad when it does.</p>
<p>The issue happens because two separate handlers both do essentially this:</p>
<pre><code>query = VoteRecord.all().filter('user =', session.user).filter('poll =', poll)
if query.count(1) > 0:
vote = query[0]
poll.votes[vote.option] -= 1
poll.votes[option] += 1
poll.put()
vote.option = option
vote.updated = datetime.now()
vote.put()
else:
vote = VoteRecord()
vote.user = session.user
vote.poll = poll
vote.option = option
vote.put()
poll.votes[option] += 1
poll.put()
session.user.votes += 1
session.user.xp += 3
session.user.put()
incr('votes')
</code></pre>
<p>My question is: what is the most effective and fastest way to handle these requests while ensuring that no request is lost and no request creates two VoteRecord objects?</p>
| 3
|
2009-02-06T22:55:04Z
| 932,242
|
<p>The easiest way to do this is to use key names for your vote objects, and use Model.get_or_insert. First, come up with a naming scheme for your key names - naming it after the poll is a good idea - and then do a get_or_insert to fetch or create the relevant entity:</p>
<pre><code>vote = VoteRecord.get_or_insert(pollname, parent=session.user, user=session.user, poll=poll, option=option)
if vote.option != option:
# Record already existed; we need to update it
vote.option = option
vote.put()
</code></pre>
| 3
|
2009-05-31T15:29:25Z
|
[
"python",
"google-app-engine",
"gae-datastore",
"consistency",
"gae-ds-transactions"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.