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
Python - lines from files - all combinations
790,860
<p>I have two files - prefix.txt and terms.txt both have about 100 lines. I'd like to write out a third file with the <em>Cartesian product</em> </p> <p><a href="http://en.wikipedia.org/wiki/Join%5F%28SQL%29#Cross%5Fjoin" rel="nofollow">http://en.wikipedia.org/wiki/Join_(SQL)#Cross_join</a> </p> <p>-about 10000 lines.</p> <p>What is the best way to approach this in Python?</p> <p>Secondly, is there a way to write the 10,000 lines to the third file in a random order?</p>
1
2009-04-26T13:35:19Z
790,866
<p>A Cartesian product enumerates all combinations. The easiest way to enumerate all combinations is to use nested loops.</p> <p>You cannot write files in a random order very easily. To write to a "random" position, you must use <code>file.seek()</code>. How will you know what position to which you will seek? How do you know how long each part (prefix+term) will be?</p> <p>You can, however, read entire files into memory (100 lines is nothing) and process the in-memory collections in "random" orders. This will assure that the output is randomized.</p>
1
2009-04-26T13:41:50Z
[ "python", "file-io", "random" ]
Python - lines from files - all combinations
790,860
<p>I have two files - prefix.txt and terms.txt both have about 100 lines. I'd like to write out a third file with the <em>Cartesian product</em> </p> <p><a href="http://en.wikipedia.org/wiki/Join%5F%28SQL%29#Cross%5Fjoin" rel="nofollow">http://en.wikipedia.org/wiki/Join_(SQL)#Cross_join</a> </p> <p>-about 10000 lines.</p> <p>What is the best way to approach this in Python?</p> <p>Secondly, is there a way to write the 10,000 lines to the third file in a random order?</p>
1
2009-04-26T13:35:19Z
790,871
<pre><code>from random import shuffle a = list(open('prefix.txt')) b = list(open('terms.txt')) c = [x.strip() + y.strip() for x in a for y in b] shuffle(c) open('result.txt', 'w').write('\n'.join(c)) </code></pre> <p>Certainly, not the best way in terms of speed and memory, but 10000 is not big enough to sacrifice brevity anyway. You should normally close your file objects and you can loop through at least one of the files without storing its content in RAM. <del>This: <code>[:-1]</code> removes the trailing newlline from each element of <code>a</code> and <code>b</code>.</del></p> <p>Edit: using <code>s.strip()</code> instead of <code>s[:-1]</code> to get rid of the newlines---it's more portable.</p>
1
2009-04-26T13:52:35Z
[ "python", "file-io", "random" ]
Python - lines from files - all combinations
790,860
<p>I have two files - prefix.txt and terms.txt both have about 100 lines. I'd like to write out a third file with the <em>Cartesian product</em> </p> <p><a href="http://en.wikipedia.org/wiki/Join%5F%28SQL%29#Cross%5Fjoin" rel="nofollow">http://en.wikipedia.org/wiki/Join_(SQL)#Cross_join</a> </p> <p>-about 10000 lines.</p> <p>What is the best way to approach this in Python?</p> <p>Secondly, is there a way to write the 10,000 lines to the third file in a random order?</p>
1
2009-04-26T13:35:19Z
790,883
<p>You need <code>itertools.product</code>.</p> <pre><code>for prefix, term in itertools.product(open('prefix.txt'), open('terms.txt')): print(prefix.strip() + term.strip()) </code></pre> <p>Print them, or accumulate them, or write them directly. You need the <code>.strip()</code> because of the newline that comes with each of them.</p> <p>Afterwards, you can shuffle them using random.shuffle(list(open('thirdfile.txt')), but I don't know how fast that will be on a file of the sizes you are using.</p>
4
2009-04-26T14:00:12Z
[ "python", "file-io", "random" ]
pyinotify bug with reading file on creation?
790,898
<p>I want to parse a file everytime a new file is created in a certain directory. For this, I'm trying to use <a href="http://pyinotify.sourceforge.net/" rel="nofollow">pyinotify</a> to setup a directory to watch for <code>IN_CREATE</code> kernel events, and fire the <code>parse()</code> method.</p> <p>Here is the module:</p> <pre><code>from pyinotify import WatchManager, ThreadedNotifier, ProcessEvent, IN_CREATE class Watcher(ProcessEvent): watchdir = '/tmp/watch' def __init__(self): ProcessEvent.__init__(self) wm = WatchManager() self.notifier = ThreadedNotifier(wm, self) wdd = wm.add_watch(self.watchdir, IN_CREATE) self.notifier.start() def process_IN_CREATE(self, event): pfile = self._parse(event.pathname) print(pfile) def _parse(self, filename): f = open(filename) file = [line.strip() for line in f.readlines()] f.close() return file if __name__ == '__main__': Watcher() </code></pre> <p>The problem is that the list returned by _parse is <em>empty</em> when triggered by a new file creation event, like so (the file is created in another window while <code>watcher.py</code> is running):</p> <pre><code>$ python watcher.py [] </code></pre> <p>...but strangely enough, it works from an interpreter session when called directly.</p> <pre><code>&gt;&gt;&gt; import watcher &gt;&gt;&gt; w = watcher.Watcher() &gt;&gt;&gt; w._parse('/tmp/watch/sample') ['This is a sample file', 'Another line', 'And another...'] </code></pre> <p>Why is this happening? The farthest I've come debugging this thing is to know that something is making pyinotify not read the file correctly. But... why?</p>
3
2009-04-26T14:07:21Z
790,908
<p>may be you want to wait till file is closed?</p>
3
2009-04-26T14:14:47Z
[ "python", "linux" ]
pyinotify bug with reading file on creation?
790,898
<p>I want to parse a file everytime a new file is created in a certain directory. For this, I'm trying to use <a href="http://pyinotify.sourceforge.net/" rel="nofollow">pyinotify</a> to setup a directory to watch for <code>IN_CREATE</code> kernel events, and fire the <code>parse()</code> method.</p> <p>Here is the module:</p> <pre><code>from pyinotify import WatchManager, ThreadedNotifier, ProcessEvent, IN_CREATE class Watcher(ProcessEvent): watchdir = '/tmp/watch' def __init__(self): ProcessEvent.__init__(self) wm = WatchManager() self.notifier = ThreadedNotifier(wm, self) wdd = wm.add_watch(self.watchdir, IN_CREATE) self.notifier.start() def process_IN_CREATE(self, event): pfile = self._parse(event.pathname) print(pfile) def _parse(self, filename): f = open(filename) file = [line.strip() for line in f.readlines()] f.close() return file if __name__ == '__main__': Watcher() </code></pre> <p>The problem is that the list returned by _parse is <em>empty</em> when triggered by a new file creation event, like so (the file is created in another window while <code>watcher.py</code> is running):</p> <pre><code>$ python watcher.py [] </code></pre> <p>...but strangely enough, it works from an interpreter session when called directly.</p> <pre><code>&gt;&gt;&gt; import watcher &gt;&gt;&gt; w = watcher.Watcher() &gt;&gt;&gt; w._parse('/tmp/watch/sample') ['This is a sample file', 'Another line', 'And another...'] </code></pre> <p>Why is this happening? The farthest I've come debugging this thing is to know that something is making pyinotify not read the file correctly. But... why?</p>
3
2009-04-26T14:07:21Z
790,975
<p>As @SilentGhost mentioned, you may be reading the file before any content has been added to file (i.e. you are getting notified of the file creation not file writes).</p> <p>Update: The loop.py example with pynotify tarball will dump the sequence of inotify events to the screen. To determine which event you need to trigger on, launch loop.py to monitor /tmp and then perform the file manipulation you want to track.</p>
1
2009-04-26T14:43:42Z
[ "python", "linux" ]
pyinotify bug with reading file on creation?
790,898
<p>I want to parse a file everytime a new file is created in a certain directory. For this, I'm trying to use <a href="http://pyinotify.sourceforge.net/" rel="nofollow">pyinotify</a> to setup a directory to watch for <code>IN_CREATE</code> kernel events, and fire the <code>parse()</code> method.</p> <p>Here is the module:</p> <pre><code>from pyinotify import WatchManager, ThreadedNotifier, ProcessEvent, IN_CREATE class Watcher(ProcessEvent): watchdir = '/tmp/watch' def __init__(self): ProcessEvent.__init__(self) wm = WatchManager() self.notifier = ThreadedNotifier(wm, self) wdd = wm.add_watch(self.watchdir, IN_CREATE) self.notifier.start() def process_IN_CREATE(self, event): pfile = self._parse(event.pathname) print(pfile) def _parse(self, filename): f = open(filename) file = [line.strip() for line in f.readlines()] f.close() return file if __name__ == '__main__': Watcher() </code></pre> <p>The problem is that the list returned by _parse is <em>empty</em> when triggered by a new file creation event, like so (the file is created in another window while <code>watcher.py</code> is running):</p> <pre><code>$ python watcher.py [] </code></pre> <p>...but strangely enough, it works from an interpreter session when called directly.</p> <pre><code>&gt;&gt;&gt; import watcher &gt;&gt;&gt; w = watcher.Watcher() &gt;&gt;&gt; w._parse('/tmp/watch/sample') ['This is a sample file', 'Another line', 'And another...'] </code></pre> <p>Why is this happening? The farthest I've come debugging this thing is to know that something is making pyinotify not read the file correctly. But... why?</p>
3
2009-04-26T14:07:21Z
791,085
<p>Here's some code that works for me, with a 2.6.18 kernel, Python 2.4.3, and pyinotify 0.7.1 -- you may be using different versions of some of these, but it's important to make sure we're talking about the same versions, I think...:</p> <pre><code>#!/usr/bin/python2.4 import os.path from pyinotify import pyinotify class Watcher(pyinotify.ProcessEvent): watchdir = '/tmp/watch' def __init__(self): pyinotify.ProcessEvent.__init__(self) wm = pyinotify.WatchManager() self.notifier = pyinotify.ThreadedNotifier(wm, self) wdd = wm.add_watch(self.watchdir, pyinotify.EventsCodes.IN_CREATE) print "Watching", self.watchdir self.notifier.start() def process_IN_CREATE(self, event): print "Seen:", event pathname = os.path.join(event.path, event.name) pfile = self._parse(pathname) print(pfile) def _parse(self, filename): f = open(filename) file = [line.strip() for line in f] f.close() return file if __name__ == '__main__': Watcher() </code></pre> <p>when this is running in a terminal window, and in another terminal window I do</p> <pre><code>echo "ciao" &gt;/tmp/watch/c3 </code></pre> <p>this program's output is:</p> <pre><code>Watching /tmp/watch Seen: event_name: IN_CREATE is_dir: False mask: 256 name: c3 path: /tmp/watch wd: 1 ['ciao'] </code></pre> <p>as expected. So can you please try this script (fixing the Python version in the hashbang if needed, of course) and tell us the exact releases of Linux kernel, pyinotify, and Python that you are using, and what do you observe in these exact circunstances? Quite possibly with more detailed info we may identify which bug or anomaly is giving you problems, exactly. Thanks!</p>
1
2009-04-26T15:55:54Z
[ "python", "linux" ]
pyinotify bug with reading file on creation?
790,898
<p>I want to parse a file everytime a new file is created in a certain directory. For this, I'm trying to use <a href="http://pyinotify.sourceforge.net/" rel="nofollow">pyinotify</a> to setup a directory to watch for <code>IN_CREATE</code> kernel events, and fire the <code>parse()</code> method.</p> <p>Here is the module:</p> <pre><code>from pyinotify import WatchManager, ThreadedNotifier, ProcessEvent, IN_CREATE class Watcher(ProcessEvent): watchdir = '/tmp/watch' def __init__(self): ProcessEvent.__init__(self) wm = WatchManager() self.notifier = ThreadedNotifier(wm, self) wdd = wm.add_watch(self.watchdir, IN_CREATE) self.notifier.start() def process_IN_CREATE(self, event): pfile = self._parse(event.pathname) print(pfile) def _parse(self, filename): f = open(filename) file = [line.strip() for line in f.readlines()] f.close() return file if __name__ == '__main__': Watcher() </code></pre> <p>The problem is that the list returned by _parse is <em>empty</em> when triggered by a new file creation event, like so (the file is created in another window while <code>watcher.py</code> is running):</p> <pre><code>$ python watcher.py [] </code></pre> <p>...but strangely enough, it works from an interpreter session when called directly.</p> <pre><code>&gt;&gt;&gt; import watcher &gt;&gt;&gt; w = watcher.Watcher() &gt;&gt;&gt; w._parse('/tmp/watch/sample') ['This is a sample file', 'Another line', 'And another...'] </code></pre> <p>Why is this happening? The farthest I've come debugging this thing is to know that something is making pyinotify not read the file correctly. But... why?</p>
3
2009-04-26T14:07:21Z
791,493
<p>I think I solved the problem by using the <code>IN_CLOSE_WRITE</code> event instead. I'm not sure what was happening before that made it not work. </p> <p>@Alex: Thanks, I tried your script, but I'm using newer versions: Python 2.6.1, pyinotify 0.8.6 and Linux 2.6.28, so it didn't work for me. </p> <p>It was definitely a matter of trying to parse the file before it was written, so kudos to SilentGhost and DanM for figuring it out.</p>
1
2009-04-26T19:58:01Z
[ "python", "linux" ]
How to do PyS60 development on OS X
790,915
<p>Is it possible to do <a href="http://sourceforge.net/projects/pys60" rel="nofollow">PyS60</a> development on Mac OS X? There is an XCode-plugin for Symbian C++ -development, but I don't know whether I can create Python-apps for my Nokia phone with that. I'm talking about a more thorough SDK experience than just editing files with Textmate/Emacs and copying them over to the device.</p>
1
2009-04-26T14:18:13Z
790,936
<p>Well, with python on phone all you need to do is be able to upload the scripts, and use <a href="http://mymobilesite.net/" rel="nofollow">MWS</a> that's the simplest way. <a href="http://mymobilesite.net/" rel="nofollow">MWS</a> supports webdav for upload, also one can use obexftp and bluetooth to drop the scripts in the right place.</p> <p>One can also wrap them in SIS files in theory, but I haven't done that myself yet.</p>
1
2009-04-26T14:28:17Z
[ "python", "nokia", "s60", "pys60" ]
How to do PyS60 development on OS X
790,915
<p>Is it possible to do <a href="http://sourceforge.net/projects/pys60" rel="nofollow">PyS60</a> development on Mac OS X? There is an XCode-plugin for Symbian C++ -development, but I don't know whether I can create Python-apps for my Nokia phone with that. I'm talking about a more thorough SDK experience than just editing files with Textmate/Emacs and copying them over to the device.</p>
1
2009-04-26T14:18:13Z
955,741
<p>S60 emulator runs only under Windows, so Mac owners run it under emulator. Heard that it works great.</p>
0
2009-06-05T13:05:54Z
[ "python", "nokia", "s60", "pys60" ]
How to do PyS60 development on OS X
790,915
<p>Is it possible to do <a href="http://sourceforge.net/projects/pys60" rel="nofollow">PyS60</a> development on Mac OS X? There is an XCode-plugin for Symbian C++ -development, but I don't know whether I can create Python-apps for my Nokia phone with that. I'm talking about a more thorough SDK experience than just editing files with Textmate/Emacs and copying them over to the device.</p>
1
2009-04-26T14:18:13Z
1,481,166
<p>I use the komodo edit 5 editor on the mac and point it to the nokia appfwui classes, then the editor will autcomplete the Nokia Pys60 apis for you.</p> <p>I also use the steps given below to copy the script onto the device to test it (as the emulator is not runnable on mac os x)</p> <p><a href="http://discussion.forum.nokia.com/forum/showthread.php?t=116771" rel="nofollow">http://discussion.forum.nokia.com/forum/showthread.php?t=116771</a></p>
1
2009-09-26T13:03:17Z
[ "python", "nokia", "s60", "pys60" ]
How to do PyS60 development on OS X
790,915
<p>Is it possible to do <a href="http://sourceforge.net/projects/pys60" rel="nofollow">PyS60</a> development on Mac OS X? There is an XCode-plugin for Symbian C++ -development, but I don't know whether I can create Python-apps for my Nokia phone with that. I'm talking about a more thorough SDK experience than just editing files with Textmate/Emacs and copying them over to the device.</p>
1
2009-04-26T14:18:13Z
1,842,898
<p>I'd recommend you add PuTools to your development environment. It allows you to easily sync files between the phone and the computer, and gives you a remote shell with more functions than the default Bluetooth shell.</p> <p>The "official" PuTools instructions are written for Windows machines, but the tools definitely does work on the Mac as well. <a href="http://www.instructables.com/id/PyS60%3a-PUTools,-Advanced-Python-console-from-your-/" rel="nofollow">These instructions</a> should help.</p> <p>(As a new user, I can only post one link. If you're looking for the original PuTools website, it's an easy Google search. Good luck! )</p> <p>EDIT: A warning if you're using PyS60 v2.x on your Symbian device: Unfortunately PuTools hasn't been updated for PyS60 v2. :(</p>
3
2009-12-03T21:01:52Z
[ "python", "nokia", "s60", "pys60" ]
How to synthesize sounds?
790,960
<p>I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that.</p> <p>What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds?</p> <p>This far I've gotten to do this, it produces quite plain sound from which I'm not sure it's even using the alsa correctly.</p> <pre><code>import numpy from numpy.fft import fft, ifft from numpy.random import random_sample from alsaaudio import PCM, PCM_NONBLOCK, PCM_FORMAT_FLOAT_LE pcm = PCM()#mode=PCM_NONBLOCK) pcm.setrate(44100) pcm.setformat(PCM_FORMAT_FLOAT_LE) pcm.setchannels(1) pcm.setperiodsize(4096) def sine_wave(x, freq=100): sample = numpy.arange(x*4096, (x+1)*4096, dtype=numpy.float32) sample *= numpy.pi * 2 / 44100 sample *= freq return numpy.sin(sample) for x in xrange(1000): sample = sine_wave(x, 100) pcm.write(sample.tostring()) </code></pre>
6
2009-04-26T14:37:33Z
790,973
<p>Sound synthesis is a complex topic which requires many years of study to master. </p> <p>It is also not an entirely solved problem, although relatively recent developments (such as physical modelling synthesis) have made progress in imitating real-world instruments.</p> <p>There are a number of options open to you. If you are sure that you want to explore synthesis further, then I suggest you start by learning about FM synthesis. It is relatively easy to learn and implement in software, at least in basic forms, and produces a wide range of interesting sounds. Also, check out the book "The Computer Music Tutorial" by Curtis Roads. It's a bible for all things computer music, and although it's a few years old it is the book of choice for learning the fundamentals.</p> <p>If you want a quicker way to produce life-like sound, consider using sampling techniques: that is, record the instruments you want to reproduce (or use a pre-existing sample bank), and just play back the samples. It's a much more straightforward (and often more effective) approach. </p>
15
2009-04-26T14:43:37Z
[ "python", "numpy", "alsa" ]
How to synthesize sounds?
790,960
<p>I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that.</p> <p>What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds?</p> <p>This far I've gotten to do this, it produces quite plain sound from which I'm not sure it's even using the alsa correctly.</p> <pre><code>import numpy from numpy.fft import fft, ifft from numpy.random import random_sample from alsaaudio import PCM, PCM_NONBLOCK, PCM_FORMAT_FLOAT_LE pcm = PCM()#mode=PCM_NONBLOCK) pcm.setrate(44100) pcm.setformat(PCM_FORMAT_FLOAT_LE) pcm.setchannels(1) pcm.setperiodsize(4096) def sine_wave(x, freq=100): sample = numpy.arange(x*4096, (x+1)*4096, dtype=numpy.float32) sample *= numpy.pi * 2 / 44100 sample *= freq return numpy.sin(sample) for x in xrange(1000): sample = sine_wave(x, 100) pcm.write(sample.tostring()) </code></pre>
6
2009-04-26T14:37:33Z
791,053
<p>I agree that this is very non-trivial and there's no set "right way", but you should consider starting with a (or making your own) <a href="http://en.wikipedia.org/wiki/Musical%5FInstrument%5FDigital%5FInterface" rel="nofollow">MIDI</a> <a href="http://en.wikipedia.org/wiki/SoundFont" rel="nofollow">SoundFont</a>.</p>
1
2009-04-26T15:28:41Z
[ "python", "numpy", "alsa" ]
How to synthesize sounds?
790,960
<p>I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that.</p> <p>What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds?</p> <p>This far I've gotten to do this, it produces quite plain sound from which I'm not sure it's even using the alsa correctly.</p> <pre><code>import numpy from numpy.fft import fft, ifft from numpy.random import random_sample from alsaaudio import PCM, PCM_NONBLOCK, PCM_FORMAT_FLOAT_LE pcm = PCM()#mode=PCM_NONBLOCK) pcm.setrate(44100) pcm.setformat(PCM_FORMAT_FLOAT_LE) pcm.setchannels(1) pcm.setperiodsize(4096) def sine_wave(x, freq=100): sample = numpy.arange(x*4096, (x+1)*4096, dtype=numpy.float32) sample *= numpy.pi * 2 / 44100 sample *= freq return numpy.sin(sample) for x in xrange(1000): sample = sine_wave(x, 100) pcm.write(sample.tostring()) </code></pre>
6
2009-04-26T14:37:33Z
791,142
<p>Cheery, if you want to generate (from scratch) something that really sounds "organic", i.e. like a physical object, you're probably best off to learn a bit about how these sounds are generated. For a solid introduction, you could have a look at a book such as Fletcher and Rossings <a href="http://rads.stackoverflow.com/amzn/click/0387983740">The Physics of Musical Instruments</a>. There's lots of stuff on the web too, you might want to have a look at a the primer James Clark has <a href="http://www.cim.mcgill.ca/~clark/emusic.html">here</a></p> <p>Having at least a skim over this sort of stuff will give you an idea of what you are up against. Modeling physical instruments accurately is very difficult!</p> <p>If what you want to do is have something that sounds physical, rather something that sounds like instrument X, your job is a bit easier. You can build up frequencies quite easily and stack them together, add a little noise, and you'll get something that at least doesn't sound anything like a pure tone.</p> <p>Reading a bit about Fourier analysis in general will help, as will Frequency Modulation (FM) techniques.</p> <p>Have fun!</p>
8
2009-04-26T16:32:34Z
[ "python", "numpy", "alsa" ]
How to synthesize sounds?
790,960
<p>I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that.</p> <p>What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds?</p> <p>This far I've gotten to do this, it produces quite plain sound from which I'm not sure it's even using the alsa correctly.</p> <pre><code>import numpy from numpy.fft import fft, ifft from numpy.random import random_sample from alsaaudio import PCM, PCM_NONBLOCK, PCM_FORMAT_FLOAT_LE pcm = PCM()#mode=PCM_NONBLOCK) pcm.setrate(44100) pcm.setformat(PCM_FORMAT_FLOAT_LE) pcm.setchannels(1) pcm.setperiodsize(4096) def sine_wave(x, freq=100): sample = numpy.arange(x*4096, (x+1)*4096, dtype=numpy.float32) sample *= numpy.pi * 2 / 44100 sample *= freq return numpy.sin(sample) for x in xrange(1000): sample = sine_wave(x, 100) pcm.write(sample.tostring()) </code></pre>
6
2009-04-26T14:37:33Z
994,522
<p>As other people said, not a trivial topic at all. There are challenges both at the programming side of things (especially if you care about low-latency) and the synthesis part. A goldmine for sound synthesis is the page by Julius O. Smith. There is <em>a lot</em> of techniques for synthesis <a href="http://ccrma-www.stanford.edu/~jos/" rel="nofollow">http://ccrma-www.stanford.edu/~jos/</a>.</p>
0
2009-06-15T04:46:25Z
[ "python", "numpy", "alsa" ]
How to offer platform-specific implementations of a module?
791,098
<p>I need to make one function in a module platform-independent by offering several implementations, without changing any files that import it. The following works:</p> <p><code>do_it = getattr(__import__(__name__), "do_on_" + sys.platform)</code></p> <p>...but breaks if the module is put into a package.</p> <p>An alternative would be an if/elif with hard-coded calls to the others in do_it().</p> <p>Anything better?</p>
1
2009-04-26T16:11:50Z
791,107
<p>Put the code for platform support in different files in your package. Then add this to the file people are supposed to import from:</p> <pre><code>if sys.platform.startswith("win"): from ._windows_support import * elif sys.platform.startswith("linux"): from ._unix_support import * else: raise ImportError("my module doesn't support this system") </code></pre>
3
2009-04-26T16:15:23Z
[ "python" ]
How to offer platform-specific implementations of a module?
791,098
<p>I need to make one function in a module platform-independent by offering several implementations, without changing any files that import it. The following works:</p> <p><code>do_it = getattr(__import__(__name__), "do_on_" + sys.platform)</code></p> <p>...but breaks if the module is put into a package.</p> <p>An alternative would be an if/elif with hard-coded calls to the others in do_it().</p> <p>Anything better?</p>
1
2009-04-26T16:11:50Z
791,116
<p>Use <code>globals()['do_on_' + platform]</code> instead of the <code>getattr</code> call and your original idea should work whether this is inside a package or not.</p>
2
2009-04-26T16:18:59Z
[ "python" ]
How to offer platform-specific implementations of a module?
791,098
<p>I need to make one function in a module platform-independent by offering several implementations, without changing any files that import it. The following works:</p> <p><code>do_it = getattr(__import__(__name__), "do_on_" + sys.platform)</code></p> <p>...but breaks if the module is put into a package.</p> <p>An alternative would be an if/elif with hard-coded calls to the others in do_it().</p> <p>Anything better?</p>
1
2009-04-26T16:11:50Z
792,648
<p>If you need to create a platform specific instance of an class you should look into the Factory Pattern: <a href="http://en.wikipedia.org/wiki/Factory%5Fmethod%5Fpattern" rel="nofollow">link text</a></p>
1
2009-04-27T08:28:37Z
[ "python" ]
How to offer platform-specific implementations of a module?
791,098
<p>I need to make one function in a module platform-independent by offering several implementations, without changing any files that import it. The following works:</p> <p><code>do_it = getattr(__import__(__name__), "do_on_" + sys.platform)</code></p> <p>...but breaks if the module is put into a package.</p> <p>An alternative would be an if/elif with hard-coded calls to the others in do_it().</p> <p>Anything better?</p>
1
2009-04-26T16:11:50Z
792,688
<p><a href="http://diveintopython.net/file_handling/index.html#d0e14344" rel="nofollow">Dive Into Python</a> offers the exceptions alternative.</p>
1
2009-04-27T08:47:17Z
[ "python" ]
Elixir reflection
791,150
<p>I define some Entities which works fine; for meta programming issues. I now need to reflect the field properties defined in the model.</p> <p>For example:</p> <pre><code>class Foo(Entity): bar = OneToMany('Bar') baz = ManyToMany('Baz') </code></pre> <p>Which type of relation is set: "ManyToMany", "OneToMany" or even a plain "Field", and the relation target?</p> <p>Is there any simple way to reflect the Elixir Entities?</p>
2
2009-04-26T16:36:33Z
791,290
<p>You can do introspection in Elixir as you would anywhere in Python -- get all names of attributes of <code>class Foo</code> with <code>dir(Foo)</code>, extract an attribute given its name with <code>getattr(Foo, thename)</code>, check the type of the attribute with <code>type(theattr)</code> or <code>isinstance</code>, etc. The string <code>'Bar'</code> that you pass as the attribute to the constructor of any <code>Relationship</code> subclass (including <code>OneToMany</code> and <code>ManyToMany</code>) ends up as the <code>r.of_kind</code> attribute of the resulting instance r of the Relationship subclass.</p> <p>Module <code>inspect</code> in the Python standard library may be a friendlier way to do introspection, but dir / getattr / isinstance &amp;c are perfectly acceptable in many cases.</p>
4
2009-04-26T18:01:52Z
[ "python", "sqlalchemy", "pylons", "python-elixir" ]
Sorting by key and value in case keys are equal
791,316
<p>The <a href="http://www.hueniverse.com/hueniverse/2008/10/beginners-gui-1.html" rel="nofollow">official oauth guide</a> makes this recommendation:</p> <blockquote> <p>It is important not to try and perform the sort operation on some combined string of both name and value as some known separators (such as '=') will cause the sort order to change due to their impact on the string value.</p> </blockquote> <p>If this is the case, then what would be an efficient way of doing this? A second iteration after the initial sort looking for equal keys?</p>
1
2009-04-26T18:19:29Z
791,325
<p>Just sort the list of tuples (name, value) -- Python does lexicographic ordering for you.</p>
4
2009-04-26T18:27:11Z
[ "python", "sorting", "oauth" ]
wxPython crashes under Vista
791,341
<p>I am following the <a href="http://wiki.wxpython.org/Getting%20Started" rel="nofollow">Getting Started</a> guide for wxPython. But unfortunately the <a href="http://wiki.wxpython.org/Getting%20Started#head-6e8427493dcc765fb873a1838adfbd6b8d08e0ee" rel="nofollow">first 'Hello World' example</a> crashes. The dialog window shows just fine, but as soon as I move my mouse over the window a "pythonw.exe has stopped working" Windows message appears. </p> <p>I use:</p> <ul> <li>Python 2.6.2</li> <li><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.2-py26.exe" rel="nofollow">wxPython2.8-win32-unicode-2.8.9.2-py26</a></li> <li>Vista (latest SP and updates installed) 32 bits, running as Admin</li> </ul> <p>Any ideas what can be wrong, or how to fix this?</p>
2
2009-04-26T18:35:21Z
791,409
<p>32 or 64 bit Vista? When you did installs did you "run as admin"? I also had some issues with permissions on vista early on.</p> <p>Also, this may be a fix if it isn't just the installation problem.</p> <p><a href="http://www.python-forum.org/pythonforum/viewtopic.php?f=4&amp;t=11331" rel="nofollow">http://www.python-forum.org/pythonforum/viewtopic.php?f=4&amp;t=11331</a></p> <p>Hope this helps...</p>
2
2009-04-26T19:09:28Z
[ "python", "windows-vista", "wxpython" ]
wxPython crashes under Vista
791,341
<p>I am following the <a href="http://wiki.wxpython.org/Getting%20Started" rel="nofollow">Getting Started</a> guide for wxPython. But unfortunately the <a href="http://wiki.wxpython.org/Getting%20Started#head-6e8427493dcc765fb873a1838adfbd6b8d08e0ee" rel="nofollow">first 'Hello World' example</a> crashes. The dialog window shows just fine, but as soon as I move my mouse over the window a "pythonw.exe has stopped working" Windows message appears. </p> <p>I use:</p> <ul> <li>Python 2.6.2</li> <li><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.2-py26.exe" rel="nofollow">wxPython2.8-win32-unicode-2.8.9.2-py26</a></li> <li>Vista (latest SP and updates installed) 32 bits, running as Admin</li> </ul> <p>Any ideas what can be wrong, or how to fix this?</p>
2
2009-04-26T18:35:21Z
791,414
<p>See here for why: <a href="http://www.tejerodgers.com/snippets/2009/why-wxpython-crashes-python-26/" rel="nofollow">http://www.tejerodgers.com/snippets/2009/why-wxpython-crashes-python-26/</a></p> <p>See wxPython's README for a hack that will let you work around the problem.</p> <p>A fix has been discovered and will be included in the next release.</p>
4
2009-04-26T19:11:20Z
[ "python", "windows-vista", "wxpython" ]
Which JSON module can I use in Python 2.5?
791,561
<p>I would like to use Python's <a href="http://docs.python.org/library/json.html">JSON</a> module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular JSON module provided with Python 2.6 available as a separate module that can be used with 2.5?</p>
61
2009-04-26T20:34:15Z
791,564
<p>You can use <a href="http://pypi.python.org/pypi/simplejson" rel="nofollow">simplejson</a>.</p> <p>As shown by <a href="http://stackoverflow.com/a/2119597">the answer</a> form <a href="http://stackoverflow.com/users/5128/pkoch">pkoch</a> you can use the following import statement to get a json library depending on the installed python version:</p> <pre><code>try: import json except ImportError: import simplejson as json </code></pre>
61
2009-04-26T20:35:22Z
[ "python", "json" ]
Which JSON module can I use in Python 2.5?
791,561
<p>I would like to use Python's <a href="http://docs.python.org/library/json.html">JSON</a> module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular JSON module provided with Python 2.6 available as a separate module that can be used with 2.5?</p>
61
2009-04-26T20:34:15Z
792,295
<p>I prefer cjson since it's much faster: <a href="http://www.vazor.com/cjson.html" rel="nofollow">http://www.vazor.com/cjson.html</a></p>
1
2009-04-27T05:03:22Z
[ "python", "json" ]
Which JSON module can I use in Python 2.5?
791,561
<p>I would like to use Python's <a href="http://docs.python.org/library/json.html">JSON</a> module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular JSON module provided with Python 2.6 available as a separate module that can be used with 2.5?</p>
61
2009-04-26T20:34:15Z
2,119,597
<p>To Wells and others:</p> <blockquote> <p>Way late here, but how can you write a script to import either json or simplejson depending on the installed python version?</p> </blockquote> <p>Here's how: <code><pre> try: import json except ImportError: import simplejson as json </pre></code></p>
48
2010-01-22T18:41:57Z
[ "python", "json" ]
Which JSON module can I use in Python 2.5?
791,561
<p>I would like to use Python's <a href="http://docs.python.org/library/json.html">JSON</a> module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular JSON module provided with Python 2.6 available as a separate module that can be used with 2.5?</p>
61
2009-04-26T20:34:15Z
4,528,153
<p>I wrote the cjson 1.0.6 patch and my advice is don't use cjson -- there are other problems with cjson in how it handles unicode etc. I don't think the speed of cjson is worth dealing with the bugs -- encoding/decoding json is usually a very small bit of the time needed to process a typical web request...</p> <p>json in python 2.6+ is basically simplejson brought into the standard library I believe...</p>
4
2010-12-24T20:09:29Z
[ "python", "json" ]
Which JSON module can I use in Python 2.5?
791,561
<p>I would like to use Python's <a href="http://docs.python.org/library/json.html">JSON</a> module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular JSON module provided with Python 2.6 available as a separate module that can be used with 2.5?</p>
61
2009-04-26T20:34:15Z
14,244,695
<p>I am programming in Python 2.5 as well and wanted a suitable library. Here is how I did it.</p> <p>donwloaded the simplejson egg file called simplejson-2.0.6-py2.5-linux-i686.egg from <a href="http://pypi.python.org/simple/simplejson/" rel="nofollow">http://pypi.python.org/simple/simplejson/</a></p> <p>installed it using the command :</p> <p><code>sudo python ./ez_setup.py ./simplejson-2.0.6-py2.5-linux-i686.egg</code></p> <p>Then imported the json library into the script file by doing :</p> <pre><code>import sys sys.path.append("/home/coolkid/Android/simplejson/simplejson-2.0.6-py2.5-linux-i686.egg") try: import simplejson as json except ImportError: print ("import error") </code></pre>
-1
2013-01-09T19:13:40Z
[ "python", "json" ]
Best way to turn a list into a dict, where the keys are a value of each object?
791,708
<p>I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object.</p> <p>Here is some code representing what im doing:</p> <pre><code>class SomeClass(object): def __init__(self, name): self.name = name object_list = [ SomeClass(name='a'), SomeClass(name='b'), SomeClass(name='c'), SomeClass(name='d'), SomeClass(name='e'), ] object_dict = {} for an_object in object_list: object_dict[an_object.name] = an_object </code></pre> <p>Now that code works, but its a bit ugly, and a bit slow. Could anyone give an example of something thats faster/"better"?</p> <p><em>edit:</em> Alright, thanks for the replies. I must say i am surprised to see the more pythonic ways <strong>seeming</strong> slower than the hand made way.</p> <p><em>edit2:</em> Alright, i updated the test code to make it a bit more readable, with so many tests heh.</p> <p>Here is where we are at in terms of code, i put authors in the code and if i messed any up please let me know.</p> <pre><code>from itertools import izip import timeit class SomeClass(object): def __init__(self, name): self.name = name object_list = [] for i in range(5): object_list.append(SomeClass(name=i)) def example_1(): 'Original Code' object_dict = {} for an_object in object_list: object_dict[an_object.name] = an_object def example_2(): 'Provided by hyperboreean' d = dict(zip([o.name for o in object_list], object_list)) def example_3(): 'Provided by Jason Baker' d = dict([(an_object.name, an_object) for an_object in object_list]) def example_4(): "Added izip to hyperboreean's code, suggested by Chris Cameron" d = dict(izip([o.name for o in object_list], object_list)) def example_5(): 'zip, improved by John Fouhy' d = dict(zip((o.name for o in object_list), object_list)) def example_6(): 'izip, improved by John Fouhy' d = dict(izip((o.name for o in object_list), object_list)) def example_7(): 'Provided by Jason Baker, removed brackets by John Fouhy' d = dict((an_object.name, an_object) for an_object in object_list) timeits = [] for example_index in range(1, 8): timeits.append( timeit.Timer( 'example_%s()' % example_index, 'from __main__ import example_%s' % example_index) ) for i in range(7): timeit_object = timeits[i] print 'Example #%s Result: "%s"' % (i+1, timeit_object.repeat(2)) </code></pre> <p>With 5 objects in the list i am getting a result of:</p> <pre><code> Example #1 Result: "[1.2428441047668457, 1.2431108951568604]" Example #2 Result: "[3.3567759990692139, 3.3188660144805908]" Example #3 Result: "[2.8346641063690186, 2.8344728946685791]" Example #4 Result: "[3.0710639953613281, 3.0573830604553223]" Example #5 Result: "[5.2079918384552002, 5.2170760631561279]" Example #6 Result: "[3.240635871887207, 3.2402129173278809]" Example #7 Result: "[3.0856869220733643, 3.0688989162445068]" </code></pre> <p>and with 50:</p> <pre><code> Example #1 Result: "[9.8108220100402832, 9.9066231250762939]" Example #2 Result: "[16.365023136138916, 16.213981151580811]" Example #3 Result: "[15.77024507522583, 15.771029949188232]" Example #4 Result: "[14.598290920257568, 14.591825008392334]" Example #5 Result: "[20.644147872924805, 20.64064884185791]" Example #6 Result: "[15.210831165313721, 15.212569952011108]" Example #7 Result: "[17.317100048065186, 17.359367847442627]" </code></pre> <p>And lastly, with 500 objects:</p> <pre><code> Example #1 Result: "[96.682723999023438, 96.678673028945923]" Example #2 Result: "[137.49416589736938, 137.48705387115479]" Example #3 Result: "[136.58069896697998, 136.5823769569397]" Example #4 Result: "[115.0344090461731, 115.1088011264801]" Example #5 Result: "[165.08325910568237, 165.06769108772278]" Example #6 Result: "[128.95187497138977, 128.96077489852905]" Example #7 Result: "[155.70515990257263, 155.74126601219177]" </code></pre> <p>Thanks to all that replied! Im very surprised with the result. If there are any other tips for a faster method i would love to hear them. Thanks all!</p>
6
2009-04-26T22:14:22Z
791,717
<pre><code>d = dict(zip([o.name for o in object_list], object_list)) </code></pre>
8
2009-04-26T22:21:48Z
[ "python" ]
Best way to turn a list into a dict, where the keys are a value of each object?
791,708
<p>I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object.</p> <p>Here is some code representing what im doing:</p> <pre><code>class SomeClass(object): def __init__(self, name): self.name = name object_list = [ SomeClass(name='a'), SomeClass(name='b'), SomeClass(name='c'), SomeClass(name='d'), SomeClass(name='e'), ] object_dict = {} for an_object in object_list: object_dict[an_object.name] = an_object </code></pre> <p>Now that code works, but its a bit ugly, and a bit slow. Could anyone give an example of something thats faster/"better"?</p> <p><em>edit:</em> Alright, thanks for the replies. I must say i am surprised to see the more pythonic ways <strong>seeming</strong> slower than the hand made way.</p> <p><em>edit2:</em> Alright, i updated the test code to make it a bit more readable, with so many tests heh.</p> <p>Here is where we are at in terms of code, i put authors in the code and if i messed any up please let me know.</p> <pre><code>from itertools import izip import timeit class SomeClass(object): def __init__(self, name): self.name = name object_list = [] for i in range(5): object_list.append(SomeClass(name=i)) def example_1(): 'Original Code' object_dict = {} for an_object in object_list: object_dict[an_object.name] = an_object def example_2(): 'Provided by hyperboreean' d = dict(zip([o.name for o in object_list], object_list)) def example_3(): 'Provided by Jason Baker' d = dict([(an_object.name, an_object) for an_object in object_list]) def example_4(): "Added izip to hyperboreean's code, suggested by Chris Cameron" d = dict(izip([o.name for o in object_list], object_list)) def example_5(): 'zip, improved by John Fouhy' d = dict(zip((o.name for o in object_list), object_list)) def example_6(): 'izip, improved by John Fouhy' d = dict(izip((o.name for o in object_list), object_list)) def example_7(): 'Provided by Jason Baker, removed brackets by John Fouhy' d = dict((an_object.name, an_object) for an_object in object_list) timeits = [] for example_index in range(1, 8): timeits.append( timeit.Timer( 'example_%s()' % example_index, 'from __main__ import example_%s' % example_index) ) for i in range(7): timeit_object = timeits[i] print 'Example #%s Result: "%s"' % (i+1, timeit_object.repeat(2)) </code></pre> <p>With 5 objects in the list i am getting a result of:</p> <pre><code> Example #1 Result: "[1.2428441047668457, 1.2431108951568604]" Example #2 Result: "[3.3567759990692139, 3.3188660144805908]" Example #3 Result: "[2.8346641063690186, 2.8344728946685791]" Example #4 Result: "[3.0710639953613281, 3.0573830604553223]" Example #5 Result: "[5.2079918384552002, 5.2170760631561279]" Example #6 Result: "[3.240635871887207, 3.2402129173278809]" Example #7 Result: "[3.0856869220733643, 3.0688989162445068]" </code></pre> <p>and with 50:</p> <pre><code> Example #1 Result: "[9.8108220100402832, 9.9066231250762939]" Example #2 Result: "[16.365023136138916, 16.213981151580811]" Example #3 Result: "[15.77024507522583, 15.771029949188232]" Example #4 Result: "[14.598290920257568, 14.591825008392334]" Example #5 Result: "[20.644147872924805, 20.64064884185791]" Example #6 Result: "[15.210831165313721, 15.212569952011108]" Example #7 Result: "[17.317100048065186, 17.359367847442627]" </code></pre> <p>And lastly, with 500 objects:</p> <pre><code> Example #1 Result: "[96.682723999023438, 96.678673028945923]" Example #2 Result: "[137.49416589736938, 137.48705387115479]" Example #3 Result: "[136.58069896697998, 136.5823769569397]" Example #4 Result: "[115.0344090461731, 115.1088011264801]" Example #5 Result: "[165.08325910568237, 165.06769108772278]" Example #6 Result: "[128.95187497138977, 128.96077489852905]" Example #7 Result: "[155.70515990257263, 155.74126601219177]" </code></pre> <p>Thanks to all that replied! Im very surprised with the result. If there are any other tips for a faster method i would love to hear them. Thanks all!</p>
6
2009-04-26T22:14:22Z
791,722
<p>In python 3.0 you can use a dict comprehension:</p> <pre><code>{an_object.name : an_object for an_object in object_list} </code></pre> <p>This is also possible in Python 2, but it's a bit uglier:</p> <pre><code>dict([(an_object.name, an_object) for an_object in object_list]) </code></pre>
13
2009-04-26T22:23:57Z
[ "python" ]
Best way to turn a list into a dict, where the keys are a value of each object?
791,708
<p>I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object.</p> <p>Here is some code representing what im doing:</p> <pre><code>class SomeClass(object): def __init__(self, name): self.name = name object_list = [ SomeClass(name='a'), SomeClass(name='b'), SomeClass(name='c'), SomeClass(name='d'), SomeClass(name='e'), ] object_dict = {} for an_object in object_list: object_dict[an_object.name] = an_object </code></pre> <p>Now that code works, but its a bit ugly, and a bit slow. Could anyone give an example of something thats faster/"better"?</p> <p><em>edit:</em> Alright, thanks for the replies. I must say i am surprised to see the more pythonic ways <strong>seeming</strong> slower than the hand made way.</p> <p><em>edit2:</em> Alright, i updated the test code to make it a bit more readable, with so many tests heh.</p> <p>Here is where we are at in terms of code, i put authors in the code and if i messed any up please let me know.</p> <pre><code>from itertools import izip import timeit class SomeClass(object): def __init__(self, name): self.name = name object_list = [] for i in range(5): object_list.append(SomeClass(name=i)) def example_1(): 'Original Code' object_dict = {} for an_object in object_list: object_dict[an_object.name] = an_object def example_2(): 'Provided by hyperboreean' d = dict(zip([o.name for o in object_list], object_list)) def example_3(): 'Provided by Jason Baker' d = dict([(an_object.name, an_object) for an_object in object_list]) def example_4(): "Added izip to hyperboreean's code, suggested by Chris Cameron" d = dict(izip([o.name for o in object_list], object_list)) def example_5(): 'zip, improved by John Fouhy' d = dict(zip((o.name for o in object_list), object_list)) def example_6(): 'izip, improved by John Fouhy' d = dict(izip((o.name for o in object_list), object_list)) def example_7(): 'Provided by Jason Baker, removed brackets by John Fouhy' d = dict((an_object.name, an_object) for an_object in object_list) timeits = [] for example_index in range(1, 8): timeits.append( timeit.Timer( 'example_%s()' % example_index, 'from __main__ import example_%s' % example_index) ) for i in range(7): timeit_object = timeits[i] print 'Example #%s Result: "%s"' % (i+1, timeit_object.repeat(2)) </code></pre> <p>With 5 objects in the list i am getting a result of:</p> <pre><code> Example #1 Result: "[1.2428441047668457, 1.2431108951568604]" Example #2 Result: "[3.3567759990692139, 3.3188660144805908]" Example #3 Result: "[2.8346641063690186, 2.8344728946685791]" Example #4 Result: "[3.0710639953613281, 3.0573830604553223]" Example #5 Result: "[5.2079918384552002, 5.2170760631561279]" Example #6 Result: "[3.240635871887207, 3.2402129173278809]" Example #7 Result: "[3.0856869220733643, 3.0688989162445068]" </code></pre> <p>and with 50:</p> <pre><code> Example #1 Result: "[9.8108220100402832, 9.9066231250762939]" Example #2 Result: "[16.365023136138916, 16.213981151580811]" Example #3 Result: "[15.77024507522583, 15.771029949188232]" Example #4 Result: "[14.598290920257568, 14.591825008392334]" Example #5 Result: "[20.644147872924805, 20.64064884185791]" Example #6 Result: "[15.210831165313721, 15.212569952011108]" Example #7 Result: "[17.317100048065186, 17.359367847442627]" </code></pre> <p>And lastly, with 500 objects:</p> <pre><code> Example #1 Result: "[96.682723999023438, 96.678673028945923]" Example #2 Result: "[137.49416589736938, 137.48705387115479]" Example #3 Result: "[136.58069896697998, 136.5823769569397]" Example #4 Result: "[115.0344090461731, 115.1088011264801]" Example #5 Result: "[165.08325910568237, 165.06769108772278]" Example #6 Result: "[128.95187497138977, 128.96077489852905]" Example #7 Result: "[155.70515990257263, 155.74126601219177]" </code></pre> <p>Thanks to all that replied! Im very surprised with the result. If there are any other tips for a faster method i would love to hear them. Thanks all!</p>
6
2009-04-26T22:14:22Z
791,827
<p>If you're concerned with speed, then we can improve things slightly. Your "verbose" solution (which is really fine) creates no intermediate data structures. On the other hand, hyperboreean's solution,</p> <pre><code>d = dict(zip([o.name for o in object_list], object_list)) </code></pre> <p>creates two unnecessary lists: <code>[o.name for o in object_list]</code> creates a list, and <code>zip(_, _)</code> creates another list. Both these lists serve only to be iterated over once in the creation of the dict.</p> <p>We can avoid the creation of one list by replacing the list comprehension with a generator expression:</p> <pre><code>d = dict(zip((o.name for o in object_list), object_list)) </code></pre> <p>Replacing <code>zip</code> with <code>itertools.izip</code> will return an iterator and avoid creating the second list:</p> <pre><code>import itertools d = dict(itertools.izip((o.name for o in object_list), object_list)) </code></pre> <p>We could modify Jason Baker's solution in the same way, by simply deleting the square brackets:</p> <pre><code>d = dict((an_object.name, an_object) for an_object in object_list) </code></pre>
7
2009-04-26T23:31:40Z
[ "python" ]
Can't decode utf-8 string in python on os x terminal.app
792,017
<p>I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors:</p> <pre><code>&gt;&gt;&gt; wtf = u'\xe4\xf6\xfc'.decode() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) &gt;&gt;&gt; wtf = u'\xe4\xf6\xfc'.decode('utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) </code></pre> <p>Anyone know what I'm doing wrong? </p>
4
2009-04-27T01:47:47Z
792,041
<p>I think you have encoding and decoding backwards. You encode Unicode into a byte stream, and decode the byte stream into Unicode.</p> <pre><code>Python 2.6.1 (r261:67515, Dec 6 2008, 16:42:21) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; wtf = u'\xe4\xf6\xfc' &gt;&gt;&gt; wtf u'\xe4\xf6\xfc' &gt;&gt;&gt; print wtf äöü &gt;&gt;&gt; wtf.encode('UTF-8') '\xc3\xa4\xc3\xb6\xc3\xbc' &gt;&gt;&gt; print '\xc3\xa4\xc3\xb6\xc3\xbc'.decode('utf-8') äöü </code></pre>
4
2009-04-27T01:58:48Z
[ "python", "osx", "unicode", "terminal" ]
Can't decode utf-8 string in python on os x terminal.app
792,017
<p>I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors:</p> <pre><code>&gt;&gt;&gt; wtf = u'\xe4\xf6\xfc'.decode() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) &gt;&gt;&gt; wtf = u'\xe4\xf6\xfc'.decode('utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) </code></pre> <p>Anyone know what I'm doing wrong? </p>
4
2009-04-27T01:47:47Z
792,068
<p>The <a href="http://docs.python.org/tutorial/introduction.html#unicode-strings" rel="nofollow">Unicode strings</a> section of the introductory tutorial explains it well :</p> <blockquote> <p>To convert a Unicode string into an 8-bit string using a specific encoding, Unicode objects provide an encode() method that takes one argument, the name of the encoding. Lowercase names for encodings are preferred.</p> <pre><code>&gt;&gt;&gt; u"äöü".encode('utf-8') '\xc3\xa4\xc3\xb6\xc3\xbc' </code></pre> </blockquote>
2
2009-04-27T02:13:28Z
[ "python", "osx", "unicode", "terminal" ]
Can't decode utf-8 string in python on os x terminal.app
792,017
<p>I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors:</p> <pre><code>&gt;&gt;&gt; wtf = u'\xe4\xf6\xfc'.decode() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) &gt;&gt;&gt; wtf = u'\xe4\xf6\xfc'.decode('utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) </code></pre> <p>Anyone know what I'm doing wrong? </p>
4
2009-04-27T01:47:47Z
792,073
<pre><code>&gt;&gt;&gt; wtf = '\xe4\xf6\xfc' &gt;&gt;&gt; wtf '\xe4\xf6\xfc' &gt;&gt;&gt; print wtf ��� &gt;&gt;&gt; print wtf.decode("latin-1") äöü &gt;&gt;&gt; wtf_unicode = unicode(wtf.decode("latin-1")) &gt;&gt;&gt; wtf_unicode u'\xe4\xf6\xfc' &gt;&gt;&gt; print wtf_unicode äöü </code></pre>
3
2009-04-27T02:14:56Z
[ "python", "osx", "unicode", "terminal" ]
Can't decode utf-8 string in python on os x terminal.app
792,017
<p>I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors:</p> <pre><code>&gt;&gt;&gt; wtf = u'\xe4\xf6\xfc'.decode() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) &gt;&gt;&gt; wtf = u'\xe4\xf6\xfc'.decode('utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) </code></pre> <p>Anyone know what I'm doing wrong? </p>
4
2009-04-27T01:47:47Z
792,139
<p>I think there is encode/decode confusion all over the place. You start with an unicode object:</p> <pre><code>u'\xe4\xf6\xfc' </code></pre> <p>This is an unicode object, the three characters are the unicode codepoints for "äöü". If you want to turn them into Utf-8, you have to <strong>encode</strong> them:</p> <pre><code>&gt;&gt;&gt; u'\xe4\xf6\xfc'.encode('utf-8') '\xc3\xa4\xc3\xb6\xc3\xbc' </code></pre> <p>The resulting six characters are the Utf-8 representation of "äöü".</p> <p>If you call <code>decode(...)</code>, you try to interpret the characters as some encoding that still needs to be converted to unicode. Since it already is Unicode, this doesn't work. Your first call tries a Ascii to Unicode conversion, the second call a Utf-8 to Unicode conversion. Since <code>u'\xe4\xf6\xfc'</code> is neither valid Ascii nor valid Utf-8 these conversion attempts fail.</p> <p>Further confusion might come from the fact that <code>'\xe4\xf6\xfc'</code> is also the Latin1/ISO-8859-1 encoding of "äöü". If you write a normal python string (without the leading "u" that marks it as unicode), you can convert it to an unicode object with <code>decode('latin1')</code>:</p> <pre><code>&gt;&gt;&gt; '\xe4\xf6\xfc'.decode('latin1') u'\xe4\xf6\xfc' </code></pre>
18
2009-04-27T03:12:20Z
[ "python", "osx", "unicode", "terminal" ]
Navigating Callable-Iterators
792,304
<p>I'd like to use regular expressions to extract information out of some chat logs. The format of the strings being parsed are <code>03:22:32 PM &lt;b&gt;blcArmadillo&lt;/b&gt;</code>. I used the python type() command to find that the variable messages is a callable-iterator. My question is how do I most efficiently navigate through a callable-iterator? Are they like arrays where you can just use an index? The only way I could find to "extract" the data was to loop through the returned values and add them to a list as shown in the code snipet below.</p> <pre><code>times = [] messages = re.compile(r'(?P&lt;time&gt;..:..:.. ..).*?&lt;b&gt;(?P&lt;usrname&gt;.*?):&lt;/b&gt;').finditer(search) for result in messages: times.append(result.group('time')) </code></pre> <p>Is there a better more effiecnt way of doing this? Thanks for the help.</p>
2
2009-04-27T05:08:21Z
792,324
<p>An iterator is just an object with a next method. Every time you call it, it returns the next item in a collection. If you need to access arbitrary indexes, you will pretty much have to convert it into a list. Instead of this:</p> <pre><code>for result in messages: times.append(result.group('time')) </code></pre> <p>You can say this though:</p> <pre><code>times = [result.group('time') for result in messages] </code></pre> <p>This does pretty much the same thing. However, I should warn you that doing this for large result sets will be pretty slow and will eat up a bunch of memory. Thus, you shouldn't do this if you don't need random access. If data an untrusted user enters will determine how many results will appear, you might also want to limit the number of things they can enter.</p> <p><strong>EDIT</strong>: I just noticed that my previous answer didn't quite do the same as the snippet you posted, so I've updated it.</p>
3
2009-04-27T05:19:33Z
[ "python" ]
Find shortest substring
792,394
<p>I have written a code to find the substring from a string. It prints all substrings. But I want a substring that ranges from length 2 to 6 and print the substring of minimum length. Please help me</p> <p>Program:</p> <pre><code>import re p=re.compile('S(.+?)N') s='ASDFANSAAAAAFGNDASMPRKYN' s1=p.findall(s) print s1 </code></pre> <p>output:</p> <pre><code>['DFA', 'AAAAAFG', 'MPRKY'] </code></pre> <p>Desired output:</p> <pre><code>'DFA' length=3 </code></pre>
2
2009-04-27T06:08:16Z
792,406
<p>The regex <code>'S(.{2,6}?)N'</code> will give you only matches with length 2 - 6 characters.</p> <p>To return the shortest matching substring, use <code>sorted(s1, key=len)[0]</code>.</p> <p>Full example:</p> <pre><code>import re p=re.compile('S(.{2,6}?)N') s='ASDFANSAAAAAFGNDASMPRKYNSAAN' s1=p.findall(s) if s1: print sorted(s1, key=len)[0] print min(s1, key=len) # as suggested by Nick Presta </code></pre> <p>This works by sorting the list returned by <code>findall</code> by length, then returning the first item in the sorted list.</p> <p>Edit: Nick Presta's answer is more elegant, I was not aware that <code>min</code> also could take a <code>key</code> argument...</p>
3
2009-04-27T06:13:47Z
[ "python", "substring" ]
Find shortest substring
792,394
<p>I have written a code to find the substring from a string. It prints all substrings. But I want a substring that ranges from length 2 to 6 and print the substring of minimum length. Please help me</p> <p>Program:</p> <pre><code>import re p=re.compile('S(.+?)N') s='ASDFANSAAAAAFGNDASMPRKYN' s1=p.findall(s) print s1 </code></pre> <p>output:</p> <pre><code>['DFA', 'AAAAAFG', 'MPRKY'] </code></pre> <p>Desired output:</p> <pre><code>'DFA' length=3 </code></pre>
2
2009-04-27T06:08:16Z
792,419
<p>If you already have the list, you can use the <a href="http://docs.python.org/library/functions.html#min" rel="nofollow">min</a> function with the <a href="http://docs.python.org/library/functions.html#len" rel="nofollow">len</a> function as the second argument.</p> <pre><code>&gt;&gt;&gt; s1 = ['DFA', 'AAAAAFG', 'MPRKY'] &gt;&gt;&gt; min(s1, key=len) 'DFA' </code></pre> <p><strong>EDIT:</strong><br /> In the event that two are the same length, you can extend this further to produce a list containing the elements that are all the same length:</p> <pre><code>&gt;&gt;&gt; s2 = ['foo', 'bar', 'baz', 'spam', 'eggs', 'knight'] &gt;&gt;&gt; s2_min_len = len(min(s2, key=len)) &gt;&gt;&gt; [e for e in s2 if len(e) is s2_min_len] ['foo', 'bar', 'baz'] </code></pre> <p>The above should work when there is only 1 'shortest' element too.</p> <p><strong>EDIT 2:</strong> Just to be complete, it should be faster, at least according to my simple tests, to compute the length of the shortest element and use that in the list comprehension. Updated above.</p>
8
2009-04-27T06:24:32Z
[ "python", "substring" ]
SQLAlchemy - Mapper configuration and declarative base
792,588
<p>I am writing a multimedia archive database backend and I want to use joined table inheritance. I am using Python with SQLAlchemy with the declarative extension. The table holding the media record is as follows:</p> <pre><code>_Base = declarative_base() class Record(_Base): __tablename__ = 'records' item_id = Column(String(M_ITEM_ID), ForeignKey('items.id')) storage_id = Column(String(M_STORAGE_ID), ForeignKey('storages.id')) id = Column(String(M_RECORD_ID), primary_key=True) uri = Column(String(M_RECORD_URI)) type = Column(String(M_RECORD_TYPE)) name = Column(String(M_RECORD_NAME)) </code></pre> <p>The column <code>type</code> is a discriminator. Now I want to define the child class <code>A</code>udioRecord from the <code>Record</code> class, but I don't how to setup the polymorphic mapper <strong>using the declarative syntax</strong>. I am looking for an equivalent for the following code (from SQLAlchemy documentation):</p> <pre><code>mapper(Record, records, polymorphic_on=records.c.type, polymorphic_identity='record') mapper(AudioRecord, audiorecords, inherits=Record, polymorphic_identity='audio_record') </code></pre> <p>How can I pass the <code>polymorphic_on</code>, <code>polymorphic_identity</code> and <code>inherits</code> keywords to the mapper created by the declarative extension?</p> <p>Thank you Jan</p>
2
2009-04-27T08:02:23Z
808,662
<p>I finally found the answer in the manual.</p> <p><a href="http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#joined-table-inheritance" rel="nofollow">http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#joined-table-inheritance</a></p>
1
2009-04-30T19:28:44Z
[ "python", "sqlalchemy" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
792,636
<p>I've seen python scripts used for building releases elsewhere so it can't be bad. Actually, I've personally used perl scripts to automate release building. I guess any scripting language could easily automate that procedure. If it's gonna be easy to do (and probably better than batch scripts), why not try it?</p>
3
2009-04-27T08:24:20Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
792,646
<p>As you're mentioning Python and SCons, I'd say go for SCons. It is Python after all. And yes, any of the above would be a better choice than hand-rolled build scripts.</p>
6
2009-04-27T08:28:34Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
792,651
<p>Personally I would use scripting as a last resort given that</p> <ul> <li>With a bit of work you can get MSBuild to do all those things for you by extending it with additional components</li> <li>There are third party equivalents to MSBuild like <a href="http://nant.sourceforge.net/" rel="nofollow">NANT</a> that can do the same thing</li> <li>There are entire tools like <a href="http://www.finalbuilder.com/" rel="nofollow">FinalBuilder</a> that also do the same thing, and are easier to configure and extend</li> </ul> <p>However, if I had to go the scripting route I would use Powershell for a couple of reasons:</p> <ul> <li>Complete access to file system</li> <li>You can easily access .NET objects</li> <li>You can easily access COM objects</li> </ul>
1
2009-04-27T08:29:02Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
792,659
<p>For a tool that is scripted with Python, I happen to think <a href="http://www.blueskyonmars.com/projects/paver/">Paver</a> is a more easily-managed and more flexible build automator than SCons. Unlike SCons, Paver is designed for the plethora of not-compiling-programs tasks that go along with managing and distributing a software project.</p>
15
2009-04-27T08:32:34Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
792,663
<p>Batch files aren't evil - they've actually come quite a long way from the brain-dead days of command.com. The command language can be pretty expressive nowadays, it just requires a bit of effort on your part to learn it.</p> <p>Unless there's an actual <em>problem</em> with your build script that you can't fix (and, if that's the case, that's the question you should be asking rather than some wishy-washy "What's the best replacement?" :-), my approach would be to stick with what you've got.</p> <p>A vague feeling of evilness would not be reason for me to waste effort 'fixing' something that isn't broken. And it would be wasted effort unless there's a clear advantage to changing ("less evil" is not something I'd consider a clear advantage).</p>
7
2009-04-27T08:35:01Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
792,676
<p>You can create custom makefiles for Microsoft nmake tool which you already have installed. Using a tool like that (SCons, Maven, etc. fall into the same category) gives you much more than regular scripts. </p> <p>The main benefit is that dependencies between files are tracked and also the timestamps of changes. For example, you can make your .zip file depend on some other files, so .zip only gets repacked if some of those files have changed in the meantime. Just like with source code and its compiled form.</p>
1
2009-04-27T08:40:17Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
792,680
<p>Python is very portable. SCons is field tested and reliable. Given what you know (from what you explained), why even ask the question?</p> <p>If your maintaining something, its not just about getting it to build, its also about explaining to the user why it can NOT build, which saves you a ton of very frustrating questions while helping users to help themselves.</p> <p>I can not think of a modern, production operating system that lacks Python, unless you get into the embedded / research arena.</p> <p>So, I'm answering to say, you answered your own question :)</p>
1
2009-04-27T08:41:21Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
793,274
<p>I would suggest using NAnt for your build script instead of python. My reasons for this are:</p> <ul> <li>It has the tasks defined already, all you need to do is write the XML and point it to the right places. If you are working with people who do not know python, XML may be a little less scary than learning a new language. </li> <li>NAnt is designed to work in the windows .Net environment, so it can already do MSBuild and NUnit tasks. </li> <li>If you are already writing in C#, if you need to extend NAnt to do new tasks you are not adding another language to the mix of your project.</li> <li>You can hook into <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome%2Bto%2BCruiseControl.NET" rel="nofollow">Cruise Control .Net</a> (for continuous builds). Which I think is the main reason why you would use NAnt. </li> </ul>
3
2009-04-27T12:29:26Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
793,349
<p>It depends on what technology your software uses. If you're building C++ programs, I'd probably say go for scons without question (unless you have weird requirements scons can't meet). On the other hand, consider the instructions for building C#: <a href="http://www.scons.org/wiki/CsharpBuilder" rel="nofollow">CSharpBuilder</a>.</p> <blockquote> <p>I would like to know (for example) what SCons gives me, over a normal Python script.</p> </blockquote> <p>Think of scons as being more of a library than a program. It provides you with code that will prevent a lot of tedium that you will have to deal with without it. In my opinion, vanilla Python isn't the best option for any kind of shell scripting stuff (not that it can't do it).</p> <blockquote> <p>But the problem is, batch files are evil.</p> </blockquote> <p>Lastly, batch files are evil if they're used for a project they're not suited to handle. For the one or two file project, batch files do just fine.</p>
0
2009-04-27T12:50:41Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
793,354
<p>Why should you use python? If your build script isn't broke don't fix it. If your having issues updating it to deal with new aditions to the project then you may want to look at rewriting it. I wouldn't use Python though tools like NANT or MSBuild do the job. I don't see the point in using a general purpis programming language to do something that tools have already been written to do unless you have a lot of obscure requirements existing tools can't deal with. Second what happens if you get hit by a bus or win the lotto? If you are determined to script everything I'd use powershell or some other Microsoft specific technology since your already wedded to Microsoft. If you leave will there be enough Python programmers to maintain the build scripts?</p>
2
2009-04-27T12:50:56Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
793,490
<p>I would strongly suggest to take a look at <a href="http://code.google.com/p/waf/" rel="nofollow">waf</a>. It's kind of what you want: "a Python-based framework for configuring, compiling and installing applications"</p>
2
2009-04-27T13:31:40Z
[ "python", "build-process", "build-automation" ]
Is Python the right hammer for this nail? (build script)
792,629
<p>Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> <p>But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate my build script in Python. Is that a smart choice? What about all those build systems, like Ant, SCons, Maven, Rake, etc. Would using any of those be a better choice?</p> <p>Note: I'm not planning to replace my Visual Studio solution/project files. I only want to script everything else that's required to create a release of my software.</p> <p><strong>Edit:</strong> I have good reasons to move away from batch, that's not what my question is about. I would like to know (for example) what SCons gives me, over a normal Python script.</p>
14
2009-04-27T08:19:11Z
1,354,100
<blockquote> <p>It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc.</p> </blockquote> <p>MSBuild and PowerShell can easily do all of this with reasonably clean succinct code. You're then sticking to purely M$ products which managers tend to like. Otherwise I would suggest you could look into Rake if not only for its large community. It has a nice syntax and iron ruby support (irake).</p> <p>To be honest all but the last task you have mentioned are <strong><em>easily</em></strong> done in MSBuild alone. I would suggest learning the tools you have before going elsewhere.</p> <p>Check out <a href="http://msbuildtasks.tigris.org/" rel="nofollow">http://msbuildtasks.tigris.org/</a> for some good add ons to MSBuild</p>
0
2009-08-30T15:27:21Z
[ "python", "build-process", "build-automation" ]
String formatting in Python version earlier than 2.6
792,721
<p>When I run the following code in Python 2.5.2:</p> <pre><code>for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#9&gt;", line 2, in &lt;module&gt; print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format' </code></pre> <p>I don't understand the problem.</p> <p>From <code>dir('hello')</code> there is no <code>format</code> attribute.</p> <p>How can I solve this?</p>
29
2009-04-27T08:57:14Z
792,738
<p>Which Python version do you use?</p> <p><strong>Edit</strong> For Python 2.5, use <code>"x = %s" % (x)</code> (for printing strings)</p> <p>If you want to print other types, <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">see here</a>.</p>
6
2009-04-27T09:00:48Z
[ "python", "format" ]
String formatting in Python version earlier than 2.6
792,721
<p>When I run the following code in Python 2.5.2:</p> <pre><code>for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#9&gt;", line 2, in &lt;module&gt; print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format' </code></pre> <p>I don't understand the problem.</p> <p>From <code>dir('hello')</code> there is no <code>format</code> attribute.</p> <p>How can I solve this?</p>
29
2009-04-27T08:57:14Z
792,740
<p>I believe that is a Python 3.0 feature, although it is in version 2.6. But if you have a version of Python below that, that type of string formatting will not work.</p> <p>If you are trying to print formatted strings in general, use Python's printf-style syntax through the <code>%</code> operator. For example:</p> <pre><code>print '%.2f' % some_var </code></pre>
8
2009-04-27T09:01:14Z
[ "python", "format" ]
String formatting in Python version earlier than 2.6
792,721
<p>When I run the following code in Python 2.5.2:</p> <pre><code>for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#9&gt;", line 2, in &lt;module&gt; print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format' </code></pre> <p>I don't understand the problem.</p> <p>From <code>dir('hello')</code> there is no <code>format</code> attribute.</p> <p>How can I solve this?</p>
29
2009-04-27T08:57:14Z
792,745
<p>The <code>str.format</code> method was <a href="http://docs.python.org/3.0/whatsnew/2.6.html#pep-3101-advanced-string-formatting">introduced in Python 3.0, and backported</a> to Python 2.6 and later.</p>
42
2009-04-27T09:04:05Z
[ "python", "format" ]
String formatting in Python version earlier than 2.6
792,721
<p>When I run the following code in Python 2.5.2:</p> <pre><code>for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#9&gt;", line 2, in &lt;module&gt; print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format' </code></pre> <p>I don't understand the problem.</p> <p>From <code>dir('hello')</code> there is no <code>format</code> attribute.</p> <p>How can I solve this?</p>
29
2009-04-27T08:57:14Z
792,776
<p>For Python versions below 2.6, use the <a href="http://docs.python.org/library/stdtypes.html#string-formatting">% operator</a> to interpolate a sequence of values into a format string:</p> <pre><code>for x in range(1, 11): print '%2d %3d %4d' % (x, x*x, x*x*x) </code></pre> <p>You should also be aware that this operator can interpolate by <em>name</em> from a mapping, instead of just positional arguments:</p> <pre><code>&gt;&gt;&gt; "%(foo)s %(bar)d" % {'bar': 42, 'foo': "spam", 'baz': None} 'spam 42' </code></pre> <p>In combination with the fact that the built-in vars() function returns attributes of a namespace as a mapping, this can be very handy:</p> <pre><code>&gt;&gt;&gt; bar = 42 &gt;&gt;&gt; foo = "spam" &gt;&gt;&gt; baz = None &gt;&gt;&gt; "%(foo)s %(bar)d" % vars() 'spam 42' </code></pre>
31
2009-04-27T09:12:12Z
[ "python", "format" ]
String formatting in Python version earlier than 2.6
792,721
<p>When I run the following code in Python 2.5.2:</p> <pre><code>for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#9&gt;", line 2, in &lt;module&gt; print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format' </code></pre> <p>I don't understand the problem.</p> <p>From <code>dir('hello')</code> there is no <code>format</code> attribute.</p> <p>How can I solve this?</p>
29
2009-04-27T08:57:14Z
2,201,681
<p><em>Although the existing answers describe the causes and point in the direction of a fix, none of them actually provide a solution that accomplishes what the question asks.</em></p> <p>You have two options to solve the problem. The first is to upgrade to Python 2.6 or greater, which supports the <a href="http://docs.python.org/library/string.html#string-formatting">format string construct</a>.</p> <p>The second option is to use the <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations">older string formatting with the % operator</a>. The equivalent code of what you've presented would be as follows.</p> <pre><code>for x in range(1,11): print '%2d %3d %4d' % (x, x*x, x*x*x) </code></pre> <p>This code snipped produces exactly the same output in Python 2.5 as your example code produces in Python 2.6 and greater.</p>
7
2010-02-04T17:16:01Z
[ "python", "format" ]
How to avoid Gdk-ERROR caused by Tkinter, visual, and ipython?
792,816
<p>The following lines cause with ipython a crash as soon as I close the tk-window instance <code>a</code>.</p> <pre><code>import visual, Tkinter a = Tkinter.Tk() a.update() display = visual.display(title = "Hallo") display.exit = 0 visual.sphere() </code></pre> <p>If I close the visual display first, the entire terminal crashes. I run everything on kubuntu 8.10. Is this a bug or am I doing something wrong? If this is a bug: Is there a smart way to avoid it?</p> <p>Cheers, Philipp</p>
1
2009-04-27T09:29:12Z
792,959
<p>Have you tried starting ipython with the <code>-gthread -tk</code> command-line switches? </p> <p>From <code>ipython --help</code>:</p> <pre> -gthread, -qthread, -q4thread, -wthread, -pylab Only ONE of these can be given, and it can only be given as the first option passed to IPython (it will have no effect in any other position). They provide threading support for the GTK, QT and WXWidgets toolkits, and for the matplotlib library. With any of the first four options, IPython starts running a separate thread for the graphical toolkit's operation, so that you can open and control graphical elements from within an IPython command line, without blocking. All four provide essentially the same functionality, respectively for GTK, QT3, QT4 and WXWidgets (via their Python interfaces). Note that with -wthread, you can additionally use the -wxversion option to request a specific version of wx to be used. This requires that you have the 'wxversion' Python module installed, which is part of recent wxPython distributions. If -pylab is given, IPython loads special support for the mat- plotlib library (http://matplotlib.sourceforge.net), allowing interactive usage of any of its backends as defined in the user's .matplotlibrc file. It automatically activates GTK, QT or WX threading for IPyhton if the choice of matplotlib backend requires it. It also modifies the %run command to correctly execute (without blocking) any matplotlib-based script which calls show() at the end. -tk The -g/q/q4/wthread options, and -pylab (if matplotlib is configured to use GTK, QT or WX), will normally block Tk graphical interfaces. This means that when GTK, QT or WX threading is active, any attempt to open a Tk GUI will result in a dead window, and possibly cause the Python interpreter to crash. An extra option, -tk, is available to address this issue. It can ONLY be given as a SECOND option after any of the above (-gthread, -qthread, q4thread, -wthread or -pylab). If -tk is given, IPython will try to coordinate Tk threading with GTK, QT or WX. This is however potentially unreliable, and you will have to test on your platform and Python configuration to determine whether it works for you. Debian users have reported success, apparently due to the fact that Debian builds all of Tcl, Tk, Tkinter and Python with pthreads support. Under other Linux environments (such as Fedora Core 2/3), this option has caused random crashes and lockups of the Python interpreter. Under other operating systems (Mac OSX and Windows), you'll need to try it to find out, since currently no user reports are available. There is unfortunately no way for IPython to determine at run- time whether -tk will work reliably or not, so you will need to do some experiments before relying on it for regular work. </pre>
1
2009-04-27T10:15:50Z
[ "python", "tkinter" ]
Can I write my apps in python and then run them from C?
792,924
<p>I need to write a client-server application. I want to write it in python, because I'm familiar with it, but I would like to know if the python code can be ran from C. I'm planning to have two C projects, one containing the server code, and one containing the client code.</p> <p>Is it possible to eval the python code and run it ? Is there another way of doing this? </p> <p>The bottom line is that the python code must run from C, and it must behave exactly as if ran under the python interpreter. I'm asking this now, because I don't want to waste time writing the python code just to find out later that I can't achieve this . As a sidenote, I only plan on using basic python modules ( socket,select, etc. ).</p> <p>EDIT: maybe this edit is in order. I haven't embedded python in C before, and I don't know what the behaviour will be. The thing is, the server will have a select loop, and will therefore run "forever". Will C let me do that ?</p> <p>EDIT2: here is why I need to do this. At school, a teacher asked us to do a pretty complex client-server app in C. I'm going to cheat, write the code in python and embed it in C.</p>
0
2009-04-27T10:06:25Z
792,935
<p>here's a nice tutorial for doing exactly that <a href="http://www.linuxjournal.com/article/8497">http://www.linuxjournal.com/article/8497</a></p>
5
2009-04-27T10:08:37Z
[ "python", "c", "interop" ]
Can I write my apps in python and then run them from C?
792,924
<p>I need to write a client-server application. I want to write it in python, because I'm familiar with it, but I would like to know if the python code can be ran from C. I'm planning to have two C projects, one containing the server code, and one containing the client code.</p> <p>Is it possible to eval the python code and run it ? Is there another way of doing this? </p> <p>The bottom line is that the python code must run from C, and it must behave exactly as if ran under the python interpreter. I'm asking this now, because I don't want to waste time writing the python code just to find out later that I can't achieve this . As a sidenote, I only plan on using basic python modules ( socket,select, etc. ).</p> <p>EDIT: maybe this edit is in order. I haven't embedded python in C before, and I don't know what the behaviour will be. The thing is, the server will have a select loop, and will therefore run "forever". Will C let me do that ?</p> <p>EDIT2: here is why I need to do this. At school, a teacher asked us to do a pretty complex client-server app in C. I'm going to cheat, write the code in python and embed it in C.</p>
0
2009-04-27T10:06:25Z
792,948
<p>Yes you can run the Python code from C by embedding the interpreter in your program. You can expose portions of your C code to Python and call your exposed C code from Python as if they were normal Python functions.</p> <p>A good start is the <a href="http://docs.python.org/extending/embedding.html" rel="nofollow">Embedding</a> section in the Python docs. Also have a look at the <a href="http://stackoverflow.com/questions/792924/can-i-write-my-apps-in-python-and-then-run-them-from-c/792935#792935">article linked to</a> by cobbal.</p>
1
2009-04-27T10:12:28Z
[ "python", "c", "interop" ]
Can I write my apps in python and then run them from C?
792,924
<p>I need to write a client-server application. I want to write it in python, because I'm familiar with it, but I would like to know if the python code can be ran from C. I'm planning to have two C projects, one containing the server code, and one containing the client code.</p> <p>Is it possible to eval the python code and run it ? Is there another way of doing this? </p> <p>The bottom line is that the python code must run from C, and it must behave exactly as if ran under the python interpreter. I'm asking this now, because I don't want to waste time writing the python code just to find out later that I can't achieve this . As a sidenote, I only plan on using basic python modules ( socket,select, etc. ).</p> <p>EDIT: maybe this edit is in order. I haven't embedded python in C before, and I don't know what the behaviour will be. The thing is, the server will have a select loop, and will therefore run "forever". Will C let me do that ?</p> <p>EDIT2: here is why I need to do this. At school, a teacher asked us to do a pretty complex client-server app in C. I'm going to cheat, write the code in python and embed it in C.</p>
0
2009-04-27T10:06:25Z
792,950
<p>It's called embedding Python -- it's well covered in the Python docs. See <a href="https://docs.python.org/extending/embedding.html" rel="nofollow">https://docs.python.org/extending/embedding.html</a></p> <p>See <a href="http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c">how do i use python libraries in C++?</a></p>
2
2009-04-27T10:12:57Z
[ "python", "c", "interop" ]
Django serializer gives 'str' object has no attribute '_meta' error
793,095
<p>I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.</p> <pre><code>'str' object has no attribute '_meta' </code></pre> <p>I have other serialization and it works.</p> <p>Here is the code.</p> <pre><code>def get_calendar_limits(request): result = serializers.serialize("json", Session.objects.aggregate(Max('date'), Min('date')), ensure_ascii=False) return HttpResponse(result, mimetype="application/javascript") </code></pre> <p>Thanks a lot beforehand.</p>
3
2009-04-27T11:14:27Z
793,383
<p>Take a look at the following:</p> <pre><code>objects= Session.objects.aggregate(Max('date'), Min('date')) print [ type[o] for o in objects ] result = serializers.serialize("json", objects, ensure_ascii=False) </code></pre> <p>You might want to just run the above in interactive Python as an experiment.</p> <p>What type are your objects? Is that type serializable?</p>
0
2009-04-27T12:58:34Z
[ "python", "django", "json" ]
Django serializer gives 'str' object has no attribute '_meta' error
793,095
<p>I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.</p> <pre><code>'str' object has no attribute '_meta' </code></pre> <p>I have other serialization and it works.</p> <p>Here is the code.</p> <pre><code>def get_calendar_limits(request): result = serializers.serialize("json", Session.objects.aggregate(Max('date'), Min('date')), ensure_ascii=False) return HttpResponse(result, mimetype="application/javascript") </code></pre> <p>Thanks a lot beforehand.</p>
3
2009-04-27T11:14:27Z
1,005,386
<p>I get the same error when trying to serialize an object that is not derived from Django's Model</p>
1
2009-06-17T06:19:37Z
[ "python", "django", "json" ]
Django serializer gives 'str' object has no attribute '_meta' error
793,095
<p>I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.</p> <pre><code>'str' object has no attribute '_meta' </code></pre> <p>I have other serialization and it works.</p> <p>Here is the code.</p> <pre><code>def get_calendar_limits(request): result = serializers.serialize("json", Session.objects.aggregate(Max('date'), Min('date')), ensure_ascii=False) return HttpResponse(result, mimetype="application/javascript") </code></pre> <p>Thanks a lot beforehand.</p>
3
2009-04-27T11:14:27Z
2,559,082
<p>Python has "json" module. It can 'dumps' and 'loads' function. They can serialize and deserialize accordingly.</p>
1
2010-04-01T08:34:58Z
[ "python", "django", "json" ]
Calling gdc/dmd shared libraries from Python using ctypes
793,125
<p>I've been playing around with the rather excellent ctypes library in Python recently. What i was wondering is, is it possible to create shared <code>D</code> libraries and call them in the same way. I'm assuming i would compile the <code>.so</code> files using the <code>-fPIC</code> with <code>dmd</code> or <code>gdc</code> and call them the same way using the <code>ctypes</code> library.</p> <p>Has anyone tried this ? It looks as if shared libs on <code>UNIX</code> are partially supported.</p> <p>Many thanks,</p> <p>Al.</p>
1
2009-04-27T11:31:53Z
4,884,444
<p>In this case Windows dlls should work just fine. I'm not sure about the situation on Linux, there are some issues with shared libraries which will be addressed as soon as the 64 bit port of dmd is finished.</p> <p>Note that you have to export your functions as extern(C) or extern(Windows) to access them from ctypes.</p>
0
2011-02-03T09:40:28Z
[ "python", "d", "ctypes" ]
Database Reporting Services in Django or Python
793,130
<p>I am wondering if there are any django based, or even Python Based Reporting Services ala JasperReports or SQL Server Reporting Services?</p> <p>Basically, I would love to be able to create reports, send them out as emails as CSV or HTML or PDF without having to code the reports. Even if I have to code the report I wouldn't mind, but the whole framework with schedules and so on would be nice!</p> <p>PS. I know I could use Django Apps to do it, but I was hoping if there was any integrated solutions or even projects such as Pinax or Satchmo which brings together the apps needed.</p> <p>PPS: It would have to work off Postgres</p> <p>Thanks and Regards</p> <p>Mark</p>
7
2009-04-27T11:35:31Z
793,567
<p>"I would love to be able to create reports ... without having to code the reports" </p> <p>So would I. Sadly, however, each report seems to be unique and require custom code.</p> <p>From Django model to CSV is easy. Start there with a few of your reports.</p> <pre><code>import csv from myApp.models import This, That, TheOther def parseCommandLine(): # setup optparse to get report query parameters def main(): wtr= csv.DictWriter( sys.stdout, ["Col1", "Col2", "Col3"] ) this, that = parseCommandLine() thisList= This.objects.filter( name=this, that__name=that ) for object in thisList: write.writerow( object.col1, object.that.col2, object.theOther.col3 ) if __name__ == "__main__": main() </code></pre> <p>HTML is pretty easy -- Django has an HTML template language. Rather than render_to_response, you simply render your template and write it to stdout. And the core of the algorithm, interestingly, is very similar to writing a CSV. Similar enough that -- without much cleverness -- you should have a design pattern that does both.</p> <p>Once you have the CSV working, add the HTML using Django's templates.</p> <p>PDF's are harder, because you have to actually work out the formatting in some detail. There are a lot of Python libraries for this. Interestingly, however, the overall pattern for PDF writing is very similar to CSV and HTML writing.</p> <p>Emailing means using Python's <a href="http://docs.python.org/library/smtplib.html" rel="nofollow">smtplib</a> directly or Django's <a href="http://docs.djangoproject.com/en/dev/topics/email/" rel="nofollow">email</a> package. This isn't too hard. All the pieces are there, you just need to email the output files produced above to some distribution list.</p> <p>Scheduling takes a little thinking to make best use of <code>crontab</code>. This -- perhaps -- is the hardest part of the job.</p>
4
2009-04-27T13:48:50Z
[ "python", "django", "reporting-services" ]
Database Reporting Services in Django or Python
793,130
<p>I am wondering if there are any django based, or even Python Based Reporting Services ala JasperReports or SQL Server Reporting Services?</p> <p>Basically, I would love to be able to create reports, send them out as emails as CSV or HTML or PDF without having to code the reports. Even if I have to code the report I wouldn't mind, but the whole framework with schedules and so on would be nice!</p> <p>PS. I know I could use Django Apps to do it, but I was hoping if there was any integrated solutions or even projects such as Pinax or Satchmo which brings together the apps needed.</p> <p>PPS: It would have to work off Postgres</p> <p>Thanks and Regards</p> <p>Mark</p>
7
2009-04-27T11:35:31Z
802,968
<p>I just thought after a fair bit of investigation I would report my findings...</p> <p><a href="http://code.google.com/p/django-reporting/" rel="nofollow">http://code.google.com/p/django-reporting/</a> - I think that this project, looks like an awesome candidate for alot of the functionality I require. Unfortunately its Django 1.1 which as of this writing (29th April 2009) has not been released.At least in the ability to create reports without too much code.</p> <p><a href="http://code.google.com/p/django-cron/" rel="nofollow">http://code.google.com/p/django-cron/</a> - Look promising for scheduling of jobs without cron access</p> <p><a href="http://www.xhtml2pdf.com/" rel="nofollow">http://www.xhtml2pdf.com/</a> - Could be used or ReportLabs PDF Libraries for conversion of HTML to PDF</p> <p>All these together with Django's Email functionality could make a nice Reporting System.</p>
3
2009-04-29T15:42:27Z
[ "python", "django", "reporting-services" ]
retrieve bounding box of a geodjango multipolygon object
793,240
<p>How can I get the bounding box of a MultiPolygon object in geodjango? Can't find anything in the API <a href="http://geodjango.org/docs/geos.html" rel="nofollow">http://geodjango.org/docs/geos.html</a> ...</p>
4
2009-04-27T12:19:59Z
794,286
<p>Use the <code>extent</code> property: <a href="http://geodjango.org/docs/geos.html#extent">http://geodjango.org/docs/geos.html#extent</a>. It returns a 4-tuple comprising the lower left and upper right coordinates, respectively.</p> <p>You can also use the <code>envelope</code> property if you want a <code>Polygon</code> object representation of the bounding box.</p>
5
2009-04-27T16:32:44Z
[ "python", "django", "gis", "geodjango" ]
Getting Aspen and Gheat on Windows working
793,341
<p>I am not really familiar Python setup, I am trying to get gheat running on a Windows box, and it tells me it can't find pygame.</p> <p>I have tried Python25,26, older pygame version too.</p> <p>I have installed those as well as numpy as it has a dependency.</p> <p>Could someone with experience try and help me out getting it up and running.</p> <p>I have tried running Process Monitor against it, and it seems to find all the files etc but aspen/gheat still tell me it can't find Pygame.</p> <p>Links below.</p> <p>1.) <a href="http://www.python.org/" rel="nofollow">http://www.python.org/</a> 2.) <a href="http://code.google.com/p/gheat/" rel="nofollow">http://code.google.com/p/gheat/</a> 3.) <a href="http://www.pygame.org/" rel="nofollow">http://www.pygame.org/</a> 4.) <a href="http://numpy.scipy.org/" rel="nofollow">http://numpy.scipy.org/</a></p> <p>Cheers for any help.</p> <p>Aside, It works fine on my ubuntu box just by install pygame and it works ! </p>
-1
2009-04-27T12:47:39Z
793,512
<p>With thanks to SeC- from the #csharp channel on Freenode, he figured out it is the problem with the latest trunk of aspen, (I thought I'd tried the older version)</p> <p><a href="http://www.zetadev.com/software/aspen/0.8/dist/aspen-0.8.zip" rel="nofollow">http://www.zetadev.com/software/aspen/0.8/dist/aspen-0.8.zip</a></p> <p>You will need the 0.8 version to get it working!!</p> <p>Cheers anyway!</p>
0
2009-04-27T13:35:35Z
[ "python", "pygame", "aspen" ]
How do I get the dimensions of the view (not obstructed by scrollbars) in a wx.ScrolledWindow?
793,381
<p>Is there an easy way to do this? Alternatively, if I could get the width of the scrollbars, I could just use the dimensions of the ScrolledWindow and subtract them out myself...</p>
1
2009-04-27T12:58:22Z
793,488
<p>Use wx.SystemSettings.GetMetric() with wx.SYS_HSCROLL_Y and wx.SYS_VSCROLL_X to get the scrollbar sizes. Then use window.GetClientSize() and subtract it out.</p> <p><a href="http://docs.wxwidgets.org/stable/wx_wxsystemsettings.html#wxsystemsettings" rel="nofollow">http://docs.wxwidgets.org/stable/wx_wxsystemsettings.html#wxsystemsettings</a></p> <pre><code>&gt;&gt;&gt; wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y) 16 &gt;&gt;&gt; wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X) 16 </code></pre>
2
2009-04-27T13:30:47Z
[ "python", "wxpython", "wxwidgets", "scrolledwindow" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
794,147
<p>Don't you just need to combine the masks together to make use of EPOLLHUP and EPOLLIN at the same time:</p> <pre> <code> epoll.register(sk.fileno(), select.EPOLLIN | select.EPOLLHUP) </code> </pre> <p>Though to be honest I'm not really familiar with the epoll library, so it's just a suggestion really...</p>
0
2009-04-27T15:53:41Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
797,206
<p>My ad-hoc solution to bypass this problem</p> <pre><code>--- epoll_demo.py.orig 2009-04-28 18:11:32.000000000 +0800 +++ epoll_demo.py 2009-04-28 18:12:56.000000000 +0800 @@ -18,6 +18,7 @@ epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} +en = {} data = '' while True: time.sleep(1) @@ -29,10 +30,18 @@ sk.setblocking(0) print addr cs[sk.fileno()] = sk + en[sk.fileno()] = 0 epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) + if not data: + en[fileno] += 1 + if en[fileno] &gt;= 3: + print 'closed' + epoll.unregister(fileno) + continue + en[fileno] = 0 print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: </code></pre>
1
2009-04-28T10:17:46Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
826,146
<p>EPOLLERR and EPOLLHUP never happens in the code pasted in the post is because they've always occurred in conjunction with an EPOLLIN or an EPOLLOUT (several of these can be set at once), so the if/then/else have always picked up an EPOLLIN or EPOLLOUT. </p> <p>Experimenting I've found that EPOLLHUP only happens in conjunction with EPOLLERR, the reason for this may be the way python interfaces with epoll and lowlevel IO, normally recv would return a -1 and set errno to EAGAIN when nothing is available on a non-blocking recv, however python uses '' (nothing returned) to signal EOF.</p> <p>Closing your telnet-session only closes that end of the tcp-connection, so it's still perfectly valid to call recv on your side, there may be pending data in the tcp receive buffers which your application hasn't read yet so that won't trigger an error-condition.</p> <p>It seems that EPOLLIN and a recv that returns an empty string is indicative of the other end having closed the connection, however, using an older version of python (before epoll were introduced) and plain select on a pipe, I've experienced that a read that returned '' did not indicate EOF just a lack of available data.</p>
3
2009-05-05T17:56:54Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
866,929
<p>After I move select.EPOLLHUP handling code to the line before select.EPOLLIN, hup event still cant be got in 'telnet'. But by coincidence I found that if I use my own client script, there are hup events! strange...</p> <p>And according to man epoll_ctl</p> <pre><code> EPOLLRDHUP (since Linux 2.6.17) Stream socket peer closed connection, or shut down writing half of connection. (This flag is especially useful for writing simple code to detect peer shutdown when using Edge Triggered monitoring.) EPOLLERR Error condition happened on the associated file descriptor. epoll_wait(2) will always wait for this event; it is not necessary to set it in events. EPOLLHUP Hang up happened on the associated file descriptor. epoll_wait(2) will always wait for this event; it is not necessary to set it in events. </code></pre> <p>Seems there shall be a EPOLLRDHUP event when remote side closed connection, which is not implemented by python, don't know why</p>
0
2009-05-15T04:01:51Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
1,749,800
<p>If the socket is still open but no read/write available epoll.poll will timeout.</p> <p>If data if available from the peer, you get an EPOLLIN and data will be available.</p> <p>If the socket is closed by the peer, you will get an EPOLLIN but when you read it it will return "".</p> <p>you could then close the socket by shutting it down and picking up the resulting EPOLLHUP event to clean up your internal structures.</p> <p>or perform cleanup and unregister the epoll.</p> <pre><code>elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) if not data: epoll.modify(fileno, 0) cs[fileno].shutdown(socket.SHUT_RDWR) </code></pre>
1
2009-11-17T15:49:38Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
3,988,175
<p>The <em>EPOLLRDHUP</em> flag is not defined in Python for no reason. If your Linux kernel is >= 2.6.17, you can define it and register your socket in epoll like this:</p> <pre><code>import select if not "EPOLLRDHUP" in dir(select): select.EPOLLRDHUP = 0x2000 ... epoll.register(socket.fileno(), select.EPOLLIN | select.EPOLLRDHUP) </code></pre> <p>You can then catch the event you need using the same flag (<em>EPOLLRDHUP</em>):</p> <pre><code>elif event &amp; select.EPOLLRDHUP: print "Stream socket peer closed connection" # try shutdown on both side, then close the socket: socket.close() epoll.unregister(socket.fileno()) </code></pre> <p>For more info you can check <a href="http://svn.python.org/view/python/tags/r27/Modules/selectmodule.c?view=markup" rel="nofollow">selectmodule.c</a> in python's repository: </p>
0
2010-10-21T13:53:54Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
6,380,258
<p>I have another approach.. </p> <pre><code>try: data = s.recv(4096) except socket.error: if e[0] in (errno.EWOULDBLOCK, errno.EAGAIN): # since this is a non-blocking socket.. return # no error else: # error socket.close() if not data: #closed either socket.close() </code></pre>
0
2011-06-17T00:47:19Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
7,803,048
<pre><code>if event &amp; select.EPOLLHUP: epoll.unregister(fd) </code></pre>
0
2011-10-18T06:01:59Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
9,412,254
<pre><code>elif event &amp; (select.EPOLLERR | select.EPOLLHUP): epoll.unregister(fileno) cs[fileno].close() del cs[fileno] </code></pre>
0
2012-02-23T11:36:01Z
[ "python", "epoll" ]
How epoll detect clientside close in Python?
793,646
<p><strong>Here is my server</strong></p> <pre><code>"""Server using epoll method""" import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() epoll.register(s.fileno(), select.EPOLLIN) # Level triggerred cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(), select.EPOLLIN) elif event &amp; select.EPOLLIN: data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, select.EPOLLOUT) elif event &amp; select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, select.EPOLLIN) elif event &amp; select.EPOLLERR: print 'err' epoll.unregister(fileno) </code></pre> <p><strong>client side input</strong></p> <pre><code>ideer@ideer:/home/chenz/source/ideerfs$ telnet localhost 8989 Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123456 123456 ^] telnet&gt; q Connection closed. </code></pre> <p><strong>server side output</strong></p> <pre><code>ideer@ideer:/chenz/source/ideerfs$ python epoll.py Polling 0 events Polling 0 events Polling 1 events ('127.0.0.1', 53975) Polling 0 events Polling 1 events recv 1234 Polling 1 events send 1234 Polling 1 events recv 56 Polling 1 events send 56 Polling 0 events Polling 0 events Polling 0 events Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv Polling 1 events send Polling 1 events recv ^CTraceback (most recent call last): File "epoll.py", line 23, in &lt;module&gt; time.sleep(1) KeyboardInterrupt </code></pre> <p>It's strange that after the client has closed the connection, epoll still can poll recv and send events! Why does EPOLLERR event never happen? it's the same if you use EPOLLHUP.</p> <p>I notice that the EPOLLERR event only happens when you try to write a closed connection. Besides this, is there another way to tell that whether the connection has been closed or not?</p> <p>Is it correct to treat the connection as closed if you get nothing in a EPOLLIN event?</p>
3
2009-04-27T14:06:45Z
25,213,161
<p>The issue why you're not detecting EPOLLHUP/EPOLLERR in your code is because of the bitwise operations you are doing. See when a socket is ready to read epoll will throw a flag with bit 1 which is equal to select.EPOLLIN (select.EPOLLIN == 1). Now say the client hangs up (gracefully or not) epoll on the server will throw a flag with bit 25 which is equal to EPOLLIN+EPOLLERR+EPOLLHUP. So with the bit 25 (event variable in your code) you can see how EPOLLERR is not being detected because all of your elif statements (with the exception of EPOLLOUT line) don't return 0 so the first elif statement is executed, for example:</p> <pre><code>&gt;&gt;&gt; from select import EPOLLIN,EPOLLOUT,EPOLLHUP,EPOLLERR &gt;&gt;&gt; event = 25 &gt;&gt;&gt; event &amp; EPOLLIN 1 &gt;&gt;&gt; event &amp; EPOLLERR 8 &gt;&gt;&gt; event &amp; EPOLLHUP 16 &gt;&gt;&gt; event &amp; EPOLLOUT 0 </code></pre> <p>Notice how the first three don't return 0? That's why your code isn't detecting EPOLLERR/EPOLLHUP correctly. When a client hangs up you can still read from the socket as the server side is still up (of course it would return 0 data if you did) hence EPOLLIN but since the client hung up it's also EPOLLHUP and since it's EPOLLHUP it's also EPOLLERR as a hangup is somewhat of an error. I know I'm late on commenting on this but I hope I helped someone out there lol</p> <p>Here is a way I would rewrite your code to express what I'm saying better:</p> <pre><code>import os import select import socket import time from oodict import OODict addr = ('localhost', 8989) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(8) s.setblocking(0) # Non blocking socket server epoll = select.epoll() read_only = select.EPOLLIN | select.EPOLLPRI | select.EPOLLHUP | select.EPOLLERR read_write = read_only | select.EPOLLOUT biterrs = [25,24,8,16,9,17,26,10,18] #Bitwise error numbers epoll.register(s.fileno(),read_only) cs = {} data = '' while True: time.sleep(1) events = epoll.poll(1) # Timeout 1 second print 'Polling %d events' % len(events) for fileno, event in events: if fileno == s.fileno(): sk, addr = s.accept() sk.setblocking(0) print addr cs[sk.fileno()] = sk epoll.register(sk.fileno(),read_only) elif (event is select.EPOLLIN) or (event is select.EPOLLPRI): data = cs[fileno].recv(4) print 'recv ', data epoll.modify(fileno, read_write) elif event is select.EPOLLOUT: print 'send ', data cs[fileno].send(data) data = '' epoll.modify(fileno, read_only) elif event in biterrs: print 'err' epoll.unregister(fileno) </code></pre>
0
2014-08-08T22:29:29Z
[ "python", "epoll" ]
psycopg2 "TypeError: not all arguments converted during string formatting"
793,679
<p>I'm trying to insert binary data (a whirlpool hash) into a PG table and am getting an error:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>code:</p> <pre><code>cur.execute(""" INSERT INTO sessions (identity_hash, posted_on) VALUES (%s, NOW()) """, identity_hash) </code></pre> <p>I tried adding conn.Binary("identity_hash") to the variable before insertion, but get the same error.</p> <p>The identity_hash column is a bytea.</p> <p>Any ideas?</p>
7
2009-04-27T14:13:53Z
794,213
<p>Have you taken a look at the "examples/binary.py" script in the psycopg2 source distribution? It works fine here. It looks a bit different than your excerpt:</p> <pre><code>data1 = {'id':1, 'name':'somehackers.jpg', 'img':psycopg2.Binary(open('somehackers.jpg').read())} curs.execute("""INSERT INTO test_binary VALUES (%(id)s, %(name)s, %(img)s)""", data1) </code></pre>
5
2009-04-27T16:10:04Z
[ "python", "postgresql", "psycopg2" ]
psycopg2 "TypeError: not all arguments converted during string formatting"
793,679
<p>I'm trying to insert binary data (a whirlpool hash) into a PG table and am getting an error:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>code:</p> <pre><code>cur.execute(""" INSERT INTO sessions (identity_hash, posted_on) VALUES (%s, NOW()) """, identity_hash) </code></pre> <p>I tried adding conn.Binary("identity_hash") to the variable before insertion, but get the same error.</p> <p>The identity_hash column is a bytea.</p> <p>Any ideas?</p>
7
2009-04-27T14:13:53Z
1,492,188
<p>The problem you have is that you are passing the object as second parameter: the second parameters should be either a tuple or a dict. There is no shortcut as in the % string operator.</p> <p>You should do:</p> <pre><code>cur.execute(""" INSERT INTO sessions (identity_hash, posted_on) VALUES (%s, NOW()) """, (identity_hash,)) </code></pre>
16
2009-09-29T12:14:57Z
[ "python", "postgresql", "psycopg2" ]
psycopg2 "TypeError: not all arguments converted during string formatting"
793,679
<p>I'm trying to insert binary data (a whirlpool hash) into a PG table and am getting an error:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>code:</p> <pre><code>cur.execute(""" INSERT INTO sessions (identity_hash, posted_on) VALUES (%s, NOW()) """, identity_hash) </code></pre> <p>I tried adding conn.Binary("identity_hash") to the variable before insertion, but get the same error.</p> <p>The identity_hash column is a bytea.</p> <p>Any ideas?</p>
7
2009-04-27T14:13:53Z
27,853,328
<p>Encountered the same problem and found that this is actually covered in their <a href="http://initd.org/psycopg/docs/faq.html" rel="nofollow">FAQ</a></p> <blockquote> <p>I try to execute a query but it fails with the error not all arguments converted during string formatting (or object does not support indexing). Why? Psycopg always require positional arguments to be passed as a sequence, even when the query takes a single parameter. And remember that to make a single item tuple in Python you need a comma! See Passing parameters to SQL queries.</p> </blockquote> <pre><code>cur.execute("INSERT INTO foo VALUES (%s)", "bar") # WRONG cur.execute("INSERT INTO foo VALUES (%s)", ("bar")) # WRONG cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct cur.execute("INSERT INTO foo VALUES (%s)", ["bar"]) # correct </code></pre>
1
2015-01-09T03:20:36Z
[ "python", "postgresql", "psycopg2" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
793,793
<p>With Python:</p> <pre><code>file = open(filename, 'r') lines = file.readlines() file.close() p = re.compile('^\d*$') for line in lines: if not p.search(line): print line, </code></pre>
2
2009-04-27T14:37:36Z
[ "python", "perl", "text", "awk", "text-processing" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
793,826
<pre><code>with open(source_filename) as src: with open(dest_filename, 'w') as dst: for line in src: if len(line.split()) &gt; 1: dst.write(line) </code></pre>
5
2009-04-27T14:42:29Z
[ "python", "perl", "text", "awk", "text-processing" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
793,830
<p>With <code>awk</code>:</p> <pre><code>awk 'NF &gt; 2' input_file &gt; output_file </code></pre>
14
2009-04-27T14:43:13Z
[ "python", "perl", "text", "awk", "text-processing" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
793,837
<p>With Perl:</p> <pre><code>perl -ne 'print if /^([0-9]+\s+){2}.+$/' $filename </code></pre>
4
2009-04-27T14:43:53Z
[ "python", "perl", "text", "awk", "text-processing" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
793,842
<pre><code>sed '/^[0-9]$/d' filename </code></pre> <p>(might have to modify the pattern if the bad lines have trailing spaces). You can also use grep -v, which will omit the matched pattern.</p>
-1
2009-04-27T14:44:24Z
[ "python", "perl", "text", "awk", "text-processing" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
793,854
<p>awk "NF>1" &lt; filename</p>
1
2009-04-27T14:47:22Z
[ "python", "perl", "text", "awk", "text-processing" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
793,865
<pre><code>grep ':' filename </code></pre>
8
2009-04-27T14:49:24Z
[ "python", "perl", "text", "awk", "text-processing" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
793,945
<p>Just working my perl here, but this might help as well:</p> <pre><code>perl -lane 'if (scalar(@F) == 3) { print @F;}' file &gt;&gt; file.out </code></pre>
3
2009-04-27T15:06:35Z
[ "python", "perl", "text", "awk", "text-processing" ]
Remove lines from file
793,759
<p>I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.</p> <p>I have a text file that looks like below:</p> <pre><code>2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 2895635937120524206 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>It is basically 3 rows: ID ID Date</p> <p>I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:</p> <pre><code>2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009 2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009 5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009 </code></pre> <p>How would you guys suggest doing this? In total the text file is around 30,000 lines long.</p> <p>Cheers</p> <p>Eef</p>
3
2009-04-27T14:30:46Z
18,123,865
<pre><code>perl -i -lane 'print if($F[1])' file </code></pre>
1
2013-08-08T10:36:10Z
[ "python", "perl", "text", "awk", "text-processing" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
793,772
<p>Use <a href="http://docs.python.org/library/hashlib.html?highlight=hash#module-hashlib">hashlib</a> as <code>hash()</code> <a href="https://docs.python.org/2/library/functions.html#hash">was designed to be used to</a>:</p> <blockquote> <p>quickly compare dictionary keys during a dictionary lookup</p> </blockquote> <p>and therefore does not guarantee that it will be the same across Python implementations.</p>
49
2009-04-27T14:33:54Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
793,802
<p>It probably just asks the operating system provided function, rather than its own algorithm. </p> <p>As other comments says, use <a href="http://docs.python.org/library/hashlib.html?highlight=hash#module-hashlib" rel="nofollow">hashlib</a> or write your own hash function.</p>
-3
2009-04-27T14:38:21Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
793,835
<p>As stated in the documentation, built-in hash() function is <em>not</em> designed for storing resulting hashes somewhere externally. It is used to provide object's hash value, to store them in dictionaries and so on. It's also implementation-specific (GAE uses a modified version of Python). Check out:</p> <pre><code>&gt;&gt;&gt; class Foo: ... pass ... &gt;&gt;&gt; a = Foo() &gt;&gt;&gt; b = Foo() &gt;&gt;&gt; hash(a), hash(b) (-1210747828, -1210747892) </code></pre> <p>As you can see, they are different, as hash() uses object's <code>__hash__</code> method instead of 'normal' hashing algorithms, such as SHA.</p> <p>Given the above, the rational choice is to use the <a href="http://docs.python.org/library/hashlib.html">hashlib</a> module.</p>
84
2009-04-27T14:43:44Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
2,909,550
<p>At a guess, AppEngine is using a 64-bit implementation of Python (-5768830964305142685 won't fit in 32 bits) and your implementation of Python is 32 bits. You can't rely on object hashes being meaningfully comparable between different implementations.</p>
6
2010-05-26T00:58:06Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
3,979,894
<p>The response is absolutely no surprise: in fact </p> <pre><code>In [1]: -5768830964305142685L &amp; 0xffffffff Out[1]: 1934711907L </code></pre> <p>so if you want to get reliable responses <strong>on ASCII strings</strong>, just get the lower 32 bits as <code>uint</code>. The hash function for strings is 32-bit-safe and <em>almost</em> portable.</p> <p>On the other side, you can't rely at all on getting the <code>hash()</code> of any object over which you haven't explicitly defined the <code>__hash__</code> method to be invariant. </p> <p>Over ASCII strings it works just because the hash is calculated on the single characters forming the string, like the following:</p> <pre><code>class string: def __hash__(self): if not self: return 0 # empty value = ord(self[0]) &lt;&lt; 7 for char in self: value = c_mul(1000003, value) ^ ord(char) value = value ^ len(self) if value == -1: value = -2 return value </code></pre> <p>where the <code>c_mul</code> function is the "cyclic" multiplication (without overflow) as in C.</p>
32
2010-10-20T16:02:17Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
5,467,932
<p>Hash results varies between 32bit and 64bit platforms</p> <p>If a calculated hash shall be the same on both platforms consider using</p> <pre><code>def hash32(value): return hash(value) &amp; 0xffffffff </code></pre>
9
2011-03-29T04:36:02Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
8,852,554
<p>What about sign bit?</p> <p>For example:</p> <p>Hex value <code>0xADFE74A5</code> represents unsigned <code>2919134373</code> and signed <code>-1375832923</code>. Currect value must be signed (sign bit = 1) but python converts it as unsigned and we have an incorrect hash value after translation from 64 to 32 bit.</p> <p>Be careful using:</p> <pre><code>def hash32(value): return hash(value) &amp; 0xffffffff </code></pre>
5
2012-01-13T15:04:33Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
9,359,045
<p>This is the hash function that Google uses in production for python 2.5:</p> <pre><code>def c_mul(a, b): return eval(hex((long(a) * b) &amp; (2**64 - 1))[:-1]) def py25hash(self): if not self: return 0 # empty value = ord(self[0]) &lt;&lt; 7 for char in self: value = c_mul(1000003, value) ^ ord(char) value = value ^ len(self) if value == -1: value = -2 if value &gt;= 2**63: value -= 2**64 return value </code></pre>
6
2012-02-20T09:46:14Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
26,106,019
<p>Polynomial hash for strings. <code>1000000009</code> and <code>239</code> are arbitrary prime numbers. Unlikely to have collisions by accident. Modular arithmetic is not very fast, but for preventing collisions this is more reliable than taking it modulo a power of <code>2</code>. Of course, it is easy to find a collision on purpose.</p> <pre><code>mod=1000000009 def hash(s): result=0 for c in s: result = (result * 239 + ord(c)) % mod return result % mod </code></pre>
3
2014-09-29T18:00:59Z
[ "python", "google-app-engine", "hash" ]