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
sequence |
---|---|---|---|---|---|---|---|---|---|
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 13,293,540 | <p>I would consider <a href="https://circleci.com" rel="nofollow">CircleCi</a> - it has great Python support, and very pretty output.</p>
| 2 | 2012-11-08T16:41:53Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 25,107,219 | <p>Check <a href="http://www.rultor.com" rel="nofollow">rultor.com</a>. As <a href="http://www.yegor256.com/2014/07/29/docker-in-rultor.html" rel="nofollow">this article</a> explains, it uses Docker for every build. Thanks to that, you can configure whatever you like inside your Docker image, including Python.</p>
| 0 | 2014-08-03T17:27:27Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 27,134,619 | <p>continuum's <a href="http://docs.binstar.org/draft/examples.html#SubmitABuildFromGithub" rel="nofollow">binstar</a> now is able to trigger builds from github and can compile for linux, osx and windows ( 32 / 64 ). the neat thing is that it really allows you to closely couple distribution and continuous integration. That's crossing the t's and dotting the I's of Integration. The site, workflow and tools are really polished and AFAIK conda is the most robust and pythonic way to distributing complex python modules, where you need to wrap <em>and</em> distribute C/C++/Fotran libraries.</p>
| 1 | 2014-11-25T19:01:39Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 32,852,066 | <p>Little disclaimer, I've actually had to build a solution like this for a client that wanted a way to automatically test and deploy <em>any</em> code on a git push plus manage the issue tickets via git notes. This also lead to my work on the <a href="https://github.com/denzuko/AIMS" rel="nofollow">AIMS project</a>.</p>
<p>One could easily just setup a bare node system that has a build user and manage their build through <code>make(1)</code>, <code>expect(1)</code>, <code>crontab(1)</code>/<code>systemd.unit(5)</code>, and <code>incrontab(1)</code>. One could even go a step further and use ansible and celery for distributed builds with a gridfs/nfs file store.</p>
<p>Although, I would not expect anyone other than a Graybeard UNIX guy or Principle level engineer/architect to actually go this far. Just makes for a nice idea and potential learning experience since a build server is nothing more than a way to arbitrarily execute scripted tasks in an automated fashion.</p>
| 0 | 2015-09-29T19:14:47Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
Unexpected list comprehension behaviour in Python | 225,675 | <p>I believe I'm getting bitten by some combination of nested scoping rules and list comprehensions. <a href="http://www.python.org/~jeremy/weblog/040204.html">Jeremy Hylton's blog post</a> is suggestive about the causes, but I don't really understand CPython's implementation well-enough to figure out how to get around this. </p>
<p>Here is an (overcomplicated?) example. If people have a simpler one that demos it, I'd like to hear it. The issue: the list comprehensions using next() are filled with the result from the last iteration. </p>
<p><strong>edit</strong>: The Problem:</p>
<p>What exactly is going on with this, and how do I fix this? Do I have to use a standard for loop? Clearly the function is running the correct number of times, but the list comprehensions end up with the <em>final</em> value instead of the result of each loop.</p>
<p>Some hypotheses:</p>
<ul>
<li>generators?</li>
<li>lazy filling of list comprehensions?</li>
</ul>
<p><strong>code</strong></p>
<pre><code>import itertools
def digit(n):
digit_list = [ (x,False) for x in xrange(1,n+1)]
digit_list[0] = (1,True)
return itertools.cycle ( digit_list)
</code></pre>
<pre>
>>> D = digit(5)
>>> [D.next() for x in range(5)]
## This list comprehension works as expected
[(1, True), (2, False), (3, False), (4, False), (5, False)]
</pre>
<pre><code>class counter(object):
def __init__(self):
self.counter = [ digit(4) for ii in range(2) ]
self.totalcount=0
self.display = [0,] * 2
def next(self):
self.totalcount += 1
self.display[-1] = self.counter[-1].next()[0]
print self.totalcount, self.display
return self.display
def next2(self,*args):
self._cycle(1)
self.totalcount += 1
print self.totalcount, self.display
return self.display
def _cycle(self,digit):
d,first = self.counter[digit].next()
#print digit, d, first
#print self._display
self.display[digit] = d
if first and digit > 0:
self._cycle(digit-1)
C = counter()
[C.next() for x in range(5)]
[C.next2() for x in range(5)]
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre>
In [44]: [C.next() for x in range(6)]
1 [0, 1]
2 [0, 2]
3 [0, 3]
4 [0, 4]
5 [0, 1]
6 [0, 2]
Out[44]: [[0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2]]
In [45]: [C.next2() for x in range(6)]
7 [0, 3]
8 [0, 4]
9 [1, 1]
10 [1, 2]
11 [1, 3]
12 [1, 4]
Out[45]: [[1, 4], [1, 4], [1, 4], [1, 4], [1, 4], [1, 4]]
# this should be: [[0,3],[0,4]....[1,4]] or similar
</pre>
| 6 | 2008-10-22T13:15:08Z | 225,801 | <p>The problem is that with <code>return self.display</code> you return a <em>reference</em> to this list (not a copy). So what you end up with is a list where each element is a reference to self.display. To illustrate, look at the following:</p>
<pre><code>>>> a = [1,2]
>>> b = [a,a]
>>> b
[[1, 2], [1, 2]]
>>> a.append(3)
>>> b
[[1, 2, 3], [1, 2, 3]]
</code></pre>
<p>You probably want to use something like <code>return self.display[:]</code>.</p>
| 14 | 2008-10-22T13:50:47Z | [
"python",
"list-comprehension",
"language-implementation"
] |
Unexpected list comprehension behaviour in Python | 225,675 | <p>I believe I'm getting bitten by some combination of nested scoping rules and list comprehensions. <a href="http://www.python.org/~jeremy/weblog/040204.html">Jeremy Hylton's blog post</a> is suggestive about the causes, but I don't really understand CPython's implementation well-enough to figure out how to get around this. </p>
<p>Here is an (overcomplicated?) example. If people have a simpler one that demos it, I'd like to hear it. The issue: the list comprehensions using next() are filled with the result from the last iteration. </p>
<p><strong>edit</strong>: The Problem:</p>
<p>What exactly is going on with this, and how do I fix this? Do I have to use a standard for loop? Clearly the function is running the correct number of times, but the list comprehensions end up with the <em>final</em> value instead of the result of each loop.</p>
<p>Some hypotheses:</p>
<ul>
<li>generators?</li>
<li>lazy filling of list comprehensions?</li>
</ul>
<p><strong>code</strong></p>
<pre><code>import itertools
def digit(n):
digit_list = [ (x,False) for x in xrange(1,n+1)]
digit_list[0] = (1,True)
return itertools.cycle ( digit_list)
</code></pre>
<pre>
>>> D = digit(5)
>>> [D.next() for x in range(5)]
## This list comprehension works as expected
[(1, True), (2, False), (3, False), (4, False), (5, False)]
</pre>
<pre><code>class counter(object):
def __init__(self):
self.counter = [ digit(4) for ii in range(2) ]
self.totalcount=0
self.display = [0,] * 2
def next(self):
self.totalcount += 1
self.display[-1] = self.counter[-1].next()[0]
print self.totalcount, self.display
return self.display
def next2(self,*args):
self._cycle(1)
self.totalcount += 1
print self.totalcount, self.display
return self.display
def _cycle(self,digit):
d,first = self.counter[digit].next()
#print digit, d, first
#print self._display
self.display[digit] = d
if first and digit > 0:
self._cycle(digit-1)
C = counter()
[C.next() for x in range(5)]
[C.next2() for x in range(5)]
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre>
In [44]: [C.next() for x in range(6)]
1 [0, 1]
2 [0, 2]
3 [0, 3]
4 [0, 4]
5 [0, 1]
6 [0, 2]
Out[44]: [[0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2]]
In [45]: [C.next2() for x in range(6)]
7 [0, 3]
8 [0, 4]
9 [1, 1]
10 [1, 2]
11 [1, 3]
12 [1, 4]
Out[45]: [[1, 4], [1, 4], [1, 4], [1, 4], [1, 4], [1, 4]]
# this should be: [[0,3],[0,4]....[1,4]] or similar
</pre>
| 6 | 2008-10-22T13:15:08Z | 231,613 | <p>Mind if i refactor this a bit?</p>
<pre><code>def digit(n):
for i in itertools.count():
yield (i%n+1, not i%n)
</code></pre>
<p>But actually you don't need that one, if you implement the whole thing as a simple iterator:</p>
<pre><code>def counter(digits, base):
counter = [0] * digits
def iterator():
for total in itertools.count(1):
for i in range(len(counter)):
counter[i] = (counter[i] + 1) % base
if counter[i]:
break
print total, list(reversed(counter))
yield list(reversed(counter))
return iterator()
c = counter(2, 4)
print list(itertools.islice(c, 10))
</code></pre>
<p>If you want to get rid of the print (debugging, is it?), go with a while-loop.</p>
<p>This incindentally also solves your initial problem, because <code>reversed</code> returns a copy of the list.</p>
<p>Oh, and it's zero-based now ;)</p>
| 3 | 2008-10-23T21:34:09Z | [
"python",
"list-comprehension",
"language-implementation"
] |
Batch Renaming of Files in a Directory | 225,735 | <p>Is there an easy way to rename a group of files already contained in a directory, using Python?</p>
<p><strong>Example:</strong> I have a directory full of *.doc files and I want to rename them in a consistent way.</p>
<blockquote>
<p>X.doc -> "new(X).doc"</p>
<p>Y.doc -> "new(Y).doc"</p>
</blockquote>
| 55 | 2008-10-22T13:33:23Z | 225,755 | <p>Try: <a href="http://www.mattweber.org/2007/03/04/python-script-renamepy/" rel="nofollow">http://www.mattweber.org/2007/03/04/python-script-renamepy/</a></p>
<blockquote>
<p>I like to have my music, movie, and
picture files named a certain way.
When I download files from the
internet, they usually donât follow my
naming convention. I found myself
manually renaming each file to fit my
style. This got old realy fast, so I
decided to write a program to do it
for me.</p>
<p>This program can convert the filename
to all lowercase, replace strings in
the filename with whatever you want,
and trim any number of characters from
the front or back of the filename.</p>
</blockquote>
<p>The program's source code is also available.</p>
| 4 | 2008-10-22T13:37:36Z | [
"python",
"file-io",
"rename",
"batch-rename"
] |
Batch Renaming of Files in a Directory | 225,735 | <p>Is there an easy way to rename a group of files already contained in a directory, using Python?</p>
<p><strong>Example:</strong> I have a directory full of *.doc files and I want to rename them in a consistent way.</p>
<blockquote>
<p>X.doc -> "new(X).doc"</p>
<p>Y.doc -> "new(Y).doc"</p>
</blockquote>
| 55 | 2008-10-22T13:33:23Z | 227,125 | <p>Such renaming is quite easy, for example with <a href="http://docs.python.org/lib/module-os.html">os</a> and <a href="http://docs.python.org/lib/module-glob.html">glob</a> modules:</p>
<pre><code>import glob, os
def rename(dir, pattern, titlePattern):
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir, titlePattern % title + ext))
</code></pre>
<p>You could then use it in your example like this:</p>
<pre><code>rename(r'c:\temp\xx', r'*.doc', r'new(%s)')
</code></pre>
<p>The above example will convert all <code>*.doc</code> files in <code>c:\temp\xx</code> dir to <code>new(%s).doc</code>, where <code>%s</code> is the previous base name of the file (without extension).</p>
| 64 | 2008-10-22T18:59:57Z | [
"python",
"file-io",
"rename",
"batch-rename"
] |
Batch Renaming of Files in a Directory | 225,735 | <p>Is there an easy way to rename a group of files already contained in a directory, using Python?</p>
<p><strong>Example:</strong> I have a directory full of *.doc files and I want to rename them in a consistent way.</p>
<blockquote>
<p>X.doc -> "new(X).doc"</p>
<p>Y.doc -> "new(Y).doc"</p>
</blockquote>
| 55 | 2008-10-22T13:33:23Z | 227,209 | <p>If you don't mind using regular expressions, then this function would give you much power in renaming files:</p>
<pre><code>import re, glob, os
def renamer(files, pattern, replacement):
for pathname in glob.glob(files):
basename= os.path.basename(pathname)
new_filename= re.sub(pattern, replacement, basename)
if new_filename != basename:
os.rename(
pathname,
os.path.join(os.path.dirname(pathname), new_filename))
</code></pre>
<p>So in your example, you could do (assuming it's the current directory where the files are):</p>
<pre><code>renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")
</code></pre>
<p>but you could also roll back to the initial filenames:</p>
<pre><code>renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")
</code></pre>
<p>and more.</p>
| 12 | 2008-10-22T19:30:05Z | [
"python",
"file-io",
"rename",
"batch-rename"
] |
Batch Renaming of Files in a Directory | 225,735 | <p>Is there an easy way to rename a group of files already contained in a directory, using Python?</p>
<p><strong>Example:</strong> I have a directory full of *.doc files and I want to rename them in a consistent way.</p>
<blockquote>
<p>X.doc -> "new(X).doc"</p>
<p>Y.doc -> "new(Y).doc"</p>
</blockquote>
| 55 | 2008-10-22T13:33:23Z | 7,917,798 | <p>I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.:</p>
<p>This replaces all underscores with hyphens in any non-hidden file in the current directory</p>
<pre><code>import os
[os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]
</code></pre>
| 54 | 2011-10-27T14:53:14Z | [
"python",
"file-io",
"rename",
"batch-rename"
] |
Batch Renaming of Files in a Directory | 225,735 | <p>Is there an easy way to rename a group of files already contained in a directory, using Python?</p>
<p><strong>Example:</strong> I have a directory full of *.doc files and I want to rename them in a consistent way.</p>
<blockquote>
<p>X.doc -> "new(X).doc"</p>
<p>Y.doc -> "new(Y).doc"</p>
</blockquote>
| 55 | 2008-10-22T13:33:23Z | 10,159,893 | <p>I've written a python script on my own. It takes as arguments the path of the directory in which the files are present and the naming pattern that you want to use. However, it renames by attaching an incremental number (1, 2, 3 and so on) to the naming pattern you give.</p>
<pre><code>import os
import sys
# checking whether path and filename are given.
if len(sys.argv) != 3:
print "Usage : python rename.py <path> <new_name.extension>"
sys.exit()
# splitting name and extension.
name = sys.argv[2].split('.')
if len(name) < 2:
name.append('')
else:
name[1] = ".%s" %name[1]
# to name starting from 1 to number_of_files.
count = 1
# creating a new folder in which the renamed files will be stored.
s = "%s/pic_folder" % sys.argv[1]
try:
os.mkdir(s)
except OSError:
# if pic_folder is already present, use it.
pass
try:
for x in os.walk(sys.argv[1]):
for y in x[2]:
# creating the rename pattern.
s = "%spic_folder/%s%s%s" %(x[0], name[0], count, name[1])
# getting the original path of the file to be renamed.
z = os.path.join(x[0],y)
# renaming.
os.rename(z, s)
# incrementing the count.
count = count + 1
except OSError:
pass
</code></pre>
<p>Hope this works for you.</p>
| 4 | 2012-04-15T05:56:20Z | [
"python",
"file-io",
"rename",
"batch-rename"
] |
Batch Renaming of Files in a Directory | 225,735 | <p>Is there an easy way to rename a group of files already contained in a directory, using Python?</p>
<p><strong>Example:</strong> I have a directory full of *.doc files and I want to rename them in a consistent way.</p>
<blockquote>
<p>X.doc -> "new(X).doc"</p>
<p>Y.doc -> "new(Y).doc"</p>
</blockquote>
| 55 | 2008-10-22T13:33:23Z | 20,371,910 | <p>I have this to simply rename all files in subfolders of folder</p>
<pre><code>import os
def replace(fpath, old_str, new_str):
for path, subdirs, files in os.walk(fpath):
for name in files:
if(old_str.lower() in name.lower()):
os.rename(os.path.join(path,name), os.path.join(path,
name.lower().replace(old_str,new_str)))
</code></pre>
<p>I am replacing all occurences of old_str with any case by new_str.</p>
| 7 | 2013-12-04T09:46:49Z | [
"python",
"file-io",
"rename",
"batch-rename"
] |
Decoding a WBXML SyncML message from an S60 device | 226,279 | <p>I'm trying to decode a WBXML encoded SyncML message from a Nokia N95.
My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> through by itself but it failed. Is there something I'm missing?</p>
<p>Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...</p>
| 3 | 2008-10-22T15:25:00Z | 230,528 | <p>Funnily enough I've been working on the same problem. I'm about halfway through writing my own pure-Python WBXML parser, but it's not yet complete enough to be useful, and I have very little time to work on it right now.</p>
<p>Those <Unknown> tags might be because pywbxml / libwbxml doesn't have the right tag vocabulary loaded. WBXML represents tags by an index number to avoid transmitting the same tag name hundreds of times, and the table that maps index numbers to tag names has to be supplied separately from the WBXML document itself. From a vague glance at <a href="http://libwbxml.aymerick.com/browser/wbxml2/trunk/src/wbxml_tables.c" rel="nofollow">the libwbxml source</a> it seems like libwbxml has a bunch of tag tables hard coded. It has tables for SyncML 1.0-1.2; I think my Nokia E71 sends SyncML 1.3 (if so, your N95 probably does too), which it looks like libwbxml doesn't support yet.</p>
<p>Getting it to work might be as simple as adding a SyncML 1.3 table to libwbxml. That said, last time I tried, pywbxml doesn't compile against the vanilla libwbxml source, so you have to apply some patches first... so "simple" may be a relative term.</p>
| 1 | 2008-10-23T16:59:13Z | [
"python",
"s60",
"syncml",
"wbxml"
] |
Decoding a WBXML SyncML message from an S60 device | 226,279 | <p>I'm trying to decode a WBXML encoded SyncML message from a Nokia N95.
My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> through by itself but it failed. Is there something I'm missing?</p>
<p>Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...</p>
| 3 | 2008-10-22T15:25:00Z | 280,928 | <p>I ended up writing a python parser myself. I managed to do it by following the spec here:
<a href="http://www.w3.org/TR/wbxml/" rel="nofollow">http://www.w3.org/TR/wbxml/</a></p>
<p>And then taking the code tables from the horde.org cvs.</p>
<p>The open mobile alliance's site and documentation are terrible, this was a very trying project :(</p>
| 1 | 2008-11-11T13:53:06Z | [
"python",
"s60",
"syncml",
"wbxml"
] |
Decoding a WBXML SyncML message from an S60 device | 226,279 | <p>I'm trying to decode a WBXML encoded SyncML message from a Nokia N95.
My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> through by itself but it failed. Is there something I'm missing?</p>
<p>Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...</p>
| 3 | 2008-10-22T15:25:00Z | 1,826,223 | <p>I used <a href="http://developer.berlios.de/projects/pywbxml/" rel="nofollow">pywbxml</a> ,
Just needed one patch in pywbxml.pyx:</p>
<p>params.lang in function wbxml2xml around line 31 set to:</p>
<pre><code>params.lang = WBXML_LANG_UNKNOWN
</code></pre>
<p>works like charm. Also changing base class for WBXMLParseError to exception helps:</p>
<pre><code>class WBXMLParseError(Exception):
</code></pre>
| 0 | 2009-12-01T13:35:16Z | [
"python",
"s60",
"syncml",
"wbxml"
] |
Django Forms - How to Use Prefix Parameter | 226,510 | <p>Say I have a form like:</p>
<pre><code>class GeneralForm(forms.Form):
field1 = forms.IntegerField(required=False)
field2 = forms. IntegerField(required=False)
</code></pre>
<p>And I want to show it twice on a page within one form tag each time with a different prefix e.g.,:</p>
<pre><code>rest of page ...
<form ..>
GeneralForm(data,prefix="form1").as_table()
GeneralForm(data,prefix="form2").as_table()
<input type="submit" />
</form>
rest of page ...
</code></pre>
<p>When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it?</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms">This was the only documentation</a> I could find and it's peckish.</p>
| 16 | 2008-10-22T16:10:03Z | 226,568 | <p>You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially.</p>
<p>Here's a slightly awkward example using the form you've given, as I don't know what the exact use case is:</p>
<pre><code>def some_view(request):
if request.method == 'POST':
form1 = GeneralForm(request.POST, prefix='form1')
form2 = GeneralForm(request.POST, prefix='form2')
if all([form1.is_valid(), form2.is_valid()]):
pass # Do stuff with the forms
else:
form1 = GeneralForm(prefix='form1')
form2 = GeneralForm(prefix='form2')
return render_to_response('some_template.html', {
'form1': form1,
'form2': form2,
})
</code></pre>
<p>Here's some real-world sample code which demonstrates processing forms using the prefix:</p>
<p><a href="http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/">http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/</a></p>
| 29 | 2008-10-22T16:27:38Z | [
"python",
"html",
"django",
"forms"
] |
Django Forms - How to Use Prefix Parameter | 226,510 | <p>Say I have a form like:</p>
<pre><code>class GeneralForm(forms.Form):
field1 = forms.IntegerField(required=False)
field2 = forms. IntegerField(required=False)
</code></pre>
<p>And I want to show it twice on a page within one form tag each time with a different prefix e.g.,:</p>
<pre><code>rest of page ...
<form ..>
GeneralForm(data,prefix="form1").as_table()
GeneralForm(data,prefix="form2").as_table()
<input type="submit" />
</form>
rest of page ...
</code></pre>
<p>When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it?</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms">This was the only documentation</a> I could find and it's peckish.</p>
| 16 | 2008-10-22T16:10:03Z | 276,697 | <p>Even better, I think <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/">formsets</a> is exactly what you're looking for. </p>
<pre><code>class GeneralForm(forms.Form):
field1 = forms.IntegerField(required=False)
field2 = forms. IntegerField(required=False)
from django.forms.formsets import formset_factory
# GeneralSet is a formset with 2 occurrences of GeneralForm
# ( as a formset allows the user to add new items, this enforces
# 2 fixed items, no less, no more )
GeneralSet = formset_factory(GeneralForm, extra=2, max_num=2)
# example view
def someview(request):
general_set = GeneralSet(request.POST)
if general_set.is_valid():
for form in general_set.forms:
# do something with data
return render_to_response("template.html", {'form': general_set}, RequestContext(request))
</code></pre>
<p>You can even have a formset automatically generated from a model with <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1">modelformset_factory</a> , which are used by the automated django admin. FormSet handle even more stuff than simple forms, like adding, removing and sorting items.</p>
| 5 | 2008-11-09T23:53:01Z | [
"python",
"html",
"django",
"forms"
] |
How does one put a link / url to the web-site's home page in Django? | 226,528 | <p>In Django templates, is there a variable in the context (e.g. <code>{{ BASE\_URL }}</code>, <code>{{ ROOT\_URL }}</code>, or <code>{{ MEDIA\_URL }}</code> that one can use to link to the <code>home</code> url of a project?</p>
<p>I.e. if Django is running in the root of a project, the variable (let's call it R) <code>{{ R }}</code> in a template would be <code>/</code>. If the root url is a sub-folder <code>http://host/X/</code> the variable <code>{{ R }}</code> would be <code>/X/</code> (or <code>http://host/X/</code>).</p>
<p>It seems painfully simple, but I can't find an answer. :) Thank you!</p>
| 17 | 2008-10-22T16:14:40Z | 226,536 | <p>I always use something like <code><a href="/"></code> (assuming your home is at the root, of course). I seem to recall looking this up once, and couldn't find a Django variable for this path; at any rate, <code>/</code> seemed pretty easy, anyway.</p>
| 6 | 2008-10-22T16:17:46Z | [
"python",
"django",
"django-urls"
] |
How does one put a link / url to the web-site's home page in Django? | 226,528 | <p>In Django templates, is there a variable in the context (e.g. <code>{{ BASE\_URL }}</code>, <code>{{ ROOT\_URL }}</code>, or <code>{{ MEDIA\_URL }}</code> that one can use to link to the <code>home</code> url of a project?</p>
<p>I.e. if Django is running in the root of a project, the variable (let's call it R) <code>{{ R }}</code> in a template would be <code>/</code>. If the root url is a sub-folder <code>http://host/X/</code> the variable <code>{{ R }}</code> would be <code>/X/</code> (or <code>http://host/X/</code>).</p>
<p>It seems painfully simple, but I can't find an answer. :) Thank you!</p>
| 17 | 2008-10-22T16:14:40Z | 226,540 | <p>You could give the URL configuration which you're using to handle the home page a name and use that:</p>
<p>urls.py:</p>
<pre><code>from django.conf.urls.defaults import *
urlpatterns = patterns('myproject.views',
url(r'^$', 'index', name='index'),
)
</code></pre>
<p>Templates:</p>
<pre><code><a href="{% url index %}">...
</code></pre>
<p>This note in the Django Book has some tips about deploying your applications to a subdirectory:</p>
<p><a href="http://www.djangobook.com/en/1.0/chapter20/#cn43">http://www.djangobook.com/en/1.0/chapter20/#cn43</a></p>
| 32 | 2008-10-22T16:19:44Z | [
"python",
"django",
"django-urls"
] |
How does one put a link / url to the web-site's home page in Django? | 226,528 | <p>In Django templates, is there a variable in the context (e.g. <code>{{ BASE\_URL }}</code>, <code>{{ ROOT\_URL }}</code>, or <code>{{ MEDIA\_URL }}</code> that one can use to link to the <code>home</code> url of a project?</p>
<p>I.e. if Django is running in the root of a project, the variable (let's call it R) <code>{{ R }}</code> in a template would be <code>/</code>. If the root url is a sub-folder <code>http://host/X/</code> the variable <code>{{ R }}</code> would be <code>/X/</code> (or <code>http://host/X/</code>).</p>
<p>It seems painfully simple, but I can't find an answer. :) Thank you!</p>
| 17 | 2008-10-22T16:14:40Z | 226,793 | <p>In your admin, go to "sites" and set the domain.</p>
<p>Pass <code>context_instance=RequestContext(request)</code> to the templates in question.</p>
<p>Now use <code>{{ SITE_URL }}</code> in any of those templates and you're golden. </p>
<p><a href="http://www.djangobook.com/en/1.0/chapter10/" rel="nofollow">Chapter 10 of the Django Book</a> has more information than you'll need regading that context processor bit.</p>
| 4 | 2008-10-22T17:33:42Z | [
"python",
"django",
"django-urls"
] |
How does one put a link / url to the web-site's home page in Django? | 226,528 | <p>In Django templates, is there a variable in the context (e.g. <code>{{ BASE\_URL }}</code>, <code>{{ ROOT\_URL }}</code>, or <code>{{ MEDIA\_URL }}</code> that one can use to link to the <code>home</code> url of a project?</p>
<p>I.e. if Django is running in the root of a project, the variable (let's call it R) <code>{{ R }}</code> in a template would be <code>/</code>. If the root url is a sub-folder <code>http://host/X/</code> the variable <code>{{ R }}</code> would be <code>/X/</code> (or <code>http://host/X/</code>).</p>
<p>It seems painfully simple, but I can't find an answer. :) Thank you!</p>
| 17 | 2008-10-22T16:14:40Z | 3,374,528 | <pre><code>(r'^$', 'django.views.generic.simple.redirect_to', {'url': '/home/'}),
</code></pre>
<p>works fine :)</p>
| 1 | 2010-07-30T18:56:56Z | [
"python",
"django",
"django-urls"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 226,796 | <p>Hash-on-disk is generally addressed with Berkeley DB or something similar - several options are listed in the <a href="http://docs.python.org/library/persistence.html">Python Data Persistence documentation</a>. You can front it with an in-memory cache, but I'd test against native performance first; with operating system caching in place it might come out about the same.</p>
| 18 | 2008-10-22T17:34:09Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 226,803 | <p>Last time I was facing a problem like this, I rewrote to use SQLite rather than a dict, and had a massive performance increase. That performance increase was at least partially on account of the database's indexing capabilities; depending on your algorithms, YMMV.</p>
<p>A thin wrapper that does SQLite queries in <code>__getitem__</code> and <code>__setitem__</code> isn't much code to write.</p>
| 6 | 2008-10-22T17:37:24Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 226,837 | <p>You should bring more than one item at a time if there's some heuristic to know which are the most likely items to be retrieved next, and don't forget the indexes like Charles mentions.</p>
| 0 | 2008-10-22T17:50:46Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 226,900 | <p>With a little bit of thought it seems like you could get the <a href="http://blog.doughellmann.com/2007/08/pymotw-shelve.html" rel="nofollow">shelve module</a> to do what you want.</p>
| 2 | 2008-10-22T18:01:42Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 228,333 | <p>The <a href="http://docs.python.org/library/shelve.html">shelve</a> module may do it; at any rate, it should be simple to test. Instead of:</p>
<pre><code>self.lengths = {}
</code></pre>
<p>do:</p>
<pre><code>import shelve
self.lengths = shelve.open('lengths.shelf')
</code></pre>
<p>The only catch is that keys to shelves must be strings, so you'll have to replace</p>
<pre><code>self.lengths[indx]
</code></pre>
<p>with</p>
<pre><code>self.lengths[str(indx)]
</code></pre>
<p>(I'm assuming your keys are just integers, as per your comment to Charles Duffy's post)</p>
<p>There's no built-in caching in memory, but your operating system may do that for you anyway.</p>
<p>[actually, that's not quite true: you can pass the argument 'writeback=True' on creation. The intent of this is to make sure storing lists and other mutable things in the shelf works correctly. But a side-effect is that the whole dictionary is cached in memory. Since this caused problems for you, it's probably not a good idea :-) ]</p>
| 5 | 2008-10-23T02:21:40Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 228,837 | <p>The 3rd party <a href="http://pypi.python.org/pypi/shove">shove</a> module is also worth taking a look at. It's very similar to shelve in that it is a simple dict-like object, however it can store to various backends (such as file, SVN, and S3), provides optional compression, and is even threadsafe. It's a very handy module</p>
<pre><code>from shove import Shove
mem_store = Shove()
file_store = Shove('file://mystore')
file_store['key'] = value
</code></pre>
| 49 | 2008-10-23T07:22:01Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 229,758 | <p>I did not try it yet but <a href="http://hamsterdb.com/" rel="nofollow">Hamster DB</a> is promising and has a Python interface.</p>
| 0 | 2008-10-23T13:42:31Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 298,401 | <p>read answer for this question from GvR ;)
<a href="http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html" rel="nofollow">Sorting a million 32-bit integers in 2MB of RAM using Python</a></p>
| 0 | 2008-11-18T10:41:46Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
Python Disk-Based Dictionary | 226,693 | <p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p>
<p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p>
<p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
| 34 | 2008-10-22T17:00:11Z | 298,422 | <p>I've read you think shelve is too slow and you tried to hack your own dict using sqlite.</p>
<p>Another did this too :</p>
<p><a href="http://sebsauvage.net/python/snyppets/index.html#dbdict" rel="nofollow">http://sebsauvage.net/python/snyppets/index.html#dbdict</a></p>
<p>It seems pretty efficient (and sebsauvage is a pretty good coder). Maybe you could give it a try ?</p>
| 1 | 2008-11-18T10:51:35Z | [
"python",
"database",
"dictionary",
"disk-based"
] |
How can you extract Hardware ID using Python? | 227,222 | <p>How do you extract an HD and Bios Unique ID, using python script?</p>
| 6 | 2008-10-22T19:33:34Z | 227,255 | <p>Solutions that come to my mind:</p>
<ol>
<li>use <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">Win32 Python Extensions</a> and call Windows APIs to do that directly</li>
<li>Use a WMI-wrapper for Python</li>
</ol>
<p>(some <a href="http://www.microsoft.com/technet/scriptcenter/scripts/python/misc/wmi/mswmpy01.mspx?mfr=true" rel="nofollow">WMI interface code</a> for reference)</p>
<p><em>Edit</em>: I assumed your OS was MS Windows :)</p>
| 2 | 2008-10-22T19:41:58Z | [
"python",
"hardware",
"extract"
] |
How can you extract Hardware ID using Python? | 227,222 | <p>How do you extract an HD and Bios Unique ID, using python script?</p>
| 6 | 2008-10-22T19:33:34Z | 227,325 | <p>Go Get Microsoft's <a href="http://www.microsoft.com/downloads/details.aspx?familyid=09dfc342-648b-4119-b7eb-783b0f7d1178&displaylang=en" rel="nofollow">Scriptomatic</a></p>
<p>Run it, Select the appropriate class from the dropdown (WIN32_BIOS)</p>
<p>It will produce the necessary Python/WMI code for you.
(It will also generate VBScript, Perl, and JScript)</p>
| 3 | 2008-10-22T20:01:08Z | [
"python",
"hardware",
"extract"
] |
How can you extract Hardware ID using Python? | 227,222 | <p>How do you extract an HD and Bios Unique ID, using python script?</p>
| 6 | 2008-10-22T19:33:34Z | 227,787 | <p>On Linux, look in the /proc directory. You'll have to parse the files to find what you are looking for.</p>
<p><a href="http://www.linux.com/feature/126718" rel="nofollow">This</a> might help.</p>
| 1 | 2008-10-22T22:38:19Z | [
"python",
"hardware",
"extract"
] |
How can you extract Hardware ID using Python? | 227,222 | <p>How do you extract an HD and Bios Unique ID, using python script?</p>
| 6 | 2008-10-22T19:33:34Z | 1,521,800 | <p>Try this library: <a href="http://www.soft.tahionic.com/download-hdd%5Fid/index.html" rel="nofollow">Hardware ID Extractor</a></p>
<p><hr /></p>
<p>Small description of the tool: </p>
<p>The Hardware ID Extractor is a Microsoft Windows program that shows data about your computer's hardware:</p>
<p>Hard disk:</p>
<ul>
<li><p>Hard drive ID (unique hardware serial number written in drive's IDE electronic chip)</p></li>
<li><p>Partition ID (volume serial number)</p></li>
</ul>
<p>CPU:</p>
<ul>
<li>CPU ID (unique hardware ID)</li>
<li>CPU vendor</li>
<li>CPU running speed</li>
<li>CPU theoretic speed</li>
</ul>
<p>Physical memory:</p>
<ul>
<li>Memory Load ( Total memory used in percentage (%) )
*Total Physical ( Total physical memory in bytes )
*Avail Physical ( Physical memory left in bytes )
*Total PageFile ( Total page file in bytes )
*Available PageFile( Page file left in bytes )
*Total Virtual( Total virtual memory in bytes )
*Available Virtual ( Virtual memory left in bytes )</li>
</ul>
| 1 | 2009-10-05T19:01:50Z | [
"python",
"hardware",
"extract"
] |
How do you create a simple Google Talk Client using the Twisted Words Python library? | 227,279 | <p>I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk.</p>
<p>Has anybody had any luck with this? Would you mind documenting a brief tutorial?</p>
<p>As a simple task, I'd like to create a client/bot that tracks the Online time of my various Google Talk accounts so that I can get an aggregate number. I figure I could friend the bot in each account and then use the XMPP presence information to keep track of the times that I can then aggregate.</p>
<p>Thanks.</p>
| 16 | 2008-10-22T19:48:33Z | 228,877 | <p>As the Twisted libs seem to be out of date, you have two choices:
Implement your own XMPP-handler or look for another library.</p>
<p>I would suggest working with the raw XML; XMPP is not that complicated and you are bound to learn something.</p>
| -2 | 2008-10-23T07:44:46Z | [
"python",
"twisted",
"xmpp",
"google-talk"
] |
How do you create a simple Google Talk Client using the Twisted Words Python library? | 227,279 | <p>I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk.</p>
<p>Has anybody had any luck with this? Would you mind documenting a brief tutorial?</p>
<p>As a simple task, I'd like to create a client/bot that tracks the Online time of my various Google Talk accounts so that I can get an aggregate number. I figure I could friend the bot in each account and then use the XMPP presence information to keep track of the times that I can then aggregate.</p>
<p>Thanks.</p>
| 16 | 2008-10-22T19:48:33Z | 228,941 | <p>I was looking building an XMPP client in python a while ago. I haven't gotten around to working on the project I was looking at it for. I didn't see anything that used twisted but are a couple XMPP libraries I found.</p>
<ul>
<li><a href="https://launchpad.net/python-xmpp/" rel="nofollow">https://launchpad.net/python-xmpp/</a></li>
<li><a href="http://xmpppy.sourceforge.net/" rel="nofollow">http://xmpppy.sourceforge.net/</a></li>
<li><a href="http://pyxmpp.jajcus.net/" rel="nofollow">http://pyxmpp.jajcus.net/</a></li>
</ul>
<p>I also found a python program, under the GPL, that acts multi-point conference system using XMPP.</p>
<p><a href="http://coders.meta.net.nz/~perry/jabber/confbot.php" rel="nofollow">http://coders.meta.net.nz/~perry/jabber/confbot.php</a></p>
| 2 | 2008-10-23T08:24:24Z | [
"python",
"twisted",
"xmpp",
"google-talk"
] |
How do you create a simple Google Talk Client using the Twisted Words Python library? | 227,279 | <p>I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk.</p>
<p>Has anybody had any luck with this? Would you mind documenting a brief tutorial?</p>
<p>As a simple task, I'd like to create a client/bot that tracks the Online time of my various Google Talk accounts so that I can get an aggregate number. I figure I could friend the bot in each account and then use the XMPP presence information to keep track of the times that I can then aggregate.</p>
<p>Thanks.</p>
| 16 | 2008-10-22T19:48:33Z | 228,959 | <p>I have written a simple Jabber bot (and thus Google talk bot) using the <code>xmpppy</code> library, which works well. The examples on <a href="http://xmpppy.sourceforge.net/" rel="nofollow">xmpppy</a> should get you started (specifically <a href="http://xmpppy.sourceforge.net/examples/bot.py" rel="nofollow"><code>bot.py</code></a>)</p>
<p>As for something actually implemented in twisted.Words:</p>
<p><a href="http://yoan.dosimple.ch/blog/2007/01/30/" rel="nofollow">Here</a> is a simple tutorial on creating a bot that prints every received message to the local terminal (and a version that replies with the revere of the received message). To track the online time of various accounts, you would add a callback for "presences" (going online/offline/away etc are "presence changes", in Jabber terminology)</p>
<p>For a more complete system, <a href="http://code.google.com/p/pownce-jabber-bot/" rel="nofollow">pownce-jabber-bot</a> uses twisted.words and <a href="http://wokkel.ik.nu/" rel="nofollow">wokkel</a> for the jabber interface.</p>
<p><a href="http://code.google.com/p/pownce-jabber-bot/source/browse/trunk/powncebot/%5F%5Finit%5F%5F.py?spec=svn15&r=15" rel="nofollow">The powncebot/__init__.py</a> file seems like a good place to start - it's seems pretty simple.</p>
| 7 | 2008-10-23T08:32:31Z | [
"python",
"twisted",
"xmpp",
"google-talk"
] |
How do you create a simple Google Talk Client using the Twisted Words Python library? | 227,279 | <p>I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk.</p>
<p>Has anybody had any luck with this? Would you mind documenting a brief tutorial?</p>
<p>As a simple task, I'd like to create a client/bot that tracks the Online time of my various Google Talk accounts so that I can get an aggregate number. I figure I could friend the bot in each account and then use the XMPP presence information to keep track of the times that I can then aggregate.</p>
<p>Thanks.</p>
| 16 | 2008-10-22T19:48:33Z | 327,229 | <p>wokkel is the future of twisted words. <a href="http://metajack.im/">metajack</a> wrote a really nice <a href="http://metajack.im/2008/09/25/an-xmpp-echo-bot-with-twisted-and-wokkel/">blog post</a> on getting started.</p>
<p>If you want a nice, functional sample project to start with, check out my <a href="http://github.com/dustin/whatsup">whatsup</a> bot.</p>
| 14 | 2008-11-29T05:42:54Z | [
"python",
"twisted",
"xmpp",
"google-talk"
] |
Solving an inequality for minimum value | 227,282 | <p>I'm working on a programming problem which boils down to a set of an equation and inequality:</p>
<pre><code>x[0]*a[0] + x[1]*a[1] + ... x[n]*a[n] >= D
x[0]*b[0] + x[1]*b[1] + ... x[n]*b[n] = C
</code></pre>
<p>I want to solve for the values of <code>X</code> that will give the absolute minimum of <code>C</code>, given the input <code>D</code> and lists and <code>A</code> and <code>B</code> consisting of <code>a[0 - n]</code> and <code>b[0 - n ]</code>.</p>
<p>I'm doing the problem at the moment in Python, but the problem in general is language-agnostic.</p>
<p>CLARIFICATION UPDATE: the coefficients <code>x[0 - n]</code> are restricted to the set of non-negative integers.</p>
| 3 | 2008-10-22T19:48:55Z | 227,306 | <p>It looks like this is a <a href="http://en.wikipedia.org/wiki/Linear_programming" rel="nofollow">linear programming</a> problem.</p>
| 2 | 2008-10-22T19:56:32Z | [
"python",
"language-agnostic",
"equation",
"linear-programming",
"inequality"
] |
Solving an inequality for minimum value | 227,282 | <p>I'm working on a programming problem which boils down to a set of an equation and inequality:</p>
<pre><code>x[0]*a[0] + x[1]*a[1] + ... x[n]*a[n] >= D
x[0]*b[0] + x[1]*b[1] + ... x[n]*b[n] = C
</code></pre>
<p>I want to solve for the values of <code>X</code> that will give the absolute minimum of <code>C</code>, given the input <code>D</code> and lists and <code>A</code> and <code>B</code> consisting of <code>a[0 - n]</code> and <code>b[0 - n ]</code>.</p>
<p>I'm doing the problem at the moment in Python, but the problem in general is language-agnostic.</p>
<p>CLARIFICATION UPDATE: the coefficients <code>x[0 - n]</code> are restricted to the set of non-negative integers.</p>
| 3 | 2008-10-22T19:48:55Z | 227,319 | <p>This looks like a <a href="http://en.wikipedia.org/wiki/Linear_programming">linear programming</a> problem. The <a href="http://en.wikipedia.org/wiki/Simplex_algorithm">Simplex algorithm</a> normally gives good results. It basically walks the boundaries of the subspace delimited by the inequalities, looking for the optimum.</p>
<p>Think of it visually: each inequality denotes a half-space, a plane in n-dimensional space that you have to be on the right side of. Your utility function is what you're trying to optimize. If the space is closed, the optimum is going to be at one of the apexes of the closed space; if it's open, it's possible that the optimum is infinite.</p>
| 11 | 2008-10-22T19:59:29Z | [
"python",
"language-agnostic",
"equation",
"linear-programming",
"inequality"
] |
Solving an inequality for minimum value | 227,282 | <p>I'm working on a programming problem which boils down to a set of an equation and inequality:</p>
<pre><code>x[0]*a[0] + x[1]*a[1] + ... x[n]*a[n] >= D
x[0]*b[0] + x[1]*b[1] + ... x[n]*b[n] = C
</code></pre>
<p>I want to solve for the values of <code>X</code> that will give the absolute minimum of <code>C</code>, given the input <code>D</code> and lists and <code>A</code> and <code>B</code> consisting of <code>a[0 - n]</code> and <code>b[0 - n ]</code>.</p>
<p>I'm doing the problem at the moment in Python, but the problem in general is language-agnostic.</p>
<p>CLARIFICATION UPDATE: the coefficients <code>x[0 - n]</code> are restricted to the set of non-negative integers.</p>
| 3 | 2008-10-22T19:48:55Z | 227,345 | <p>You might want to use Matlab or Mathematica or look at code from <a href="http://www.nrbook.com/a/bookcpdf.php" rel="nofollow">Numerical Recipes in C</a> for ideas on how to implement minimization functions. The link provided is to the 1992 version of the book. Newer versions are available at Amazon.</p>
| 1 | 2008-10-22T20:07:37Z | [
"python",
"language-agnostic",
"equation",
"linear-programming",
"inequality"
] |
Solving an inequality for minimum value | 227,282 | <p>I'm working on a programming problem which boils down to a set of an equation and inequality:</p>
<pre><code>x[0]*a[0] + x[1]*a[1] + ... x[n]*a[n] >= D
x[0]*b[0] + x[1]*b[1] + ... x[n]*b[n] = C
</code></pre>
<p>I want to solve for the values of <code>X</code> that will give the absolute minimum of <code>C</code>, given the input <code>D</code> and lists and <code>A</code> and <code>B</code> consisting of <code>a[0 - n]</code> and <code>b[0 - n ]</code>.</p>
<p>I'm doing the problem at the moment in Python, but the problem in general is language-agnostic.</p>
<p>CLARIFICATION UPDATE: the coefficients <code>x[0 - n]</code> are restricted to the set of non-negative integers.</p>
| 3 | 2008-10-22T19:48:55Z | 227,436 | <p>This <a href="http://www.lindo.com/" rel="nofollow">company</a> has a tool to do that sort of thing.</p>
| 0 | 2008-10-22T20:33:19Z | [
"python",
"language-agnostic",
"equation",
"linear-programming",
"inequality"
] |
Solving an inequality for minimum value | 227,282 | <p>I'm working on a programming problem which boils down to a set of an equation and inequality:</p>
<pre><code>x[0]*a[0] + x[1]*a[1] + ... x[n]*a[n] >= D
x[0]*b[0] + x[1]*b[1] + ... x[n]*b[n] = C
</code></pre>
<p>I want to solve for the values of <code>X</code> that will give the absolute minimum of <code>C</code>, given the input <code>D</code> and lists and <code>A</code> and <code>B</code> consisting of <code>a[0 - n]</code> and <code>b[0 - n ]</code>.</p>
<p>I'm doing the problem at the moment in Python, but the problem in general is language-agnostic.</p>
<p>CLARIFICATION UPDATE: the coefficients <code>x[0 - n]</code> are restricted to the set of non-negative integers.</p>
| 3 | 2008-10-22T19:48:55Z | 227,614 | <p>Have a look at the <a href="http://en.wikipedia.org/wiki/Integer_programming#Integer_unknowns" rel="nofollow">wikipedia</a> entry on linear programming. The integer programming section is what you're searching for (the constraint of the x[i] being integers is not an easy one). </p>
<p>Search python libraries for branch&bound, branch&cut and the like (I don't think they have been implemented in scipy yet).</p>
<p>Other interesting links:</p>
<ul>
<li><a href="http://www.gnu.org/software/glpk/" rel="nofollow">GNU Linear Programming Kit</a></li>
<li><a href="http://www-128.ibm.com/developerworks/linux/library/l-glpk1/" rel="nofollow">IBM article on GLPK</a></li>
</ul>
| 3 | 2008-10-22T21:28:01Z | [
"python",
"language-agnostic",
"equation",
"linear-programming",
"inequality"
] |
ASCII value of a character in Python | 227,459 | <p>How do I get the <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> value of a character as an int in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
| 548 | 2008-10-22T20:39:57Z | 227,466 | <p>You are looking for:</p>
<pre><code>ord()
</code></pre>
| 34 | 2008-10-22T20:41:56Z | [
"python",
"ascii"
] |
ASCII value of a character in Python | 227,459 | <p>How do I get the <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> value of a character as an int in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
| 548 | 2008-10-22T20:39:57Z | 227,472 | <p>From <a href="http://mail.python.org/pipermail/python-win32/2005-April/003100.html">here</a>:</p>
<blockquote>
<p>function ord() would get the int value
of the char. And in case you want to
convert back after playing with the
number, function chr() does the trick.</p>
</blockquote>
<pre><code>>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>
</code></pre>
<p>There is also the <code>unichr</code> function, returning the <a href="http://en.wikipedia.org/wiki/Unicode">Unicode</a> character whose ordinal is the <code>unichr</code> argument:</p>
<pre><code>>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'
</code></pre>
| 705 | 2008-10-22T20:43:04Z | [
"python",
"ascii"
] |
ASCII value of a character in Python | 227,459 | <p>How do I get the <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> value of a character as an int in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
| 548 | 2008-10-22T20:39:57Z | 227,889 | <p>Note that ord() doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä') can be 228 if you're using Latin-1, or it can raise a TypeError if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:</p>
<pre><code>>>> ord(u'ã')
12354
</code></pre>
| 113 | 2008-10-22T23:19:20Z | [
"python",
"ascii"
] |
ASCII value of a character in Python | 227,459 | <p>How do I get the <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> value of a character as an int in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
| 548 | 2008-10-22T20:39:57Z | 36,225,223 | <p>The accepted answer is correct, but there is a more clever/efficient way to do this if you need to convert a whole bunch of ASCII characters to their ASCII codes at once. Instead of doing:</p>
<pre><code>for ch in mystr:
code = ord(cd)
</code></pre>
<p>or the slightly faster:</p>
<pre><code>for code in map(ord, mystr):
</code></pre>
<p>you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:</p>
<pre><code>for code in mystr.encode('ascii'):
</code></pre>
<p>and on Python 2.6/2.7, it's only slightly more involved because it doesn't have a Py3 style <code>bytes</code> object (<code>bytes</code> is an alias for <code>str</code>, which iterates by character), but they do have <code>bytearray</code>:</p>
<pre><code># If mystr is definitely str, not unicode
for code in bytearray(mystr):
# If mystr could be either str or unicode
for code in bytearray(mystr, 'ascii'):
</code></pre>
<p>Encoding as a type that natively iterates by ordinal means the conversion goes much faster; in local tests on both Py2.7 and Py3.5, iterating a <code>str</code> to get its ASCII codes using <code>map(ord, mystr)</code> starts off taking about twice as long for a <code>len</code> 10 <code>str</code> than using <code>bytearray(mystr)</code> on Py2 or <code>mystr.encode('ascii')</code> on Py3, and as the <code>str</code> gets longer, the multiplier paid for <code>map(ord, mystr)</code> rises to ~6.5x-7x.</p>
<p>The only downside is that the conversion is all at once, so your first result might take a little longer, and a truly enormous <code>str</code> would have a proportionately large temporary <code>bytes</code>/<code>bytearray</code>, but unless this forces you into page thrashing, this isn't likely to matter.</p>
| 3 | 2016-03-25T17:56:08Z | [
"python",
"ascii"
] |
Open file, read it, process, and write back - shortest method in Python | 227,461 | <p>I want to do some basic filtering on a file. Read it, do processing, write it back. </p>
<p>I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:</p>
<pre><code>from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
</code></pre>
<p>The <code>with</code> statement makes things shorter since I don't have to explicitly open and close the file.</p>
<p>Any other ideas ?</p>
| 13 | 2008-10-22T20:40:00Z | 227,721 | <p>This seems to work:</p>
<pre><code>with open(filename, "r+") as f:
new_txt = process(f.read())
f.truncate(0)
f.write(new_txt)
</code></pre>
| 3 | 2008-10-22T22:15:46Z | [
"python",
"coding-style"
] |
Open file, read it, process, and write back - shortest method in Python | 227,461 | <p>I want to do some basic filtering on a file. Read it, do processing, write it back. </p>
<p>I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:</p>
<pre><code>from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
</code></pre>
<p>The <code>with</code> statement makes things shorter since I don't have to explicitly open and close the file.</p>
<p>Any other ideas ?</p>
| 13 | 2008-10-22T20:40:00Z | 227,746 | <p>I would go for elegance a different way: implement your file-reading and filtering operations as generators, You'll write more lines of code, but it will be more flexible, maintainable, and performant code.</p>
<p>See David M. Beazley's <a href="http://www.dabeaz.com/generators/" rel="nofollow">Generator Tricks for Systems Programmers</a>, which is a really important thing for anyone who's writing this kind of code to read.</p>
| 4 | 2008-10-22T22:22:27Z | [
"python",
"coding-style"
] |
Open file, read it, process, and write back - shortest method in Python | 227,461 | <p>I want to do some basic filtering on a file. Read it, do processing, write it back. </p>
<p>I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:</p>
<pre><code>from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
</code></pre>
<p>The <code>with</code> statement makes things shorter since I don't have to explicitly open and close the file.</p>
<p>Any other ideas ?</p>
| 13 | 2008-10-22T20:40:00Z | 227,788 | <p>If you're looking for the python equivalent of "perl -pi", here's a pretty good one:</p>
<pre>
import fileinput
for line in fileinput.input():
# process line
</pre>
<p>See <a href="http://www.python.org/doc/2.5.2/lib/module-fileinput.html" rel="nofollow">http://www.python.org/doc/2.5.2/lib/module-fileinput.html</a> for more.</p>
<p>Done this way, you would use your python script in a pipe to create the new file:</p>
<pre>
$ myscript.py infile.txt > outfile.txt
</pre>
| 2 | 2008-10-22T22:38:23Z | [
"python",
"coding-style"
] |
Open file, read it, process, and write back - shortest method in Python | 227,461 | <p>I want to do some basic filtering on a file. Read it, do processing, write it back. </p>
<p>I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:</p>
<pre><code>from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
</code></pre>
<p>The <code>with</code> statement makes things shorter since I don't have to explicitly open and close the file.</p>
<p>Any other ideas ?</p>
| 13 | 2008-10-22T20:40:00Z | 228,858 | <p>To do it in a way which won't <a href="http://www.linux.org.au/conf/2007/talk/278.html" rel="nofollow">eat your data</a> if you crash in the middle:</p>
<pre><code>from twisted.python.filepath import FilePath
p = FilePath(filename)
p.setContent(process(p.getContent()))
</code></pre>
| 1 | 2008-10-23T07:33:50Z | [
"python",
"coding-style"
] |
Open file, read it, process, and write back - shortest method in Python | 227,461 | <p>I want to do some basic filtering on a file. Read it, do processing, write it back. </p>
<p>I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:</p>
<pre><code>from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
</code></pre>
<p>The <code>with</code> statement makes things shorter since I don't have to explicitly open and close the file.</p>
<p>Any other ideas ?</p>
| 13 | 2008-10-22T20:40:00Z | 230,416 | <p>Actually an easier way using fileinput is to use the inplace parameter:</p>
<pre><code>import fileinput
for line in fileinput.input (filenameToProcess, inplace=1):
process (line)
</code></pre>
<p>If you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file.</p>
<p>This example adds line numbers to your file:</p>
<pre><code>import fileinput
for line in fileinput.input ("b.txt",inplace=1):
print "%d: %s" % (fileinput.lineno(),line),
</code></pre>
| 25 | 2008-10-23T16:28:39Z | [
"python",
"coding-style"
] |
Open file, read it, process, and write back - shortest method in Python | 227,461 | <p>I want to do some basic filtering on a file. Read it, do processing, write it back. </p>
<p>I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:</p>
<pre><code>from __future__ import with_statement
filename = "..." # or sys.argv...
with open(filename) as f:
new_txt = # ...some translation of f.read()
open(filename, 'w').write(new_txt)
</code></pre>
<p>The <code>with</code> statement makes things shorter since I don't have to explicitly open and close the file.</p>
<p>Any other ideas ?</p>
| 13 | 2008-10-22T20:40:00Z | 344,925 | <p>My ugly (but short as stated in the question) solution with <a href="http://www.python.org/doc/2.5.2/ref/genexpr.html" rel="nofollow">generator expressions</a>;</p>
<pre><code># Some setup first
file('test.txt', 'w').write('\n'.join('%05d' % i for i in range(100)))
# This is the filter function
def f(i):
return i % 3
# This is the main part
file('test2.txt', 'w').write('\n'.join(str(f(int(l))) for l in file('test.txt', 'r').readlines()))
# And a wrapper for sanity
def filter_file(infile, outfile, filter_function)
outfile.write('\n'.join(filter_function(l) for l in infile.readlines()))
</code></pre>
| 0 | 2008-12-05T19:52:55Z | [
"python",
"coding-style"
] |
Passing a list while retaining the original | 227,790 | <p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p>
<p>Example:</p>
<pre><code>def burninate(b):
c = []
for i in range(3):
c.append(b.pop())
return c
a = range(6)
d = burninate(a)
print a, d
</code></pre>
<p>Output: [0, 1, 2] [5, 4, 3]<br>
Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p>
<p>Thanks!</p>
| 12 | 2008-10-22T22:38:49Z | 227,802 | <p>You can call <code>burninate()</code> with a copy of the list like this:</p>
<p><code>d = burninate(a[:])</code></p>
<p>or,</p>
<p><code>d = burninate(list(a))</code></p>
<p>The other alternative is to make a copy of the list in your method:</p>
<pre><code>def burninate(b):
c=[]
b=b[:]
for i in range(3):
c.append(b.pop())
return c
>>> a = range(6)
>>> b = burninate(a)
>>> print a, b
>>> [0, 1, 2, 3, 4, 5] [5, 4, 3]
</code></pre>
| 10 | 2008-10-22T22:42:32Z | [
"python",
"list"
] |
Passing a list while retaining the original | 227,790 | <p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p>
<p>Example:</p>
<pre><code>def burninate(b):
c = []
for i in range(3):
c.append(b.pop())
return c
a = range(6)
d = burninate(a)
print a, d
</code></pre>
<p>Output: [0, 1, 2] [5, 4, 3]<br>
Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p>
<p>Thanks!</p>
| 12 | 2008-10-22T22:38:49Z | 227,810 | <p>A slightly more readable way to do the same thing is:</p>
<pre><code>d = burninate(list(a))
</code></pre>
<p>Here, the <code>list()</code> constructor creates a new list based on <code>a</code>.</p>
| 6 | 2008-10-22T22:45:13Z | [
"python",
"list"
] |
Passing a list while retaining the original | 227,790 | <p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p>
<p>Example:</p>
<pre><code>def burninate(b):
c = []
for i in range(3):
c.append(b.pop())
return c
a = range(6)
d = burninate(a)
print a, d
</code></pre>
<p>Output: [0, 1, 2] [5, 4, 3]<br>
Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p>
<p>Thanks!</p>
| 12 | 2008-10-22T22:38:49Z | 227,850 | <p>Other versions:</p>
<pre><code>def burninate(b):
c = []
for i in range(1, 4):
c.append(b[-i])
return c
</code></pre>
<pre><code>def burninate(b):
c = b[-4:-1]
c.reverse()
return c
</code></pre>
<p>And someday you will love list comprehensions:</p>
<pre><code>def burninate(b):
return [b[-i] for i in range(1,4)]
</code></pre>
| 2 | 2008-10-22T22:58:06Z | [
"python",
"list"
] |
Passing a list while retaining the original | 227,790 | <p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p>
<p>Example:</p>
<pre><code>def burninate(b):
c = []
for i in range(3):
c.append(b.pop())
return c
a = range(6)
d = burninate(a)
print a, d
</code></pre>
<p>Output: [0, 1, 2] [5, 4, 3]<br>
Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p>
<p>Thanks!</p>
| 12 | 2008-10-22T22:38:49Z | 227,854 | <p>A more general solution would be to <code>import copy</code>, and use <code>copy.copy()</code> on the parameter.</p>
| 5 | 2008-10-22T23:00:00Z | [
"python",
"list"
] |
Passing a list while retaining the original | 227,790 | <p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p>
<p>Example:</p>
<pre><code>def burninate(b):
c = []
for i in range(3):
c.append(b.pop())
return c
a = range(6)
d = burninate(a)
print a, d
</code></pre>
<p>Output: [0, 1, 2] [5, 4, 3]<br>
Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p>
<p>Thanks!</p>
| 12 | 2008-10-22T22:38:49Z | 227,855 | <p>As other answers have suggested, you can provide your function with a copy of the list.</p>
<p>As an alternative, your function could take a copy of the argument:</p>
<pre><code>def burninate(b):
c = []
b = list(b)
for i in range(3):
c.append(b.pop())
return c
</code></pre>
<p>Basically, you need to be clear in your mind (and in your documentation) whether your function will change its arguments. In my opinion, functions that return computed values should not change their arguments, and functions that change their arguments should not return anything. See python's [].sort(), [].extend(), {}.update(), etc. for examples. Obviously there are exceptions (like .pop()).</p>
<p>Also, depending on your particular case, you could rewrite the function to avoid using pop() or other functions that modify the argument. e.g.</p>
<pre><code>def burninante(b):
return b[:-4:-1] # return the last three elements in reverse order
</code></pre>
| 14 | 2008-10-22T23:00:37Z | [
"python",
"list"
] |
Passing a list while retaining the original | 227,790 | <p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p>
<p>Example:</p>
<pre><code>def burninate(b):
c = []
for i in range(3):
c.append(b.pop())
return c
a = range(6)
d = burninate(a)
print a, d
</code></pre>
<p>Output: [0, 1, 2] [5, 4, 3]<br>
Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p>
<p>Thanks!</p>
| 12 | 2008-10-22T22:38:49Z | 227,875 | <pre><code>burninate = lambda x: x[:-4:-1]</code></pre>
| 0 | 2008-10-22T23:09:10Z | [
"python",
"list"
] |
Passing a list while retaining the original | 227,790 | <p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p>
<p>Example:</p>
<pre><code>def burninate(b):
c = []
for i in range(3):
c.append(b.pop())
return c
a = range(6)
d = burninate(a)
print a, d
</code></pre>
<p>Output: [0, 1, 2] [5, 4, 3]<br>
Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p>
<p>Thanks!</p>
| 12 | 2008-10-22T22:38:49Z | 523,600 | <p>You can use copy.deepcopy()</p>
| 1 | 2009-02-07T10:52:00Z | [
"python",
"list"
] |
What's win32con module in python? Where can I find it? | 227,928 | <p>I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:</p>
<pre><code> ImportError: No module named win32con
</code></pre>
<p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p>
<p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p>
<p>I have Python2.6, should I have that module already installed?
Is that something of VC++?</p>
<p>Thank you for the help.</p>
<p>I got this url <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
| 17 | 2008-10-22T23:38:30Z | 227,930 | <p>This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project.</p>
<p><strong>Edit:</strong> I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.</p>
| 10 | 2008-10-22T23:40:26Z | [
"python",
"module"
] |
What's win32con module in python? Where can I find it? | 227,928 | <p>I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:</p>
<pre><code> ImportError: No module named win32con
</code></pre>
<p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p>
<p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p>
<p>I have Python2.6, should I have that module already installed?
Is that something of VC++?</p>
<p>Thank you for the help.</p>
<p>I got this url <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
| 17 | 2008-10-22T23:38:30Z | 227,945 | <p>See the <a href="http://oreilly.com/catalog/9781565926219/" rel="nofollow">Python Programming On Win32</a> for details on this package.</p>
| 3 | 2008-10-22T23:46:09Z | [
"python",
"module"
] |
What's win32con module in python? Where can I find it? | 227,928 | <p>I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:</p>
<pre><code> ImportError: No module named win32con
</code></pre>
<p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p>
<p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p>
<p>I have Python2.6, should I have that module already installed?
Is that something of VC++?</p>
<p>Thank you for the help.</p>
<p>I got this url <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
| 17 | 2008-10-22T23:38:30Z | 228,679 | <p>Note that the <a href="http://sourceforge.net/project/platformdownload.php?group_id=78018" rel="nofollow">Pywin32 download</a> page contains installers for version 2.6 (i386 and AMD64). The <a href="http://www.activestate.com/Products/activepython/feature_list.mhtml" rel="nofollow">ActiveState</a> distribution is a <em>single installer that includes pywin32</em> - currently at version 2.5.2.</p>
| 1 | 2008-10-23T05:56:35Z | [
"python",
"module"
] |
What's win32con module in python? Where can I find it? | 227,928 | <p>I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:</p>
<pre><code> ImportError: No module named win32con
</code></pre>
<p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p>
<p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p>
<p>I have Python2.6, should I have that module already installed?
Is that something of VC++?</p>
<p>Thank you for the help.</p>
<p>I got this url <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
| 17 | 2008-10-22T23:38:30Z | 10,886,718 | <p>Ok I stumbled here twice for installs on two machines so here is a quick link for that ressource</p>
<p><a href="http://sourceforge.net/projects/pywin32/files/pywin32/">http://sourceforge.net/projects/pywin32/files/pywin32/</a></p>
<p>This is the actual download page of the project and now a readme download</p>
| 5 | 2012-06-04T18:59:55Z | [
"python",
"module"
] |
What's win32con module in python? Where can I find it? | 227,928 | <p>I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:</p>
<pre><code> ImportError: No module named win32con
</code></pre>
<p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p>
<p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p>
<p>I have Python2.6, should I have that module already installed?
Is that something of VC++?</p>
<p>Thank you for the help.</p>
<p>I got this url <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
| 17 | 2008-10-22T23:38:30Z | 27,031,096 | <p>The PyWin32 download references including project references are found in the <a href="https://pypi.python.org/pypi/pywin32" rel="nofollow">pypi</a> registry.</p>
| 0 | 2014-11-20T03:10:48Z | [
"python",
"module"
] |
What's win32con module in python? Where can I find it? | 227,928 | <p>I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:</p>
<pre><code> ImportError: No module named win32con
</code></pre>
<p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p>
<p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p>
<p>I have Python2.6, should I have that module already installed?
Is that something of VC++?</p>
<p>Thank you for the help.</p>
<p>I got this url <a href="http://sourceforge.net/projects/pywin32/">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
| 17 | 2008-10-22T23:38:30Z | 39,329,641 | <pre><code>pip install pypiwin32
</code></pre>
<p><a href="https://glyph.twistedmatrix.com" rel="nofollow">Glyph</a> had packed packed it until somebody sends patch to build wheels as part of <code>pywin32</code> build process to close <a href="https://sourceforge.net/p/pywin32/bugs/680/" rel="nofollow">https://sourceforge.net/p/pywin32/bugs/680/</a></p>
| 0 | 2016-09-05T11:29:31Z | [
"python",
"module"
] |
Python debugger: Stepping into a function that you have called interactively | 228,642 | <p>Python is quite cool, but unfortunately, its debugger is not as good as perl -d. </p>
<p>One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:</p>
<pre><code># NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO()
~> cat -n /tmp/show_perl.pl
1 #!/usr/local/bin/perl
2
3 sub foo {
4 print "hi\n";
5 print "bye\n";
6 }
7
8 exit 0;
~> perl -d /tmp/show_perl.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(/tmp/show_perl.pl:8): exit 0;
# MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY
DB<1> s foo()
main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3: foo();
DB<<2>> s
main::foo(/tmp/show_perl.pl:4): print "hi\n";
DB<<2>> n
hi
main::foo(/tmp/show_perl.pl:5): print "bye\n";
DB<<2>> n
bye
DB<2> n
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<2> q
</code></pre>
<p>This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).</p>
<p>So my question is twofold:</p>
<ol>
<li>Am I missing something?</li>
<li>Is there a python debugger that would indeed let me do this?</li>
</ol>
<p>Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.</p>
| 25 | 2008-10-23T05:35:32Z | 228,653 | <p>And I've answered my own question! It's the "debug" command in pydb:</p>
<pre><code>~> cat -n /tmp/test_python.py
1 #!/usr/local/bin/python
2
3 def foo():
4 print "hi"
5 print "bye"
6
7 exit(0)
8
~> pydb /tmp/test_python.py
(/tmp/test_python.py:7): <module>
7 exit(0)
(Pydb) debug foo()
ENTERING RECURSIVE DEBUGGER
------------------------Call level 11
(/tmp/test_python.py:3): foo
3 def foo():
((Pydb)) s
(/tmp/test_python.py:4): foo
4 print "hi"
((Pydb)) s
hi
(/tmp/test_python.py:5): foo
5 print "bye"
((Pydb)) s
bye
------------------------Return from level 11 (<type 'NoneType'>)
----------------------Return from level 10 (<type 'NoneType'>)
LEAVING RECURSIVE DEBUGGER
(/tmp/test_python.py:7): <module>
</code></pre>
| 17 | 2008-10-23T05:42:00Z | [
"python",
"debugging",
"pdb"
] |
Python debugger: Stepping into a function that you have called interactively | 228,642 | <p>Python is quite cool, but unfortunately, its debugger is not as good as perl -d. </p>
<p>One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:</p>
<pre><code># NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO()
~> cat -n /tmp/show_perl.pl
1 #!/usr/local/bin/perl
2
3 sub foo {
4 print "hi\n";
5 print "bye\n";
6 }
7
8 exit 0;
~> perl -d /tmp/show_perl.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(/tmp/show_perl.pl:8): exit 0;
# MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY
DB<1> s foo()
main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3: foo();
DB<<2>> s
main::foo(/tmp/show_perl.pl:4): print "hi\n";
DB<<2>> n
hi
main::foo(/tmp/show_perl.pl:5): print "bye\n";
DB<<2>> n
bye
DB<2> n
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<2> q
</code></pre>
<p>This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).</p>
<p>So my question is twofold:</p>
<ol>
<li>Am I missing something?</li>
<li>Is there a python debugger that would indeed let me do this?</li>
</ol>
<p>Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.</p>
| 25 | 2008-10-23T05:35:32Z | 228,662 | <p>There is a python debugger that is part of the core distribution of python called 'pdb'. I rarely use it myself, but find it useful sometimes.</p>
<p>Given this program:</p>
<pre><code>def foo():
a = 0
print "hi"
a += 1
print "bye"
foo()
</code></pre>
<p>Here is a session debugging it:</p>
<pre><code>$ python /usr/lib/python2.5/pdb.py /var/tmp/pdbtest.py ~
> /var/tmp/pdbtest.py(2)<module>()
-> def foo():
(Pdb) s
> /var/tmp/pdbtest.py(10)<module>()
-> foo()
(Pdb) s
--Call--
> /var/tmp/pdbtest.py(2)foo()
-> def foo():
(Pdb) s
> /var/tmp/pdbtest.py(3)foo()
-> a = 0
(Pdb) s
> /var/tmp/pdbtest.py(4)foo()
-> print "hi"
(Pdb) print a
0
(Pdb) s
hi
> /var/tmp/pdbtest.py(6)foo()
-> a += 1
(Pdb) s
> /var/tmp/pdbtest.py(8)foo()
-> print "bye"
(Pdb) print a
1
(Pdb) s
bye
--Return--
> /var/tmp/pdbtest.py(8)foo()->None
-> print "bye"
(Pdb) s
--Return--
> /var/tmp/pdbtest.py(10)<module>()->None
-> foo()
(Pdb) s
</code></pre>
| 3 | 2008-10-23T05:46:25Z | [
"python",
"debugging",
"pdb"
] |
Python debugger: Stepping into a function that you have called interactively | 228,642 | <p>Python is quite cool, but unfortunately, its debugger is not as good as perl -d. </p>
<p>One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:</p>
<pre><code># NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO()
~> cat -n /tmp/show_perl.pl
1 #!/usr/local/bin/perl
2
3 sub foo {
4 print "hi\n";
5 print "bye\n";
6 }
7
8 exit 0;
~> perl -d /tmp/show_perl.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(/tmp/show_perl.pl:8): exit 0;
# MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY
DB<1> s foo()
main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3: foo();
DB<<2>> s
main::foo(/tmp/show_perl.pl:4): print "hi\n";
DB<<2>> n
hi
main::foo(/tmp/show_perl.pl:5): print "bye\n";
DB<<2>> n
bye
DB<2> n
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<2> q
</code></pre>
<p>This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).</p>
<p>So my question is twofold:</p>
<ol>
<li>Am I missing something?</li>
<li>Is there a python debugger that would indeed let me do this?</li>
</ol>
<p>Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.</p>
| 25 | 2008-10-23T05:35:32Z | 229,311 | <p>For interactive work on code I'm developing, I usually find it more efficient to set a programmatic "break point" in the code itself with <code>pdb.set_trace</code>. This makes it easir to break on the program's state deep in a a loop, too: <code>if <state>: pdb.set_trace()</code></p>
| 1 | 2008-10-23T10:55:53Z | [
"python",
"debugging",
"pdb"
] |
Python debugger: Stepping into a function that you have called interactively | 228,642 | <p>Python is quite cool, but unfortunately, its debugger is not as good as perl -d. </p>
<p>One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:</p>
<pre><code># NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO()
~> cat -n /tmp/show_perl.pl
1 #!/usr/local/bin/perl
2
3 sub foo {
4 print "hi\n";
5 print "bye\n";
6 }
7
8 exit 0;
~> perl -d /tmp/show_perl.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(/tmp/show_perl.pl:8): exit 0;
# MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY
DB<1> s foo()
main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3: foo();
DB<<2>> s
main::foo(/tmp/show_perl.pl:4): print "hi\n";
DB<<2>> n
hi
main::foo(/tmp/show_perl.pl:5): print "bye\n";
DB<<2>> n
bye
DB<2> n
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<2> q
</code></pre>
<p>This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).</p>
<p>So my question is twofold:</p>
<ol>
<li>Am I missing something?</li>
<li>Is there a python debugger that would indeed let me do this?</li>
</ol>
<p>Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.</p>
| 25 | 2008-10-23T05:35:32Z | 229,380 | <p>You can interactively debug a function with pdb as well, provided the script you want to debug does not exit() at the end:</p>
<pre><code>$ cat test.py
#!/usr/bin/python
def foo(f, g):
h = f+g
print h
return 2*f
</code></pre>
<p>To debug, start an interactive python session and import pdb:</p>
<pre><code>$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb
>>> import test
>>> pdb.runcall(test.foo, 1, 2)
> /Users/simon/Desktop/test.py(4)foo()
-> h = f+g
(Pdb) n
> /Users/simon/Desktop/test.py(5)foo()
-> print h
(Pdb)
</code></pre>
<p>The pdb module comes with python and is documented in the modules docs at <a href="http://docs.python.org/modindex.html">http://docs.python.org/modindex.html</a></p>
| 14 | 2008-10-23T11:27:26Z | [
"python",
"debugging",
"pdb"
] |
Python debugger: Stepping into a function that you have called interactively | 228,642 | <p>Python is quite cool, but unfortunately, its debugger is not as good as perl -d. </p>
<p>One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:</p>
<pre><code># NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO()
~> cat -n /tmp/show_perl.pl
1 #!/usr/local/bin/perl
2
3 sub foo {
4 print "hi\n";
5 print "bye\n";
6 }
7
8 exit 0;
~> perl -d /tmp/show_perl.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(/tmp/show_perl.pl:8): exit 0;
# MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY
DB<1> s foo()
main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3):
3: foo();
DB<<2>> s
main::foo(/tmp/show_perl.pl:4): print "hi\n";
DB<<2>> n
hi
main::foo(/tmp/show_perl.pl:5): print "bye\n";
DB<<2>> n
bye
DB<2> n
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.
DB<2> q
</code></pre>
<p>This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).</p>
<p>So my question is twofold:</p>
<ol>
<li>Am I missing something?</li>
<li>Is there a python debugger that would indeed let me do this?</li>
</ol>
<p>Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.</p>
| 25 | 2008-10-23T05:35:32Z | 230,561 | <p>If you're more familiar with a GUI debugger, there's winpdb ('win' in this case does not refer to Windows). I actually use it on Linux.</p>
<p>On debian/ubuntu:</p>
<pre><code>sudo aptitude install winpdb
</code></pre>
<p>Then just put this in your code where you want it to break:</p>
<pre><code>import rpdb2; rpdb2.start_embedded_debugger_interactive_password()
</code></pre>
<p>Then start winpdb and attach to your running script.</p>
| 3 | 2008-10-23T17:07:50Z | [
"python",
"debugging",
"pdb"
] |
How to get hex string from signed integer | 228,702 | <p>Say I have the classic 4-byte signed integer, and I want something like
<p> print hex(-1)
<p> to give me something like
<p>>> 0xffffffff
<p> In reality, the above gives me -0x1. I'm dawdling about in some lower level language, and python commandline is quick n easy.
<p> So.. is there a way to do it?</p>
| 7 | 2008-10-23T06:14:02Z | 228,708 | <p>This will do the trick:</p>
<pre><code>>>> print hex (-1 & 0xffffffff)
0xffffffffL
</code></pre>
<p>or, in function form (and stripping off the trailing "L"):</p>
<pre><code>>>> def hex2(n):
... return hex (n & 0xffffffff)[:-1]
...
>>> print hex2(-1)
0xffffffff
>>> print hex2(17)
0x11
</code></pre>
<p>or, a variant that always returns fixed size (there may well be a better way to do this):</p>
<pre><code>>>> def hex3(n):
... return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]
...
>>> print hex3(-1)
0xffffffff
>>> print hex3(17)
0x00000011
</code></pre>
<p>Or, avoiding the hex() altogether, thanks to Ignacio and bobince:</p>
<pre><code>def hex2(n):
return "0x%x"%(n&0xffffffff)
def hex3(n):
return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]
</code></pre>
| 21 | 2008-10-23T06:17:15Z | [
"python"
] |
How to get hex string from signed integer | 228,702 | <p>Say I have the classic 4-byte signed integer, and I want something like
<p> print hex(-1)
<p> to give me something like
<p>>> 0xffffffff
<p> In reality, the above gives me -0x1. I'm dawdling about in some lower level language, and python commandline is quick n easy.
<p> So.. is there a way to do it?</p>
| 7 | 2008-10-23T06:14:02Z | 228,785 | <p>Try this function:</p>
<pre><code>'%#4x' % (-1 & 0xffffffff)
</code></pre>
| 4 | 2008-10-23T07:03:23Z | [
"python"
] |
How to get hex string from signed integer | 228,702 | <p>Say I have the classic 4-byte signed integer, and I want something like
<p> print hex(-1)
<p> to give me something like
<p>>> 0xffffffff
<p> In reality, the above gives me -0x1. I'm dawdling about in some lower level language, and python commandline is quick n easy.
<p> So.. is there a way to do it?</p>
| 7 | 2008-10-23T06:14:02Z | 39,483,945 | <p>"0x{:04x}".format((int(my_num) & 0xFFFF), '04x') , where my_num is the required number</p>
| 0 | 2016-09-14T06:39:10Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 228,734 | <p>Something like this?</p>
<pre><code>for letter in range(ord('a'), ord('z') + 1):
print chr(letter) + ":", lowertext.count(chr(letter))
</code></pre>
<p>(I don't speak Python; please forgive my syntax errors)</p>
| 3 | 2008-10-23T06:35:04Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 228,762 | <blockquote>
<p>the question is how to make
allTheLetters equal to said letters
without something like allTheLetters =
"abcdefg...xyz"</p>
</blockquote>
<p>That's actually provided by the string module, it's not like you have to manually type it yourself ;)</p>
<pre><code>import string
allTheLetters = string.ascii_lowercase
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 14 | 2008-10-23T06:49:27Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 228,766 | <p>Do you mean using:</p>
<pre><code>import string
string.ascii_lowercase
</code></pre>
<p>then,</p>
<pre><code>counters = dict()
for letter in string.ascii_lowercase:
counters[letter] = lowertext.count(letter)
</code></pre>
<p>All lowercase letters are accounted for, missing counters will have zero value.</p>
<p>using generators:</p>
<pre><code>counters =
dict( (letter,lowertext.count(letter)) for letter in string.ascii_lowercase )
</code></pre>
| 3 | 2008-10-23T06:50:46Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 228,790 | <p>If you just want to do a frequency count of a string, try this:</p>
<pre><code>s = 'hi there'
f = {}
for c in s:
f[c] = f.get(c, 0) + 1
print f
</code></pre>
| 9 | 2008-10-23T07:04:14Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 228,845 | <p>Main question is "iterate through the alphabet":</p>
<pre><code>import string
for c in string.lowercase:
print c
</code></pre>
<p>How get letter frequencies with some efficiency and without counting non-letter characters:</p>
<pre><code>import string
sample = "Hello there, this is a test!"
letter_freq = dict((c,0) for c in string.lowercase)
for c in [c for c in sample.lower() if c.isalpha()]:
letter_freq[c] += 1
print letter_freq
</code></pre>
| 2 | 2008-10-23T07:25:01Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 228,850 | <p>The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).</p>
<p>You can use string.lowercase, as other posters have suggested:</p>
<pre><code>import string
allTheLetters = string.lowercase
</code></pre>
<p>To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out:</p>
<pre><code>def getAllTheLetters(begin='a', end='z'):
beginNum = ord(begin)
endNum = ord(end)
for number in xrange(beginNum, endNum+1):
yield chr(number)
</code></pre>
<p>You can tell it does the right thing because this code prints <code>True</code>:</p>
<pre><code>import string
print ''.join(getAllTheLetters()) == string.lowercase
</code></pre>
<p>But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:</p>
<pre><code>from collections import defaultdict
def letterOccurrances(string):
frequencies = defaultdict(lambda: 0)
for character in string:
frequencies[character.lower()] += 1
return frequencies
</code></pre>
<p>Use like so:</p>
<pre><code>occs = letterOccurrances("Hello, world!")
print occs['l']
print occs['h']
</code></pre>
<p>This will print '3' and '1' respectively.</p>
<p>Note that this works for unicode as well:</p>
<pre><code># -*- coding: utf-8 -*-
occs = letterOccurrances(u"héĺĺó, áºÃ³Åĺd!")
print occs[u'l']
print occs[u'ĺ']
</code></pre>
<p>If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters.</p>
<p>To implement your original function (print the counts of each letter in alphabetical order) in terms of this:</p>
<pre><code>def alphCount(text):
for character, count in sorted(letterOccurrances(text).iteritems()):
print "%s: %s" % (character, count)
alphCount("hello, world!")
</code></pre>
| 72 | 2008-10-23T07:28:05Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 8,659,737 | <p>For counting objects, the <em>obvious</em> solution is the <a href="http://docs.python.org/dev/library/collections.html#collections.Counter" rel="nofollow">Counter</a></p>
<pre><code>from collections import Counter
import string
c = Counter()
for letter in text.lower():
c[letter] += 1
for letter in string.lowercase:
print("%s: %d" % (letter, c[letter]))
</code></pre>
| 4 | 2011-12-28T18:27:08Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 10,820,994 | <p>This is what I do:</p>
<pre><code>import string
for x in list(string.lowercase):
print x
</code></pre>
| -1 | 2012-05-30T17:10:35Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 14,206,285 | <p>How about this, to use letters, figures and punctuation (all usable to form a Django key):</p>
<pre><code>import random
import string
chars = string.letters + string.digits + string.punctuation
chars_len = len(chars)
n = 40
print(''.join([chars[random.randint(0, chars_len)] for i in range(n)]))
</code></pre>
<p>Example result: coOL:V!D+P,&S*hzbO{a0_6]2!{4|OIbVuAbq0:</p>
| 0 | 2013-01-08T00:09:51Z | [
"python"
] |
How do I iterate through a string in Python? | 228,730 | <p>As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?</p>
<p>This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.</p>
<pre><code>def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
</code></pre>
| 39 | 2008-10-23T06:32:30Z | 15,001,537 | <p>Just use:</p>
<pre><code>import string
string.lowercase
string.uppercase
</code></pre>
<p>or</p>
<pre><code>string.letters[:26]
string.letters[26:]
</code></pre>
| 0 | 2013-02-21T11:50:55Z | [
"python"
] |
SQLite parameter substitution problem | 228,912 | <p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
| 45 | 2008-10-23T08:13:36Z | 228,961 | <p>have You tried this ? :</p>
<pre><code>for item in self.inventory_names:
t = (item,)
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", t)
self.cursor.close()
</code></pre>
<p>cursor.execute() expects a sequence (list,tuple) as second parameter. (-> ddaa )</p>
| 2 | 2008-10-23T08:32:39Z | [
"python",
"sqlite"
] |
SQLite parameter substitution problem | 228,912 | <p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
| 45 | 2008-10-23T08:13:36Z | 228,981 | <p>The <code>Cursor.execute()</code> method expects a sequence as second parameter. You are supplying a string which happens to be 8 characters long.</p>
<p>Use the following form instead:</p>
<pre><code>self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", [item])
</code></pre>
<p>Python library reference 13.13.3: sqlite3 <a href="http://www.python.org/doc/2.5.2/lib/sqlite3-Cursor-Objects.html">Cursor Objects</a>.</p>
| 113 | 2008-10-23T08:41:23Z | [
"python",
"sqlite"
] |
SQLite parameter substitution problem | 228,912 | <p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
| 45 | 2008-10-23T08:13:36Z | 597,198 | <p>I have spent half a day trying to figure out why something like this would give me an error:</p>
<pre><code>cursor.execute("SELECT * from ? WHERE name = ?", (table_name, name))
</code></pre>
<p>only to find out that table names <em>cannot be parametrized</em>. Hope this will help other people save some time.</p>
| 28 | 2009-02-28T00:32:57Z | [
"python",
"sqlite"
] |
SQLite parameter substitution problem | 228,912 | <p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
| 45 | 2008-10-23T08:13:36Z | 2,238,193 | <p>Quoting (is that what the parens mean?) the ? with parens seems to work for me. I kept trying with (literally) '?' but I kept getting</p>
<blockquote>
<p>ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.</p>
</blockquote>
<p>When I did:</p>
<blockquote>
<p>SELECT fact FROM factoids WHERE key LIKE (?)</p>
</blockquote>
<p>instead of:</p>
<blockquote>
<p>SELECT fact FROM factoids WHERE key LIKE '?'</p>
</blockquote>
<p>It worked.</p>
<p>Is this some python 2.6 thing?</p>
| 1 | 2010-02-10T15:54:12Z | [
"python",
"sqlite"
] |
SQLite parameter substitution problem | 228,912 | <p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
| 45 | 2008-10-23T08:13:36Z | 3,346,710 | <p>Try</p>
<pre><code>execute("select fact from factoids where key like ?", "%%s%" % val)
</code></pre>
<p>You don't wrap anything around the <code>?</code> at all, Python sqlite will correctly convert it into a quoted entity.</p>
| -5 | 2010-07-27T18:31:20Z | [
"python",
"sqlite"
] |
SQLite parameter substitution problem | 228,912 | <p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
| 45 | 2008-10-23T08:13:36Z | 7,305,758 | <p>The argument of <code>cursor.execute</code> that represents the values you need inserted in the database should be a tuple (sequence). However consider this example and see what's happening:</p>
<pre><code>>>> ('jason')
'jason'
>>> ('jason',)
('jason',)
</code></pre>
<p>The first example evaluates to a string instead; so the correct way of representing single valued tuple is as in the second evaluation. Anyhow, the code below to fix your error.</p>
<pre><code>self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", (item,))
</code></pre>
<p>Also giving the <code>cursor.execute</code> value arguments as strings,(which is what you are doing) results in the first evaluation in the example and results into the error you are getting.</p>
| 21 | 2011-09-05T08:51:03Z | [
"python",
"sqlite"
] |
SQLite parameter substitution problem | 228,912 | <p>Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.</p>
<p>I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)
self.cursor.close()
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.</p>
</blockquote>
<p>I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.</p>
<pre><code>cursor.execute("""CREATE TABLE Equipment
(id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER,
weight REAL,
info TEXT,
ammo_cap INTEGER,
availability_west TEXT,
availability_east TEXT)""")
</code></pre>
<p>However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)
self.cursor.close()
</code></pre>
<p>I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?</p>
| 45 | 2008-10-23T08:13:36Z | 23,729,861 | <p>each element of items has to be a tuple.
assuming names looks something like this:</p>
<pre><code>names = ['Joe', 'Bob', 'Mary']
</code></pre>
<p>you should do the following:</p>
<pre><code>for item in self.inventory_names:
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", (item, ))
</code></pre>
<p>by using (item, ) you are making it a tuple instead of a string.</p>
| 0 | 2014-05-19T04:45:45Z | [
"python",
"sqlite"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 229,192 | <p>You could use <a href="http://www.python.org/doc/2.5.2/lib/os-file-dir.html"><code>os.listdir()</code></a> which returns a list of names (for both files and directories) in a given directory. If you need to distinguish between files and directories, call <code>os.stat()</code> on each name.</p>
| 6 | 2008-10-23T10:06:02Z | [
"python",
"file",
"os.walk"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 229,219 | <p>Don't use os.walk.</p>
<p>Example:</p>
<pre><code>import os
root = "C:\\"
for item in os.listdir(root):
if os.path.isfile(os.path.join(root, item)):
print item
</code></pre>
| 108 | 2008-10-23T10:15:38Z | [
"python",
"file",
"os.walk"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 229,293 | <p>The suggestion to use <code>listdir</code> is a good one. The direct answer to your question is <code>root, dirs, files = os.walk(dir_name).next()</code></p>
| 11 | 2008-10-23T10:46:22Z | [
"python",
"file",
"os.walk"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 229,300 | <p>If you have more complex requirements than just the top directory (eg ignore VCS dirs etc), you can also modify the list of directories to prevent os.walk recursing through them.</p>
<p>ie:</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
dirs[:] = [d for d in dirs if is_good(d)]
for f in files:
do_stuff()
</code></pre>
<p>Note - be careful to mutate the list, rather than just rebind it. Obviously os.walk doesn't know about the external rebinding.</p>
| 5 | 2008-10-23T10:49:05Z | [
"python",
"file",
"os.walk"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 234,329 | <p>Use the <code>walklevel</code> function.</p>
<pre><code>import os
def walklevel(some_dir, level=1):
some_dir = some_dir.rstrip(os.path.sep)
assert os.path.isdir(some_dir)
num_sep = some_dir.count(os.path.sep)
for root, dirs, files in os.walk(some_dir):
yield root, dirs, files
num_sep_this = root.count(os.path.sep)
if num_sep + level <= num_sep_this:
del dirs[:]
</code></pre>
<p>It works just like <code>os.walk</code>, but you can pass it a <code>level</code> parameter that indicates how deep the recursion will go.</p>
| 54 | 2008-10-24T16:46:02Z | [
"python",
"file",
"os.walk"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 12,965,151 | <p>You could also do the following:</p>
<pre><code>for path, subdirs, files in os.walk(dir_name):
for name in files:
if path == ".": #this will filter the files in the current directory
#code here
</code></pre>
| 1 | 2012-10-18T23:15:07Z | [
"python",
"file",
"os.walk"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 20,868,760 | <p>I think the solution is actually very simple.</p>
<p>use </p>
<pre><code>break
</code></pre>
<p>to only do first iteration of the for loop, there must be a more elegant way.</p>
<pre><code>for root, dirs, files in os.walk(dir_name):
...
...
break
</code></pre>
<p>The first time you call os.walk, it returns tulips for the current directory, then on next loop the contents of the next directory. </p>
<p>Take original script and just add a <strong>break</strong>.</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
break
return outputList
</code></pre>
| 9 | 2014-01-01T12:44:22Z | [
"python",
"file",
"os.walk"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 24,418,093 | <p>The same idea with <code>listdir</code>, but shorter:</p>
<pre class="lang-python prettyprint-override"><code>[f for f in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, f))]
</code></pre>
| 4 | 2014-06-25T20:38:16Z | [
"python",
"file",
"os.walk"
] |
os.walk without digging into directories below | 229,186 | <p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p>
<pre><code>def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
</code></pre>
| 50 | 2008-10-23T10:03:59Z | 27,804,208 | <p>This is how I solved it</p>
<pre><code>if recursive:
items = os.walk(target_directory)
else:
items = [next(os.walk(target_directory))]
...
</code></pre>
| 0 | 2015-01-06T17:47:02Z | [
"python",
"file",
"os.walk"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.