title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How frequently should Python decorators be used?
1,054,249
<p>I recently started experimenting with Python decorators (and higher-order functions) because it looked like they might make my Django unit tests more concise. e.g., instead of writing:</p> <pre><code>def visit1(): login() do_stuff() logout() </code></pre> <p>I could instead do</p> <pre><code>@handle_login def visit1(): do_stuff() </code></pre> <p>However, after some experimenting, I have found that decorators are not as simple as I had hoped. First, I was confused by the different decorator syntax I found in different examples, until I learned that decorators behave very differently when they <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240845" rel="nofollow">take arguments</a>. Then I tried decorating a method, and eventually learned that it wasn't working because I first have to <a href="http://www.nabble.com/Decorating-methods---where-do-my-arguments-go--td23448341.html" rel="nofollow">turn my decorator into a descriptor</a> by adding a <code>__get__</code> method. During this whole process I've ended up confused more than a few times and still find that debugging this "decorated" code is more complicated than it normally is for Python. I'm now re-evaluating whether I really need decorators in my code, since my initial motivation was to save a bit of typing, not because there was anything that really required higher-order functions.</p> <p>So my question is: should decorators be used liberally or sparingly? Is it ever more Pythonic to avoid using them?</p>
3
2009-06-28T04:41:28Z
1,054,807
<p>Decorators are a way to hoist a common <strong>Aspect</strong> out of your code.</p> <p><a href="http://en.wikipedia.org/wiki/Aspect-oriented%5Fprogramming" rel="nofollow">Aspect-Oriented Programming</a> proponents will tell you that there are so many common aspects that AOP is essential and central. Indeed, you can read a silly debate on this topic here:</p> <p><a href="http://stackoverflow.com/questions/232884/aspect-oriented-programming-vs-object-oriented-programming">http://stackoverflow.com/questions/232884/aspect-oriented-programming-vs-object-oriented-programming</a></p> <p>There are a few common use cases for AOP. You can read a few here:</p> <p><a href="http://stackoverflow.com/questions/20663/do-you-use-aop-aspect-oriented-programming-in-production-software">http://stackoverflow.com/questions/20663/do-you-use-aop-aspect-oriented-programming-in-production-software</a></p> <p>There a few cross-cutting concerns for which decorators are helpful.</p> <ul> <li><p>Access Controls ("security") Authentication, Authorization, Permissions, Ownership</p></li> <li><p>Logging (including Debugging aids and Auditing)</p></li> <li><p>Caching (often an implementation of <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">Memoization</a>)</p></li> <li><p>Some error handling might be a common aspect and therefore suitable for decorator implementation.</p></li> </ul> <p>There are very few other design patterns that are truly cross-cutting and deserve an AOP decorator.</p>
3
2009-06-28T12:12:57Z
[ "python", "django", "decorator" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
1,054,281
<p>Inside a package hierarchy, use two dots, as the <a href="http://docs.python.org/reference/simple_stmts.html#the-import-statement">import statement</a> doc says:</p> <blockquote> <p>When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after <code>from</code> you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. <strong>Two dots means up one package level</strong>. Three dots is up two levels, etc. So if you execute <code>from . import mod</code> from a module in the <code>pkg</code> package then you will end up importing <code>pkg.mod</code>. If you execute <code>from ..subpkg2 import mod</code> from within <code>pkg.subpkg1</code> you will import <code>pkg.subpkg2.mod</code>. The specification for relative imports is contained within <a href="http://www.python.org/dev/peps/pep-0328/">PEP 328</a>.</p> </blockquote> <p><a href="http://www.python.org/dev/peps/pep-0328/">PEP 328</a> deals with absolute/relative imports.</p>
73
2009-06-28T05:01:14Z
[ "python", "module", "directory", "python-import" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
1,054,293
<p>@gimel's answer is correct <em>if</em> you can guarantee the package hierarchy he mentions. If you can't -- if your real need is as you expressed it, exclusively tied to directories and without any necessary relationship to packaging -- then you need to work on <code>__file__</code> to find out the parent directory (a couple of <code>os.path.dirname</code> calls will do;-), then (if that directory is not already on <code>sys.path</code>) prepend temporarily insert said dir at the very start of <code>sys.path</code>, <code>__import__</code>, remove said dir again -- messy work indeed, but, "when you must, you must" (and Pyhon strives to never stop the programmer from doing what <strong>must</strong> be done -- just like the ISO C standard says in the "Spirit of C" section in its preface!-).</p> <p>Here is an example that may work for you:</p> <pre><code>import sys import os.path sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import module_in_parent_dir </code></pre>
47
2009-06-28T05:07:01Z
[ "python", "module", "directory", "python-import" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
11,096,846
<pre><code>import sys sys.path.append("..") # Adds higher directory to python modules path. </code></pre>
32
2012-06-19T08:06:11Z
[ "python", "module", "directory", "python-import" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
23,103,505
<pre><code>from .. import module # Import module from a higher directory. </code></pre>
8
2014-04-16T08:05:59Z
[ "python", "module", "directory", "python-import" ]
How to import a Python class that is in a directory above?
1,054,271
<p>I want to inherit from a class in a file that lies in a directory above the current one.</p> <p>Is it possible to relatively import that file?</p>
83
2009-06-28T04:56:25Z
30,861,009
<p>I believe that when your code is all self contained in a module, you can always reference that module as a top level namespace.</p> <pre><code>foo/ __init__.py bar/ __init__.py baz/ __init__.py </code></pre> <p>.</p> <pre><code>foo/baz/__init__.py #!/usr/bin/env python2 import foo # or from foo import bar </code></pre>
-3
2015-06-16T07:10:50Z
[ "python", "module", "directory", "python-import" ]
How can you read keystrokes when the python program isn't in the foreground?
1,054,380
<p>I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. </p> <p>I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?</p> <p>I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP.</p>
4
2009-06-28T06:20:52Z
1,057,058
<p>Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program <a href="http://www.workrave.org/" rel="nofollow">Workrave</a> is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which you probably could use (unless you want very detailed/more specific statistics). In worst case you could look at the source (C++) to find how it is done.</p>
0
2009-06-29T07:53:03Z
[ "python", "keyboard", "background", "keylogger" ]
How can you read keystrokes when the python program isn't in the foreground?
1,054,380
<p>I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. </p> <p>I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?</p> <p>I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP.</p>
4
2009-06-28T06:20:52Z
1,191,072
<p>Unless you are planning on writing the interfaces yourself, you are going to require some library, since as other posters have pointed out, you need to access low-level key press events managed by the desktop environment.</p> <p>On Windows, the <a href="http://pypi.python.org/pypi/pyHook/1.4/" rel="nofollow">PyHook</a> library would give you the functionality you need.</p> <p>On Linux, you can use the <a href="http://python-xlib.sourceforge.net/" rel="nofollow">Python X Library</a> (assuming you are running a graphical desktop).</p> <p>Both of these are used to good effect by <a href="http://pykeylogger.wiki.sourceforge.net/" rel="nofollow">pykeylogger</a>. You'd be best off downloading the source (see e.g. pyxhook.py) to see specific examples of how key press events are captured. It should be trivial to modify this to sum the distribution of keys rather than recording the ordering.</p>
2
2009-07-27T22:47:08Z
[ "python", "keyboard", "background", "keylogger" ]
How can you read keystrokes when the python program isn't in the foreground?
1,054,380
<p>I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. </p> <p>I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?</p> <p>I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP.</p>
4
2009-06-28T06:20:52Z
1,267,515
<p>It looks like you need <a href="http://patorjk.com/keyboard-layout-analyzer/" rel="nofollow">http://patorjk.com/keyboard-layout-analyzer/</a></p> <p>This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.</p> <p>To answer your original question, on Linux you can read from /dev/event* for local keyboard, mouse and joystick events. I believe you could for example simply <code>cat /dev/event0 &gt; keylogger</code>. The events are instances of <code>struct input_event</code>. See also <a href="http://www.linuxjournal.com/article/6429" rel="nofollow">http://www.linuxjournal.com/article/6429</a>.</p> <p>Python's <a href="http://docs.python.org/library/struct.html" rel="nofollow">struct</a> module is a convenient way to parse binary data.</p> <p>For OSX, take a look at the source code to logkext. <a href="http://code.google.com/p/logkext/" rel="nofollow">http://code.google.com/p/logkext/</a></p>
4
2009-08-12T17:19:14Z
[ "python", "keyboard", "background", "keylogger" ]
How can you read keystrokes when the python program isn't in the foreground?
1,054,380
<p>I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses. </p> <p>I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?</p> <p>I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP.</p>
4
2009-06-28T06:20:52Z
1,344,274
<p>As the current X server's <em>Record</em> extension seems to be broken, using <code>pykeylogger</code> for Linux doesn't really help. Take a look at <a href="http://svn.navi.cx/misc/trunk/python/evdev/" rel="nofollow"><code>evdev</code></a> and its <code>demo</code> function, instead. The solution is nastier, but it does at least work.</p> <p>It comes down to setting up a hook to the device</p> <pre><code>import evdev keyboard_location = '/dev/input/event1' # get the correct one from HAL or so keyboard_device = evdev.Device(keyboard_location) </code></pre> <p>Then, regularly poll the device to get the status of keys and other information: </p> <pre><code>keyboard_device.poll() </code></pre>
2
2009-08-27T23:28:23Z
[ "python", "keyboard", "background", "keylogger" ]
compound sorting in python
1,054,454
<p>I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits</p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems </code></pre> <p>What would be the best way to sort this correctly on the first field, so that this sample would read </p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETT PACKARD Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc </code></pre> <p>My efforts have been very messy, and resulted in numbers such as 12 coming before 5!</p> <p>As ever, many thanks for your patience.</p>
1
2009-06-28T07:26:10Z
1,054,465
<pre><code>def lineKey (line): keyStr, rest = line.split(' ', 1) a, b = keyStr.split('/', 1) return (a, int(b)) sorted(lines, key=lineKey) </code></pre>
5
2009-06-28T07:35:28Z
[ "python", "sorting" ]
compound sorting in python
1,054,454
<p>I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits</p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems </code></pre> <p>What would be the best way to sort this correctly on the first field, so that this sample would read </p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETT PACKARD Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc </code></pre> <p>My efforts have been very messy, and resulted in numbers such as 12 coming before 5!</p> <p>As ever, many thanks for your patience.</p>
1
2009-06-28T07:26:10Z
1,054,467
<p>You can define a <a href="http://docs.python.org/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>cmp()</code> comparison function</a>, for <code>.sort([cmp[, key[, reverse]]])</code> calls:</p> <blockquote> <p>The sort() method takes optional arguments for controlling the comparisons.</p> <p><code>cmp</code> specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.</p> </blockquote> <p>In the <code>cmp()</code> function, retrieve the numeric key and use <code>int(field)</code> to ensure numeric (not textual) comparison.</p> <p>Alternately, a <a href="http://docs.python.org/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>key()</code> function</a> can be defined (thanks, @ Anurag Uniyal):</p> <blockquote> <p><code>key</code> specifies a function of one argument that is used to extract a comparison key from each list element: (e.g. <code>key=str.lower</code>). The default value is None.</p> </blockquote>
1
2009-06-28T07:36:43Z
[ "python", "sorting" ]
compound sorting in python
1,054,454
<p>I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits</p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems </code></pre> <p>What would be the best way to sort this correctly on the first field, so that this sample would read </p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETT PACKARD Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc </code></pre> <p>My efforts have been very messy, and resulted in numbers such as 12 coming before 5!</p> <p>As ever, many thanks for your patience.</p>
1
2009-06-28T07:26:10Z
1,054,473
<p>to sort split each line such that you have two tuple, part before / and integer part after that, so each line should be sorted on something like ('Gi6', 12), see example below</p> <pre><code>s="""Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems""" lines = s.split("\n") def sortKey(l): a,b = l.split("/") b=int(b[:2].strip()) return (a,b) lines.sort(key=sortKey) for l in lines: print l </code></pre>
4
2009-06-28T07:40:41Z
[ "python", "sorting" ]
compound sorting in python
1,054,454
<p>I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits</p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems </code></pre> <p>What would be the best way to sort this correctly on the first field, so that this sample would read </p> <pre><code>Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi3/7 --.--.--.-- 0009.4392.34f2 Cisco Systems Gi3/16 --.--.--.-- 0009.7c92.7af2 Cisco Systems Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEME GMBH Gi4/5 --.--.--.-- 0009.4392.6db2 Cisco Systems Gi4/6 --.--.--.-- 000b.cd39.c7c8 Hewlett Packard Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETT PACKARD Gi5/12 --.--.--.-- 0020.ac00.3fb0 INTERFLEX DATENSYSTEME GMBH Gi6/14 --.--.--.-- 0009.7c91.fa71 Cisco Systems Gi6/4 --.--.--.-- 0021.70d7.8d33 Dell Inc Gi6/6 --.--.--.-- 001c.2333.bd5a Dell Inc </code></pre> <p>My efforts have been very messy, and resulted in numbers such as 12 coming before 5!</p> <p>As ever, many thanks for your patience.</p>
1
2009-06-28T07:26:10Z
1,054,474
<p>If you are working in a unix environment, you can use "sort" to sort such lists.</p> <p>Another possibility is to use some kind of bucket sort in your python script, which should be a lot faster.</p>
0
2009-06-28T07:40:46Z
[ "python", "sorting" ]
Django official tutorial for the absolute beginner, absolutely failed!
1,054,494
<p>Not that level of failure indeed. I just completed the 4 part tutorial from djangoproject.com, my administration app works fine and my entry point url (/polls/) works well, with the exception that I get this http response: </p> <p><strong>No polls are available.</strong></p> <p>Even if the database has one registry. Entering with the admin app, the entry shows up the way it should be.</p> <p>At the end of the tutorial, you change all your hard-coded views by replacing it for generic views on your URLconf. It's supossed that after all the modifications your urls.py ends up like this:</p> <pre><code>from django.conf.urls.defaults import * from mysite.polls.models import Poll info_dict = { 'queryset': Poll.objects.all(), } urlpatterns = patterns('', (r'^$', 'django.views.generic.list_detail.object_list', info_dict), (r'^(?P&lt;object_id&gt;\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict), url(r'^(?P&lt;object_id&gt;\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'), (r'^(?P&lt;poll_id&gt;\d+)/vote/$', 'mysite.polls.views.vote'), ) </code></pre> <p>Using these generic views, It'll be pointless to copy/paste my views.py file, I'll only mention that there's just a vote function (since django generic views do all the magic). My supposition is that the urls.py file needs some tweak, or is wrong at something In order to send that "No polls available." output at /polls/ url. My poll_list.html file looks like this:</p> <pre><code>{% if latest_poll_list %} &lt;ul&gt; {% for poll in latest_poll_list %} &lt;li&gt;{{ poll.question }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% else %} &lt;p&gt;No polls are available.&lt;/p&gt; {% endif %} </code></pre> <p>It evals latest_poll_list to false, and that's why the else block is executed.</p> <p>Can you give me a hand at this? (I searched at stackoverflow for duplicate question's, and even at google for this issue, but I couldn't find anything). <strong>Why do I get this message when I enter at <a href="http://127.0.0.1:8000/polls" rel="nofollow">http://127.0.0.1:8000/polls</a>?</strong></p>
2
2009-06-28T07:59:10Z
1,054,535
<p>You overlooked this paragraph in the 4. part of the tutorial:</p> <blockquote> <p>In previous parts of the tutorial, the templates have been provided with a context that contains the poll and <code>latest_poll_list</code> context variables. However, the generic views provide the variables <code>object</code> and <code>object_list</code> as context. Therefore, you need to change your templates to match the new context variables. Go through your templates, and modify any reference to <code>latest_poll_list</code> to <code>object_list</code>, and change any reference to <code>poll</code> to <code>object</code>.</p> </blockquote>
12
2009-06-28T08:40:02Z
[ "python", "django" ]
Consuming Python COM Server from .NET
1,054,849
<p>I wanted to implement python com server using win32com extensions. Then consume the server from within the .NET. I used the following example to implement the com server and it runs without a problem but when I try to consume it using C# I got FileNotFoundException with the following message "Retrieving the COM class factory for component with CLSID {676E38A6-7FA7-4BFF-9179-AE959734DEBB} failed due to the following error: 8007007e." . I posted the C# code as well.I wonder if I'm missing something I would appreciate any help.</p> <p>Thanks, Sarah </p> <pre><code>#PythonCOMServer.py import pythoncom class PythonUtilities: _public_methods_ = [ 'SplitString' ] _reg_progid_ = "PythonDemos.Utilities" # NEVER copy the following ID # Use"print pythoncom.CreateGuid()" to make a new one. _reg_clsid_ = pythoncom.CreateGuid() print _reg_clsid_ def SplitString(self, val, item=None): import string if item != None: item = str(item) return string.split(str(val), item) # Add code so that when this script is run by # Python.exe,.it self-registers. if __name__=='__main__': print 'Registering Com Server' import win32com.server.register win32com.server.register.UseCommandLine(PythonUtilities) // the C# code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Type pythonServer; object pythonObject; pythonServer = Type.GetTypeFromProgID("PythonDemos.Utilities"); pythonObject = Activator.CreateInstance(pythonServer); } } } </code></pre>
1
2009-06-28T12:36:51Z
1,054,861
<p>You need run <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow">Process Monitor</a> on your C# Executable to track down the file that is not found.</p>
0
2009-06-28T12:45:08Z
[ ".net", "python", "com" ]
Consuming Python COM Server from .NET
1,054,849
<p>I wanted to implement python com server using win32com extensions. Then consume the server from within the .NET. I used the following example to implement the com server and it runs without a problem but when I try to consume it using C# I got FileNotFoundException with the following message "Retrieving the COM class factory for component with CLSID {676E38A6-7FA7-4BFF-9179-AE959734DEBB} failed due to the following error: 8007007e." . I posted the C# code as well.I wonder if I'm missing something I would appreciate any help.</p> <p>Thanks, Sarah </p> <pre><code>#PythonCOMServer.py import pythoncom class PythonUtilities: _public_methods_ = [ 'SplitString' ] _reg_progid_ = "PythonDemos.Utilities" # NEVER copy the following ID # Use"print pythoncom.CreateGuid()" to make a new one. _reg_clsid_ = pythoncom.CreateGuid() print _reg_clsid_ def SplitString(self, val, item=None): import string if item != None: item = str(item) return string.split(str(val), item) # Add code so that when this script is run by # Python.exe,.it self-registers. if __name__=='__main__': print 'Registering Com Server' import win32com.server.register win32com.server.register.UseCommandLine(PythonUtilities) // the C# code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Type pythonServer; object pythonObject; pythonServer = Type.GetTypeFromProgID("PythonDemos.Utilities"); pythonObject = Activator.CreateInstance(pythonServer); } } } </code></pre>
1
2009-06-28T12:36:51Z
1,054,986
<p>A COM server is just a piece of software (a DLL or an executable) that will accept remote procedure calls (RPC) through a defined protocol. Part of the protocol says that the server must have a unique ID, stored in the Windows' registry. In our case, this means that you have "registered" a server that is not existing. Thus the error (component not found).</p> <p>So, it should be something like this (as usual, this is untested code!):</p> <pre><code>import pythoncom class HelloWorld: _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER _reg_clsid_ = "{B83DD222-7750-413D-A9AD-01B37021B24B}" _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] def __init__(self): self.softspace = 1 self.noCalls = 0 def Hello(self, who): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Hello" + " " * self.softspace + str(who) if __name__ == '__main__': if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]: import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) else: # start the server. from win32com.server import localserver localserver.serve('B83DD222-7750-413D-A9AD-01B37021B24B') </code></pre> <p>Then you should run from the command line (assuming the script is called HelloWorldCOM.py):</p> <pre>HelloWorldCOM.py --register HelloWorldCOM.py</pre> <p>Class HelloWorld is the actual implementation of the server. It expose one method (Hello) and a couple of attributes, one of the two is read-only. With the first command, you register the server; with the second one, you run it and then it becomes available to usage from other applications.</p>
3
2009-06-28T14:07:55Z
[ ".net", "python", "com" ]
Recursive delete in google app engine
1,054,868
<p>I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this:</p> <pre> class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) </pre> <p>Now, when I delete an object of type 'Top', I want all the associated 'Bottom' objects to be deleted as well.</p> <p>As things are now, when I delete a 'Top' object, the 'Bottom' objects stay and then I get data that doesn't belong anywhere. When accessing the datastore in a view, I end up with:</p> <pre>Caught an exception while rendering: ReferenceProperty failed to be resolved.</pre> <p>I could of course find all objects and delete them, but since my real model is at least 5 levels deep, I'm hoping there's a way to make sure this can be done automatically.</p> <p>I've found this <a href="http://code.google.com/appengine/docs/java/datastore/relationships.html#Dependent%5FChildren%5Fand%5FCascading%5FDeletes">article</a> about how it works with Java and that seems to be pretty much what I want as well. </p> <p>Anyone know how I could get that behavior in django as well?</p>
6
2009-06-28T12:48:36Z
1,054,927
<p>Actually that behavior is GAE-specific. Django's ORM simulates "ON DELETE CASCADE" on .delete().</p> <p>I know that this is not an answer to your question, but maybe it can help you from looking in the wrong places.</p>
2
2009-06-28T13:23:27Z
[ "python", "django", "google-app-engine" ]
Recursive delete in google app engine
1,054,868
<p>I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this:</p> <pre> class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) </pre> <p>Now, when I delete an object of type 'Top', I want all the associated 'Bottom' objects to be deleted as well.</p> <p>As things are now, when I delete a 'Top' object, the 'Bottom' objects stay and then I get data that doesn't belong anywhere. When accessing the datastore in a view, I end up with:</p> <pre>Caught an exception while rendering: ReferenceProperty failed to be resolved.</pre> <p>I could of course find all objects and delete them, but since my real model is at least 5 levels deep, I'm hoping there's a way to make sure this can be done automatically.</p> <p>I've found this <a href="http://code.google.com/appengine/docs/java/datastore/relationships.html#Dependent%5FChildren%5Fand%5FCascading%5FDeletes">article</a> about how it works with Java and that seems to be pretty much what I want as well. </p> <p>Anyone know how I could get that behavior in django as well?</p>
6
2009-06-28T12:48:36Z
1,055,009
<p>If your hierarchy is only a small number of levels deep, then you might be able to do something with a field that looks like a file path:</p> <pre><code>daddy.ancestry = "greatgranddaddy/granddaddy/daddy/" me.ancestry = daddy.ancestry + me.uniquename + "/" </code></pre> <p>sort of thing. You do need unique names, at least unique among siblings.</p> <p>The path in object IDs sort of does this already, but IIRC that's bound up with entity groups, which you're advised not to use to express relationships in the data domain.</p> <p>Then you can construct a query to return all of granddaddy's descendants using the initial substring trick, like this:</p> <pre><code>query = Person.all() query.filter("ancestry &gt;", gdaddy.ancestry + "\U0001") query.filter("ancestry &lt;", gdaddy.ancestry + "\UFFFF") </code></pre> <p>Obviously this is no use if you can't fit the ancestry into a 500 byte StringProperty.</p>
1
2009-06-28T14:20:07Z
[ "python", "django", "google-app-engine" ]
Recursive delete in google app engine
1,054,868
<p>I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this:</p> <pre> class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) </pre> <p>Now, when I delete an object of type 'Top', I want all the associated 'Bottom' objects to be deleted as well.</p> <p>As things are now, when I delete a 'Top' object, the 'Bottom' objects stay and then I get data that doesn't belong anywhere. When accessing the datastore in a view, I end up with:</p> <pre>Caught an exception while rendering: ReferenceProperty failed to be resolved.</pre> <p>I could of course find all objects and delete them, but since my real model is at least 5 levels deep, I'm hoping there's a way to make sure this can be done automatically.</p> <p>I've found this <a href="http://code.google.com/appengine/docs/java/datastore/relationships.html#Dependent%5FChildren%5Fand%5FCascading%5FDeletes">article</a> about how it works with Java and that seems to be pretty much what I want as well. </p> <p>Anyone know how I could get that behavior in django as well?</p>
6
2009-06-28T12:48:36Z
1,058,125
<p>You need to implement this manually, by looking up affected records and deleting them at the same time as you delete the parent record. You can simplify this, if you wish, by overriding the .delete() method on your parent class to automatically delete all related records.</p> <p>For performance reasons, you almost certainly want to use key-only queries (allowing you to get the keys of entities to be deleted without having to fetch and decode the actual entities), and batch deletes. For example:</p> <pre><code>db.delete(Bottom.all(keys_only=True).filter("daddy =", top).fetch(1000)) </code></pre>
6
2009-06-29T12:55:02Z
[ "python", "django", "google-app-engine" ]
Recursive delete in google app engine
1,054,868
<p>I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this:</p> <pre> class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) </pre> <p>Now, when I delete an object of type 'Top', I want all the associated 'Bottom' objects to be deleted as well.</p> <p>As things are now, when I delete a 'Top' object, the 'Bottom' objects stay and then I get data that doesn't belong anywhere. When accessing the datastore in a view, I end up with:</p> <pre>Caught an exception while rendering: ReferenceProperty failed to be resolved.</pre> <p>I could of course find all objects and delete them, but since my real model is at least 5 levels deep, I'm hoping there's a way to make sure this can be done automatically.</p> <p>I've found this <a href="http://code.google.com/appengine/docs/java/datastore/relationships.html#Dependent%5FChildren%5Fand%5FCascading%5FDeletes">article</a> about how it works with Java and that seems to be pretty much what I want as well. </p> <p>Anyone know how I could get that behavior in django as well?</p>
6
2009-06-28T12:48:36Z
25,092,119
<p>Reconsider the data structure. If the relationship will never change on the record lifetime, you could use "ancestors" feature of GAE:</p> <pre><code>class Top(db.Model): pass class Middle(db.Model): pass class Bottom(db.Model): pass top = Top() middles = [Middle(parent=top) for i in range(0,10)] bottoms = [Bottom(parent=middle) for i in range(0,10) for middle in middles] </code></pre> <p>Then querying for ancestor=top will find all the records from all levels. So it will be easy to delete them.</p> <pre><code>descendants = list(db.Query().ancestor(top)) # should return [top] + middles + bottoms </code></pre>
1
2014-08-02T05:52:04Z
[ "python", "django", "google-app-engine" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out of the box anymore.</p> <p>I'm an Emacs addict and prefer my documentation installed in Info.</p> <p>Does anyone have Python 2.6 or later docs in Texinfo format? How did you convert them? Or, is there a maintained build somewhere out there?</p> <p>I know I can use w3m or <a href="http://furius.ca/haddoc/">haddoc</a> to view the html docs - I really want them in Info.</p> <p>I've played with <a href="http://johnmacfarlane.net/pandoc/">Pandoc</a> but after a few small experiments it doesn't seem to deal well with links between documents, and my larger experiment - running it across all docs cat'ed together to see what happens - is still chugging along two days since I started it!</p>
30
2009-06-28T13:11:38Z
1,060,706
<p>Python docs are now generated using Sphynx framework. This framework does not have texinfo output format. Currently it has:</p> <ol> <li>HTML</li> <li>latex</li> <li>plain text</li> </ol> <p>Maybe you can get what you want using the Latex output. With the text output you will lost the cross ref.</p> <p>Personnaly I prefer using pydoc when I want textual output. With Vim I have a shorcut to call pydoc and open a window with the doc for the entity under my cursor...</p>
1
2009-06-29T21:34:56Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out of the box anymore.</p> <p>I'm an Emacs addict and prefer my documentation installed in Info.</p> <p>Does anyone have Python 2.6 or later docs in Texinfo format? How did you convert them? Or, is there a maintained build somewhere out there?</p> <p>I know I can use w3m or <a href="http://furius.ca/haddoc/">haddoc</a> to view the html docs - I really want them in Info.</p> <p>I've played with <a href="http://johnmacfarlane.net/pandoc/">Pandoc</a> but after a few small experiments it doesn't seem to deal well with links between documents, and my larger experiment - running it across all docs cat'ed together to see what happens - is still chugging along two days since I started it!</p>
30
2009-06-28T13:11:38Z
1,068,731
<p>Another "workaround" is to execute <code>pydoc</code> as suggested by Nikokrock directly in Emacs:</p> <pre><code>(defun pydoc (&amp;optional arg) (interactive) (when (not (stringp arg)) (setq arg (thing-at-point 'word))) (setq cmd (concat "pydoc " arg)) (ad-activate-regexp "auto-compile-yes-or-no-p-always-yes") (shell-command cmd) (setq pydoc-buf (get-buffer "*Shell Command Output*")) (switch-to-buffer-other-window pydoc-buf) (python-mode) (ad-deactivate-regexp "auto-compile-yes-or-no-p-always-yes") ) </code></pre>
2
2009-07-01T11:54:06Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out of the box anymore.</p> <p>I'm an Emacs addict and prefer my documentation installed in Info.</p> <p>Does anyone have Python 2.6 or later docs in Texinfo format? How did you convert them? Or, is there a maintained build somewhere out there?</p> <p>I know I can use w3m or <a href="http://furius.ca/haddoc/">haddoc</a> to view the html docs - I really want them in Info.</p> <p>I've played with <a href="http://johnmacfarlane.net/pandoc/">Pandoc</a> but after a few small experiments it doesn't seem to deal well with links between documents, and my larger experiment - running it across all docs cat'ed together to see what happens - is still chugging along two days since I started it!</p>
30
2009-06-28T13:11:38Z
1,080,974
<p>Michael Ernst used to maintain Info formats of Python docs:</p> <p><a href="http://www.cs.washington.edu/homes/mernst/software/#python-info" rel="nofollow">http://www.cs.washington.edu/homes/mernst/software/#python-info</a></p> <p>You can try using his makefile and html2texi script to generate an updated version. Both are linked at the above URL. I'm not sure how well it works now (the last version was around 2001), but his script is well commented (grep for "python").</p>
2
2009-07-03T21:55:21Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out of the box anymore.</p> <p>I'm an Emacs addict and prefer my documentation installed in Info.</p> <p>Does anyone have Python 2.6 or later docs in Texinfo format? How did you convert them? Or, is there a maintained build somewhere out there?</p> <p>I know I can use w3m or <a href="http://furius.ca/haddoc/">haddoc</a> to view the html docs - I really want them in Info.</p> <p>I've played with <a href="http://johnmacfarlane.net/pandoc/">Pandoc</a> but after a few small experiments it doesn't seem to deal well with links between documents, and my larger experiment - running it across all docs cat'ed together to see what happens - is still chugging along two days since I started it!</p>
30
2009-06-28T13:11:38Z
3,673,619
<p>For those following this question in the hope of an answer, I found another rst2texinfo implementation which you might like to try:</p> <p><a href="http://bitbucket.org/jonwaltman/rst2texinfo/src" rel="nofollow">http://bitbucket.org/jonwaltman/rst2texinfo/src</a></p>
2
2010-09-09T03:43:26Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out of the box anymore.</p> <p>I'm an Emacs addict and prefer my documentation installed in Info.</p> <p>Does anyone have Python 2.6 or later docs in Texinfo format? How did you convert them? Or, is there a maintained build somewhere out there?</p> <p>I know I can use w3m or <a href="http://furius.ca/haddoc/">haddoc</a> to view the html docs - I really want them in Info.</p> <p>I've played with <a href="http://johnmacfarlane.net/pandoc/">Pandoc</a> but after a few small experiments it doesn't seem to deal well with links between documents, and my larger experiment - running it across all docs cat'ed together to see what happens - is still chugging along two days since I started it!</p>
30
2009-06-28T13:11:38Z
3,952,588
<p>Jon Waltman <a href="http://bitbucket.org/jonwaltman/sphinx-info">http://bitbucket.org/jonwaltman/sphinx-info</a> has forked sphinx and written a texinfo builder, it can build the python documentation (I've yet done it). It seems that it will be merged soon into sphinx.</p> <p>Here's the quick links for the downloads (temporary):</p> <ul> <li><a href="http://dl.dropbox.com/u/1276730/python.info">http://dl.dropbox.com/u/1276730/python.info</a></li> <li><a href="http://dl.dropbox.com/u/1276730/python.texi">http://dl.dropbox.com/u/1276730/python.texi</a></li> </ul> <p>Steps to generate python doc in texinfo format:</p> <p>Download the python source code</p> <p>Download and install the <a href="http://bitbucket.org/jonwaltman/sphinx-info">sphinx-info</a> package (in a virtualenv)</p> <p>Enter in the Python/Doc directory from the python sources</p> <p>Edit the Makefile, to the <code>build</code> target replace <code>$(PYTHON) tools/sphinx-build.py</code> with <code>sphinx-build</code>, then add this target to the makefile, pay attention, the space before echo is a TAB:</p> <pre><code>texinfo: BUILDER = texinfo texinfo: build @echo @echo "Build finished. The Texinfo files are in _build/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." </code></pre> <p>Edit the Python/Doc/conf.py adding:</p> <pre><code>texinfo_documents = [ ('contents', 'python', 'Python Documentation', 'Georg Brandl', 'Python', 'The Python Programming Language', 'Documentation tools', 1), ] </code></pre> <p>Then run <code>make texinfo</code> and it should produce the texifile in the build/texinfo directory. To generate the info file run <code>makeinfo python.texi</code></p>
22
2010-10-17T08:48:56Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
How do you get Python documentation in Texinfo Info format?
1,054,903
<p>Since Python 2.6, it seems the documentation is in the new <a href="http://docs.python.org/whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">reStructuredText</a> format, and it doesn't seem very easy to build a <a href="http://en.wikipedia.org/wiki/Info%5F%28Unix%29">Texinfo Info</a> file out of the box anymore.</p> <p>I'm an Emacs addict and prefer my documentation installed in Info.</p> <p>Does anyone have Python 2.6 or later docs in Texinfo format? How did you convert them? Or, is there a maintained build somewhere out there?</p> <p>I know I can use w3m or <a href="http://furius.ca/haddoc/">haddoc</a> to view the html docs - I really want them in Info.</p> <p>I've played with <a href="http://johnmacfarlane.net/pandoc/">Pandoc</a> but after a few small experiments it doesn't seem to deal well with links between documents, and my larger experiment - running it across all docs cat'ed together to see what happens - is still chugging along two days since I started it!</p>
30
2009-06-28T13:11:38Z
18,847,967
<p>I've packaged up the <a href="https://github.com/wilfred/python-info">Python docs as a texinfo file</a>. </p> <p>If you're using Emacs with MELPA, you can simply install this with <code>M-x package-install python-info</code>.</p>
7
2013-09-17T10:56:02Z
[ "python", "emacs", "restructuredtext", "texinfo" ]
Unable to make a MySQL database of SO questions by Python
1,054,964
<p><a href="http://meta.stackexchange.com/questions/73/is-the-fastest-gun-in-the-west-solved/106#106">Brent's answer</a> suggests me that has made a database of SO questions such that he can fast analyze the questions.</p> <p>I am interested in making a similar database by MySQL such that I can practice MySQL with similar queries as Brent.</p> <p>The database should include at the least the following fields (I am guessing here, since the API of SO's api seems to be sectet). I aim to list only relevant variables which would allow me to make similar analysis as Brent. </p> <ul> <li>Questions</li> <li>Question_id (private key)</li> <li><p>Question_time</p></li> <li><p>Comments</p></li> <li>Comment_id (private key)</li> <li><p>Comment_time</p></li> <li><p>User_id (private key)</p></li> <li>User_name </li> </ul> <p>We need apparently scrape the data by Python's Beautiful Soap because Brent's database is apparently hidden.</p> <p><strong>How can you make such a MySQL database</strong> by Python's Beautiful Soap?**</p>
0
2009-06-28T13:52:05Z
1,054,985
<p>I don't know the details of how to import the data into MySQL, but the raw data of Stack Overflow is freely available: <a href="http://blog.stackoverflow.com/2009/06/stack-overflow-creative-commons-data-dump/" rel="nofollow">http://blog.stackoverflow.com/2009/06/stack-overflow-creative-commons-data-dump/</a></p> <p>There's no secret API, nor any need to use Beautiful Soup.</p>
1
2009-06-28T14:06:56Z
[ "python", "mysql", "database" ]
Unable to make a MySQL database of SO questions by Python
1,054,964
<p><a href="http://meta.stackexchange.com/questions/73/is-the-fastest-gun-in-the-west-solved/106#106">Brent's answer</a> suggests me that has made a database of SO questions such that he can fast analyze the questions.</p> <p>I am interested in making a similar database by MySQL such that I can practice MySQL with similar queries as Brent.</p> <p>The database should include at the least the following fields (I am guessing here, since the API of SO's api seems to be sectet). I aim to list only relevant variables which would allow me to make similar analysis as Brent. </p> <ul> <li>Questions</li> <li>Question_id (private key)</li> <li><p>Question_time</p></li> <li><p>Comments</p></li> <li>Comment_id (private key)</li> <li><p>Comment_time</p></li> <li><p>User_id (private key)</p></li> <li>User_name </li> </ul> <p>We need apparently scrape the data by Python's Beautiful Soap because Brent's database is apparently hidden.</p> <p><strong>How can you make such a MySQL database</strong> by Python's Beautiful Soap?**</p>
0
2009-06-28T13:52:05Z
1,055,057
<p>I'm sure it's possible to work directly with the XML data dump @RichieHindle mentions, but I was much happier with @nobody_'s <a href="http://modos.org/so-export-sqlite-2009-05.torrent" rel="nofollow">sqlite</a> version -- especially after adding the indices as the README file in that sqlite version says.</p> <p>If you have the complete, indexed sqlite version and want to load the Python-tagged subset into a MySQL database, that can be seen as a simple but neat exercise in using two DB API instances, reading from the sqlite one and writing to the MySQL one (personally I found the sqlite performance entirely satisfactory once the index-building is done, so I did no subset extraction nor any moving to other DB engines) -- no Soup <em>nor</em> Soap needed for the purpose. In any case, it was much simpler and faster for me than loading from XML directly, despite lxml and all.</p> <p>Of course if you do still want to perform the subset-load, and if you experience any trouble at all coding it up, ask (with schema and code samples, error messages if any, etc) and SOers will try to answer, as usual!-)</p>
1
2009-06-28T14:55:16Z
[ "python", "mysql", "database" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,111
<p>My ancient <a href="http://code.activestate.com/recipes/52305/" rel="nofollow">YAPTU</a> and Palmer's <a href="http://code.activestate.com/recipes/465508/" rel="nofollow">yaptoo</a> variant on it should be usable if you want something very simple and lightweight -- but there are many, many other general and powerful templating engines to chose among, these days. A pretty complete list is <a href="http://wiki.python.org/moin/Templating" rel="nofollow">here</a>.</p>
1
2009-06-28T15:34:40Z
[ "python", "xml" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,115
<p>You asked for the easiest and quickest, so see this post: <a href="http://simonwillison.net/2003/Jul/28/simpleTemplates/" rel="nofollow">http://simonwillison.net/2003/Jul/28/simpleTemplates/</a></p> <p>If you want something smarter, take a look <a href="http://www.webwareforpython.org/Papers/Templates/" rel="nofollow">here</a>.</p>
1
2009-06-28T15:37:20Z
[ "python", "xml" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,121
<p>Two choices.</p> <ol> <li><p>A template tool, for example <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a>.</p></li> <li><p>Build the DOM object. Not as bad as it sounds. ElementTree has a pleasant factory for building XML tags and creating the necessary structure. </p></li> </ol>
3
2009-06-28T15:43:44Z
[ "python", "xml" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,122
<p>A lightweight option is <a href="http://docs.python.org/library/xml.dom.minidom.html#module-xml.dom.minidom" rel="nofollow">xml.dom.minidom</a></p> <blockquote> <p>xml.dom.minidom is a light-weight implementation of the Document Object Model interface. It is intended to be simpler than the full DOM and also significantly smaller.</p> </blockquote> <p>You can create DOM object using the <code>xml.dom</code> API, for example <a href="http://docs.python.org/library/xml.dom.html#dom-element-objects" rel="nofollow">DOM Element objects</a>, and generate the XML using <a href="http://docs.python.org/library/xml.dom.minidom.html#xml.dom.minidom.Node.writexml" rel="nofollow"><code>Node.writexml</code></a>. Note that this requires building DOM hierarchies, which may not be what you are after.</p> <p>more pythonic option is <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">ElementTree</a>.</p> <blockquote> <p>The Element type is a flexible container object, designed to store hierarchical data structures in memory. The type can be described as a cross between a list and a dictionary.</p> </blockquote> <p>ElementTree objects are easier to create and handle in <code>Python</code>, and can be serialized to XML with <a href="http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.dump" rel="nofollow">ElementTree.dump()</a> or <a href="http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.tostring" rel="nofollow">ElementTree.tostring()</a></p>
3
2009-06-28T15:44:20Z
[ "python", "xml" ]
fast and easy way to template xml files in python
1,055,108
<p>Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. </p> <p>What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?</p>
2
2009-06-28T15:28:44Z
1,055,145
<p><strong>Short answer is:</strong> You should be focusing, and dealing with, the data (i.e., python object) and not the raw XML</p> <p><strong>Basic story:</strong> XML is supposed to be a representation of some data, or data set. You don't have a lot of detail in your question about the type of data, what it represents, etc, etc -- so I'll give you some basic answers.</p> <p><strong>Python choices:</strong> BeautifulSoup, lxml and other python libraries (ElementTree, etc.), make dealing with XML more easy. They let me read in, or write out, XML data much more easily than if I'd tried to work directly with the XML in raw form.</p> <p>In the middle of those 2 (input,output) activities, my python program is dealing with a nice python object or some kind of parse tree I can walk. You can read data in, create an object from that string, manipulate it and write out XML.</p> <p><strong>Other choice, Templates:</strong> OK -- maybe you like XML and just want to "template" it so you can populate it with the data.</p> <p>You might be more comfortable with this, if you aren't really manipulating the data -- but just representing it for output. And, this is similar to the XML strings you are currently using -- so may be more familiar.</p> <p>Use Cheetah, Jinja, or other template libraries to help. Make a template for the XML file, using that template language. </p> <p>For example, you just read a list of books from a file or database table. You would pass this list of book objects to the template engine, with a template, and then tell it to write out your XML output. </p> <p>Example template for these book objects:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;catalog&gt; {% for object in object_list %} &lt;book id="{{ object.bookID }}"&gt; &lt;author&gt;{{ object.author_name }}&lt;/author&gt; &lt;title&gt;{{ object.title }}&lt;/title&gt; &lt;genre&gt;{{ object.genre }}&lt;/genre&gt; &lt;price&gt;{{ object.price }}&lt;/price&gt; &lt;publish_date&gt;{{ object.pub_date }}&lt;/publish_date&gt; &lt;description&gt;{{ object.description }}&lt;/description&gt; &lt;/book&gt; {% endfor %} &lt;/catalog&gt; &lt;/xml&gt; </code></pre> <p>The template engine would loop through the "object_list" and output a long XML file with all your books. That would be <strong>much</strong> better than storing raw XML strings, as you currently are.</p> <p>This makes the update &amp; modification of the display of XML separate from the data, data storage, and data manipulation -- making your life easier.</p>
1
2009-06-28T15:58:22Z
[ "python", "xml" ]
How to modify a NumPy.recarray using its two views
1,055,131
<p>I am new to Python and Numpy, and I am facing a problem, that I can not modify a numpy.recarray, when applying to masked views. I read recarray from a file, then create two masked views, then try to modify the values in for loop. Here is an example code.</p> <pre><code>import numpy as np import matplotlib.mlab as mlab dat = mlab.csv2rec(args[0], delimiter=' ') m_Obsr = dat.is_observed == 1 m_ZeroScale = dat[m_Obsr].scale_mean &lt; 0.01 for d in dat[m_Obsr][m_ZeroScale]: d.scale_mean = 1.0 </code></pre> <p>But when I print the result</p> <pre><code>newFile = args[0] + ".no-zero-scale" mlab.rec2csv(dat[m_Obsr][m_ZeroScale], newFile, delimiter=' ') </code></pre> <p>All the scale_means in the files, are still zero.</p> <p>I must be doing something wrong. Is there a proper way of modifying values of the view? Is it because I am applying two views one by one?</p> <p>Thank you.</p>
1
2009-06-28T15:47:55Z
1,055,180
<p>I think you have a misconception in this term "masked views" and should (re-)read <a href="http://www.tramy.us/numpybook.pdf" rel="nofollow">The Book</a> (now freely downloadable) to clarify your understanding.</p> <p>I quote from section 3.4.2:</p> <blockquote> <p>Advanced selection is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are two types of advanced indexing: integer and Boolean. Advanced selection always returns a copy of the data (contrast with basic slicing that returns a view).</p> </blockquote> <p>What you're doing here is advanced selection (of the Boolean kind) so you're getting a copy and never binding it anywhere -- you make your changes on the copy and then just let it go away, then write a new fresh copy from the original.</p> <p>Once you understand the issue the solution should be simple: make your copy once, make your changes on that copy, and write that same copy. I.e.:</p> <pre><code>dat = mlab.csv2rec(args[0], delimiter=' ') m_Obsr = dat.is_observed == 1 m_ZeroScale = dat[m_Obsr].scale_mean &lt; 0.01 the_copy = dat[m_Obsr][m_ZeroScale] for d in the_copy: d.scale_mean = 1.0 newFile = args[0] + ".no-zero-scale" mlab.rec2csv(the_copy, newFile, delimiter=' ') </code></pre>
3
2009-06-28T16:13:37Z
[ "python", "numpy", "matplotlib" ]
Unicode friendly alphabetic pattern for python regex?
1,055,160
<p>I'm looking for a pattern equivalent to \w, and which doesn't match numeric pattern. I cannot use [a-zA-Z] because I would like it to match japanese kanjis as well.</p> <p>Is there a way to write something like [\w^[0-9]] ? Is there an equivalent of [:alpha:] in python regex?</p>
4
2009-06-28T16:04:58Z
1,055,173
<pre><code>[^\W\d] </code></pre> <p>Throw out non-word characters and throw out digits. Keep the rest.</p>
11
2009-06-28T16:09:44Z
[ "python", "regex" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("ff") no </pre> <p>The problem is that string is technically iterable, so I can't just catch the ValueError when trying <code>arg[1]</code>. I don't want to use isinstance(), because that's not good practice (or so I'm told).</p>
37
2009-06-28T17:45:28Z
1,055,378
<p>Use isinstance (I don't see why it's bad practice)</p> <pre><code>import types if not isinstance(arg, types.StringTypes): </code></pre> <p>Note the use of StringTypes. It ensures that we don't forget about some obscure type of string.</p> <p>On the upside, this also works for derived string classes.</p> <pre><code>class MyString(str): pass isinstance(MyString(" "), types.StringTypes) # true </code></pre> <p>Also, you might want to have a look at this <a href="http://stackoverflow.com/questions/836387/how-can-i-tell-if-a-python-variable-is-a-string-or-a-list">previous question</a>.</p> <p>Cheers.</p>
29
2009-06-28T17:56:28Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("ff") no </pre> <p>The problem is that string is technically iterable, so I can't just catch the ValueError when trying <code>arg[1]</code>. I don't want to use isinstance(), because that's not good practice (or so I'm told).</p>
37
2009-06-28T17:45:28Z
1,055,402
<p>As you point out correctly, a single string is a character sequence.</p> <p>So the thing you really want to do is to find out what kind of sequence <code>arg</code> is by using isinstance or type(a)==str.</p> <p>If you want to realize a function that takes a variable amount of parameters, you should do it like this:</p> <pre><code>def function(*args): # args is a tuple for arg in args: do_something(arg) </code></pre> <p>function("ff") and function("ff", "ff") will work.</p> <p>I can't see a scenario where an isiterable() function like yours is needed. It isn't isinstance() that is bad style but situations where you need to use isinstance().</p>
1
2009-06-28T18:09:15Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("ff") no </pre> <p>The problem is that string is technically iterable, so I can't just catch the ValueError when trying <code>arg[1]</code>. I don't want to use isinstance(), because that's not good practice (or so I'm told).</p>
37
2009-06-28T17:45:28Z
1,055,540
<p>Since Python 2.6, with the introduction of abstract base classes, <code>isinstance</code> (used on ABCs, not concrete classes) is now considered perfectly acceptable. Specifically:</p> <pre><code>from abc import ABCMeta, abstractmethod class NonStringIterable: __metaclass__ = ABCMeta @abstractmethod def __iter__(self): while False: yield None @classmethod def __subclasshook__(cls, C): if cls is NonStringIterable: if any("__iter__" in B.__dict__ for B in C.__mro__): return True return NotImplemented </code></pre> <p>This is an exact copy (changing only the class name) of <code>Iterable</code> as defined in <code>_abcoll.py</code> (an implementation detail of <code>collections.py</code>)... the reason this works as you wish, while <code>collections.Iterable</code> doesn't, is that the latter goes the extra mile to ensure strings are considered iterable, by calling <code>Iterable.register(str)</code> explicitly just after this <code>class</code> statement.</p> <p>Of course it's easy to augment <code>__subclasshook__</code> by returning <code>False</code> before the <code>any</code> call for other classes you want to specifically exclude from your definition.</p> <p>In any case, after you have imported this new module as <code>myiter</code>, <code>isinstance('ciao', myiter.NonStringIterable)</code> will be <code>False</code>, and <code>isinstance([1,2,3], myiter.NonStringIterable)</code>will be <code>True</code>, just as you request -- and in Python 2.6 and later this is considered the proper way to embody such checks... define an abstract base class and check <code>isinstance</code> on it.</p>
14
2009-06-28T19:11:24Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("ff") no </pre> <p>The problem is that string is technically iterable, so I can't just catch the ValueError when trying <code>arg[1]</code>. I don't want to use isinstance(), because that's not good practice (or so I'm told).</p>
37
2009-06-28T17:45:28Z
17,222,092
<p>I realise this is an old post but thought it was worth adding my approach for Internet posterity. The function below seems to work for me under most circumstances with both Python 2 and 3:</p> <pre><code>def is_collection(obj): """ Returns true for any iterable which is not a string or byte sequence. """ try: if isinstance(obj, unicode): return False except NameError: pass if isinstance(obj, bytes): return False try: iter(obj) except TypeError: return False try: hasattr(None, obj) except TypeError: return True return False </code></pre> <p>This checks for a non-string iterable by (mis)using the built-in <code>hasattr</code> which will raise a <code>TypeError</code> when its second argument is not a string or unicode string.</p>
3
2013-06-20T19:23:32Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("ff") no </pre> <p>The problem is that string is technically iterable, so I can't just catch the ValueError when trying <code>arg[1]</code>. I don't want to use isinstance(), because that's not good practice (or so I'm told).</p>
37
2009-06-28T17:45:28Z
27,537,028
<p>By combining previous replies, I'm using:</p> <pre><code>import types import collections #[...] if isinstance(var, types.StringTypes ) \ or not isinstance(var, collections.Iterable): #[Do stuff...] </code></pre> <p>Not 100% fools proof, but if an object is not an iterable you still can let it pass and fall back to duck typing.</p>
0
2014-12-18T00:00:41Z
[ "python" ]
how to tell a variable is iterable but not a string
1,055,360
<p>I have a function that take an argument which can be either a single item or a double item:</p> <pre><code>def iterable(arg) if #arg is an iterable: print "yes" else: print "no" </code></pre> <p>so that:</p> <pre> >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("ff") no </pre> <p>The problem is that string is technically iterable, so I can't just catch the ValueError when trying <code>arg[1]</code>. I don't want to use isinstance(), because that's not good practice (or so I'm told).</p>
37
2009-06-28T17:45:28Z
32,496,618
<p>huh, don't get it... what's wrong with going </p> <pre><code>hasattr( x, '__iter__' ) </code></pre> <p>?</p> <p>... NB elgehelge puts this in a comment here, saying "look at my more detailed answer" but I couldn't find his/her detailed answer</p> <p><strong><em>later</em></strong></p> <p>In view of David Charles' comment about Python3, what about:</p> <pre><code>hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) </code></pre> <p>? Apparently "basestring" is no longer a type in Python3:</p> <p><a href="https://docs.python.org/3.0/whatsnew/3.0.html" rel="nofollow">https://docs.python.org/3.0/whatsnew/3.0.html</a></p> <pre><code>The builtin basestring abstract type was removed. Use str instead. The str and bytes types don’t have functionality enough in common to warrant a shared base class. </code></pre>
1
2015-09-10T08:19:34Z
[ "python" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict['density'] = mydict['mass']/mydict['volume'] </code></pre> <p>So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):</p> <pre><code>mydict['density_calc'] = lambda x,y: x/y mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!</p> <p>Cheers,</p> <p>Dave</p>
1
2009-06-28T18:11:53Z
1,055,423
<p>Short answer is you can't.</p> <p>The assigned expression is evaluated <a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Strict_evaluation" rel="nofollow">strictly</a> when it's encountered so any changes to the terms later on don't matter.</p> <p>You could solve this with a custom dict class that overwrites the <strong>getitem</strong> and <strong>setitem</strong> methods and does something special (i.e. computes the value) for some of the keys (say density and a finite number of others).</p> <pre><code>class MyDict(dict): def __getitem__(self, key): if key == "density": return self["mass"] / self["volume"] return dict.__getitem__(self, key) d = MyDict() d["mass"] = 2.0 d["volume"] = 4.0 d["density"] # 0.5 </code></pre> <p>Have a look at <a href="http://diveintopython.net/object_oriented_framework/special_class_methods.html" rel="nofollow">this</a>.</p>
3
2009-06-28T18:18:19Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict['density'] = mydict['mass']/mydict['volume'] </code></pre> <p>So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):</p> <pre><code>mydict['density_calc'] = lambda x,y: x/y mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!</p> <p>Cheers,</p> <p>Dave</p>
1
2009-06-28T18:11:53Z
1,055,436
<p>Seems like an abuse of a dictionary structure. Why not create a simple class?</p> <pre><code>class Entity(object): def __init__(self, mass, volume): self.mass = mass self.volume = volume def _density(self): return self.mass / self.volume density = property(_density) </code></pre>
9
2009-06-28T18:23:36Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict['density'] = mydict['mass']/mydict['volume'] </code></pre> <p>So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):</p> <pre><code>mydict['density_calc'] = lambda x,y: x/y mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!</p> <p>Cheers,</p> <p>Dave</p>
1
2009-06-28T18:11:53Z
1,055,438
<p>A class would do this better:</p> <pre><code>class Thing: def __init__(self, mass, volume): self._mass = mass self._volume = volume self._update_density() def _update_density(self): self._density = self._mass / self._volume def get_density(self): return self._density density = property(get_density) # You're unlikely to need these, but to demonstrate the point: def set_mass(self, mass): self._mass = mass self._update_density() def set_volume(self, volume): self._volume = volume self._update_density() brick = Thing(mass=2, volume=0.8) print brick.density # Prints 2.5 brick.set_mass(4) print brick.density # Prints 5.0 </code></pre> <p>I'm taking you at your word that you want the density updated when you set the other values - an easier way would be to simply calculate it on the fly when asked for it:</p> <pre><code> def get_density(self): return self._mass / self._volume </code></pre> <p>Then you wouldn't need <code>_update_density()</code> at all.</p>
4
2009-06-28T18:24:42Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict['density'] = mydict['mass']/mydict['volume'] </code></pre> <p>So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):</p> <pre><code>mydict['density_calc'] = lambda x,y: x/y mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!</p> <p>Cheers,</p> <p>Dave</p>
1
2009-06-28T18:11:53Z
1,055,439
<p>You would be best off creating a class for this in this case and using a dynamic property. e.g.:</p> <pre> <code> class Body(object): def __init__(self): self.mass=1.0 self.volume=0.5 @property def density(self): return self.mass/self.volume </code> </pre> <p>This will give you mass, volume and density properties, where density is calculated based on the other two values. e.g.</p> <pre> <code> b=Body() b.mass=1 b.volume=0.5 print b.density # should be 2 b.mass=2.0 print b.density # should be 4 </code> </pre> <p>However if you are wedded to using a dictionary you should probably extend it and override the <code>__getitem__</code> and <code>__setitem__</code> "magic" methods to and detect when mass has changed or else when density is being accessed and recalculate as needed.</p>
6
2009-06-28T18:25:19Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict['density'] = mydict['mass']/mydict['volume'] </code></pre> <p>So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):</p> <pre><code>mydict['density_calc'] = lambda x,y: x/y mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!</p> <p>Cheers,</p> <p>Dave</p>
1
2009-06-28T18:11:53Z
1,055,440
<p>Here's a quick hack on how to subclass <code>dict</code> to meet your specs, but probably not to meet Python's specs for a dictionary:</p> <pre><code>class MyDict(dict): def __getitem__(self, key): if key == 'density': return self['mass'] / self['volume'] else: return dict.__getitem__(self,key) def keys(self): return ['density'] + dict.keys(self) x = MyDict() x['mass'] = 1.0 x['volume'] = 0.5 print x print x.keys() print x['density'] x['mass'] = 2.0 print x['density'] </code></pre> <p>which prints</p> <pre><code>{'volume': 0.5, 'mass': 1.0} ['density', 'volume', 'mass'] 2.0 4.0 </code></pre> <p>But that doesn't account for dict.iterkeys(), among other things.</p>
-2
2009-06-28T18:25:58Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict['density'] = mydict['mass']/mydict['volume'] </code></pre> <p>So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):</p> <pre><code>mydict['density_calc'] = lambda x,y: x/y mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!</p> <p>Cheers,</p> <p>Dave</p>
1
2009-06-28T18:11:53Z
1,055,441
<p>The problem is that dictionaries aren't the right tool for your problem. Your question is like "how can I hammer a nail in with a screwdriver" ;-)</p> <p>Dictionaries are supposed to map keys to values and don't care about other values in the dictionary. What you want is a class</p> <pre><code>class PhysicalObject: def __init__(self, mass, volume): self.mass = float(mass) self.volume = float(volume) def setMass(self, mass): self.mass = float(mass) def setVolume(self, volume): self.volume = float(volume) def getDensity(self): return self.mass/float(self.volume) v = PhysicalObject(1.0, 2.0) print v.getDensity() # prints 0.5 v.setMass(2.0) v.setVolume(1.0) print v.getDensity() # prints 2.0 </code></pre> <p>This example recalculates the density every time you want to get it, buy you can also calculate it in the setMass and setVolume functions.</p>
3
2009-06-28T18:26:23Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict['density'] = mydict['mass']/mydict['volume'] </code></pre> <p>So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):</p> <pre><code>mydict['density_calc'] = lambda x,y: x/y mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!</p> <p>Cheers,</p> <p>Dave</p>
1
2009-06-28T18:11:53Z
1,055,457
<p>This is so easy:</p> <pre><code>&gt;&gt;&gt; mydict = {'mass':100, 'volume': 2, 'density': lambda: mydict['mass']/mydict['volume']} &gt;&gt;&gt; mydict['density']() 50 &gt;&gt;&gt; mydict['mass']=200 &gt;&gt;&gt; mydict['density']() 100 &gt;&gt;&gt; mydict['volume'] = 4 &gt;&gt;&gt; mydict['density']() 50 </code></pre> <p>My lambda references mydict and later on retrieves the newest data hold in mydict, so sparing me the trouble of passing the mass and volume to the function each time I want to call it, like in your solution:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>However mydict['density'] is a function, not the value itself.</p>
1
2009-06-28T18:32:50Z
[ "python", "variables", "dictionary" ]
Python: linking/binding variables together in a dictionary
1,055,410
<p>first post, so play nice!</p> <p>I have a fairly basic question about Python dictionaries. I would like to have some dict value that updates when another variable is changed (or at least recalculated when it is next called) - eg:</p> <pre><code>mass = 1.0 volume = 0.5 mydict = {'mass':mass,'volume':volume} mydict['density'] = mydict['mass']/mydict['volume'] </code></pre> <p>So in this case, mydict['density'] just returns 2.0. If I change mydict['mass'] = 2.0, the density will not be updated. Fine - I can kind of understand why - the density is defined by the values when they were passed to the declaration. So I thought maybe I could approach this with a lambda expression, eg (apologies for the horrid code!):</p> <pre><code>mydict['density_calc'] = lambda x,y: x/y mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>But again, this only returns the original density, despite changing mydict['mass']. As a final attempt, I tried this:</p> <pre><code>def density(mass,volume): return mass/volume mydict['density_calc'] = lambda x,y: density(x,y) mydict['density'] = mydict['density_calc'](mydict['mass'],mydict['volume']) </code></pre> <p>Again, no dice. This seems like a really simple problem to solve, so apologies in advance, but if anyone could help me out, I'd be very appreciative!</p> <p>Cheers,</p> <p>Dave</p>
1
2009-06-28T18:11:53Z
39,757,186
<p>A self-referential dictionary would almost match your second attempt (from 7 years ago) and would play nicely with any other code that uses this dictionary. In other words it will still look and act like a duck.</p> <pre><code>class MyDict(dict): def __getitem__(self,key): value=dict.__getitem__(self,key) if callable(value): value=value(self) return value mydict=MyDict({'mass':1.0,'volume':0.5}) mydict['density'] = lambda mydict: mydict['mass']/mydict['volume'] print(mydict['density']) </code></pre> <p>2.0</p> <pre><code>mydict['mass']=2.0 print(mydict['density']) </code></pre> <p>4.0</p>
0
2016-09-28T20:35:33Z
[ "python", "variables", "dictionary" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have imagined that!</p>
7
2009-06-28T18:27:35Z
1,055,453
<p>From the Python REPL (the command-line interpreter / Read-Eval-Print-Loop), type <code>help("modules")</code> to see a list of all your available libs.</p> <p>Then to see functions within a module, do <code>help("posix")</code>, for example. If you haven't <code>import</code>ed the library yet, you have to put quotes around the library's name.</p>
31
2009-06-28T18:31:07Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have imagined that!</p>
7
2009-06-28T18:27:35Z
1,055,463
<p>Every standard python distribution has <a href="http://docs.python.org/library/index.html" rel="nofollow">these</a> libraries, which cover most of what you will need in a project.</p> <p>In case you need to find out if a library exists at runtime, you do it like this</p> <pre><code>try: import ObscureModule except ImportError: print "you need to install ObscureModule" sys.exit(1) # or something like that </code></pre>
2
2009-06-28T18:34:55Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have imagined that!</p>
7
2009-06-28T18:27:35Z
1,055,474
<p>On Leopard, depending on the python package you're using and the version number, the modules can be found in /Library/Python:</p> <p>/Library/Python/2.5/site-packages</p> <p>or in /Library/Frameworks</p> <p>/Library/Frameworks/Python.framework/Versions/Current/lib/python2.6/site-packages</p> <p>(it could also be 3.0 or whatever version)... I guess it is quite the same with Tiger</p>
2
2009-06-28T18:39:30Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have imagined that!</p>
7
2009-06-28T18:27:35Z
1,055,520
<p>You can install another library: yolk.</p> <p>yolk is a python package manager and will show you everything you have added via pypi. But it will also show you site-packages added through whatever local package manager you run.</p>
3
2009-06-28T18:59:23Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have imagined that!</p>
7
2009-06-28T18:27:35Z
1,055,554
<p>just run the Python interpeter and type the command import "lib_name" if it gives an error, you don't have the lib installed...else you are good to go</p>
1
2009-06-28T19:17:19Z
[ "python" ]
How do I find out what Python libraries are installed on my Mac?
1,055,443
<p>I'm just starting out with Python, and have found out that I can import various libraries. How do I find out what libraries exist on my Mac that I can import? How do I find out what functions they include?</p> <p>I seem to remember using some web server type thing to browse through local help files, but I may have imagined that!</p>
7
2009-06-28T18:27:35Z
1,055,787
<p>For the web server, you can run the <code>pydoc</code> module that is included in the python distribution as a script:</p> <pre><code>python /path/to/pydoc.py -p 1234 </code></pre> <p>where <code>1234</code> is the port you want the server to run at. You can then visit <code>http://localhost:1234/</code> and browse the documentation. </p>
4
2009-06-28T21:10:09Z
[ "python" ]
item frequency in a python list of dictionaries
1,055,646
<p>Ok, so I have a list of dicts:</p> <pre><code>[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] </code></pre> <p>and I want the 'frequency' of the items within each column. So for this I'd get something like:</p> <pre><code>{'name': {'johnny': 2, 'jakob': 1, 'aaron': 1, 'max': 1}, 'surname': {'smith': 2, 'ryan': 1, 'specter': 1, 'headroom': 1}, 'age': {53:1, 13:1, 27: 1. 22:1, 108:1}} </code></pre> <p>Any modules out there that can do stuff like this?</p>
7
2009-06-28T20:15:42Z
1,055,662
<p><code>collections.defaultdict</code> from the standard library to the rescue:</p> <pre><code>from collections import defaultdict LofD = [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] def counters(): return defaultdict(int) def freqs(LofD): r = defaultdict(counters) for d in LofD: for k, v in d.items(): r[k][v] += 1 return dict((k, dict(v)) for k, v in r.items()) print freqs(LofD) </code></pre> <p>emits</p> <pre><code>{'age': {27: 1, 108: 1, 53: 1, 22: 1, 13: 1}, 'surname': {'headroom': 1, 'smith': 2, 'specter': 1, 'ryan': 1}, 'name': {'jakob': 1, 'max': 1, 'aaron': 1, 'johnny': 2}} </code></pre> <p>as desired (order of keys apart, of course -- it's irrelevant in a dict).</p>
13
2009-06-28T20:23:10Z
[ "python", "dictionary" ]
item frequency in a python list of dictionaries
1,055,646
<p>Ok, so I have a list of dicts:</p> <pre><code>[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] </code></pre> <p>and I want the 'frequency' of the items within each column. So for this I'd get something like:</p> <pre><code>{'name': {'johnny': 2, 'jakob': 1, 'aaron': 1, 'max': 1}, 'surname': {'smith': 2, 'ryan': 1, 'specter': 1, 'headroom': 1}, 'age': {53:1, 13:1, 27: 1. 22:1, 108:1}} </code></pre> <p>Any modules out there that can do stuff like this?</p>
7
2009-06-28T20:15:42Z
1,055,664
<p>This?</p> <pre><code>from collections import defaultdict fq = { 'name': defaultdict(int), 'surname': defaultdict(int), 'age': defaultdict(int) } for row in listOfDicts: for field in fq: fq[field][row[field]] += 1 print fq </code></pre>
1
2009-06-28T20:23:47Z
[ "python", "dictionary" ]
item frequency in a python list of dictionaries
1,055,646
<p>Ok, so I have a list of dicts:</p> <pre><code>[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] </code></pre> <p>and I want the 'frequency' of the items within each column. So for this I'd get something like:</p> <pre><code>{'name': {'johnny': 2, 'jakob': 1, 'aaron': 1, 'max': 1}, 'surname': {'smith': 2, 'ryan': 1, 'specter': 1, 'headroom': 1}, 'age': {53:1, 13:1, 27: 1. 22:1, 108:1}} </code></pre> <p>Any modules out there that can do stuff like this?</p>
7
2009-06-28T20:15:42Z
1,055,673
<pre><code>items = [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}] global_dict = {} for item in items: for key, value in item.items(): if not global_dict.has_key(key): global_dict[key] = {} if not global_dict[key].has_key(value): global_dict[key][value] = 0 global_dict[key][value] += 1 print global_dict </code></pre> <p>Simplest solution and actually tested.</p>
2
2009-06-28T20:26:59Z
[ "python", "dictionary" ]
item frequency in a python list of dictionaries
1,055,646
<p>Ok, so I have a list of dicts:</p> <pre><code>[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] </code></pre> <p>and I want the 'frequency' of the items within each column. So for this I'd get something like:</p> <pre><code>{'name': {'johnny': 2, 'jakob': 1, 'aaron': 1, 'max': 1}, 'surname': {'smith': 2, 'ryan': 1, 'specter': 1, 'headroom': 1}, 'age': {53:1, 13:1, 27: 1. 22:1, 108:1}} </code></pre> <p>Any modules out there that can do stuff like this?</p>
7
2009-06-28T20:15:42Z
1,055,680
<p>New in Python 3.1: The <code>collections.Counter</code> class:</p> <pre><code>mydict=[{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] import collections newdict = {} for key in mydict[0].keys(): l = [value[key] for value in mydict] newdict[key] = dict(collections.Counter(l)) print(newdict) </code></pre> <p>outputs:</p> <pre><code>{'age': {27: 1, 108: 1, 53: 1, 22: 1, 13: 1}, 'surname': {'headroom': 1, 'smith': 2, 'specter': 1, 'ryan': 1}, 'name': {'jakob': 1, 'max': 1, 'aaron': 1, 'johnny': 2}} </code></pre>
1
2009-06-28T20:33:07Z
[ "python", "dictionary" ]
JSON serialization in Spidermonkey
1,055,805
<p>I'm using <code>python-spidermonkey</code> to run JavaScript code.</p> <p>In order to pass objects (instead of just strings) to Python, I'm thinking of returning a JSON string.</p> <p>This seems like a common issue, so I wonder whether there are any facilities for this built into either Spidermonkey or <code>python-spidermonkey</code>. (I do know about <code>uneval</code> but that is not meant to be used for JSON serialization - and I'd rather avoid injecting a block of JavaScript to do this.)</p>
3
2009-06-28T21:19:17Z
1,056,753
<p>I would use JSON.stringify. It's part of the ECMAScript 5 standard, and it's implemented in the current version of spidermonkey. I don't know if it's in the version used by python-spidermonkey, but if it isn't, you can get a JavaScript implementation from <a href="http://www.json.org/js.html">http://www.json.org/js.html</a>.</p>
6
2009-06-29T05:54:28Z
[ "javascript", "python", "json", "spidermonkey" ]
file I/O in Spidermonkey
1,055,850
<p>Thanks to <code>python-spidermonkey</code>, using JavaScript code from Python is really easy.</p> <p>However, instead of using Python to read JS code from a file and passing the string to Spidermonkey, is there a way to read the file from within Spidermonkey (or pass the filepath as an argument, as in Rhino)?</p>
2
2009-06-28T21:40:29Z
1,057,949
<p>The SpiderMonkey as a library allows that by calling the <a href="https://developer.mozilla.org/en/SpiderMonkey/JSAPI%5FReference/JS%5FEvaluateScript" rel="nofollow"><code>JS_EvaluateScript</code></a> with a non-NULL <code>filename</code> argument.</p> <p>However, the <a href="http://code.google.com/p/python-spidermonkey/source/browse/trunk/spidermonkey.pyx" rel="nofollow">interfacing code</a> of <code>python-spidermonkey</code> calls <code>JS_EvaluateScript</code> only inside the <code>eval_script</code> method, which as coded supplies source only as a string.</p> <p>You should address your issue to the python-spidermonkey developer, or —better, if possible!— provide a patch for a, say, <code>eval_file_script</code> method :)</p>
2
2009-06-29T12:07:18Z
[ "javascript", "python", "spidermonkey" ]
file I/O in Spidermonkey
1,055,850
<p>Thanks to <code>python-spidermonkey</code>, using JavaScript code from Python is really easy.</p> <p>However, instead of using Python to read JS code from a file and passing the string to Spidermonkey, is there a way to read the file from within Spidermonkey (or pass the filepath as an argument, as in Rhino)?</p>
2
2009-06-28T21:40:29Z
1,087,978
<p>Turns out you can just bind a Python function and use it from within Spidermonkey: <a href="http://davisp.lighthouseapp.com/projects/26898/tickets/23-support-for-file-io-js_evaluatescript" rel="nofollow">http://davisp.lighthouseapp.com/projects/26898/tickets/23-support-for-file-io-js_evaluatescript</a></p> <pre><code>import spidermonkey def loadfile(fname): return open(fname).read() rt = spidermonkey.Runtime() cx = rt.new_context() cx.add_global("loadfile", loadfile) ret = cx.execute('var contents = loadfile("foo.js"); eval(contents);') </code></pre>
2
2009-07-06T16:41:40Z
[ "javascript", "python", "spidermonkey" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,055,921
<p>We've always logged data to a <em>separate</em> database.</p> <p>This lets us query without impacting the application database. It also simplifies things if we realize that we need to disable logging or change the amount of what we log.</p> <p>But most modern logging libraries support embedding the logging into your application and choosing the destination by configuration - file, database, whatever.</p> <p><a href="http://docs.python.org/library/logging.html" rel="nofollow">Logger</a> gives you lots of ways to manage your logging, and although the default package doesn't have a database logger, it wouldn't be hard to write such an event handler.</p>
1
2009-06-28T22:26:42Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,056,010
<p>Mix file.log + db would be the best. Log into db information that you eventually might need to analyse, for example average number of users per day etc. And use file.log to store some debug information.</p>
2
2009-06-28T23:12:36Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,056,119
<p>If you decide on a log file format that is parseable, then you can log to a file and then have an external process (perhaps run by cron) that processes your log files and inserts the details into your database. This can be arranged to happen at a time when your application and database load is low.</p> <p>I always worry about what happens if the database becomes unavailable: would this prevent your application from running, or degrade it in any way? Logging to the filesystem avoids having to deal with that issue, but you'd still need to worry about disks filling up and log file rotation.</p>
1
2009-06-29T00:25:06Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,056,139
<p>Log to the DB only if it generates revenue.</p> <p>For example, for one site, we logged all advertisements placed in a web site to a database. It generated revenue. No reason to be parsing log files for something that important.</p> <p>Everything else goes to the file system.</p> <p>Log to the file system for debugging. It's generally private stuff. Implementation details. Not to be shared.</p> <p>Apache logs a mountain of stuff to the filesystem. Do not duplicate this. </p> <p>Access control logs go to the file system. You'll rarely want to look at these in detail.</p> <p>User activity may have to be summarized into a database. This is marketing and usability information that you'll want to study to improve your site. However, detailed activity information is too voluminous to record in the database. Put it on the file system and digest it to a marketing/product improvement/usability analysis database.</p>
1
2009-06-29T00:37:02Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,056,213
<p>First, use a logging library like SLF4J/Logback that allows you to make this decision dynamically. Then you can tweak a configuration file and route some or all of your log messages to each of several different destinations.</p> <p>Be very careful before logging to your application database, you can easily overwhelm it if you're logging a lot of stuff and volume starts to get high. And if your application is running close to full capacity or in a failure mode, the log messages may be inaccessible and you'll be flying blind. Probably the only messages that should go to your application database are high-level application-oriented events (a type of application data).</p> <p>It's much better to "log to the file system" (which for a large production environment includes logging to a multicast address read by redundant log aggregation servers). </p> <p>Log files can be read into special analytics databases where you could use eg, Hadoop to do map/reduce analyses of log data.</p>
10
2009-06-29T01:21:13Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,056,983
<p>Just in case you consider to tweak the standard Python logger to log to a database, this recipe might give you a head start: <a href="http://code.activestate.com/recipes/498158/" rel="nofollow">Logging to a Jabber account</a>.</p>
0
2009-06-29T07:28:01Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,057,729
<p>I would primarily use filesystem logging, just as most other answers recommend. With Python's logging package, you can easily create a database handler, by adapting the suggestion made <a href="http://stackoverflow.com/questions/935930/creating-a-logging-handler-to-connect-to-oracle/1014450#1014450">here</a>. You can also create a custom Filter instance and attach it to your database handler - this will allow you to determine at run-time exactly which events you actually log to the database. In line with other answers, I would say it's only really worth logging some types of event to the database for later analysis.</p> <p>I would concur with the recommendation to log to a separate database (on a separate server) if your main application is high-throughput.</p>
0
2009-06-29T11:02:58Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,057,771
<p>The type of logging depends upon what you're going to do with the data and how you are going to do it. Logging to db is advantageous if you are going to build a reporting system based upon this log db. Else you can log things in a specific format which you can parse later if you want to utilize the data for some analysis. For example, from the file log you can parse only the required information and generate CSVs as and when required. If you're planning to use a db logger, as already suggested, have it separately from your application db.</p> <p>Secondly, you can consider having the logger independent of your main application. Either spawn a thread which does the logging, or run a logger at specific port/socket and pass on the log messages to it, or collect all logging messages together and flush it off into the log at the end of each cycle.</p>
0
2009-06-29T11:13:34Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,058,093
<p>We do both.</p> <p>We log operational information/progress/etc. to the logfile. Standard logfile stuff.</p> <p>In the database, we log statuses of operations. E.g. each item that's processed, so we can do queries on throughput/elapsed time/etc. This data is particularly useful when trending and detecting anomalies (system is "too quiet" etc.) that are potentially indicative of other issues.</p>
0
2009-06-29T12:45:35Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,142,704
<p>Indeed it seems important that you can later switch between DB/File logging. Database logging seems to be much slower than plain text file logging which may become important with high log traffic. I've made a library (which can act standalone or as a handler) when I had the same requirement. It logs into database and/or files, and allows to archive critical messages (and the archive may, for example, be a database while everything goes into text files.) It may save you from coding another one from scratch ... See: <a href="http://www.reifenberg.de/rrlog/" rel="nofollow">The rrlog library</a></p>
0
2009-07-17T11:27:59Z
[ "python", "logging" ]
Server Logging - in Database or Logfile?
1,055,917
<p>I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.</p> <p>I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.</p> <p>On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?</p> <p>(If it makes a difference, I'm using mod_python on an Apache server with a MySQL db. So I'd either be using the <a href="http://docs.python.org/library/logging.html" rel="nofollow">logging</a> library or just creating some logging tables in the db.)</p>
10
2009-06-28T22:23:18Z
1,289,740
<p>It looks like many of you are logging some of the events to a database. I am doing the same, but its adding a bit of delay. Do any of you log to database through a message queue? If so, what do you use for queuing and what is your logging architecture like? I am using Java/J2EE.</p>
0
2009-08-17T18:53:02Z
[ "python", "logging" ]
Can two versions of the same library coexist in the same Python install?
1,055,926
<p>The C libraries have a nice form of late binding, where the exact version of the library that was used during linking is recorded, and thus an executable can find the correct file, even when several versions of the same library are installed.</p> <p>Can the same be done in Python?</p> <p>To be more specific, I work on a Python project that uses some 3rd-party libraries, such as paramiko. Paramiko is now version 1.7.4, but some distributions carry an older version of it, while supplying about the same version of the Python interpreter.</p> <p>Naturally, I would like to support as many configurations as possible, and not just the latest distros. But if I upgrade the installed version of paramiko from what an old distro provides, I 1) make life hard for the package manager 2) might break some existing apps due to incompatibilities in the library version and 3) might get broken if the package manager decides to overwrite my custom installation.</p> <p>Is it possible to resolve this problem cleanly in Python? (i.e., how would i do the setup, and what should the code look like). Ideally, it would just install several versions of a library in site_libraries and let my script select the right one, rather than maintaining a private directory with a set of manually installed libraries..</p> <p>P.S.: I could compile the Python program to a binary, carrying all the necessary dependencies with it, but it kind of works against the idea of using the interpreter provided by the distro. I do it on Windows though.</p>
2
2009-06-28T22:30:09Z
1,055,966
<p>You may want to take a look at <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a></p>
8
2009-06-28T22:52:20Z
[ "python", "shared-libraries" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?</p> <p>Thanks for the answer so far - <strong>however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!</strong></p>
29
2009-06-28T23:37:19Z
1,056,057
<p>I recommend the <a href="http://www.linuxjournal.com/article/8497" rel="nofollow">approaches detailed here</a>. It starts by explaining how to execute strings of Python code, then from there details how to set up a Python environment to interact with your C program, call Python functions from your C code, manipulate Python objects from your C code, etc.</p> <p><b>EDIT</b>: If you really want to go the route of IPC, then you'll want to use <a href="http://docs.python.org/library/struct.html" rel="nofollow">the struct module</a> or better yet, <a href="http://courtwright.org/protlib" rel="nofollow">protlib</a>. Most communication between a Python and C process revolves around passing structs back and forth, either <a href="http://docs.python.org/library/socket.html" rel="nofollow">over a socket</a> or through <a href="http://docs.python.org/library/mmap.html" rel="nofollow">shared memory</a>.</p> <p>I recommend creating a <code>Command</code> struct with fields and codes to represent commands and their arguments. I can't give much more specific advice without knowing more about what you want to accomplish, but in general I recommend the <a href="http://courtwright.org/protlib/" rel="nofollow">protlib</a> library, since it's what I use to communicate between C and Python programs (disclaimer: I am the author of protlib).</p>
9
2009-06-28T23:42:27Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?</p> <p>Thanks for the answer so far - <strong>however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!</strong></p>
29
2009-06-28T23:37:19Z
1,056,067
<p>See the relevant chapter in the manual: <a href="http://docs.python.org/extending/" rel="nofollow">http://docs.python.org/extending/</a></p> <p>Essentially you'll have to embed the python interpreter into your program.</p>
4
2009-06-28T23:48:34Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?</p> <p>Thanks for the answer so far - <strong>however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!</strong></p>
29
2009-06-28T23:37:19Z
1,056,087
<p>Have you considered just wrapping your python application in a shell script and invoking it from with in your C application?</p> <p>Not the most elegant solution, but it is very simple.</p>
4
2009-06-29T00:00:42Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?</p> <p>Thanks for the answer so far - <strong>however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!</strong></p>
29
2009-06-28T23:37:19Z
1,056,105
<p>I haven't used an IPC approach for Python&lt;->C communication but it should work pretty well. I would have the C program do a standard fork-exec and use redirected <code>stdin</code> and <code>stdout</code> in the child process for the communication. A nice text-based communication will make it very easy to develop and test the Python program.</p>
1
2009-06-29T00:15:01Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?</p> <p>Thanks for the answer so far - <strong>however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!</strong></p>
29
2009-06-28T23:37:19Z
1,056,365
<p>If I had decided to go with IPC, I'd probably splurge with <a href="http://www.xmlrpc.com/" rel="nofollow">XML-RPC</a> -- cross-platform, lets you easily put the Python server project on a different node later if you want, has many excellent implementations (see <a href="http://www.xmlrpc.com/directory/1568/implementations" rel="nofollow">here</a> for many, including C and Python ones, and <a href="http://docs.python.org/library/simplexmlrpcserver.html" rel="nofollow">here</a> for the simple XML-RPC server that's part the Python standard library -- not as highly scalable as other approaches but probably fine and convenient for your use case).</p> <p>It may not be a perfect IPC approach for all cases (or even a perfect RPC one, by all means!), but the convenience, flexibility, robustness, and broad range of implementations outweigh a lot of minor defects, in my opinion.</p>
1
2009-06-29T02:44:04Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?</p> <p>Thanks for the answer so far - <strong>however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!</strong></p>
29
2009-06-28T23:37:19Z
1,621,442
<p>apparently Python need to be able to compile to win32 dll, it will solve the problem</p> <p>In such a way that converting c# code to win32 dlls will make it usable by any development tool</p>
0
2009-10-25T17:16:09Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?</p> <p>Thanks for the answer so far - <strong>however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!</strong></p>
29
2009-06-28T23:37:19Z
32,536,011
<p>This seems quite nice <a href="http://thrift.apache.org/" rel="nofollow">http://thrift.apache.org/</a>, there is even a book about it.</p> <p>Details:</p> <blockquote> <p>The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.</p> </blockquote>
0
2015-09-12T06:40:06Z
[ "python", "c", "interop", "cross-domain" ]
How do you call Python code from C code?
1,056,051
<p>I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.</p> <p>I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?</p> <p>Thanks for the answer so far - <strong>however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!</strong></p>
29
2009-06-28T23:37:19Z
33,875,127
<p>I've used the "standard" approach of <a href="https://docs.python.org/2/extending/embedding.html#embedding-python-in-another-application" rel="nofollow">Embedding Python in Another Application</a>. But it's complicated/tedious. Each new function in Python is painful to implement.</p> <p>I saw an example of <a href="http://doc.pypy.org/en/latest/embedding.html#more-complete-example" rel="nofollow">Calling PyPy from C</a>. It uses CFFI to simplify the interface but it requires PyPy, not Python. Read and understand this example first, at least at a high level.</p> <p>I modified the C/PyPy example to work with Python. Here's how to call Python from C using CFFI. </p> <p>My example is more complicated because I implemented three functions in Python instead of one. I wanted to cover additional aspects of passing data back and forth. </p> <p>The complicated part is now isolated to passing the address of <code>api</code> to Python. That only has to be implemented once. After that it's easy to add new functions in Python.</p> <p>interface.h</p> <pre><code>// These are the three functions that I implemented in Python. // Any additional function would be added here. struct API { double (*add_numbers)(double x, double y); char* (*dump_buffer)(char *buffer, int buffer_size); int (*release_object)(char *obj); }; </code></pre> <p>test_cffi.c</p> <pre><code>// // Calling Python from C. // Based on Calling PyPy from C: // http://doc.pypy.org/en/latest/embedding.html#more-complete-example // #include &lt;stdio.h&gt; #include &lt;assert.h&gt; #include "Python.h" #include "interface.h" struct API api; /* global var */ int main(int argc, char *argv[]) { int rc; // Start Python interpreter and initialize "api" in interface.py using // old style "Embedding Python in Another Application": // https://docs.python.org/2/extending/embedding.html#embedding-python-in-another-application PyObject *pName, *pModule, *py_results; PyObject *fill_api; #define PYVERIFY(exp) if ((exp) == 0) { fprintf(stderr, "%s[%d]: ", __FILE__, __LINE__); PyErr_Print(); exit(1); } Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString( "import sys;" "sys.path.insert(0, '.')" ); PYVERIFY( pName = PyString_FromString("interface") ) PYVERIFY( pModule = PyImport_Import(pName) ) Py_DECREF(pName); PYVERIFY( fill_api = PyObject_GetAttrString(pModule, "fill_api") ) // "k" = [unsigned long], // see https://docs.python.org/2/c-api/arg.html#c.Py_BuildValue PYVERIFY( py_results = PyObject_CallFunction(fill_api, "k", &amp;api) ) assert(py_results == Py_None); // Call Python function from C using cffi. printf("sum: %f\n", api.add_numbers(12.3, 45.6)); // More complex example. char buffer[20]; char * result = api.dump_buffer(buffer, sizeof buffer); assert(result != 0); printf("buffer: %s\n", result); // Let Python perform garbage collection on result now. rc = api.release_object(result); assert(rc == 0); // Close Python interpreter. Py_Finalize(); return 0; } </code></pre> <p>interface.py</p> <pre><code>import cffi import sys import traceback ffi = cffi.FFI() ffi.cdef(file('interface.h').read()) # Hold references to objects to prevent garbage collection. noGCDict = {} # Add two numbers. # This function was copied from the PyPy example. @ffi.callback("double (double, double)") def add_numbers(x, y): return x + y # Convert input buffer to repr(buffer). @ffi.callback("char *(char*, int)") def dump_buffer(buffer, buffer_len): try: # First attempt to access data in buffer. # Using the ffi/lib objects: # http://cffi.readthedocs.org/en/latest/using.html#using-the-ffi-lib-objects # One char at time, Looks inefficient. #data = ''.join([buffer[i] for i in xrange(buffer_len)]) # Second attempt. # FFI Interface: # http://cffi.readthedocs.org/en/latest/using.html#ffi-interface # Works but doc says "str() gives inconsistent results". #data = str( ffi.buffer(buffer, buffer_len) ) # Convert C buffer to Python str. # Doc says [:] is recommended instead of str(). data = ffi.buffer(buffer, buffer_len)[:] # The goal is to return repr(data) # but it has to be converted to a C buffer. result = ffi.new('char []', repr(data)) # Save reference to data so it's not freed until released by C program. noGCDict[ffi.addressof(result)] = result return result except: print &gt;&gt;sys.stderr, traceback.format_exc() return ffi.NULL # Release object so that Python can reclaim the memory. @ffi.callback("int (char*)") def release_object(ptr): try: del noGCDict[ptr] return 0 except: print &gt;&gt;sys.stderr, traceback.format_exc() return 1 def fill_api(ptr): global api api = ffi.cast("struct API*", ptr) api.add_numbers = add_numbers api.dump_buffer = dump_buffer api.release_object = release_object </code></pre> <p>Compile:</p> <pre><code>gcc -o test_cffi test_cffi.c -I/home/jmudd/pgsql-native/Python-2.7.10.install/include/python2.7 -L/home/jmudd/pgsql-native/Python-2.7.10.install/lib -lpython2.7 </code></pre> <p>Execute:</p> <pre><code>$ test_cffi sum: 57.900000 buffer: 'T\x9e\x04\x08\xa8\x93\xff\xbf]\x86\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00' $ </code></pre>
0
2015-11-23T15:51:23Z
[ "python", "c", "interop", "cross-domain" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in the case above I want <code>'a'</code> to be returned roughly half the time.</p>
31
2009-06-29T00:46:06Z
1,056,154
<p>This would work:</p> <pre><code>random.choice([k for k in d for x in d[k]]) </code></pre>
32
2009-06-29T00:48:31Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in the case above I want <code>'a'</code> to be returned roughly half the time.</p>
31
2009-06-29T00:46:06Z
1,056,155
<p>Make a list in which each key is repeated a number of times equal to the length of its value. In your example: <code>['a', 'a', 'a', 'b', 'c', 'c']</code>. Then use <code>random.choice()</code>.</p> <p>Edit: or, less elegantly but more efficiently, try this: take the sum of the lengths of all values in the dictionary, <code>S</code> (you can cache and invalidate this value, or keep it up to date as you edit the dictionary, depending on the exact usage pattern you anticipate). Generate a random number from 0 to S, and do a linear search through the dictionary keys to find the range into which your random number falls.</p> <p>I think that's the best you can do without changing or adding to your data representation.</p>
3
2009-06-29T00:48:57Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in the case above I want <code>'a'</code> to be returned roughly half the time.</p>
31
2009-06-29T00:46:06Z
1,056,187
<p>Do you always know the total number of values in the dictionary? If so, this might be easy to do with the following algorithm, which can be used whenever you want to make a probabilistic selection of some items from an ordered list:</p> <ol> <li>Iterate over your list of keys.</li> <li>Generate a uniformly distributed random value between 0 and 1 (aka "roll the dice").</li> <li>Assuming that this key has N_VALS values associated with it and there are TOTAL_VALS total values in the entire dictionary, accept this key with a probability N_VALS / N_REMAINING, where N_REMAINING is the number of items left in the list.</li> </ol> <p>This algorithm has the advantage of not having to generate any new lists, which is important if your dictionary is large. Your program is only paying for the loop over K keys to calculate the total, a another loop over the keys which will on average end halfway through, and whatever it costs to generate a random number between 0 and 1. Generating such a random number is a very common application in programming, so most languages have a fast implementation of such a function. In Python the <a href="http://docs.python.org/library/random.html" rel="nofollow">random number generator</a> a C implementation of the <a href="http://en.wikipedia.org/wiki/Mersenne%5FTwister" rel="nofollow">Mersenne Twister algorithm</a>, which should be very fast. Additionally, the documentation claims that this implementation is thread-safe. </p> <p>Here's the code. I'm sure that you can clean it up if you'd like to use more Pythonic features:</p> <pre><code>#!/usr/bin/python import random def select_weighted( d ): # calculate total total = 0 for key in d: total = total + len(d[key]) accept_prob = float( 1.0 / total ) # pick a weighted value from d n_seen = 0 for key in d: current_key = key for val in d[key]: dice_roll = random.random() accept_prob = float( 1.0 / ( total - n_seen ) ) n_seen = n_seen + 1 if dice_roll &lt;= accept_prob: return current_key dict = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } counts = {} for key in dict: counts[key] = 0 for s in range(1,100000): k = select_weighted(dict) counts[k] = counts[k] + 1 print counts </code></pre> <p>After running this 100 times, I get select keys this number of times:</p> <pre><code>{'a': 49801, 'c': 33548, 'b': 16650} </code></pre> <p>Those are fairly close to your expected values of:</p> <pre><code>{'a': 0.5, 'c': 0.33333333333333331, 'b': 0.16666666666666666} </code></pre> <p>Edit: Miles pointed out a serious error in my original implementation, which has since been corrected. Sorry about that!</p>
17
2009-06-29T01:08:17Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in the case above I want <code>'a'</code> to be returned roughly half the time.</p>
31
2009-06-29T00:46:06Z
1,056,201
<p>Given that your dict fits in memory, the random.choice method should be reasonable. But assuming otherwise, the next technique is to use a list of increasing weights, and use bisect to find a randomly chosen weight.</p> <pre><code>&gt;&gt;&gt; import random, bisect &gt;&gt;&gt; items, total = [], 0 &gt;&gt;&gt; for key, value in d.items(): total += len(value) items.append((total, key)) &gt;&gt;&gt; items[bisect.bisect_left(items, (random.randint(1, total),))][1] 'a' &gt;&gt;&gt; items[bisect.bisect_left(items, (random.randint(1, total),))][1] 'c' </code></pre>
6
2009-06-29T01:17:05Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in the case above I want <code>'a'</code> to be returned roughly half the time.</p>
31
2009-06-29T00:46:06Z
1,056,301
<p>Here is some code that is based on a previous answer I gave for <a href="http://stackoverflow.com/questions/526255/probability-distribution-in-python/526585#526585">probability distribution in python</a> but is using the length to set the weight. It uses an iterative markov chain so that it does not need to know what the total of all of the weights are. Currently it calculates the max length but if that is too slow just change </p> <pre><code> self._maxw = 1 </code></pre> <p>to </p> <pre><code> self._maxw = max lenght </code></pre> <p>and remove</p> <pre><code>for k in self._odata: if len(self._odata[k])&gt; self._maxw: self._maxw=len(self._odata[k]) </code></pre> <p>Here is the code.</p> <pre><code>import random class RandomDict: """ The weight is the length of each object in the dict. """ def __init__(self,odict,n=0): self._odata = odict self._keys = list(odict.keys()) self._maxw = 1 # to increase speed set me to max length self._len=len(odict) if n==0: self._n=self._len else: self._n=n # to increase speed set above max value and comment out next 3 lines for k in self._odata: if len(self._odata[k])&gt; self._maxw: self._maxw=len(self._odata[k]) def __iter__(self): return self.next() def next(self): while (self._len &gt; 0) and (self._n&gt;0): self._n -= 1 for i in range(100): k=random.choice(self._keys) rx=random.uniform(0,self._maxw) if rx &lt;= len(self._odata[k]): # test to see if that is the value we want break # if you do not find one after 100 tries then just get a random one yield k def GetRdnKey(self): for i in range(100): k=random.choice(self._keys) rx=random.uniform(0,self._maxw) if rx &lt;= len(self._odata[k]): # test to see if that is the value we want break # if you do not find one after 100 tries then just get a random one return k #test code d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } rd=RandomDict(d) dc = { 'a': 0, 'b': 0, 'c': 0 } for i in range(100000): k=rd.GetRdnKey() dc[k]+=1 print("Key count=",dc) #iterate over the objects dc = { 'a': 0, 'b': 0, 'c': 0 } for k in RandomDict(d,100000): dc[k]+=1 print("Key count=",dc) </code></pre> <p>Test results</p> <pre><code>Key count= {'a': 50181, 'c': 33363, 'b': 16456} Key count= {'a': 50080, 'c': 33411, 'b': 16509} </code></pre>
1
2009-06-29T02:09:23Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in the case above I want <code>'a'</code> to be returned roughly half the time.</p>
31
2009-06-29T00:46:06Z
1,144,955
<p>I'd say this:</p> <pre><code>random.choice("".join([k * len(d[k]) for k in d])) </code></pre> <p>This makes it clear that each k in d gets as many chances as the length of its value. Of course, it is relying on dictionary keys of length 1 that are characters....</p> <hr> <p>Much later:</p> <pre><code>table = "".join([key * len(value) for key, value in d.iteritems()]) random.choice(table) </code></pre>
1
2009-07-17T18:31:58Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in the case above I want <code>'a'</code> to be returned roughly half the time.</p>
31
2009-06-29T00:46:06Z
2,321,466
<p>Without constructing a new, possibly big list with repeated values:</p> <pre><code>def select_weighted(d): offset = random.randint(0, sum(d.itervalues())-1) for k, v in d.iteritems(): if offset &lt; v: return k offset -= v </code></pre>
8
2010-02-23T20:28:04Z
[ "python", "random", "dictionary" ]
Random Python dictionary key, weighted by values
1,056,151
<p>I have a dictionary where each key has a list of variable length, eg:</p> <pre><code>d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] } </code></pre> <p>Is there a clean way to get a random dictionary key, weighted by the length of its value? <code>random.choice(d.keys())</code> will weight the keys equally, but in the case above I want <code>'a'</code> to be returned roughly half the time.</p>
31
2009-06-29T00:46:06Z
6,619,814
<p>I modified some of the other answers to come up with this. It's a bit more configurable. It takes 2 arguments, a list and a lambda function to tell it how to generate a key.</p> <pre><code>def select_weighted(lst, weight): """ Usage: select_weighted([0,1,10], weight=lambda x: x) """ thesum = sum([weight(x) for x in lst]) if thesum == 0: return random.choice(lst) offset = random.randint(0, thesum - 1) for k in lst: v = weight(k) if offset &lt; v: return k offset -= v </code></pre> <p>Thanks to sth for the base code for this.</p>
0
2011-07-08T03:59:16Z
[ "python", "random", "dictionary" ]
Python 2.4 plistlib on Linux
1,056,593
<p>According to <a href="http://docs.python.org/dev/library/plistlib.html" rel="nofollow">http://docs.python.org/dev/library/plistlib.html</a>, plistlib is available to non-Mac platforms only since 2.6, but I'm wondering if there's a way to get it work on 2.4 on Linux.</p>
2
2009-06-29T04:47:15Z
1,056,644
<p>Download it and give it a try:</p> <p><a href="http://svn.python.org/projects/python/trunk/Lib/plistlib.py" rel="nofollow">http://svn.python.org/projects/python/trunk/Lib/plistlib.py</a></p> <p>(If that doesn't work, you may have more luck with the <a href="http://svn.python.org/projects/python/branches/release24-maint/Lib/plat-mac/plistlib.py" rel="nofollow">2.4 version</a>.)</p>
3
2009-06-29T05:05:20Z
[ "python", "linux" ]
Cherrypy server does not accept incoming http request on MS Windows if output (stdout) is not redirected
1,056,642
<p>It is a rather strange 'bug'. </p> <p>I have written a cherrypy based server. If I run it this way:</p> <pre><code>python simple_server.py &gt; out.txt </code></pre> <p>It works as expected. </p> <p>Without the the redirection at the end, however, the server will not accept any connection at all.</p> <p>Anyone has any idea?</p> <p>I am using python 2.4 on a Win XP professional machine. </p>
0
2009-06-29T05:05:17Z
1,056,670
<p>Are you running the script in an XP "command window"? Otherwise (if there's neither redirection nor command window available), standard output might simply be closed, which might inhibit the script (or rather its underlying framework).</p>
1
2009-06-29T05:17:07Z
[ "python", "cherrypy" ]
Cherrypy server does not accept incoming http request on MS Windows if output (stdout) is not redirected
1,056,642
<p>It is a rather strange 'bug'. </p> <p>I have written a cherrypy based server. If I run it this way:</p> <pre><code>python simple_server.py &gt; out.txt </code></pre> <p>It works as expected. </p> <p>Without the the redirection at the end, however, the server will not accept any connection at all.</p> <p>Anyone has any idea?</p> <p>I am using python 2.4 on a Win XP professional machine. </p>
0
2009-06-29T05:05:17Z
1,059,551
<p>CherryPy runs in a "development" mode by default, which includes logging startup messages to stdout. If stdout is not available, I would assume the server is not able to start successfully.</p> <p>You can change this by setting 'log.screen: False' in config (and replacing it with 'log.error_file: "/path/to/error.log"' if you know what's good for you ;) ). Note that the global config entry 'environment: production' will also turn off log.screen.</p>
0
2009-06-29T17:48:07Z
[ "python", "cherrypy" ]
Python Scrapy , how to define a pipeline for an item?
1,056,651
<p>I am using scrapy to crawl different sites, for each site I have an Item (different information is extracted)</p> <p>Well, for example I have a generic pipeline (most of information is the same) but now I am crawling some google search response and the pipeline must be different.</p> <p>For example:</p> <p><code>GenericItem</code> uses <code>GenericPipeline</code></p> <p>But the <code>GoogleItem</code> uses <code>GoogleItemPipeline</code>, but when the spider is crawling it tries to use <code>GenericPipeline</code> instead of <code>GoogleItemPipeline</code>....how can I specify which pipeline Google spider must use?</p>
12
2009-06-29T05:09:33Z
1,330,564
<p>Now only one way - check Item type in pipeline and process it or return "as is"</p> <p><em>pipelines.py</em>:</p> <pre><code>from grabbers.items import FeedItem class StoreFeedPost(object): def process_item(self, domain, item): if isinstance(item, FeedItem): #process it... return item </code></pre> <p><em>items.py</em>:</p> <pre><code>from scrapy.item import ScrapedItem class FeedItem(ScrapedItem): pass </code></pre>
14
2009-08-25T19:54:00Z
[ "python", "screen-scraping", "scrapy" ]
Django failing to find apps
1,056,675
<p>I have been working on a django app on my local computer for some time now and i am trying to move it to a mediatemple container and im having a problem when i try to start up django. it gives me this traceback:</p> <pre><code>application failed to start, starting manage.py fastcgi failed:Traceback (most recent call last): File "manage.py", line 11, in ? execute_manager(settings) File "/home/58626/data/python/lib/django/core/management/__init__.py", line 340, in execute_manager utility.execute() File "/home/58626/data/python/lib/django/core/management/__init__.py", line 295, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/58626/data/python/lib/django/core/management/base.py", line 192, in run_from_argv self.execute(*args, **options.__dict__) File "/home/58626/data/python/lib/django/core/management/base.py", line 210, in execute translation.activate('en-us') File "/home/58626/data/python/lib/django/utils/translation/__init__.py", line 73, in activate return real_activate(language) File "/home/58626/data/python/lib/django/utils/translation/__init__.py", line 43, in delayed_loader return g['real_%s' % caller](*args, **kwargs) File "/home/58626/data/python/lib/django/utils/translation/trans_real.py", line 209, in activate _active[currentThread()] = translation(language) File "/home/58626/data/python/lib/django/utils/translation/trans_real.py", line 198, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/home/58626/data/python/lib/django/utils/translation/trans_real.py", line 181, in _fetch app = getattr(__import__(appname[:p], {}, {}, [appname[p+1:]]), appname[p+1:]) AttributeError: 'module' object has no attribute 'web' </code></pre> <p>The name of the first app is "web".</p>
0
2009-06-29T05:19:30Z
1,057,244
<p>Steps I would take would be </p> <ol> <li>Run the dev server on your Media Template instance. If that runs successfully, it obviously is an error with your apache/nginx/whaever setup.</li> <li>I dont have experience running apps as FCGI, which it looks to em you are trying to do. It looks to me that somehow when Fcgi runs, it is unable to find your apps. So this is possibly a PYTHONPATH issue. Log/Print sys.path from your fcgi script and look there.</li> </ol>
3
2009-06-29T08:46:50Z
[ "python", "django" ]
How to analyze IE activity when opening a specific web page
1,056,739
<p>I'd like to retrieve data from a specific webpage by using urllib library. The problem is that in order to open this page some data should be sent to the server before. If I do it with IE, i need to update first some checkboxes and then press "display data" button, which opens the desired page. Looking into the source code, I see that pressing "display data" submits some kind of form - there is no specific url address there. I cannot figure out by looking at the code what paramaters are sent to the server... I think that maybe the simpler way to do that would be to analyze the communication between the IE and the webserver after pressing the "display data" button. If I could see explicitly what IE does, I could mimic it with urllib.</p> <p>What is the easiest way to do that?</p>
1
2009-06-29T05:50:57Z
1,056,819
<p>You can use a <em>web debugging proxy</em> (e.g. <a href="http://www.fiddler2.com/fiddler2/" rel="nofollow">Fiddler</a>, <a href="http://www.charlesproxy.com/" rel="nofollow">Charles</a>) or a <em>browser addon</em> (e.g. <a href="https://addons.mozilla.org/en-US/firefox/addon/6647" rel="nofollow">HttpFox</a>, <a href="https://addons.mozilla.org/en-US/firefox/addon/966" rel="nofollow">TamperData</a>) or a <em>packet sniffer</em> (e.g. <a href="http://www.wireshark.org/" rel="nofollow">Wireshark</a>).</p>
0
2009-06-29T06:19:28Z
[ "python", "html", "internet-explorer", "information-retrieval" ]
How to analyze IE activity when opening a specific web page
1,056,739
<p>I'd like to retrieve data from a specific webpage by using urllib library. The problem is that in order to open this page some data should be sent to the server before. If I do it with IE, i need to update first some checkboxes and then press "display data" button, which opens the desired page. Looking into the source code, I see that pressing "display data" submits some kind of form - there is no specific url address there. I cannot figure out by looking at the code what paramaters are sent to the server... I think that maybe the simpler way to do that would be to analyze the communication between the IE and the webserver after pressing the "display data" button. If I could see explicitly what IE does, I could mimic it with urllib.</p> <p>What is the easiest way to do that?</p>
1
2009-06-29T05:50:57Z
1,056,898
<p>An HTML debugging proxy would be the best tool to use in this situation. As you're using IE, I recommend <a href="http://fiddler2.com" rel="nofollow">Fiddler</a>, as it is developed by Microsoft and automatically integrates with Internet Explorer through a plugin. I personally use Fiddler all the time, and it is a really helpful tool, as I'm building an app that mimics a user's browsing session with a website. Fiddler has really good debugging of request parameters, responses, and can even decode encrypted packets. </p>
3
2009-06-29T06:59:13Z
[ "python", "html", "internet-explorer", "information-retrieval" ]
Python, Django, datetime
1,056,934
<p>In my model, I have 2 datetime properties:</p> <pre><code>start_date end_date </code></pre> <p>I would like to count the end date as a one week after the start_date. </p> <p>How can I accomplish this?</p>
1
2009-06-29T07:10:05Z
1,056,959
<pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; start_date = datetime.datetime.now() &gt;&gt;&gt; end_date = start_date + datetime.timedelta(7) &gt;&gt;&gt; print end_date </code></pre>
5
2009-06-29T07:19:09Z
[ "python", "django", "datetime" ]
Python, Django, datetime
1,056,934
<p>In my model, I have 2 datetime properties:</p> <pre><code>start_date end_date </code></pre> <p>I would like to count the end date as a one week after the start_date. </p> <p>How can I accomplish this?</p>
1
2009-06-29T07:10:05Z
1,056,971
<p>If you always want your end_date to be one week after the start_date, what you could do, is to make a custom save method for your model. Another option would be to use signals instead. The result would be the same, but since you are dealing with the models data, I would suggest that you go for the custom save method. The code for it would look something like this:</p> <pre><code>class ModelName(models.Model): ... def save(self): # Place code here, which is excecuted the same # time the ``pre_save``-signal would be self.end_date = self.start_date + datetime.timedelta(days=7) # Call parent's ``save`` function super(ModelName, self).save() </code></pre> <p>You can read about a bit about how the save method/signals is called in the django docs at: <a href="http://docs.djangoproject.com/en/dev/ref/models/instances/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/instances/</a></p>
8
2009-06-29T07:24:21Z
[ "python", "django", "datetime" ]