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 |
|---|---|---|---|---|---|---|---|---|---|
Strip all non-numeric characters (except for ".") from a string in Python | 947,776 | <p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p>
<pre><code>val = ''.join([c for c in val if c in '1234567890.'])
</code></pre>
<p>What would you do?</p>
| 37 | 2009-06-03T23:12:00Z | 951,765 | <p>If the set of characters were larger, using sets as below might be faster. As it is, this is a bit slower than a.py.</p>
<pre><code>dec = set('1234567890.')
a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw'
for i in xrange(1000000):
''.join(ch for ch in a if ch in dec)</code></pre>
<p>At least on my system, you can save a tiny bit of time (and memory if your string were long enough to matter) by using a generator expression instead of a list comprehension in a.py:</p>
<pre><code>a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw'
for i in xrange(1000000):
''.join(c for c in a if c in '1234567890.')</code></pre>
<p>Oh, and here's the fastest way I've found by far on this test string (much faster than regex) if you are doing this many, many times and are willing to put up with the overhead of building a couple of character tables.</p>
<pre><code>chrs = ''.join(chr(i) for i in xrange(256))
deletable = ''.join(ch for ch in chrs if ch not in '1234567890.')
a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw'
for i in xrange(1000000):
a.translate(chrs, deletable)</code></pre>
<p>On my system, that runs in ~1.0 seconds where the regex b.py runs in ~4.3 seconds.</p>
| 2 | 2009-06-04T16:49:37Z | [
"python"
] |
Strip all non-numeric characters (except for ".") from a string in Python | 947,776 | <p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p>
<pre><code>val = ''.join([c for c in val if c in '1234567890.'])
</code></pre>
<p>What would you do?</p>
| 37 | 2009-06-03T23:12:00Z | 8,718,713 | <pre><code>import string
filter(lambda c: c in string.digits + '.', s)
</code></pre>
| 2 | 2012-01-03T21:15:16Z | [
"python"
] |
Strip all non-numeric characters (except for ".") from a string in Python | 947,776 | <p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p>
<pre><code>val = ''.join([c for c in val if c in '1234567890.'])
</code></pre>
<p>What would you do?</p>
| 37 | 2009-06-03T23:12:00Z | 35,552,565 | <p>Mine solution is simpler using regex:</p>
<pre><code>import re
re.sub("[^0-9^.]", "", data)
</code></pre>
| 1 | 2016-02-22T11:34:56Z | [
"python"
] |
How can I get an accurate absolute url from get_absolute_url with an included urls.py in Django? | 947,797 | <p>I've building a app right now that I'm trying to keep properly decoupled from the other apps in my Django project (feel free to lecture me on keeping Django apps decoupled, I'd be happy to learn more any/all the time).</p>
<p>My problem is this: <strong>The get_ absolute_url() method I've written is returning a relative path</strong> based on my view. I think it's wrong to have to add a special named view in the project urls.py just so I can have absolute urls in my app, and I can't figure out what I'm doing wrong. So if someone can help me out, I'll really appreciate it (and mention you when I release this sucker!)</p>
<p>I have a project-level urls.py that includes another urls.py based on the URL pattern like so (the names are verbose for this example only):</p>
<p>project-urls.py</p>
<pre><code>urlpatterns = patterns('',
('^$', direct_to_template, {'template': 'base.html'}),
(r'^app', include('project.app.urls')),
)
</code></pre>
<p>app-urls.py</p>
<pre><code>urlpatterns = patterns('',
url(r'(?P<slug>[-\w]+)?/?$', 'app.views.home', name='app_home'),
)
</code></pre>
<p>Now, in my Model, I have something like this:</p>
<pre><code>class AppModel(models.Model):
title = models.CharField(_('title'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
@permalink
def get_absolute_url(self):
return ('app_home', None, {'slug': self.slug})
</code></pre>
<p>When I call <strong>{{ AppInstance.get_ absolute_url }}</strong> in the template, I get something like this:</p>
<pre><code>/slug-is-here
</code></pre>
<p>Which is obvs not absolute & makes sense based on my urls.py. What should I change to get a real absolute url while keeping this app clean & not couple it too deeply w/the project?</p>
| 0 | 2009-06-03T23:16:41Z | 948,239 | <p>Welp, </p>
<p>It turns out that when I was seeing this:</p>
<pre><code>/slug-is-here
</code></pre>
<p>I should have looked closer. What was really happening was:</p>
<pre><code>/app-pathslug-is-here
</code></pre>
<p>I was missing a trailing slash on my app's regex in my project urls.py.</p>
<p>So yea. let that be a lesson to y'all.</p>
| 0 | 2009-06-04T01:52:26Z | [
"python",
"regex",
"django",
"url",
"models"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 947,820 | <p>There is a <a href="http://docs.python.org/tutorial/interactive.html?highlight=atexit">way</a> to do it. Store the file in <code>~/.pystartup</code>...</p>
<pre><code># Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.
import atexit
import os
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
</code></pre>
<p>and then set the environment variable <code>PYTHONSTARTUP</code> in your shell (e.g. in <code>~/.bashrc</code>):</p>
<pre class="lang-bash prettyprint-override"><code>export PYTHONSTARTUP=$HOME/.pystartup
</code></pre>
<p>You can also add this to get autocomplete for free:</p>
<pre><code>readline.parse_and_bind('tab: complete')
</code></pre>
<p>Please note that this will only work on *nix systems. As readline is only available in Unix platform.</p>
| 68 | 2009-06-03T23:23:20Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 947,846 | <p><a href="http://ipython.scipy.org/moin/">IPython</a> is extremely useful if you like using interactive sessions. For example for your usecase there is the <em>%save</em> magic command, you just input <em>%save my_useful_session 10-20 23</em> to save input lines 10 to 20 and 23 to my_useful_session.py. (to help with this, every line is prefixed by its number)</p>
<p>Look at the videos on the documentation page to get a quick overview of the features.</p>
| 225 | 2009-06-03T23:34:21Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 948,006 | <p>Also, <a href="http://blog.fishsoup.net/2007/11/10/reinteract-better-interactive-python/">reinteract</a> gives you a notebook-like interface to a Python session.</p>
| 11 | 2009-06-04T00:28:21Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 948,082 | <p>In addition to IPython, a similar utility <a href="http://bpython-interpreter.org/">bpython</a> has a "save the code you've entered to a file" feature</p>
| 11 | 2009-06-04T01:03:36Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 9,593,579 | <p>On windows, PythonWin is a lot more productive than that the default python terminal. It has a lot of features that you usually find in IDEs:</p>
<ul>
<li>save the terminal session to a file</li>
<li>colored syntax highlighting</li>
<li>code completion for classes/properties/variables when you press tab. </li>
<li>properly browsing when you type "."</li>
<li>parameter hints when you type "("</li>
<li>it's a GUI rather than a DOS window, so you have easier copy/paste and autowrapping long lines if you resize the window. </li>
</ul>
<p>You can download it as part of Python for Windows extensions
<a href="http://sourceforge.net/projects/pywin32/files/pywin32/" rel="nofollow">http://sourceforge.net/projects/pywin32/files/pywin32/</a></p>
| 0 | 2012-03-06T23:29:00Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 9,720,341 | <p><a href="http://www.andrewhjon.es/save-interactive-python-session-history">http://www.andrewhjon.es/save-interactive-python-session-history</a></p>
<pre><code>import readline
readline.write_history_file('/home/ahj/history')
</code></pre>
| 83 | 2012-03-15T13:06:35Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 10,474,449 | <p>Just putting another suggesting in the bowl:
<a href="https://github.com/spyder-ide/spyder" rel="nofollow">Spyder</a></p>
<p><a href="http://i.stack.imgur.com/kh91E.png" rel="nofollow"><img src="http://i.stack.imgur.com/kh91E.png" alt="enter image description here"></a></p>
<p>It has <em>History log</em> and <em>Variable explorer</em>. If you have worked with MatLab, then you'll see the similarities. </p>
| 1 | 2012-05-06T21:25:47Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 17,325,071 | <p>there is another option --- pyslice.
in the "wxpython 2.8 docs demos and tools", there is a open source program named "pyslices".</p>
<p>you can use it like a editor, and it also support using like a console ---- executing each line like a interactive interpreter with immediate echo.</p>
<p>of course, all the blocks of codes and results of each block will be recorded into a txt file automatically. </p>
<p>the results are logged just behind the corresponding block of code. very convenient.</p>
<p><img src="http://i.stack.imgur.com/VsJ1w.png" alt="the overview of pyslices"></p>
| 1 | 2013-06-26T16:03:33Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 25,447,411 | <p>I had to struggle to find an answer, I was very new to iPython environment.</p>
<p>This will work</p>
<p>If your iPython session looks like this </p>
<pre><code>In [1] : import numpy as np
....
In [135]: counter=collections.Counter(mapusercluster[3])
In [136]: counter
Out[136]: Counter({2: 700, 0: 351, 1: 233})
</code></pre>
<p>You want to save lines from 1 till 135 then on the same ipython session use this command</p>
<pre><code>In [137]: %save test.py 1-135
</code></pre>
<p>This will save all your python statements in test.py file in your current directory ( where you initiated the ipython).</p>
| 2 | 2014-08-22T12:47:02Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 26,663,400 | <p>After installing <a href="http://ipython.org/">Ipython</a>, and opening an Ipython session by running the command:</p>
<pre><code>ipython
</code></pre>
<p>from your command line, just run the following Ipython 'magic' command to automatically log your entire Ipython session:</p>
<pre><code>%logstart
</code></pre>
<p>This will create a uniquely named .py file and store your session for later use as an interactive Ipython session or for use in the script(s) of your choosing.</p>
| 6 | 2014-10-30T21:12:47Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 29,974,624 | <p>If you are using <a href="http://ipython.org/">IPython</a> you can save to a file all your previous commands using the magic function <em><a href="http://ipython.org/ipython-doc/2/api/generated/IPython.core.magics.history.html#IPython.core.magics.history.HistoryMagics">%history</a></em> with the <em>-f</em> parameter, p.e:</p>
<pre><code>%history -f /tmp/history.py
</code></pre>
| 18 | 2015-04-30T17:56:37Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 35,237,125 | <p>There is %history magic for printing and saving the input history (and optionally the output).</p>
<p>To store your current session to a file named <code>my_history.py</code>:</p>
<pre><code>>>> %hist -f my_history.py
</code></pre>
<p>History IPython stores both the commands you enter, and the results it produces. You can easily go through previous commands with the up- and down-arrow keys, or access your history in more sophisticated ways.</p>
<p>You can use the %history magic function to examine past input and output. Input history from previous sessions is saved in a database, and IPython can be configured to save output history.</p>
<p>Several other magic functions can use your input history, including %edit, %rerun, %recall, %macro, %save and %pastebin. You can use a standard format to refer to lines:</p>
<pre><code>%pastebin 3 18-20 ~1/1-5
</code></pre>
<p>This will take line 3 and lines 18 to 20 from the current session, and lines 1-5 from the previous session.</p>
<p>See %history? for the Docstring and more examples.</p>
<p>Also, be sure to explore the capabilities of <a href="http://ipython.org/ipython-doc/rel-0.12/config/extensions/storemagic.html" rel="nofollow">%store magic</a> for lightweight persistence of variables in IPython.</p>
<blockquote>
<p>Stores variables, aliases and macros in IPythonâs database.</p>
</blockquote>
<pre><code>d = {'a': 1, 'b': 2}
%store d # stores the variable
del d
%store -r d # Refresh the variable from IPython's database.
>>> d
{'a': 1, 'b': 2}
</code></pre>
<p>To autorestore stored variables on startup, specify<code>c.StoreMagic.autorestore = True</code> in ipython_config.py.</p>
| 1 | 2016-02-06T03:48:30Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 37,228,036 | <p>As far as Linux goes, one can use <code>script</code> command to record the whole session. It is part of <code>util-linux</code> package so should be on most Linux systems . You can create and alias or function that will call <code>script -c python</code> and that will be saved to a <code>typescript</code> file. For instance, here's a reprint of one such file.</p>
<pre><code>$ cat typescript
Script started on Sat 14 May 2016 08:30:08 AM MDT
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello Pythonic World'
Hello Pythonic World
>>>
Script done on Sat 14 May 2016 08:30:42 AM MDT
</code></pre>
<p>Small disadvantage here is that the <code>script</code> records everything , even line-feeds, whenever you hit backspaces , etc. So you may want to use <code>col</code> to clean up the output (see <a href="http://unix.stackexchange.com/q/86901/85039">this post on Unix&Linux Stackexchange</a>) . </p>
| 0 | 2016-05-14T14:45:52Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
How to save a Python interactive session? | 947,810 | <p>I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like <code>script</code> I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?</p>
<p><b>UPDATE</b>: I am really amazed at the quality and usefulness of these packages. For those with a similar itch:</p>
<ul>
<li>IPython -- should have been using this for ages, kind of what I had in mind</li>
<li><a href="http://blog.fishsoup.net/category/coding/reinteract/">reinteract</a> -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: <a href="http://www.reinteract.org/trac/wiki/GettingIt">http://www.reinteract.org/trac/wiki/GettingIt</a> . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too.</li>
<li><a href="http://bpython-interpreter.org/">bpython</a> -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge.</li>
</ul>
<p>I am converted, these really fill a need between interpreter and editor.</p>
| 240 | 2009-06-03T23:21:02Z | 38,593,747 | <p>Some comments were asking how to save all of the IPython inputs at once. For %save magic in IPython, you can save all of the commands programmatically as shown below, to avoid the prompt message and also to avoid specifying the input numbers.
currentLine = len(In)-1
%save -f my_session 1-$currentLine</p>
<p>The <code>-f</code> option is used for forcing file replacement and the <code>len(IN)-1</code> shows the current input prompt in IPython, allowing you to save the whole session programmatically. </p>
| 0 | 2016-07-26T15:14:54Z | [
"python",
"shell",
"read-eval-print-loop",
"interactive-session"
] |
Python Opencv Ubuntu not creating Windows | 947,829 | <p>I have a strange problem with opencv running on an Ubuntu.
I installed OpenCV from the apt sources. And most of the Examples work fine.</p>
<p>But in my programs, which are working with Mac OS, no windows are created.</p>
<p>The following code is showing a window and an image in this on my Mac but not on my Ubuntu powered machine</p>
<pre><code>import time
from opencv import highgui
if __name__ == '__main__':
highgui.cvNamedWindow('Image', highgui.CV_WINDOW_AUTOSIZE)
highgui.cvMoveWindow('Image', 10, 40)
image = highgui.cvLoadImage("verena.jpg", 1)
highgui.cvShowImage('Image', image)
time.sleep(3)
</code></pre>
<p>The code is taken from one of the examples that is actually working on both machines.</p>
| 1 | 2009-06-03T23:27:53Z | 948,018 | <p>The code works if I add a highgui.cvStartWindowThread() call before creating the window. </p>
<p>Now the next question would be why the program works on mac os without starting the windowThread.</p>
| 3 | 2009-06-04T00:35:26Z | [
"python",
"osx",
"ubuntu",
"opencv"
] |
Python Opencv Ubuntu not creating Windows | 947,829 | <p>I have a strange problem with opencv running on an Ubuntu.
I installed OpenCV from the apt sources. And most of the Examples work fine.</p>
<p>But in my programs, which are working with Mac OS, no windows are created.</p>
<p>The following code is showing a window and an image in this on my Mac but not on my Ubuntu powered machine</p>
<pre><code>import time
from opencv import highgui
if __name__ == '__main__':
highgui.cvNamedWindow('Image', highgui.CV_WINDOW_AUTOSIZE)
highgui.cvMoveWindow('Image', 10, 40)
image = highgui.cvLoadImage("verena.jpg", 1)
highgui.cvShowImage('Image', image)
time.sleep(3)
</code></pre>
<p>The code is taken from one of the examples that is actually working on both machines.</p>
| 1 | 2009-06-03T23:27:53Z | 11,784,815 | <p>For the new binding, I mean <code>cv2</code>. The code is <code>cv2.startWindowThread()</code></p>
| 0 | 2012-08-02T19:55:29Z | [
"python",
"osx",
"ubuntu",
"opencv"
] |
If slicing does not create a copy of a list nor does list() how can I get a real copy of my list? | 948,032 | <p>I am trying to modify a list and since my modifications were getting a bit tricky and my list large I took a slice of my list using the following code</p>
<pre><code>tempList=origList[0:10]
for item in tempList:
item[-1].insert(0 , item[1])
del item[1]
</code></pre>
<p>I did this thinking that all of the modifications to the list would affect tempList object and not origList objects.</p>
<p>Well once I got my code right and ran it on my original list the first ten items (indexed 0-9) were affected by my manipulation in testing the code printed above. </p>
<p>So I googled it and I find references that say taking a slice copies the list and creates a new-one. I also found code that helped me find the id of the items so I created my origList from scratch, got the ids of the first ten items. I sliced the list again and found that the ids from the slices matched the ids from the first ten items of the origList.</p>
<p>I found more notes that suggested a more pythonic way to copy a list would be to use</p>
<pre><code>tempList=list(origList([0:10])
</code></pre>
<p>I tried that and I still find that the ids from the tempList match the ids from the origList.</p>
<p>Please don't suggest better ways to do the coding-I am going to figure out how to do this in a list Comprehension on my own after I understand what how copying works</p>
<p>Based on Kai's answer the correct method is:</p>
<pre><code>import copy
tempList=copy.deepcopy(origList[0:10])
id(origList[0])
>>>>42980096
id(tempList[0])
>>>>42714136
</code></pre>
<p>Works like a charm</p>
| 9 | 2009-06-04T00:40:53Z | 948,049 | <p>Slicing creates a shallow copy. In your example, I see that you are calling insert() on item[-1], which means that item is a list of lists. That means that your shallow copies still reference the original objects. You can think of it as making copies of the pointers, not the actual objects.</p>
<p>Your solution lies in using deep copies instead. Python provides a <a href="http://docs.python.org/library/copy.html">copy module</a> for just this sort of thing. You'll find lots more information on shallow vs deep copying when you search for it.</p>
| 22 | 2009-06-04T00:48:32Z | [
"python",
"list",
"copy"
] |
If slicing does not create a copy of a list nor does list() how can I get a real copy of my list? | 948,032 | <p>I am trying to modify a list and since my modifications were getting a bit tricky and my list large I took a slice of my list using the following code</p>
<pre><code>tempList=origList[0:10]
for item in tempList:
item[-1].insert(0 , item[1])
del item[1]
</code></pre>
<p>I did this thinking that all of the modifications to the list would affect tempList object and not origList objects.</p>
<p>Well once I got my code right and ran it on my original list the first ten items (indexed 0-9) were affected by my manipulation in testing the code printed above. </p>
<p>So I googled it and I find references that say taking a slice copies the list and creates a new-one. I also found code that helped me find the id of the items so I created my origList from scratch, got the ids of the first ten items. I sliced the list again and found that the ids from the slices matched the ids from the first ten items of the origList.</p>
<p>I found more notes that suggested a more pythonic way to copy a list would be to use</p>
<pre><code>tempList=list(origList([0:10])
</code></pre>
<p>I tried that and I still find that the ids from the tempList match the ids from the origList.</p>
<p>Please don't suggest better ways to do the coding-I am going to figure out how to do this in a list Comprehension on my own after I understand what how copying works</p>
<p>Based on Kai's answer the correct method is:</p>
<pre><code>import copy
tempList=copy.deepcopy(origList[0:10])
id(origList[0])
>>>>42980096
id(tempList[0])
>>>>42714136
</code></pre>
<p>Works like a charm</p>
| 9 | 2009-06-04T00:40:53Z | 948,089 | <p>If you copy an object the contents of it are not copied. In probably most cases this is what you want. In your case you have to make sure that the contents are copied by yourself. You could use copy.deepcopy but if you have a list of lists or something similar i would recommend using <code>copy = [l[:] for l in list_of_lists]</code>, that should be a lot faster.</p>
<p>A little note to your codestyle:</p>
<ul>
<li>del is a statement and not a function so it is better to not use parens there, they are just confusing.</li>
<li>Whitespaces around operators and after commas would make your code easier to read.</li>
<li>list(alist) copies a list but it is not more pythonic than alist[:], I think alist[:] is even more commonly used then the alternative. </li>
</ul>
| 4 | 2009-06-04T01:04:32Z | [
"python",
"list",
"copy"
] |
Preventing file handle inheritance in multiprocessing lib | 948,119 | <p>Using multiprocessing on windows it appears that any open file handles are inherited by spawned processes. This has the unpleasant side effect of locking them.</p>
<p>I'm interested in either:<br>
1) Preventing the inheritance<br>
2) A way to release the file from the spawned process</p>
<p>Consider the following code which works fine on OSX, but crashes on windows at os.rename</p>
<pre><code>from multiprocessing import Process
import os
kFileA = "a.txt"
kFileB = "b.txt"
def emptyProcess():
while 1:
pass
def main():
# Open a file and write a message
testFile = open(kFileA, 'a')
testFile.write("Message One\n")
# Spawn a process
p = Process(target=emptyProcess)
p.start()
# Close the file
testFile.close()
# This will crash
# WindowsError: [Error 32] The process cannot access the file
# because it is being used by another process
os.rename(kFileA, kFileB)
testFile = open(kFileA, 'a')
testFile.write("Message Two\n")
testFile.close()
p.terminate()
if __name__ == "__main__":
main()
</code></pre>
| 11 | 2009-06-04T01:12:51Z | 948,144 | <p>After you open a file handle, you can use the SetHandleInformation() function to remove the <code>HANDLE_FLAG_INHERIT</code> flag.</p>
| 0 | 2009-06-04T01:20:52Z | [
"python",
"windows",
"multiprocessing",
"handle"
] |
Preventing file handle inheritance in multiprocessing lib | 948,119 | <p>Using multiprocessing on windows it appears that any open file handles are inherited by spawned processes. This has the unpleasant side effect of locking them.</p>
<p>I'm interested in either:<br>
1) Preventing the inheritance<br>
2) A way to release the file from the spawned process</p>
<p>Consider the following code which works fine on OSX, but crashes on windows at os.rename</p>
<pre><code>from multiprocessing import Process
import os
kFileA = "a.txt"
kFileB = "b.txt"
def emptyProcess():
while 1:
pass
def main():
# Open a file and write a message
testFile = open(kFileA, 'a')
testFile.write("Message One\n")
# Spawn a process
p = Process(target=emptyProcess)
p.start()
# Close the file
testFile.close()
# This will crash
# WindowsError: [Error 32] The process cannot access the file
# because it is being used by another process
os.rename(kFileA, kFileB)
testFile = open(kFileA, 'a')
testFile.write("Message Two\n")
testFile.close()
p.terminate()
if __name__ == "__main__":
main()
</code></pre>
| 11 | 2009-06-04T01:12:51Z | 948,214 | <p>I don't know about the <em>multiprocessing</em> module, but with the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><em>subprocess</em></a> module you can instruct it to not inherit any file descriptors:</p>
<blockquote>
<p>If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr.</p>
</blockquote>
<p>Alternatively you could close all file descriptors in your child process with <a href="http://docs.python.org/library/os.html#os.closerange" rel="nofollow">os.closerange</a></p>
<blockquote>
<p>Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Availability: Unix, Windows.</p>
</blockquote>
| 0 | 2009-06-04T01:41:10Z | [
"python",
"windows",
"multiprocessing",
"handle"
] |
Preventing file handle inheritance in multiprocessing lib | 948,119 | <p>Using multiprocessing on windows it appears that any open file handles are inherited by spawned processes. This has the unpleasant side effect of locking them.</p>
<p>I'm interested in either:<br>
1) Preventing the inheritance<br>
2) A way to release the file from the spawned process</p>
<p>Consider the following code which works fine on OSX, but crashes on windows at os.rename</p>
<pre><code>from multiprocessing import Process
import os
kFileA = "a.txt"
kFileB = "b.txt"
def emptyProcess():
while 1:
pass
def main():
# Open a file and write a message
testFile = open(kFileA, 'a')
testFile.write("Message One\n")
# Spawn a process
p = Process(target=emptyProcess)
p.start()
# Close the file
testFile.close()
# This will crash
# WindowsError: [Error 32] The process cannot access the file
# because it is being used by another process
os.rename(kFileA, kFileB)
testFile = open(kFileA, 'a')
testFile.write("Message Two\n")
testFile.close()
p.terminate()
if __name__ == "__main__":
main()
</code></pre>
| 11 | 2009-06-04T01:12:51Z | 984,238 | <p>The <code>fileno()</code> method returns the file number as assigned by the runtime library. Given the file number, you can then call <code>msvcrt.get_osfhandle()</code> to get the Win32 file handle. Use this handle in the call to <code>SetHandleInformation</code>. So something like the following may work:</p>
<pre><code>win32api.SetHandleInformation(
msvcrt.get_osfhandle(testFile.fileno()),
win32api.HANDLE_FLAG_INHERIT,
0)
</code></pre>
<p>I'm not certain of the exact usage of the <code>win32api</code> module, but this should help bridge the gap between a Python file object and a Win32 handle.</p>
| 4 | 2009-06-11T23:05:35Z | [
"python",
"windows",
"multiprocessing",
"handle"
] |
Preventing file handle inheritance in multiprocessing lib | 948,119 | <p>Using multiprocessing on windows it appears that any open file handles are inherited by spawned processes. This has the unpleasant side effect of locking them.</p>
<p>I'm interested in either:<br>
1) Preventing the inheritance<br>
2) A way to release the file from the spawned process</p>
<p>Consider the following code which works fine on OSX, but crashes on windows at os.rename</p>
<pre><code>from multiprocessing import Process
import os
kFileA = "a.txt"
kFileB = "b.txt"
def emptyProcess():
while 1:
pass
def main():
# Open a file and write a message
testFile = open(kFileA, 'a')
testFile.write("Message One\n")
# Spawn a process
p = Process(target=emptyProcess)
p.start()
# Close the file
testFile.close()
# This will crash
# WindowsError: [Error 32] The process cannot access the file
# because it is being used by another process
os.rename(kFileA, kFileB)
testFile = open(kFileA, 'a')
testFile.write("Message Two\n")
testFile.close()
p.terminate()
if __name__ == "__main__":
main()
</code></pre>
| 11 | 2009-06-04T01:12:51Z | 36,304,219 | <p>I have encountered this issue when using a rotating log and multiprocessing. When the parent process tries to rotate the log, it fails with a </p>
<blockquote>
<p>WindowsError: [Error 32] The process cannot access the file because it is being used by another process</p>
</blockquote>
<p>based on some of the other answers, the following is a working solution in python 2.7 to prevent log file handlers from been inherited</p>
<pre><code>fd = logging.getLogger().handlers[0].stream.fileno() # The log handler file descriptor
fh = msvcrt.get_osfhandle(fd) # The actual windows handler
win32api.SetHandleInformation(fh, win32con.HANDLE_FLAG_INHERIT, 0) # Disable inheritance
</code></pre>
<p>Please note this issue was somewhat address in python 3.4. for more info see
<a href="https://www.python.org/dev/peps/pep-0446/" rel="nofollow">https://www.python.org/dev/peps/pep-0446/</a></p>
| 0 | 2016-03-30T09:04:36Z | [
"python",
"windows",
"multiprocessing",
"handle"
] |
Sqlalchemy complex in_ clause | 948,212 | <p>I'm trying to find a way to cause sqlalchemy to generate sql of the following form:</p>
<pre>
select * from t where (a,b) in ((a1,b1),(a2,b2));
</pre>
<p>Is this possible?</p>
<p>If not, any suggestions on a way to emulate it?</p>
<p>Thanks kindly!</p>
| 6 | 2009-06-04T01:40:38Z | 948,342 | <p>Standard caveat: I'm no expert in the large and twisty ecosystem that is SQLAlchemy.</p>
<p>So let's say you have a Table named <code>stocks</code> and a Session named <code>session</code>. Then the query would just be something like</p>
<pre><code>x = "(stocks.person, stocks.number) IN ((100, 100), (200, 200))"
session.query(stocks).filter(x).all()
</code></pre>
<p>A good rule of thumb is that SQLAlchemy will accept raw SQL in most places where it looks like it might be generated, such as the <code>filter</code> method.</p>
<p>However, I don't believe there's a way to do it without raw SQL. The <code>in_</code> operator seems to be defined only on <code>Column</code>s rather than tuples of columns like you have in your example. (Also, this only works on SQL implementations that support it--SQLite in particular seems to not support this in the quick examples I ran. You also have to be careful in qualifying the columns in the left tuple, especially if SQLAlchemy kindly handled the table creation.)</p>
| 4 | 2009-06-04T02:44:04Z | [
"python",
"sql",
"sqlalchemy"
] |
Sqlalchemy complex in_ clause | 948,212 | <p>I'm trying to find a way to cause sqlalchemy to generate sql of the following form:</p>
<pre>
select * from t where (a,b) in ((a1,b1),(a2,b2));
</pre>
<p>Is this possible?</p>
<p>If not, any suggestions on a way to emulate it?</p>
<p>Thanks kindly!</p>
| 6 | 2009-06-04T01:40:38Z | 951,640 | <p>Well, thanks to Hao Lian above, I came up with a functional if painful solution.</p>
<p>Assume that we have a declarative-style mapped class, <code>Clazz</code>, and a <code>list</code> of tuples of compound primary key values, <code>values</code>
(Edited to use a better (IMO) sql generation style):</p>
<pre>
from sqlalchemy.sql.expression import text,bindparam
...
def __gParams(self, f, vs, ts, bs):
for j,v in enumerate(vs):
key = f % (j+97)
bs.append(bindparam(key, value=v, type_=ts[j]))
yield ':%s' % key
def __gRows(self, ts, values, bs):
for i,vs in enumerate(values):
f = '%%c%d' % i
yield '(%s)' % ', '.join(self.__gParams(f, vs, ts, bs))
def __gKeys(self, k, ts):
for c in k:
ts.append(c.type)
yield str(c)
def __makeSql(self,Clazz, values):
t = []
b = []
return text(
'(%s) in (%s)' % (
', '.join(self.__gKeys(Clazz.__table__.primary_key,t)),
', '.join(self.__gRows(t,values,b))),
bindparams=b)
</pre>
<p>This solution works for compound or simple primary keys. It's probably marginally slower than the <code>col.in_(keys)</code> for simple primary keys though.</p>
<p>I'm still interested in suggestions of better ways to do this, but this way is working for now and performs noticeably better than the <code>or_(and_(conditions))</code> way, or the <code>for key in keys: do_stuff(q.get(key))</code> way.</p>
| 3 | 2009-06-04T16:25:35Z | [
"python",
"sql",
"sqlalchemy"
] |
Sqlalchemy complex in_ clause | 948,212 | <p>I'm trying to find a way to cause sqlalchemy to generate sql of the following form:</p>
<pre>
select * from t where (a,b) in ((a1,b1),(a2,b2));
</pre>
<p>Is this possible?</p>
<p>If not, any suggestions on a way to emulate it?</p>
<p>Thanks kindly!</p>
| 6 | 2009-06-04T01:40:38Z | 2,563,927 | <p>see the <a href="http://www.sqlalchemy.org/docs/reference/sqlalchemy/expressions.html?highlight=tuple#sqlalchemy.sql.expression.tuple_" rel="nofollow">tuple_ construct</a> in SQLAlchemy 0.6</p>
| 2 | 2010-04-01T21:51:20Z | [
"python",
"sql",
"sqlalchemy"
] |
Sqlalchemy complex in_ clause | 948,212 | <p>I'm trying to find a way to cause sqlalchemy to generate sql of the following form:</p>
<pre>
select * from t where (a,b) in ((a1,b1),(a2,b2));
</pre>
<p>Is this possible?</p>
<p>If not, any suggestions on a way to emulate it?</p>
<p>Thanks kindly!</p>
| 6 | 2009-06-04T01:40:38Z | 6,724,961 | <p>Use tuple_</p>
<pre><code>keys = [(a1, b1), (a2, b2)]
session.query(T).filter(tuple_(T.a, T.b).in_(keys)).all()
</code></pre>
<p><a href="http://www.sqlalchemy.org/docs/core/expression_api.html">http://www.sqlalchemy.org/docs/core/expression_api.html</a> => Look for tuple_</p>
| 16 | 2011-07-17T15:48:17Z | [
"python",
"sql",
"sqlalchemy"
] |
method for creating a unique validation key/number | 948,493 | <p>I'm using django for a web-magazine with subscriber-content. when a user purchases a subscription, the site will create a validation key, and send it to the user email address.
The validation key would be added to a list of "valid keys" until it is used.</p>
<p>What is the best method for creating a simple yet unique key? Can someone suggest a standard python library for key-creation/validation/ect?</p>
<p>This might be a very simple question, but I'm very new. ;)</p>
| 2 | 2009-06-04T03:42:26Z | 948,499 | <p>I'd recommend using a GUID. They are quickly becoming industry standard for this kind of thing.</p>
<p>See how to create them here: <a href="http://stackoverflow.com/questions/534839/how-to-create-a-guid-in-python">http://stackoverflow.com/questions/534839/how-to-create-a-guid-in-python</a></p>
| 2 | 2009-06-04T03:44:46Z | [
"python",
"django",
"validation"
] |
method for creating a unique validation key/number | 948,493 | <p>I'm using django for a web-magazine with subscriber-content. when a user purchases a subscription, the site will create a validation key, and send it to the user email address.
The validation key would be added to a list of "valid keys" until it is used.</p>
<p>What is the best method for creating a simple yet unique key? Can someone suggest a standard python library for key-creation/validation/ect?</p>
<p>This might be a very simple question, but I'm very new. ;)</p>
| 2 | 2009-06-04T03:42:26Z | 948,500 | <p>Well, you can always use a GUID. As you said it would be stored as a valid key.</p>
| 0 | 2009-06-04T03:45:05Z | [
"python",
"django",
"validation"
] |
method for creating a unique validation key/number | 948,493 | <p>I'm using django for a web-magazine with subscriber-content. when a user purchases a subscription, the site will create a validation key, and send it to the user email address.
The validation key would be added to a list of "valid keys" until it is used.</p>
<p>What is the best method for creating a simple yet unique key? Can someone suggest a standard python library for key-creation/validation/ect?</p>
<p>This might be a very simple question, but I'm very new. ;)</p>
| 2 | 2009-06-04T03:42:26Z | 948,513 | <p>As other posters mentioned, you are looking for a GUID, of which the most popular implemntation UUID (see <a href="http://en.wikipedia.org/wiki/Universally%5FUnique%5FIdentifier" rel="nofollow">here</a>) . Django extensions (see <a href="http://code.google.com/p/django-command-extensions/" rel="nofollow">here</a>) offer a UUID field just for this purpose.</p>
| 2 | 2009-06-04T03:49:37Z | [
"python",
"django",
"validation"
] |
IMAP4_SSL with gmail in python | 948,761 | <p>We are retrieving mails from our gmail account using IMAP4_SSL and python.
The email body is retrieved in html format.
We need to convert that to plaintext.
Can anyone help us with that?</p>
| 0 | 2009-06-04T05:49:24Z | 948,805 | <p>Stand on the shoulders of giants...<br />
Peter Bengtsson has worked out a solution to this exact problem <a href="http://www.peterbe.com/plog/html2plaintext" rel="nofollow">here</a>.<br />
Peter's script uses the awesome <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>, by Leonard Richardson, <br />
and Fredrik Lundh's <a href="http://effbot.org/zone/re-sub.htm" rel="nofollow">unescape() function</a>.</p>
<p>Using Peter's test case, you get this:</p>
<pre><code>This is a paragraph.
Foobar [1]
http://two.com
Visit http://www.google.com.
Text elsewhere. Elsewhere [2]
[1] http://one.com
[2] http://three.com
</code></pre>
<p>...from this: </p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body>
<div id="main">
<p>This is a paragraph.</p>
<p><a href="http://one.com">Foobar</a>
<br />
<a href="http://two.com">two.com</a>
</p>
<p>Visit <a href="http://www.google.com">www.google.com</a>.</p>
<br />
Text elsewhere.
<a href="http://three.com">Elsewhere</a>
</div>
</body>
</html>
</code></pre>
| 2 | 2009-06-04T06:05:17Z | [
"python",
"html",
"gmail"
] |
Python web framework with low barrier to entry | 948,815 | <p>I am looking for a LAMPish/WAMPish experience.</p>
<p>Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.</p>
<p>I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.</p>
<p>I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.</p>
<p>This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.</p>
<p>An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.</p>
<p>Can you help me out here?</p>
<p>Thanks!</p>
<p>PS: I did not really find anything matching these criteria in older posts.</p>
| 4 | 2009-06-04T06:09:54Z | 948,836 | <p>Look at:</p>
<ul>
<li><a href="http://www.wsgi.org/wsgi/" rel="nofollow">WSGI</a>, the standard Python API for HTTP servers to call Python code.</li>
<li><a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, a popular, feature-rich, well documented Python web framework</li>
<li><a href="http://webpy.org/" rel="nofollow">web.py</a>, a minimal Python web framework</li>
</ul>
| 1 | 2009-06-04T06:18:12Z | [
"python"
] |
Python web framework with low barrier to entry | 948,815 | <p>I am looking for a LAMPish/WAMPish experience.</p>
<p>Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.</p>
<p>I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.</p>
<p>I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.</p>
<p>This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.</p>
<p>An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.</p>
<p>Can you help me out here?</p>
<p>Thanks!</p>
<p>PS: I did not really find anything matching these criteria in older posts.</p>
| 4 | 2009-06-04T06:09:54Z | 948,841 | <p>Have you looked into the <a href="http://djangoproject.com" rel="nofollow">Django</a> web framework? Its an MVC framework written in python, and is relatively simple to set up and get started. You can run it with nothing but python, as it can use SQLite and its own development server, or you can set it up to use MySQL and Apache if you'd like.</p>
<p><a href="http://pylonshq.com/" rel="nofollow">Pylons</a> is another framework that supports SQLAlchemy for models. I've never used it but it seems promising.</p>
| 1 | 2009-06-04T06:19:28Z | [
"python"
] |
Python web framework with low barrier to entry | 948,815 | <p>I am looking for a LAMPish/WAMPish experience.</p>
<p>Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.</p>
<p>I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.</p>
<p>I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.</p>
<p>This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.</p>
<p>An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.</p>
<p>Can you help me out here?</p>
<p>Thanks!</p>
<p>PS: I did not really find anything matching these criteria in older posts.</p>
| 4 | 2009-06-04T06:09:54Z | 948,927 | <p><a href="http://cherrypy.org" rel="nofollow">CherryPy</a> might be what you need. It transparently maps URLs onto Python functions, and handles all the cookie and session stuff (and of course the POST / GET parameters for you).</p>
<p>It's not a full-stack solution like Django or Rails. On the other hand, that means that it doesn't lump you with a template engine or ORM you don't like; you're free to use whatever you like.</p>
<p>It includes a WSGI compliant web server, so you don't even need Apache.</p>
| 6 | 2009-06-04T06:45:13Z | [
"python"
] |
Python web framework with low barrier to entry | 948,815 | <p>I am looking for a LAMPish/WAMPish experience.</p>
<p>Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.</p>
<p>I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.</p>
<p>I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.</p>
<p>This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.</p>
<p>An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.</p>
<p>Can you help me out here?</p>
<p>Thanks!</p>
<p>PS: I did not really find anything matching these criteria in older posts.</p>
| 4 | 2009-06-04T06:09:54Z | 948,972 | <p>What you're describing most resembles <a href="http://pylonshq.com/" rel="nofollow">Pylons</a>, it seems to me. However, the number of web frameworks in/for Python is huge -- see <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">this page</a> for an attempt to list and VERY briefly characterize each and every one of them!-)</p>
| 5 | 2009-06-04T06:57:27Z | [
"python"
] |
Python web framework with low barrier to entry | 948,815 | <p>I am looking for a LAMPish/WAMPish experience.</p>
<p>Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.</p>
<p>I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.</p>
<p>I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.</p>
<p>This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.</p>
<p>An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.</p>
<p>Can you help me out here?</p>
<p>Thanks!</p>
<p>PS: I did not really find anything matching these criteria in older posts.</p>
| 4 | 2009-06-04T06:09:54Z | 1,267,400 | <p>For low barrier to entry, <a href="http://webpy.org/" rel="nofollow">web.py</a> is very very light and simple. </p>
<p>Features:</p>
<ul>
<li>easy (dev) deploy... copy web.py folder into your app directory, then start the server</li>
<li>regex-based url mapping</li>
<li>very simple class mappings</li>
<li>built-in server (most frameworks have this of course)</li>
<li><em>very thin</em> (as measured by lines of code, at least) layer over python application code. </li>
</ul>
<p>Here is its <strong>hello world</strong>:</p>
<pre><code>import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
</code></pre>
<p>As much as I like Werkzeug conceptually, writing wsgi plumbing in the Hello, World! is deeply unpleasant, and totally gets in the way of actually demoing an app. </p>
<p>That said, web.py isn't perfect, and for big jobs, it's probably not the right tool, since:</p>
<ul>
<li>routes style systems are (imho) better than pure regex ones</li>
<li>integrating web.py with other middlewares might be adventurous</li>
</ul>
| 5 | 2009-08-12T16:55:35Z | [
"python"
] |
Python web framework with low barrier to entry | 948,815 | <p>I am looking for a LAMPish/WAMPish experience.</p>
<p>Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.</p>
<p>I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.</p>
<p>I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.</p>
<p>This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.</p>
<p>An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.</p>
<p>Can you help me out here?</p>
<p>Thanks!</p>
<p>PS: I did not really find anything matching these criteria in older posts.</p>
| 4 | 2009-06-04T06:09:54Z | 1,522,835 | <p>Check out <a href="http://web2py.com/" rel="nofollow">web2py</a>. It runs out of the box with no configuration - even from a USB stick. The template language is pure Python and you can develop your entire app through the browser editor (although I find vim faster ;)</p>
| 0 | 2009-10-05T22:57:27Z | [
"python"
] |
Python web framework with low barrier to entry | 948,815 | <p>I am looking for a LAMPish/WAMPish experience.</p>
<p>Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction.
SQLAlchemy and (maybe) some simple templating engine will be used.</p>
<p>I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects.</p>
<p>I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI.</p>
<p>This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers.</p>
<p>An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired.</p>
<p>Can you help me out here?</p>
<p>Thanks!</p>
<p>PS: I did not really find anything matching these criteria in older posts.</p>
| 4 | 2009-06-04T06:09:54Z | 1,993,396 | <p>Don't forget <a href="http://bottle.paws.de" rel="nofollow">Bottle</a>. It is a single-file micro web framework with no dependencies and very easy to use. Here is an "Hello world" example:</p>
<pre><code>from bottle import route, run
@route('/')
def index():
return 'Hello World!'
run(host='localhost', port=8080)
</code></pre>
<p>And here an example for accessing POST variables (cookies and GET vars are similar)</p>
<pre><code>from bottle import route, request
@route('/submit', method='POST')
def submit():
name = request.POST.get('name', 'World')
return 'Hello %s!' % name
</code></pre>
| 1 | 2010-01-03T00:08:06Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 949,110 | <p><strong>First go</strong> (pre-OP-edit): Use sets:</p>
<pre><code>mylist = [1,2,3,4,5,6,7]
goodvals = [1,3,7,8,9]
myset = set(mylist)
goodset = set(goodvals)
print list(myset.intersection(goodset)) # [1, 3, 7]
print list(myset.difference(goodset)) # [2, 4, 5, 6]
</code></pre>
<p>That's good for both readability (IMHO) and performance.</p>
<p><strong>Second go</strong> (post-OP-edit):</p>
<p>Create your list of good extensions as a set:</p>
<pre><code>IMAGE_TYPES = set(['.jpg','.jpeg','.gif','.bmp','.png'])
</code></pre>
<p>and that will increase performance. Otherwise, what you have looks fine to me.</p>
| 13 | 2009-06-04T07:41:20Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 949,121 | <p>Personally, I like the version you cited, assuming you already have a list of <code>goodvals</code> hanging around. If not, something like:</p>
<pre><code>good = filter(lambda x: is_good(x), mylist)
bad = filter(lambda x: not is_good(x), mylist)
</code></pre>
<p>Of course, that's really very similar to using a list comprehension like you originally did, but with a function instead of a lookup:</p>
<pre><code>good = [x for x in mylist if is_good(x)]
bad = [x for x in mylist if not is_good(x)]
</code></pre>
<p>In general, I find the aesthetics of list comprehensions to be very pleasing. Of course, if you don't actually need to preserve ordering and don't need duplicates, using the <code>intersection</code> and <code>difference</code> methods on sets would work well too.</p>
| 5 | 2009-06-04T07:45:43Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 949,139 | <p>For perfomance, try <code>itertools</code>.</p>
<blockquote>
<p>The <a href="http://docs.python.org/library/itertools.html" rel="nofollow">itertools</a> module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an âiterator algebraâ making it possible to construct specialized tools succinctly and efficiently in pure Python.</p>
</blockquote>
<p>See <a href="http://docs.python.org/library/itertools.html#itertools.ifilter" rel="nofollow">itertools.ifilter</a> or imap.</p>
<blockquote>
<p>itertools.ifilter(predicate, iterable)</p>
<p>Make an iterator that filters elements from iterable returning only those for which the predicate is True</p>
</blockquote>
| 1 | 2009-06-04T07:51:54Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 949,191 | <p>Problem with all proposed solutions is that it will scan and apply the filtering function twice. I'd make a simple small function like this:</p>
<pre><code>def SplitIntoTwoLists(l, f):
a = []
b = []
for i in l:
if f(i):
a.append(i)
else:
b.append(i)
return (a,b)
</code></pre>
<p>That way you are not processing anything twice and also are not repeating code.</p>
| 20 | 2009-06-04T08:10:50Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 949,490 | <p>Here's the lazy iterator approach:</p>
<pre><code>from itertools import tee
def split_on_condition(seq, condition):
l1, l2 = tee((condition(item), item) for item in seq)
return (i for p, i in l1 if p), (i for p, i in l2 if not p)
</code></pre>
<p>It evaluates the condition once per item and returns two generators, first yielding values from the sequence where the condition is true, the other where it's false.</p>
<p>Because it's lazy you can use it on any iterator, even an infinite one:</p>
<pre><code>from itertools import count, islice
def is_prime(n):
return n > 1 and all(n % i for i in xrange(2, n))
primes, not_primes = split_on_condition(count(), is_prime)
print("First 10 primes", list(islice(primes, 10)))
print("First 10 non-primes", list(islice(not_primes, 10)))
</code></pre>
<p>Usually though the non-lazy list returning approach is better:</p>
<pre><code>def split_on_condition(seq, condition):
a, b = [], []
for item in seq:
(a if condition(item) else b).append(item)
return a, b
</code></pre>
<p>Edit: For your more specific usecase of splitting items into different lists by some key, heres a generic function that does that:</p>
<pre><code>DROP_VALUE = lambda _:_
def split_by_key(seq, resultmapping, keyfunc, default=DROP_VALUE):
"""Split a sequence into lists based on a key function.
seq - input sequence
resultmapping - a dictionary that maps from target lists to keys that go to that list
keyfunc - function to calculate the key of an input value
default - the target where items that don't have a corresponding key go, by default they are dropped
"""
result_lists = dict((key, []) for key in resultmapping)
appenders = dict((key, result_lists[target].append) for target, keys in resultmapping.items() for key in keys)
if default is not DROP_VALUE:
result_lists.setdefault(default, [])
default_action = result_lists[default].append
else:
default_action = DROP_VALUE
for item in seq:
appenders.get(keyfunc(item), default_action)(item)
return result_lists
</code></pre>
<p>Usage:</p>
<pre><code>def file_extension(f):
return f[2].lower()
split_files = split_by_key(files, {'images': IMAGE_TYPES}, keyfunc=file_extension, default='anims')
print split_files['images']
print split_files['anims']
</code></pre>
| 72 | 2009-06-04T09:32:23Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 950,207 | <p>If you insist on clever, you could take Winden's solution and just a bit spurious cleverness:</p>
<pre><code>def splay(l, f, d=None):
d = d or {}
for x in l: d.setdefault(f(x), []).append(x)
return d
</code></pre>
| 0 | 2009-06-04T12:25:01Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 950,591 | <blockquote>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
</blockquote>
<p>That code is perfectly readable, and extremely clear!</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
<p>Again, this is <em>fine!</em></p>
<p>There might be slight performance improvements using sets, but it's a trivial difference, and I find the list comprehension far easier to read, and you don't have to worry about the order being messed up, duplicates being removed as so on.</p>
<p>In fact, I may go another step "backward", and just use a simple for loop:</p>
<pre><code>images, anims = [], []
for f in files:
if f.lower() in IMAGE_TYPES:
images.append(f)
else:
anims.append(f)
</code></pre>
<p>The a list-comprehension or using <code>set()</code> is fine until you need to add some other check or another bit of logic - say you want to remove all 0-byte jpeg's, you just add something like..</p>
<pre><code>if f[1] == 0:
continue
</code></pre>
| 63 | 2009-06-04T13:28:23Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 950,631 | <p><a href="http://docs.python.org/library/itertools.html#itertools.groupby">itertools.groupby</a> almost does what you want, except it requires the items to be sorted to ensure that you get a single contiguous range, so you need to sort by your key first (otherwise you'll get multiple interleaved groups for each type). eg.</p>
<pre><code>def is_good(f):
return f[2].lower() in IMAGE_TYPES
files = [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ('file3.gif', 123L, '.gif')]
for key, group in itertools.groupby(sorted(files, key=is_good), key=is_good):
print key, list(group)
</code></pre>
<p>gives:</p>
<pre><code>False [('file2.avi', 999L, '.avi')]
True [('file1.jpg', 33L, '.jpg'), ('file3.gif', 123L, '.gif')]
</code></pre>
<p>Similar to the other solutions, the key func can be defined to divide into any number of groups you want.</p>
| 6 | 2009-06-04T13:34:29Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 2,799,738 | <p>If you want to make it in FP style:</p>
<pre><code>good, bad = [ sum(x, []) for x in zip(*(([y], []) if y in goodvals else ([], [y])
for y in mylist)) ]
</code></pre>
<p>Not the most readable solution, but at least iterates through mylist only once.</p>
| 3 | 2010-05-10T00:28:43Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 3,281,886 | <p>I basically like Anders' approach as it is very general. Here's a version that puts the categorizer first (to match filter syntax) and uses a defaultdict (assumed imported).</p>
<pre><code>def categorize(func, seq):
"""Return mapping from categories to lists
of categorized items.
"""
d = defaultdict(list)
for item in seq:
d[func(item)].append(item)
return d
</code></pre>
| 9 | 2010-07-19T14:20:02Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 5,859,746 | <p>Sometimes you won't need that other half of the list.
For example:</p>
<pre><code>import sys
from itertools import ifilter
trustedPeople = sys.argv[1].split(',')
newName = sys.argv[2]
myFriends = ifilter(lambda x: x.startswith('Shi'), trustedPeople)
print '%s is %smy friend.' % (newName, newName not in myFriends 'not ' or '')
</code></pre>
| 1 | 2011-05-02T16:33:47Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 7,881,048 | <p>My take on it. I propose a lazy, single-pass, <code>partition</code> function,
which preserves relative order in the output subsequences.</p>
<h2>1. Requirements</h2>
<p>I assume that the requirements are:</p>
<ul>
<li>maintain elements' relative order (hence, no sets and
dictionaries)</li>
<li>evaluate condition only once for every element (hence not using
(<code>i</code>)<code>filter</code> or <code>groupby</code>)</li>
<li>allow for lazy consumption of either sequence (if we can afford to
precomute them, then the naïve implementation is likely to be
acceptable too)</li>
</ul>
<h2>2. <code>split</code> library</h2>
<p>My <code>partition</code> function (introduced below) and other similar functions
have made it into a small library:</p>
<ul>
<li><a href="https://bitbucket.org/astanin/python-split">python-split</a></li>
</ul>
<p>It's installable normally via PyPI:</p>
<pre><code>pip install --user split
</code></pre>
<p>To split a list base on condition, use <code>partition</code> function:</p>
<pre><code>>>> from split import partition
>>> files = [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi') ]
>>> image_types = ('.jpg','.jpeg','.gif','.bmp','.png')
>>> images, other = partition(lambda f: f[-1] in image_types, files)
>>> list(images)
[('file1.jpg', 33L, '.jpg')]
>>> list(other)
[('file2.avi', 999L, '.avi')]
</code></pre>
<h2>3. <code>partition</code> function explained</h2>
<p>Internally we need to build two subsequences at once, so consuming
only one output sequence will force the other one to be computed
too. And we need to keep state between user requests (store processed
but not yet requested elements). To keep state, I use two double-ended
queues (<code>deques</code>):</p>
<pre><code>from collections import deque
</code></pre>
<p><code>SplitSeq</code> class takes care of the housekeeping:</p>
<pre><code>class SplitSeq:
def __init__(self, condition, sequence):
self.cond = condition
self.goods = deque([])
self.bads = deque([])
self.seq = iter(sequence)
</code></pre>
<p>Magic happens in its <code>.getNext()</code> method. It is almost like <code>.next()</code>
of the iterators, but allows to specify which kind of element we want
this time. Behind the scene it doesn't discard the rejected elements,
but instead puts them in one of the two queues:</p>
<pre><code> def getNext(self, getGood=True):
if getGood:
these, those, cond = self.goods, self.bads, self.cond
else:
these, those, cond = self.bads, self.goods, lambda x: not self.cond(x)
if these:
return these.popleft()
else:
while 1: # exit on StopIteration
n = self.seq.next()
if cond(n):
return n
else:
those.append(n)
</code></pre>
<p>The end user is supposed to use <code>partition</code> function. It takes a
condition function and a sequence (just like <code>map</code> or <code>filter</code>), and
returns two generators. The first generator builds a subsequence of
elements for which the condition holds, the second one builds the
complementary subsequence. Iterators and generators allow for lazy
splitting of even long or infinite sequences.</p>
<pre><code>def partition(condition, sequence):
cond = condition if condition else bool # evaluate as bool if condition == None
ss = SplitSeq(cond, sequence)
def goods():
while 1:
yield ss.getNext(getGood=True)
def bads():
while 1:
yield ss.getNext(getGood=False)
return goods(), bads()
</code></pre>
<p>I chose the test function to be the first argument to facilitate
partial application in the future (similar to how <code>map</code> and <code>filter</code>
have the test function as the first argument).</p>
| 13 | 2011-10-24T19:42:33Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 10,456,007 | <p>If your concern is not to use two lines of code for an operation whose semantics only need once you just wrap some of the approaches above (even your own) in a single function:</p>
<pre><code>def part_with_predicate(l, pred):
return [i for i in l if pred(i)], [i for i in l if not pred(i)]
</code></pre>
<p>It is not a lazy-eval approach and it does iterate twice through the list, but it allows you to partition the list in one line of code.</p>
| 0 | 2012-05-04T20:53:55Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 12,135,169 | <pre><code>good, bad = [], []
for x in mylist:
(bad, good)[x in goodvals].append(x)
</code></pre>
| 100 | 2012-08-27T00:51:47Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 15,407,422 | <p>Inspired by @gnibbler's <a href="http://stackoverflow.com/a/12135169/182469">great (but terse!) answer</a>, we can apply that approach to map to multiple partitions:</p>
<pre><code>from collections import defaultdict
def splitter(l, mapper):
"""Split an iterable into multiple partitions generated by a callable mapper."""
results = defaultdict(list)
for x in l:
results[mapper(x)].append(x)
return results
</code></pre>
<p>Then <code>splitter</code> can then be used as follows:</p>
<pre><code>>>> l = [1, 2, 3, 4, 2, 3, 4, 5, 6, 4, 3, 2, 3]
>>> split = splitter(l, lambda x: x % 2 == 0) # partition l into odds and evens
>>> split.items()
>>> [(False, [1, 3, 3, 5, 3, 3]), (True, [2, 4, 2, 4, 6, 4, 2])]
</code></pre>
<p>This works for more than two partitions with a more complicated mapping (and on iterators, too):</p>
<pre><code>>>> import math
>>> l = xrange(1, 23)
>>> split = splitter(l, lambda x: int(math.log10(x) * 5))
>>> split.items()
[(0, [1]),
(1, [2]),
(2, [3]),
(3, [4, 5, 6]),
(4, [7, 8, 9]),
(5, [10, 11, 12, 13, 14, 15]),
(6, [16, 17, 18, 19, 20, 21, 22])]
</code></pre>
<p>Or using a dictionary to map:</p>
<pre><code>>>> map = {'A': 1, 'X': 2, 'B': 3, 'Y': 1, 'C': 2, 'Z': 3}
>>> l = ['A', 'B', 'C', 'C', 'X', 'Y', 'Z', 'A', 'Z']
>>> split = splitter(l, map.get)
>>> split.items()
(1, ['A', 'Y', 'A']), (2, ['C', 'C', 'X']), (3, ['B', 'Z', 'Z'])]
</code></pre>
| 0 | 2013-03-14T11:03:24Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 20,492,553 | <pre><code>def partition(pred, seq):
return reduce( lambda (yes, no), x: (yes+[x], no) if pred(x) else (yes, no+[x]), seq, ([], []) )
</code></pre>
| -1 | 2013-12-10T10:56:11Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 22,264,716 | <p>Already quite a few solutions here, but yet another way of doing that would be -</p>
<pre><code>anims = []
images = [f for f in files if (lambda t: True if f[2].lower() in IMAGE_TYPES else anims.append(t) and False)(f)]
</code></pre>
<p>Iterates over the list only once, and looks a bit more pythonic and hence readable to me. </p>
<pre><code>>>> files = [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ('file1.bmp', 33L, '.bmp')]
>>> IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
>>> anims = []
>>> images = [f for f in files if (lambda t: True if f[2].lower() in IMAGE_TYPES else anims.append(t) and False)(f)]
>>> print '\n'.join([str(anims), str(images)])
[('file2.avi', 999L, '.avi')]
[('file1.jpg', 33L, '.jpg'), ('file1.bmp', 33L, '.bmp')]
>>>
</code></pre>
| 0 | 2014-03-08T03:40:43Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 27,517,204 | <p>I'd take a 2-pass approach, separating evaluation of the predicate from filtering the list:</p>
<pre><code>def partition(pred, iterable):
xs = list(zip(map(pred, iterable), iterable))
return [x[1] for x in xs if x[0]], [x[1] for x in xs if not x[0]]
</code></pre>
<p>What's nice about this, performance-wise (in addition to evaluating <code>pred</code> only once on each member of <code>iterable</code>), is that it moves a lot of logic out of the interpreter and into highly-optimized iteration and mapping code. This can speed up iteration over long iterables, as described <a href="http://stackoverflow.com/a/25881130/3408454">in this answer</a>.</p>
<p>Expressivity-wise, it takes advantage of expressive idioms like comprehensions and mapping.</p>
| 0 | 2014-12-17T02:00:27Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 28,692,091 | <pre><code>def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
</code></pre>
<p>Check <a href="https://docs.python.org/3/library/itertools.html#itertools-recipes" rel="nofollow">this</a></p>
| 3 | 2015-02-24T09:26:53Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 29,913,433 | <h1>solution</h1>
<pre><code>from itertools import tee
def unpack_args(fn):
return lambda t: fn(*t)
def separate(fn, lx):
return map(
unpack_args(
lambda i, ly: filter(
lambda el: bool(i) == fn(el),
ly)),
enumerate(tee(lx, 2)))
</code></pre>
<h1>test</h1>
<pre><code>[even, odd] = separate(
lambda x: bool(x % 2),
[1, 2, 3, 4, 5])
print(list(even) == [2, 4])
print(list(odd) == [1, 3, 5])
</code></pre>
| 0 | 2015-04-28T07:49:17Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 29,990,598 | <p>I think a generalization of splitting a an iterable based on N conditions is handy</p>
<pre><code>from collections import OrderedDict
def partition(iterable,*conditions):
'''Returns a list with the elements that satisfy each of condition.
Conditions are assumed to be exclusive'''
d= OrderedDict((i,list())for i in range(len(conditions)))
for e in iterable:
for i,condition in enumerate(conditions):
if condition(e):
d[i].append(e)
break
return d.values()
</code></pre>
<p>For instance: </p>
<pre><code>ints,floats,other = partition([2, 3.14, 1, 1.69, [], None],
lambda x: isinstance(x, int),
lambda x: isinstance(x, float),
lambda x: True)
print " ints: {}\n floats:{}\n other:{}".format(ints,floats,other)
ints: [2, 1]
floats:[3.14, 1.69]
other:[[], None]
</code></pre>
<p>If the element may satisfy multiple conditions, remove the break. </p>
| 3 | 2015-05-01T16:08:09Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 31,448,772 | <p>Sometimes, it looks like list comprehension is not the best thing to use !</p>
<p>I made a little test based on the answer people gave to this topic, tested on a random generated list. Here is the generation of the list (there's probably a better way to do, but it's not the point) :</p>
<pre><code>good_list = ('.jpg','.jpeg','.gif','.bmp','.png')
import random
import string
my_origin_list = []
for i in xrange(10000):
fname = ''.join(random.choice(string.lowercase) for i in range(random.randrange(10)))
if random.getrandbits(1):
fext = random.choice(good_list)
else:
fext = "." + ''.join(random.choice(string.lowercase) for i in range(3))
my_origin_list.append((fname + fext, random.randrange(1000), fext))
</code></pre>
<p>And here we go</p>
<pre><code># Parand
def f1():
return [e for e in my_origin_list if e[2] in good_list], [e for e in my_origin_list if not e[2] in good_list]
# dbr
def f2():
a, b = list(), list()
for e in my_origin_list:
if e[2] in good_list:
a.append(e)
else:
b.append(e)
return a, b
# John La Rooy
def f3():
a, b = list(), list()
for e in my_origin_list:
(b, a)[e[2] in good_list].append(e)
return a, b
# Ants Aasma
def f4():
l1, l2 = tee((e[2] in good_list, e) for e in my_origin_list)
return [i for p, i in l1 if p], [i for p, i in l2 if not p]
# My personal way to do
def f5():
a, b = zip(*[(e, None) if e[2] in good_list else (None, e) for e in my_origin_list])
return list(filter(None, a)), list(filter(None, b))
# BJ Homer
def f6():
return filter(lambda e: e[2] in good_list, my_origin_list), filter(lambda e: not e[2] in good_list, my_origin_list)
</code></pre>
<p>Using the <a href="https://gist.github.com/sekimura/660557" rel="nofollow" title="cmpthese function">cmpthese</a> function, the best result is the dbr answer :</p>
<pre><code>f1 204/s -- -5% -14% -15% -20% -26%
f6 215/s 6% -- -9% -11% -16% -22%
f3 237/s 16% 10% -- -2% -7% -14%
f4 240/s 18% 12% 2% -- -6% -13%
f5 255/s 25% 18% 8% 6% -- -8%
f2 277/s 36% 29% 17% 15% 9% --
</code></pre>
| 1 | 2015-07-16T08:12:37Z | [
"python"
] |
Python: split a list based on a condition? | 949,098 | <p>What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>is there a more elegant way to do this?</p>
<p>Update: here's the actual use case, to better explain what I'm trying to do:</p>
<pre><code># files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
</code></pre>
| 132 | 2009-06-04T07:37:18Z | 31,562,455 | <p>Yet another solution to this problem. I needed a solution that is as fast as possible. That means only one iteration over the list and preferably O(1) for adding data to one of the resulting lists. This is very similar to the solution provided by <em>sastanin</em>, except much shorter:</p>
<pre><code>from collections import deque
def split(iterable, function):
dq_true = deque()
dq_false = deque()
# deque - the fastest way to consume an iterator and append items
deque((
(dq_true if function(item) else dq_false).append(item) for item in iterable
), maxlen=0)
return dq_true, dq_false
</code></pre>
<p>Then, you can use the function in the following way:</p>
<pre><code>lower, higher = split([0,1,2,3,4,5,6,7,8,9], lambda x: x < 5)
selected, other = split([0,1,2,3,4,5,6,7,8,9], lambda x: x in {0,4,9})
</code></pre>
<p>If you're not fine with the resulting <code>deque</code> object, you can easily convert it to <code>list</code>, <code>set</code>, whatever you like (for example <code>list(lower)</code>). The conversion is much faster, that construction of the lists directly.</p>
<p>This methods keeps order of the items, as well as any duplicates.</p>
| 1 | 2015-07-22T11:58:18Z | [
"python"
] |
ODFPy documentation | 949,171 | <p>I need to manipulate the ODF file format (open document format, the open office's internal format), and I need to do it in Python.</p>
<p>It seem's ODFPy is a wonderful library for this purpose. Unfortunately the official documentation is very poor, almost unuseful. I can't find almost anything online - maybe it is not so popular?</p>
<p>Is there anyone who can point me at some some information or better documentation?</p>
| 13 | 2009-06-04T08:03:41Z | 950,025 | <p>Okay, here's a quick help:</p>
<ol>
<li><p>Grab odfpy source code:</p>
<pre><code>~$ svn checkout https://svn.forge.osor.eu/svn/odfpy/trunk odfpy
</code></pre></li>
<li><p>Install it:</p>
<pre><code> ~$ cd odfpy
~/odfpy$ python setup.py install
</code></pre></li>
<li><p>Generate the documentation:</p>
<pre><code>~/odfpy$ epydoc --pdf odf
</code></pre>
<p>I have uploaded the generated documentation <a href="http://www.scribd.com/share/upload/12470875/fzwrhznjbjmlmfkulet" rel="nofollow">here</a>.</p></li>
<li><p>Run this simple example program:</p>
<pre><code>from odf.opendocument import OpenDocumentText
from odf.text import P
textdoc = OpenDocumentText()
p = P(text="Hello World!")
textdoc.text.addElement(p)
textdoc.save("helloworld", True)
</code></pre></li>
<li><p>Read the examples and try to make sense of everything:</p>
<pre><code>~/odfpy$ emacs examples/*.py
</code></pre></li>
</ol>
<p>Hope that helps! Good luck!</p>
| -1 | 2009-06-04T11:45:14Z | [
"python",
"openoffice.org",
"odf"
] |
ODFPy documentation | 949,171 | <p>I need to manipulate the ODF file format (open document format, the open office's internal format), and I need to do it in Python.</p>
<p>It seem's ODFPy is a wonderful library for this purpose. Unfortunately the official documentation is very poor, almost unuseful. I can't find almost anything online - maybe it is not so popular?</p>
<p>Is there anyone who can point me at some some information or better documentation?</p>
| 13 | 2009-06-04T08:03:41Z | 2,183,603 | <p>The documentation is unfortunately horrible, and the generated Python wrapper is lousily documented in code, providing lots of functions whose argument lists look like func(*args).</p>
<p>The reference manual <em>is</em> actually useful, but not when you're starting out - it doesn't provide any context of how to use these functions. I would suggest starting with the <a href="http://odfpy.forge.osor.eu/tutorial/" rel="nofollow">tutorial</a> and all the <a href="https://github.com/eea/odfpy/tree/master/examples" rel="nofollow">examples</a>. Even though they may have <em>nothing</em> to do with your use case, they will help you get the feel of how the package works. After you've gotten used to the way the package is structured, you can often make sense of the documentation by combining the API doc with the information in the <a href="http://books.evc-cit.info/odbook/book.html" rel="nofollow">OpenDocument Essentials</a> book.</p>
<p>(The relationship is somewhat tenuous at best, but you can often intuit method and attribute values from it. When working with the spreadsheet, for example, the handy list of office:value-type data in the book provided the necessary constants for building proper TableCell(valuetype=...) instances)</p>
<p>Also, making small documents in OpenOffice and then inspecting the xml and comparing it to the XML generated from ODFPy greatly helps you debug where you might have gone wrong.</p>
| 7 | 2010-02-02T11:26:47Z | [
"python",
"openoffice.org",
"odf"
] |
ODFPy documentation | 949,171 | <p>I need to manipulate the ODF file format (open document format, the open office's internal format), and I need to do it in Python.</p>
<p>It seem's ODFPy is a wonderful library for this purpose. Unfortunately the official documentation is very poor, almost unuseful. I can't find almost anything online - maybe it is not so popular?</p>
<p>Is there anyone who can point me at some some information or better documentation?</p>
| 13 | 2009-06-04T08:03:41Z | 12,596,531 | <p>try <a href="http://pypi.python.org/pypi/ezodf/0.2.1" rel="nofollow">ezodf</a>
they also have a <a href="http://packages.python.org/ezodf/" rel="nofollow">doc</a></p>
| 1 | 2012-09-26T07:19:17Z | [
"python",
"openoffice.org",
"odf"
] |
ODFPy documentation | 949,171 | <p>I need to manipulate the ODF file format (open document format, the open office's internal format), and I need to do it in Python.</p>
<p>It seem's ODFPy is a wonderful library for this purpose. Unfortunately the official documentation is very poor, almost unuseful. I can't find almost anything online - maybe it is not so popular?</p>
<p>Is there anyone who can point me at some some information or better documentation?</p>
| 13 | 2009-06-04T08:03:41Z | 14,034,221 | <p>I found more documentation (the web site has been reorganized in the past few years) in <a href="https://joinup.ec.europa.eu/sites/default/files/api-for-odfpy.odt" rel="nofollow">api-for-odfpy.odt</a>.</p>
| 2 | 2012-12-25T21:47:02Z | [
"python",
"openoffice.org",
"odf"
] |
ODFPy documentation | 949,171 | <p>I need to manipulate the ODF file format (open document format, the open office's internal format), and I need to do it in Python.</p>
<p>It seem's ODFPy is a wonderful library for this purpose. Unfortunately the official documentation is very poor, almost unuseful. I can't find almost anything online - maybe it is not so popular?</p>
<p>Is there anyone who can point me at some some information or better documentation?</p>
| 13 | 2009-06-04T08:03:41Z | 19,583,120 | <p>There's a good example of odfpy usage at <a href="http://mashupguide.net/1.0/html/ch17s04.xhtml" rel="nofollow">http://mashupguide.net/1.0/html/ch17s04.xhtml</a></p>
| 4 | 2013-10-25T06:59:24Z | [
"python",
"openoffice.org",
"odf"
] |
ODFPy documentation | 949,171 | <p>I need to manipulate the ODF file format (open document format, the open office's internal format), and I need to do it in Python.</p>
<p>It seem's ODFPy is a wonderful library for this purpose. Unfortunately the official documentation is very poor, almost unuseful. I can't find almost anything online - maybe it is not so popular?</p>
<p>Is there anyone who can point me at some some information or better documentation?</p>
| 13 | 2009-06-04T08:03:41Z | 28,577,394 | <p>It's outdated, a bit, but could help someone.
I have found only one way to work with ODFPY:</p>
<ol>
<li>generate your ODF document (i.e. f1.ods)</li>
<li>make copy of it and edit in LibreOffice/OpenOffice or other (i.e. f2.odf)</li>
<li>change both files to f1.zip and f2.zip</li>
<li>extract both files.</li>
</ol>
<p>main formatting and data is located in "content.xml" and "styles.xml"</p>
<ol start="5">
<li>compare both formatting</li>
<li>make changes in python script</li>
<li>iterate 1-7 until you have sufficient result :D:D</li>
</ol>
<p>Here is some date-time format example, I have made that way:</p>
<pre><code>from odf.opendocument import OpenDocumentSpreadsheet
from odf.style import Style, TableCellProperties
from odf.number import DateStyle, Text, Year, Month, Day, Hours, Minutes, Seconds
from odf.text import P
from odf.table import Table, TableRow, TableCell
# Generate document object
doc = OpenDocumentSpreadsheet()
table = Table(name="Exported data")
#create custom format in styles.xml
date_style = DateStyle(name="date-style1") #, language="lv", country="LV")
date_style.addElement(Year(style="long"))
date_style.addElement(Text(text=u"-"))
date_style.addElement(Month(style="long"))
date_style.addElement(Text(text=u"-"))
date_style.addElement(Day(style="long"))
date_style.addElement(Text(text=u" "))
date_style.addElement(Hours(style="long"))
date_style.addElement(Text(text=u":"))
date_style.addElement(Minutes(style="long"))
date_style.addElement(Text(text=u":"))
date_style.addElement(Seconds(style="long", decimalplaces="3"))
doc.styles.addElement(date_style)
#link to generated style from content.xml
ds = Style(name="ds1", datastylename="date-style1",parentstylename="Default", family="table-cell")
doc.automaticstyles.addElement(ds)
#create simple cell
tr = TableRow()
tc = TableCell(valuetype='string')
tc.addElement(P(text = "Date-Time"))
tr.addElement(tc)
table.addElement(tr)
#create cell with custom formatting
lineDT = #some date-time variable
tr = TableRow()
tc = TableCell(valuetype='date',datevalue = lineDT.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],stylename=ds)
tc.addElement(P(text=lineDT.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]))
tr.addElement(tc)
table.addElement(tr)
#save ods
doc.spreadsheet.addElement(table)
doc.save("test.ods", True)
</code></pre>
<p>I have updated code, a bit, because previous version opened wrong on MS product.</p>
| 1 | 2015-02-18T06:31:49Z | [
"python",
"openoffice.org",
"odf"
] |
How do I infer the class to which a @staticmethod belongs? | 949,259 | <p>I am trying to implement <code>infer_class</code> function that, given a method, figures out the class to which the method belongs.</p>
<p>So far I have something like this:</p>
<pre><code>import inspect
def infer_class(f):
if inspect.ismethod(f):
return f.im_self if f.im_class == type else f.im_class
# elif ... what about staticmethod-s?
else:
raise TypeError("Can't infer the class of %r" % f)
</code></pre>
It does not work for @staticmethod-s because I was not able to come up with a way to achieve this.
Any suggestions?
Here's `infer_class` in action:
<pre><code>
>>> class Wolf(object):
... @classmethod
... def huff(cls, a, b, c):
... pass
... def snarl(self):
... pass
... @staticmethod
... def puff(k,l, m):
... pass
...
>>> print infer_class(Wolf.huff)
<class '__main__.Wolf'>
>>> print infer_class(Wolf().huff)
<class '__main__.Wolf'>
>>> print infer_class(Wolf.snarl)
<class '__main__.Wolf'>
>>> print infer_class(Wolf().snarl)
<class '__main__.Wolf'>
>>> print infer_class(Wolf.puff)
</code></pre><pre>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in infer_class
TypeError: Can't infer the class of <function puff at ...>
</pre>
| 4 | 2009-06-04T08:30:23Z | 949,407 | <p>That's because staticmethods really aren't methods. The staticmethod descriptor returns the original function as is. There is no way to get the class via which the function was accessed. But there is no real reason to use staticmethods for methods anyway, always use classmethods.</p>
<p>The only use that I have found for staticmethods is to store function objects as class attributes and not have them turn into methods.</p>
| 3 | 2009-06-04T09:09:15Z | [
"python",
"decorator",
"static-methods",
"inspect"
] |
How do I infer the class to which a @staticmethod belongs? | 949,259 | <p>I am trying to implement <code>infer_class</code> function that, given a method, figures out the class to which the method belongs.</p>
<p>So far I have something like this:</p>
<pre><code>import inspect
def infer_class(f):
if inspect.ismethod(f):
return f.im_self if f.im_class == type else f.im_class
# elif ... what about staticmethod-s?
else:
raise TypeError("Can't infer the class of %r" % f)
</code></pre>
It does not work for @staticmethod-s because I was not able to come up with a way to achieve this.
Any suggestions?
Here's `infer_class` in action:
<pre><code>
>>> class Wolf(object):
... @classmethod
... def huff(cls, a, b, c):
... pass
... def snarl(self):
... pass
... @staticmethod
... def puff(k,l, m):
... pass
...
>>> print infer_class(Wolf.huff)
<class '__main__.Wolf'>
>>> print infer_class(Wolf().huff)
<class '__main__.Wolf'>
>>> print infer_class(Wolf.snarl)
<class '__main__.Wolf'>
>>> print infer_class(Wolf().snarl)
<class '__main__.Wolf'>
>>> print infer_class(Wolf.puff)
</code></pre><pre>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in infer_class
TypeError: Can't infer the class of <function puff at ...>
</pre>
| 4 | 2009-06-04T08:30:23Z | 966,095 | <p>I have trouble bringing myself to actually <em>recommend</em> this, but it does seem to work for straightforward cases, at least:</p>
<pre><code>import inspect
def crack_staticmethod(sm):
"""
Returns (class, attribute name) for `sm` if `sm` is a
@staticmethod.
"""
mod = inspect.getmodule(sm)
for classname in dir(mod):
cls = getattr(mod, classname, None)
if cls is not None:
try:
ca = inspect.classify_class_attrs(cls)
for attribute in ca:
o = attribute.object
if isinstance(o, staticmethod) and getattr(cls, sm.__name__) == sm:
return (cls, sm.__name__)
except AttributeError:
pass
</code></pre>
| 3 | 2009-06-08T17:55:32Z | [
"python",
"decorator",
"static-methods",
"inspect"
] |
Terminating a Python Program | 949,504 | <p>What command do you use in python to terminate a program?</p>
<p>i.e. the equivalent of "end" in basic, or "quit" in BASH.</p>
<p>I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried </p>
<pre><code>import sys
sys.exit()
</code></pre>
<p>but it will display following error :</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
</code></pre>
<p>is there any solution for it .</p>
| 4 | 2009-06-04T09:35:06Z | 949,519 | <p>sys.exit(error_code) </p>
<p>Error_code will be 0 for a normal exit, 1 or some other positive number for an exit due to an error of some kind, e.g. the user has entered the wrong parameters.</p>
<p>sys.exit() "is undefined on some architectures", (although it worked when I tried it on my Linux box!)</p>
<p>The <a href="http://docs.python.org/library/sys.html" rel="nofollow">official python docs</a> explains this more fully. </p>
<p>It's an extremely good idea for all your programs and scripts to follow the return convention. </p>
<p>For example if you run a script which grabs some data out of a database; returning 0 and no output, means the database is perfectly fine there's just nothing in it (or nothing matching your query). returning 1 and no output means there is a fault with the database, the whole process should abort, because to continue would corrupt the other system too.</p>
| 8 | 2009-06-04T09:37:34Z | [
"python"
] |
Terminating a Python Program | 949,504 | <p>What command do you use in python to terminate a program?</p>
<p>i.e. the equivalent of "end" in basic, or "quit" in BASH.</p>
<p>I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried </p>
<pre><code>import sys
sys.exit()
</code></pre>
<p>but it will display following error :</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
</code></pre>
<p>is there any solution for it .</p>
| 4 | 2009-06-04T09:35:06Z | 949,520 | <p>Try running a python interpreter out of your IDE. In my Windows installation the simple command line <code>python.exe</code>, both options work:</p>
<pre><code>>>> import sys
>>> sys.exit()
</code></pre>
<p>or</p>
<pre><code>>>> raise SystemExit
</code></pre>
| 0 | 2009-06-04T09:37:41Z | [
"python"
] |
Terminating a Python Program | 949,504 | <p>What command do you use in python to terminate a program?</p>
<p>i.e. the equivalent of "end" in basic, or "quit" in BASH.</p>
<p>I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried </p>
<pre><code>import sys
sys.exit()
</code></pre>
<p>but it will display following error :</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
</code></pre>
<p>is there any solution for it .</p>
| 4 | 2009-06-04T09:35:06Z | 949,923 | <p><code>sys.exit()</code> raises the <code>SystemExit</code> exception.</p>
<p>If you don't catch that exception the program ends.</p>
<p>Since you're getting that output, I'm not sure what is happening, but I guess that you're catching all exceptions and printing them yourself:</p>
<pre><code>try:
...
except:
print exception somehow
raise
</code></pre>
<p>If that's the case, don't do that. catch <code>Exception</code> instead:</p>
<pre><code>...
except Exception:
...
</code></pre>
<p>That way you won't catch things not meant to be catched (like <code>SystemExit</code>).</p>
| 9 | 2009-06-04T11:19:34Z | [
"python"
] |
Terminating a Python Program | 949,504 | <p>What command do you use in python to terminate a program?</p>
<p>i.e. the equivalent of "end" in basic, or "quit" in BASH.</p>
<p>I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried </p>
<pre><code>import sys
sys.exit()
</code></pre>
<p>but it will display following error :</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
</code></pre>
<p>is there any solution for it .</p>
| 4 | 2009-06-04T09:35:06Z | 950,152 | <p>import sys</p>
<p>sys.exit(0)</p>
| 1 | 2009-06-04T12:14:30Z | [
"python"
] |
Terminating a Python Program | 949,504 | <p>What command do you use in python to terminate a program?</p>
<p>i.e. the equivalent of "end" in basic, or "quit" in BASH.</p>
<p>I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried </p>
<pre><code>import sys
sys.exit()
</code></pre>
<p>but it will display following error :</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
</code></pre>
<p>is there any solution for it .</p>
| 4 | 2009-06-04T09:35:06Z | 953,385 | <p>You should also consider alternatives to exiting directly. Often <code>return</code> works just as well if you wrap code in a function. (Better, in fact, because it avoids sys.exit() weirdness.)</p>
<pre><code>def main():
...do something...
if something:
return # <----- return takes the place of exit
...do something else...
main()
</code></pre>
| 6 | 2009-06-04T22:08:19Z | [
"python"
] |
Terminating a Python Program | 949,504 | <p>What command do you use in python to terminate a program?</p>
<p>i.e. the equivalent of "end" in basic, or "quit" in BASH.</p>
<p>I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried </p>
<pre><code>import sys
sys.exit()
</code></pre>
<p>but it will display following error :</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
</code></pre>
<p>is there any solution for it .</p>
| 4 | 2009-06-04T09:35:06Z | 953,495 | <p>In your case, your error is likely that you have a bare except block that is catching the SystemExit exception, like this:</p>
<pre><code>import sys
try:
sys.exit(return_code)
except:
pass
</code></pre>
<p>The correct way to fix your problem is to remove the <strong>except:</strong> portion, and instead just catch the Exceptions you expect to be possibly raised. For example:</p>
<pre><code>try:
# Code which could raise exceptions
except (NameError, ValueError):
# Do something in case of NameError or ValueError, but
# ignore other exceptions (like SystemExit)
</code></pre>
<p>However, if you really wanted your program to exit, the following code will work:</p>
<pre><code>import os
try:
os._exit(return_code)
except:
pass
</code></pre>
<p>This will exit even with the <strong>except:</strong> clause, as it just directly calls the C function of the same name which kills your process. This is <strong>not recommended</strong> unless you know what you are doing, since this will not call cleanup handlers or flush open IO buffers.</p>
| 0 | 2009-06-04T22:44:10Z | [
"python"
] |
Terminating a Python Program | 949,504 | <p>What command do you use in python to terminate a program?</p>
<p>i.e. the equivalent of "end" in basic, or "quit" in BASH.</p>
<p>I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried </p>
<pre><code>import sys
sys.exit()
</code></pre>
<p>but it will display following error :</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
</code></pre>
<p>is there any solution for it .</p>
| 4 | 2009-06-04T09:35:06Z | 14,329,160 | <pre><code>sys.exit() #to exit the program
return #to exit from a function
</code></pre>
| 0 | 2013-01-15T00:16:17Z | [
"python"
] |
Python REPL for a running process | 949,784 | <p>I am currently developing a simple application in python that connects to a server. At the moment, it's single-threaded (as multithreading is not currently required).</p>
<p>However I would like - for debugging, maintenance and such to also be able to have a REPL via stdin.</p>
<p>How do I go about that, if possible? Will I need to keep anything in mind? Will I have to make a separate thread for it?</p>
| 5 | 2009-06-04T10:42:26Z | 949,847 | <p>You either need to go non-blocking or use a thread.</p>
<p>I would personally use Twisted for concurrency, which also offers a REPL-protocol which is easy to integrate.</p>
| 3 | 2009-06-04T10:56:59Z | [
"python",
"read-eval-print-loop"
] |
Python REPL for a running process | 949,784 | <p>I am currently developing a simple application in python that connects to a server. At the moment, it's single-threaded (as multithreading is not currently required).</p>
<p>However I would like - for debugging, maintenance and such to also be able to have a REPL via stdin.</p>
<p>How do I go about that, if possible? Will I need to keep anything in mind? Will I have to make a separate thread for it?</p>
| 5 | 2009-06-04T10:42:26Z | 949,919 | <p>Maybe <a href="http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application">this</a> question could help. You can modify it a bit to create a customized REPL.</p>
| 1 | 2009-06-04T11:18:07Z | [
"python",
"read-eval-print-loop"
] |
Python REPL for a running process | 949,784 | <p>I am currently developing a simple application in python that connects to a server. At the moment, it's single-threaded (as multithreading is not currently required).</p>
<p>However I would like - for debugging, maintenance and such to also be able to have a REPL via stdin.</p>
<p>How do I go about that, if possible? Will I need to keep anything in mind? Will I have to make a separate thread for it?</p>
| 5 | 2009-06-04T10:42:26Z | 38,931,278 | <p>There's also <a href="https://github.com/aaiyer/rfoo" rel="nofollow">rfoo</a>. From the README:</p>
<blockquote>
<p>rconsole - included with rfoo package is a remote Python console with
auto completion, which can be used to inspect and modify namespace of a
running script.</p>
<p>To activate in a script do:</p>
</blockquote>
<pre><code>from rfoo.utils import rconsole
rconsole.spawn_server()
</code></pre>
<blockquote>
<p>To attach from a shell do:</p>
</blockquote>
<pre><code>$ rconsole
</code></pre>
<blockquote>
<p>SECURITY NOTE:<br>
The rconsole listener started with spawn_server() will accept any local
connection and may therefore be insecure to use in shared hosting
or similar environments!</p>
</blockquote>
| 0 | 2016-08-13T09:27:57Z | [
"python",
"read-eval-print-loop"
] |
Error trapping when a user inputs incorect information | 949,941 | <p>So, i have recently started learning python...i am writing a small script that pulls information from a csv and i need to be able to notify a user of an incorrect input</p>
<p>for example</p>
<p>the user is asked for his id number, the id number is anything from r1 to r5
i would like my script to be able to tell the user that they have input something wrong
for example, if the user inputs a1 or r50, the user needs to be notified that they have input the wrong parameters. how do i do this?</p>
<p>i have looked into
def statements, but i cannot seem to grasp all the syntax in python....(i dont know all the commands...parameters and stuff)</p>
<p>any help would be very much appreciated =D</p>
<pre><code>while True:
import csv
DATE, ROOM, COURSE, STAGE = range (4)
csv_in = open("roombookings.csv", "rb")
reader = csv.reader (csv_in)
data = []
for row in reader:
data.append(row)
roomlist = raw_input ("Enter the room number: ")
print "The room you have specified has the following courses running: "
for sub_list in data:
if sub_list[ROOM] == roomlist:
Date, Room, Course, Stage = sub_list
print Date, Course
</code></pre>
| 0 | 2009-06-04T11:25:16Z | 950,080 | <p>I'm not sure what are you asking for, but if you wish to check if user entered correct id, you should try regular expressions. Look at <a href="http://docs.python.org/library/re.html" rel="nofollow">Python Documentation on module re</a>. Or ask google for "python re"</p>
<p>Here's an example that will check user's input:</p>
<pre><code>import re
id_patt = re.compile(r'^r[1-5]$')
def checkId(id):
if id_patt.match(id):
return True
return False
</code></pre>
<p>HTH, regards.</p>
<p>EDIT: I read you're question again, here's some more code:
(just paste it below previous code fragment)</p>
<pre><code>validId = False
while not validId:
id = raw_input("Enter id: ")
validId = checkId(id)
</code></pre>
<p>By the way, it could be written in quite shorter way, but this piece of code should be easier to understand for someone new to Python.</p>
| 1 | 2009-06-04T11:57:55Z | [
"python",
"csv",
"reporting",
"user-input"
] |
Error trapping when a user inputs incorect information | 949,941 | <p>So, i have recently started learning python...i am writing a small script that pulls information from a csv and i need to be able to notify a user of an incorrect input</p>
<p>for example</p>
<p>the user is asked for his id number, the id number is anything from r1 to r5
i would like my script to be able to tell the user that they have input something wrong
for example, if the user inputs a1 or r50, the user needs to be notified that they have input the wrong parameters. how do i do this?</p>
<p>i have looked into
def statements, but i cannot seem to grasp all the syntax in python....(i dont know all the commands...parameters and stuff)</p>
<p>any help would be very much appreciated =D</p>
<pre><code>while True:
import csv
DATE, ROOM, COURSE, STAGE = range (4)
csv_in = open("roombookings.csv", "rb")
reader = csv.reader (csv_in)
data = []
for row in reader:
data.append(row)
roomlist = raw_input ("Enter the room number: ")
print "The room you have specified has the following courses running: "
for sub_list in data:
if sub_list[ROOM] == roomlist:
Date, Room, Course, Stage = sub_list
print Date, Course
</code></pre>
| 0 | 2009-06-04T11:25:16Z | 950,102 | <p>Seriously, read a tutorial. The <a href="http://docs.python.org/tut" rel="nofollow">official</a> one is pretty good. I also like <a href="http://greenteapress.com/thinkpython/thinkpython.html" rel="nofollow">this book</a> for beginners.</p>
<pre><code>import csv
while True:
id_number = raw_input('(enter to quit) ID number:')
if not id_number:
break
# open the csv file
csvfile = csv.reader(open('file.csv'))
for row in csvfile:
# for this simple example I assume that the first column
# on the csv is the ID:
if row[0] == id_number:
print "Found. Here's the data:", row
break
else:
print "ID not found, try again!"
</code></pre>
<p><hr /></p>
<p>EDIT
Now that you've added code, I update the example:</p>
<pre><code>import csv
DATE, ROOM, COURSE, STAGE = range(4)
while True:
csv_in = open("roombookings.csv", "rb")
reader = csv.reader(csv_in)
roomlist = raw_input("(Enter to quit) Room number: ")
if not roomlist:
break
print "The room you have specified has the following courses running: "
for sub_list in reader:
if sub_list[ROOM] == roomlist:
print sub_list[DATE], sub_list[COURSE]
</code></pre>
| 1 | 2009-06-04T12:03:23Z | [
"python",
"csv",
"reporting",
"user-input"
] |
Referencing a class' method, not an instance's | 950,053 | <p>I'm writing a function that exponentiates an object, i.e. given a and n, returns a<sup>n</sup>. Since a needs not be a built-in type, the function accepts, as a keyword argument, a function to perform multiplications. If undefined, it defaults to the objects <code>__mul__</code> method, i.e. the object itself is expected to have multiplication defined. That part is sort of easy:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
if mul is None :
mul = lambda x,y : x*y
</code></pre>
<p>The thing is that in the process of calculating a<sup>n</sup> the are a lot of intermediate squarings, and there often are more efficient ways to compute them than simply multiplying the object by itself. It is easy to define another function that computes the square and pass it as another keyword argument, something like:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
</code></pre>
<p>The problem here comes if the function to square the object is not a standalone function, but is a method of the object being exponentiated, which would be a very reasonable thing to do. The only way of doing this I can think of is something like this:</p>
<pre><code>import inspect
def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
elif inspect.isfunction(sqr) == False : # if not a function, it is a string
sqr = lambda x : eval('x.'+sqr+'()')
</code></pre>
<p>It does work, but I find it an extremely unelegant way of doing things... My mastery of OOP is limited, but if there was a way to have sqr point to the class' function, not to an instance's one, then I could get away with something like <code>sqr = lambda x : sqr(x)</code>, or maybe <code>sqr = lambda x: x.sqr()</code>. Can this be done? Is there any other more pythonic way?</p>
| 0 | 2009-06-04T11:53:40Z | 950,139 | <p>I understand it's the sqr-bit at the end you want to fix. If so, I suggest <code>getattr</code>. Example:</p>
<pre><code>class SquarableThingy:
def __init__(self, i):
self.i = i
def squarify(self):
return self.i**2
class MultipliableThingy:
def __init__(self, i):
self.i = i
def __mul__(self, other):
return self.i * other.i
x = SquarableThingy(3)
y = MultipliableThingy(4)
z = 5
sqr = 'squarify'
sqrFunX = getattr(x, sqr, lambda: x*x)
sqrFunY = getattr(y, sqr, lambda: y*y)
sqrFunZ = getattr(z, sqr, lambda: z*z)
assert sqrFunX() == 9
assert sqrFunY() == 16
assert sqrFunZ() == 25
</code></pre>
| -1 | 2009-06-04T12:12:30Z | [
"python"
] |
Referencing a class' method, not an instance's | 950,053 | <p>I'm writing a function that exponentiates an object, i.e. given a and n, returns a<sup>n</sup>. Since a needs not be a built-in type, the function accepts, as a keyword argument, a function to perform multiplications. If undefined, it defaults to the objects <code>__mul__</code> method, i.e. the object itself is expected to have multiplication defined. That part is sort of easy:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
if mul is None :
mul = lambda x,y : x*y
</code></pre>
<p>The thing is that in the process of calculating a<sup>n</sup> the are a lot of intermediate squarings, and there often are more efficient ways to compute them than simply multiplying the object by itself. It is easy to define another function that computes the square and pass it as another keyword argument, something like:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
</code></pre>
<p>The problem here comes if the function to square the object is not a standalone function, but is a method of the object being exponentiated, which would be a very reasonable thing to do. The only way of doing this I can think of is something like this:</p>
<pre><code>import inspect
def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
elif inspect.isfunction(sqr) == False : # if not a function, it is a string
sqr = lambda x : eval('x.'+sqr+'()')
</code></pre>
<p>It does work, but I find it an extremely unelegant way of doing things... My mastery of OOP is limited, but if there was a way to have sqr point to the class' function, not to an instance's one, then I could get away with something like <code>sqr = lambda x : sqr(x)</code>, or maybe <code>sqr = lambda x: x.sqr()</code>. Can this be done? Is there any other more pythonic way?</p>
| 0 | 2009-06-04T11:53:40Z | 950,161 | <p>here's how I'd do it:</p>
<pre><code>import operator
def bin_pow(a, n, **kwargs) :
pow_function = kwargs.pop('pow' ,None)
if pow_function is None:
pow_function = operator.pow
return pow_function(a, n)
</code></pre>
<p>That's the fastest way. See also <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fpow%5F%5F" rel="nofollow"><code>object.__pow__</code></a> and the <a href="http://docs.python.org/library/operator.html" rel="nofollow"><code>operator</code></a> module documentations.</p>
<p>Now, to pass an object method you can pass it directly, no need to pass a string with the name. In fact, never use strings for this kind of thing, using the object directly is much better.</p>
<p>If you want the unbound method, you can pass it just as well:</p>
<pre><code>class MyClass(object):
def mymethod(self, other):
return do_something_with_self_and_other
m = MyClass()
n = MyClass()
bin_pow(m, n, pow=MyClass.mymethod)
</code></pre>
<p>If you want the class method, so just pass it instead:</p>
<pre><code>class MyClass(object):
@classmethod
def mymethod(cls, x, y):
return do_something_with_x_and_y
m = MyClass()
n = MyClass()
bin_pow(m, n, pow=MyClass.mymethod)
</code></pre>
| 3 | 2009-06-04T12:17:34Z | [
"python"
] |
Referencing a class' method, not an instance's | 950,053 | <p>I'm writing a function that exponentiates an object, i.e. given a and n, returns a<sup>n</sup>. Since a needs not be a built-in type, the function accepts, as a keyword argument, a function to perform multiplications. If undefined, it defaults to the objects <code>__mul__</code> method, i.e. the object itself is expected to have multiplication defined. That part is sort of easy:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
if mul is None :
mul = lambda x,y : x*y
</code></pre>
<p>The thing is that in the process of calculating a<sup>n</sup> the are a lot of intermediate squarings, and there often are more efficient ways to compute them than simply multiplying the object by itself. It is easy to define another function that computes the square and pass it as another keyword argument, something like:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
</code></pre>
<p>The problem here comes if the function to square the object is not a standalone function, but is a method of the object being exponentiated, which would be a very reasonable thing to do. The only way of doing this I can think of is something like this:</p>
<pre><code>import inspect
def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
elif inspect.isfunction(sqr) == False : # if not a function, it is a string
sqr = lambda x : eval('x.'+sqr+'()')
</code></pre>
<p>It does work, but I find it an extremely unelegant way of doing things... My mastery of OOP is limited, but if there was a way to have sqr point to the class' function, not to an instance's one, then I could get away with something like <code>sqr = lambda x : sqr(x)</code>, or maybe <code>sqr = lambda x: x.sqr()</code>. Can this be done? Is there any other more pythonic way?</p>
| 0 | 2009-06-04T11:53:40Z | 950,166 | <p>If you want to call the class's method, and not the (possibly overridden) instance's method, you can do</p>
<pre><code>instance.__class__.method(instance)
</code></pre>
<p>instead of</p>
<pre><code>instance.method()
</code></pre>
<p>I'm not sure though if that's what you want.</p>
| 1 | 2009-06-04T12:18:19Z | [
"python"
] |
Referencing a class' method, not an instance's | 950,053 | <p>I'm writing a function that exponentiates an object, i.e. given a and n, returns a<sup>n</sup>. Since a needs not be a built-in type, the function accepts, as a keyword argument, a function to perform multiplications. If undefined, it defaults to the objects <code>__mul__</code> method, i.e. the object itself is expected to have multiplication defined. That part is sort of easy:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
if mul is None :
mul = lambda x,y : x*y
</code></pre>
<p>The thing is that in the process of calculating a<sup>n</sup> the are a lot of intermediate squarings, and there often are more efficient ways to compute them than simply multiplying the object by itself. It is easy to define another function that computes the square and pass it as another keyword argument, something like:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
</code></pre>
<p>The problem here comes if the function to square the object is not a standalone function, but is a method of the object being exponentiated, which would be a very reasonable thing to do. The only way of doing this I can think of is something like this:</p>
<pre><code>import inspect
def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
elif inspect.isfunction(sqr) == False : # if not a function, it is a string
sqr = lambda x : eval('x.'+sqr+'()')
</code></pre>
<p>It does work, but I find it an extremely unelegant way of doing things... My mastery of OOP is limited, but if there was a way to have sqr point to the class' function, not to an instance's one, then I could get away with something like <code>sqr = lambda x : sqr(x)</code>, or maybe <code>sqr = lambda x: x.sqr()</code>. Can this be done? Is there any other more pythonic way?</p>
| 0 | 2009-06-04T11:53:40Z | 950,362 | <p>You can call unbound methods with the instance as the first parameter:</p>
<pre><code>class A(int):
def sqr(self):
return A(self*self)
sqr = A.sqr
a = A(5)
print sqr(a) # Prints 25
</code></pre>
<p>So in your case you don't actually need to do anything specific, just the following:</p>
<pre><code>bin_pow(a, n, sqr=A.sqr)
</code></pre>
<p>Be aware that this is early binding, so if you have a subclass B that overrides sqr then still A.sqr is called. For late binding you can use a lambda at the callsite:</p>
<pre><code>bin_pow(a, n, sqr=lambda x: x.sqr())
</code></pre>
| 4 | 2009-06-04T12:50:55Z | [
"python"
] |
Referencing a class' method, not an instance's | 950,053 | <p>I'm writing a function that exponentiates an object, i.e. given a and n, returns a<sup>n</sup>. Since a needs not be a built-in type, the function accepts, as a keyword argument, a function to perform multiplications. If undefined, it defaults to the objects <code>__mul__</code> method, i.e. the object itself is expected to have multiplication defined. That part is sort of easy:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
if mul is None :
mul = lambda x,y : x*y
</code></pre>
<p>The thing is that in the process of calculating a<sup>n</sup> the are a lot of intermediate squarings, and there often are more efficient ways to compute them than simply multiplying the object by itself. It is easy to define another function that computes the square and pass it as another keyword argument, something like:</p>
<pre><code>def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
</code></pre>
<p>The problem here comes if the function to square the object is not a standalone function, but is a method of the object being exponentiated, which would be a very reasonable thing to do. The only way of doing this I can think of is something like this:</p>
<pre><code>import inspect
def bin_pow(a, n, **kwargs) :
mul = kwargs.pop('mul',None)
sqr = kwargs.pop('sqr',None)
if mul is None :
mul = lambda x,y : x*y
if sqr is None :
sqr = lambda x : mul(x,x)
elif inspect.isfunction(sqr) == False : # if not a function, it is a string
sqr = lambda x : eval('x.'+sqr+'()')
</code></pre>
<p>It does work, but I find it an extremely unelegant way of doing things... My mastery of OOP is limited, but if there was a way to have sqr point to the class' function, not to an instance's one, then I could get away with something like <code>sqr = lambda x : sqr(x)</code>, or maybe <code>sqr = lambda x: x.sqr()</code>. Can this be done? Is there any other more pythonic way?</p>
| 0 | 2009-06-04T11:53:40Z | 952,533 | <p>If I understand the design goals of the library function, you want to provide a library "power" function which will raise any object passed to it to the Nth power. But you also want to provide a "shortcut" for efficiency.</p>
<p>The design goals seem a little odd--Python already defines the <strong>mul</strong> method to allow the designer of a class to multiply it by an arbitrary value, and the <strong>pow</strong> method to allow the designer of a class to support raising it to a power. If I were building this, I'd expect and require the users to have a <strong>mul</strong> method, and I'd do something like this:</p>
<pre><code>def bin_or_pow(a, x):
pow_func = getattr(a, '__pow__', None)
if pow_func is None:
def pow_func(n):
v = 1
for i in xrange(n):
v = a * v
return v
return pow_func(x)
</code></pre>
<p>That will let you do the following:</p>
<pre><code>class Multable(object):
def __init__(self, x):
self.x = x
def __mul__(self, n):
print 'in mul'
n = getattr(n, 'x', n)
return type(self)(self.x * n)
class Powable(Multable):
def __pow__(self, n):
print 'in pow'
n = getattr(n, 'x', n)
return type(self)(self.x ** n)
print bin_or_pow(5, 3)
print
print bin_or_pow(Multable(5), 5).x
print
print bin_or_pow(Powable(5), 5).x
</code></pre>
<p>... and you get ...</p>
<blockquote>
<p>125 </p>
<p>in mul<br />
in mul<br />
in mul<br />
in mul<br />
in mul<br />
3125 </p>
<p>in pow<br />
3125 </p>
</blockquote>
| 0 | 2009-06-04T19:13:58Z | [
"python"
] |
Embedding a 3-D editor (such as Blender) in a wxPython application | 950,145 | <p>Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.)</p>
<p>My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and the 3-D editor to interact with each other.</p>
<p>Possible? How?</p>
| 1 | 2009-06-04T12:13:25Z | 950,177 | <p>For <a href="http://www.blender.org" rel="nofollow">Blender</a> specifically, I doubt it. Blender uses a custom UI based on OpenGL, and I'm not sure you can force it to use a pre-existing window. I suggest browsing the code of "Ghost", which is Blender's custom adaption layer (responsible for interacting with the OS for UI purposes).</p>
| 0 | 2009-06-04T12:20:06Z | [
"python",
"3d",
"wxpython",
"embedding",
"blender"
] |
Embedding a 3-D editor (such as Blender) in a wxPython application | 950,145 | <p>Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.)</p>
<p>My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and the 3-D editor to interact with each other.</p>
<p>Possible? How?</p>
| 1 | 2009-06-04T12:13:25Z | 950,196 | <p>Blender has python plugins, you can write a plugin to interract with your program.</p>
| 2 | 2009-06-04T12:23:28Z | [
"python",
"3d",
"wxpython",
"embedding",
"blender"
] |
Embedding a 3-D editor (such as Blender) in a wxPython application | 950,145 | <p>Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.)</p>
<p>My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and the 3-D editor to interact with each other.</p>
<p>Possible? How?</p>
| 1 | 2009-06-04T12:13:25Z | 950,244 | <p>Perhaps <a href="http://www.blender.org/forum/viewtopic.php?t=1122&sid=3547dbaaf0e412da6ab510870c44ebf7" rel="nofollow">this script</a> might provide some context for your project. It integrates Blender, ActiveX, and wxPython.</p>
<p>Caveat: Windows only.</p>
| 0 | 2009-06-04T12:30:23Z | [
"python",
"3d",
"wxpython",
"embedding",
"blender"
] |
Embedding a 3-D editor (such as Blender) in a wxPython application | 950,145 | <p>Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.)</p>
<p>My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and the 3-D editor to interact with each other.</p>
<p>Possible? How?</p>
| 1 | 2009-06-04T12:13:25Z | 951,020 | <p>I second Luper Rouch's idea of Blender plugins. But if you must have your own window you need to fork Blender. Take a look at <a href="http://www.makehuman.org/" rel="nofollow">makehuman</a> project. It used to have Blender as a platform. (I'm not sure but I think they have a different infrastructure now)</p>
| 1 | 2009-06-04T14:41:05Z | [
"python",
"3d",
"wxpython",
"embedding",
"blender"
] |
Embedding a 3-D editor (such as Blender) in a wxPython application | 950,145 | <p>Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.)</p>
<p>My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and the 3-D editor to interact with each other.</p>
<p>Possible? How?</p>
| 1 | 2009-06-04T12:13:25Z | 3,286,201 | <p>For Blender2.5 on linux you can use gtk.Socket, code example is <a href="http://pastebin.com/vYtJmmAC" rel="nofollow">here on pastebin</a> </p>
| 0 | 2010-07-20T00:48:22Z | [
"python",
"3d",
"wxpython",
"embedding",
"blender"
] |
Use Django Framework with Website and Stand-alone App | 950,790 | <p>I'm planning on writing a web crawler and a web-based front end for it (or, at least, the information it finds). I was wondering if it's possible to use the Django framework to let the web crawler use the same MySQL backend as the website (without making the web crawler a "website" in it's self).</p>
| 1 | 2009-06-04T14:03:45Z | 950,874 | <p>Yes, you can use the same database.</p>
<p>Some people use Django on top of a PHP application for its admin functionality, or to build newer features with Django and its ORM.</p>
<p>What I'm trying to say is that if you're putting data from your crawl into the same place that you will let Django store its data, you can access them as long as you create Django models for each table.</p>
<p>However, I don't see why the crawler can't be written within Django itself. I've written some non web based apps (a crawler and an aggregator) in Django and it works quite well.</p>
| 4 | 2009-06-04T14:15:19Z | [
"python",
"django"
] |
Use Django Framework with Website and Stand-alone App | 950,790 | <p>I'm planning on writing a web crawler and a web-based front end for it (or, at least, the information it finds). I was wondering if it's possible to use the Django framework to let the web crawler use the same MySQL backend as the website (without making the web crawler a "website" in it's self).</p>
| 1 | 2009-06-04T14:03:45Z | 950,997 | <p>You can use Django ORM outside of an HTTP server.</p>
<p>Basically you need to set <code>DJANGO_SETTINGS_MODULE</code> environment variable. Then you can import and use your django code. Here's an <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/" rel="nofollow">article on stand-alone Django scripts</a>.</p>
<p>Alternatively you can choose to interact with your Django server via <a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands" rel="nofollow">custom management commands</a>. This will be a bit more work. But in the end this method allows for a greater decoupling between the crawler and the controller (Django project).</p>
| 3 | 2009-06-04T14:37:20Z | [
"python",
"django"
] |
Create SQL query using SqlAlchemy select and join functions | 950,910 | <p>I have two tables "tags" and "deal_tag", and table definition follows,</p>
<pre><code>Table('tags', metadata,
Column('id', types.Integer(), Sequence('tag_uid_seq'),
primary_key=True),
Column('name', types.String()),
)
Table('deal_tag', metadata,
Column('dealid', types.Integer(), ForeignKey('deals.id')),
Column('tagid', types.Integer(), ForeignKey
('tags.id')),
)
</code></pre>
<p>I want to select tag id, tag name and deal count (number of deals per
tag). Sample query is</p>
<pre><code>SELECT tags.Name,tags.id,COUNT(deal_tag.dealid) FROM tags INNER JOIN
deal_tag ON tags.id = deal_tag.tagid GROUP BY deal_tag.tagid;
</code></pre>
<p>How do I create the above query using SqlAlchemy select & join functions?</p>
| 3 | 2009-06-04T14:21:32Z | 951,136 | <p>Give this a try...</p>
<pre><code>s = select([tags.c.Name, tags.c.id, func.count(deal_tag.dealid)],
tags.c.id == deal_tag.c.tagid).group_by(tags.c.Name, tags.c.id)
</code></pre>
| 2 | 2009-06-04T15:01:22Z | [
"python",
"sqlalchemy"
] |
Create SQL query using SqlAlchemy select and join functions | 950,910 | <p>I have two tables "tags" and "deal_tag", and table definition follows,</p>
<pre><code>Table('tags', metadata,
Column('id', types.Integer(), Sequence('tag_uid_seq'),
primary_key=True),
Column('name', types.String()),
)
Table('deal_tag', metadata,
Column('dealid', types.Integer(), ForeignKey('deals.id')),
Column('tagid', types.Integer(), ForeignKey
('tags.id')),
)
</code></pre>
<p>I want to select tag id, tag name and deal count (number of deals per
tag). Sample query is</p>
<pre><code>SELECT tags.Name,tags.id,COUNT(deal_tag.dealid) FROM tags INNER JOIN
deal_tag ON tags.id = deal_tag.tagid GROUP BY deal_tag.tagid;
</code></pre>
<p>How do I create the above query using SqlAlchemy select & join functions?</p>
| 3 | 2009-06-04T14:21:32Z | 1,052,563 | <p>you can join table in the time of mapping table</p>
<p>in the <strong>orm.mapper()</strong></p>
<p>for more information you can go thru the link</p>
<p>www.sqlalchemy.org/docs/</p>
| 0 | 2009-06-27T10:19:07Z | [
"python",
"sqlalchemy"
] |
Which validating python XML api to use? | 950,974 | <p>I new to xml stuff, so I have no idea which api I should use in python.
Till now I used xmlproc, but I heard it is not developed any more.</p>
<p>I have basically only one requirement: I want to validate against a dtd that I can choose in my program. I can't thrust the doctype thing.</p>
<p>Performance does not really matter, so I would like to use the most easy api that exists.</p>
<p>What to use? Have you guys a simple example?</p>
| 1 | 2009-06-04T14:32:20Z | 951,045 | <p>For my current project, I'm using <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>, which is fairly easy to use. Validation with DTD is described on <a href="http://codespeak.net/lxml/validation.html" rel="nofollow">this page</a></p>
| 3 | 2009-06-04T14:45:39Z | [
"python",
"xml",
"validation",
"dtd"
] |
Dynamic loading of python modules | 951,124 | <p>In python how do you dynamically add modules to a package while your programming is running.</p>
<p>I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program:</p>
<pre><code>import package
def doSomething(name):
pkg = __import__("package." + name)
mod = getattr(pkg, name)
mod.doSomething()
</code></pre>
<p>How do I do this?</p>
| 32 | 2009-06-04T14:59:25Z | 951,142 | <p>Add the module directory to <code>sys.path</code> and use the normal <code>import</code> statement.</p>
| 0 | 2009-06-04T15:02:24Z | [
"python",
"dynamic",
"python-import"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.