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
listlengths
1
5
referencing class methods in class lists in Python
1,351,669
<p>I am writing a class in Python 2.6.2 that contains a lookup table. Most cases are simple enough that the table contains data. Some of the cases are more complex and I want to be able call a function. However, I'm running into some trouble referencing the function.</p> <p>Here's some sample code:</p> <pre><code>class a: lut = [1, 3, 17, [12,34], 5] </code></pre> <p>Where <code>lut</code> is static, and is expected to be constant as well.</p> <p>and now I wan to do the following:</p> <pre><code>class a: def spam0(self): return (some_calculation_based_on_self) def spam1(self): return (a_different_calculation_based_on_self) lut = [1, 3, 17, [12,34], 5, self.spam0 self.spam1] </code></pre> <p>This doesn't compile because <code>self.spam0</code> and <code>self.spam1</code> are undefined. I tried using <code>a.spam</code> but that is also undefined. How can I set <code>lut[5]</code> to return a reference to <code>self.spam</code>?</p> <p><strong>Edit:</strong> This is what I plan to do:</p> <p>(continuing the definition of <code>class a</code>): import inspect</p> <pre><code># continue to somewhere in the definition of class a def __init__(self, param): self.param = param def eggs(self): tmp = lut[param] if (insect.isfunction(tmp)): # if tmp is self.spam() return tmp() # should call it here return tmp </code></pre> <p>So I want to either return a simple value or run some extra code, depending on the parameter.</p> <p><strong>Edit:</strong> <code>lut</code> doesn't have to be a class property, but the methods <code>spam0</code> and <code>spam1</code> do need to access the class members, so they have to belong to the class.</p> <p>I'm not sure that this is the best way to do this. I'm still in the process of working this out.</p>
1
2009-08-29T15:11:45Z
1,369,481
<p>Remember that there's no such thing as static, or constant, in Python. Just make it easy to read. Here's an example which generates a cached version of <code>lut</code> per object:</p> <pre><code>class A(object): def __init__(self): self.__cached_lut = None def spam0(self): return (some_calculation_based_on_self) def spam1(self): return (a_different_calculation_based_on_self) @property def lut(self): if self.__cached_lut is None: self.__cached_lut = [1, 3, 17, [12,34], 5, self.spam0() self.spam1()] return self.__cached_lut a = A() print a.lut </code></pre>
1
2009-09-02T18:49:42Z
[ "python", "class", "reference" ]
How do I form a URL in Django for what I'm doing
1,352,073
<p>Desperate, please help. Will work for food :)</p> <p>I want to be able to have pages at the following URLs, and I want to be able to look them up by their URL (ie, If somebody goes to a certain URL, I want to be able to check for a page there).</p> <pre> mysite.com/somepage/somesubpage/somesubsubpage/ mysite.com/somepage/somesubpage/anothersubpage/ mysite.com/somepage/somesubpage/somesubpage/ mysite.com/somepage/somepage/ </pre> <p>Notice I want to be able to reuse each page's slug (ie, somepage/somepage). Of course each slug will be unique for it's level (ie, cannot have two pages with mysite.com/somepage/other/ and mysite.com/somepage/other/ because they would in essence be the same page). What is a good way to do this. I've tried to store the slug for a page ('somesubpage') in a field called 'slug', and make each slug unique for it's parent page so that the above circumstance can't happen. The problem with this is that if I try to look up a page by it's slug (ie, 'somepage'), and there happens to be a page at mysite.com/other/somepage/ and mysite.com/page/somepage/, how would my application know which one to get (they both have the same slug 'somepage').</p>
1
2009-08-29T18:34:55Z
1,352,086
<p>You need to also store <code>level</code> and <code>parent</code> attributes, so that you can always get the right object.</p> <p>The requirement to store hierarchical data comes up very frequently, and I always recommend <a href="http://code.google.com/p/django-mptt/" rel="nofollow">django-mptt</a>. It's the Django implementation of an efficient algorithm for storing hierarchical data in a database. I've used it on several projects. Basically, as well as storing level and parent, it also stores a <code>left</code> and <code>right</code> for each object, so that it can describe the tree and all its sub-elements uniquely. There are some explanatory links on the project's home page.</p>
2
2009-08-29T18:40:10Z
[ "python", "regex", "django", "django-urls" ]
How do I form a URL in Django for what I'm doing
1,352,073
<p>Desperate, please help. Will work for food :)</p> <p>I want to be able to have pages at the following URLs, and I want to be able to look them up by their URL (ie, If somebody goes to a certain URL, I want to be able to check for a page there).</p> <pre> mysite.com/somepage/somesubpage/somesubsubpage/ mysite.com/somepage/somesubpage/anothersubpage/ mysite.com/somepage/somesubpage/somesubpage/ mysite.com/somepage/somepage/ </pre> <p>Notice I want to be able to reuse each page's slug (ie, somepage/somepage). Of course each slug will be unique for it's level (ie, cannot have two pages with mysite.com/somepage/other/ and mysite.com/somepage/other/ because they would in essence be the same page). What is a good way to do this. I've tried to store the slug for a page ('somesubpage') in a field called 'slug', and make each slug unique for it's parent page so that the above circumstance can't happen. The problem with this is that if I try to look up a page by it's slug (ie, 'somepage'), and there happens to be a page at mysite.com/other/somepage/ and mysite.com/page/somepage/, how would my application know which one to get (they both have the same slug 'somepage').</p>
1
2009-08-29T18:34:55Z
1,352,174
<p>It sounds like you're looking for a CMS app. There's a <a href="http://code.djangoproject.com/wiki/CMSAppsComparison" rel="nofollow">comparison</a> of several Django-based CMS. If you want a full-featured CMS at the center of your project, <a href="http://github.com/digi604/django-cms-2.0/tree/master" rel="nofollow">DjangoCMS 2</a> or <a href="http://code.google.com/p/django-page-cms/" rel="nofollow">django-page-cms</a> might be the right fit. If you prefer a CMS that supports the basic CMS use cases but goes out of your way most of the time <a href="http://github.com/matthiask/feincms/tree/master" rel="nofollow">feincms</a> could be something to look at.</p> <p>edit: incidentally, most of the CMS on the comparision page use django-mptt that Daniel mentions.</p>
0
2009-08-29T19:18:09Z
[ "python", "regex", "django", "django-urls" ]
suppress/redirect stderr when calling python webrowser
1,352,361
<p>I have a python program that opens several urls in seperate tabs in a new browser window, however when I run the program from the command line and open the browser using </p> <pre><code>webbrowser.open_new(url) </code></pre> <p>The stderr from firefox prints to bash. Looking at the docs I can't seem to find a way to redirect or suppress them</p> <p>I have resorted to using </p> <pre><code>browserInstance = subprocess.Popen(['firefox'], stdout=log, stderr=log) </code></pre> <p>Where log is a tempfile &amp; then opening the other tabs with webbrowser.open_new. </p> <p>Is there a way to do this within the webbrowser module? </p>
6
2009-08-29T21:01:51Z
1,352,363
<p>What about sending the output to <code>/dev/null</code> instead of a temporary file?</p>
0
2009-08-29T21:03:52Z
[ "python", "browser", "stderr" ]
suppress/redirect stderr when calling python webrowser
1,352,361
<p>I have a python program that opens several urls in seperate tabs in a new browser window, however when I run the program from the command line and open the browser using </p> <pre><code>webbrowser.open_new(url) </code></pre> <p>The stderr from firefox prints to bash. Looking at the docs I can't seem to find a way to redirect or suppress them</p> <p>I have resorted to using </p> <pre><code>browserInstance = subprocess.Popen(['firefox'], stdout=log, stderr=log) </code></pre> <p>Where log is a tempfile &amp; then opening the other tabs with webbrowser.open_new. </p> <p>Is there a way to do this within the webbrowser module? </p>
6
2009-08-29T21:01:51Z
1,352,392
<p>What is webbrowser.get() giving you?</p> <p>If you do</p> <pre><code> webbrowser.get('firefox').open(url) </code></pre> <p>then you shouldn't see any output. The webbrowser module choses to leave stderr for some browsers - in particular the text browsers, and then ones where it isn't certain. For all UnixBrowsers that have set background to True, no output should be visible.</p>
5
2009-08-29T21:14:34Z
[ "python", "browser", "stderr" ]
suppress/redirect stderr when calling python webrowser
1,352,361
<p>I have a python program that opens several urls in seperate tabs in a new browser window, however when I run the program from the command line and open the browser using </p> <pre><code>webbrowser.open_new(url) </code></pre> <p>The stderr from firefox prints to bash. Looking at the docs I can't seem to find a way to redirect or suppress them</p> <p>I have resorted to using </p> <pre><code>browserInstance = subprocess.Popen(['firefox'], stdout=log, stderr=log) </code></pre> <p>Where log is a tempfile &amp; then opening the other tabs with webbrowser.open_new. </p> <p>Is there a way to do this within the webbrowser module? </p>
6
2009-08-29T21:01:51Z
1,352,478
<p>I think Martin is right about Unix systems, but it looks like things are different on Windows. Is this on a Windows system?</p> <p>On Windows it looks like webbrowser.py is either going to give you a webbrowser.WindowsDefault browser, which opens the url using</p> <pre><code>os.startfile(url) </code></pre> <p>or if Firefox is present it's going to give you a webbrowser.BackgroundBrowser, which starts the browser on Windows using:</p> <pre><code>p = subprocess.Popen(cmdline) </code></pre> <p>It looks like only Unix browsers have the ability to redirect stderr in the webbrowser module. You should be able to find out what browser type you're getting by doing</p> <pre><code>&gt;&gt;&gt; webbrowser.get('firefox') </code></pre> <p>In a Python interactive console.</p>
0
2009-08-29T21:50:51Z
[ "python", "browser", "stderr" ]
Why is Python's enumerate so slow?
1,352,497
<p>Why is "enumerate" slower than "xrange + lst[i]"?</p> <pre> <code> >>> from timeit import Timer >>> lst = [1,2,3,0,1,2]*1000 >>> setup = 'from __main__ import lst' >>> s1 = """ for i in range(len(lst)): elem = lst[i] """ >>> s2 = """ for i in xrange(len(lst)): elem = lst[i] """ >>> s3 = """ for i, v in enumerate(lst): elem = v """ >>> t1 = Timer(s1, setup); t2 = Timer(s2, setup); t3 = Timer(s3, setup) >>> t1.timeit(3000), t2.timeit(3000), t3.timeit(3000) (1.9263118636586494, 1.6119261665937992, 1.9606022553145719) >>> t1.timeit(3000), t2.timeit(3000), t3.timeit(3000) (1.93520258859715, 1.6145745478824836, 1.9529405971988041) </code> </pre> <p>EDIT: I keep in mind why </p> <pre><code>for i, v in enumerate(lst): elem = i, v </code></pre> slower than <pre><code>for i in xrange(len(lst)): elem = i, lst[i] </code></pre>
3
2009-08-29T21:57:28Z
1,352,514
<p>Possibly because you have hobbled <code>enumerate</code>. Try this:</p> <pre><code>&gt;&gt;&gt; s3 = """ for i, elem in enumerate(lst): pass """ </code></pre> <p><strong>Update</strong> Two extra reasons for using <code>timeit</code> at the shell prompt that Alex didn't mention:</p> <p>(1) It does "best of N" for you.<br /> (2) It works out for you how many iterations are necessary to get a meaningful result.</p>
5
2009-08-29T22:05:46Z
[ "python" ]
Why is Python's enumerate so slow?
1,352,497
<p>Why is "enumerate" slower than "xrange + lst[i]"?</p> <pre> <code> >>> from timeit import Timer >>> lst = [1,2,3,0,1,2]*1000 >>> setup = 'from __main__ import lst' >>> s1 = """ for i in range(len(lst)): elem = lst[i] """ >>> s2 = """ for i in xrange(len(lst)): elem = lst[i] """ >>> s3 = """ for i, v in enumerate(lst): elem = v """ >>> t1 = Timer(s1, setup); t2 = Timer(s2, setup); t3 = Timer(s3, setup) >>> t1.timeit(3000), t2.timeit(3000), t3.timeit(3000) (1.9263118636586494, 1.6119261665937992, 1.9606022553145719) >>> t1.timeit(3000), t2.timeit(3000), t3.timeit(3000) (1.93520258859715, 1.6145745478824836, 1.9529405971988041) </code> </pre> <p>EDIT: I keep in mind why </p> <pre><code>for i, v in enumerate(lst): elem = i, v </code></pre> slower than <pre><code>for i in xrange(len(lst)): elem = i, lst[i] </code></pre>
3
2009-08-29T21:57:28Z
1,352,521
<p>If you measure properly you'll see there's essentially no difference (enumerate is microscopically faster than xrange in this example, but well within noise):</p> <pre><code>$ python -mtimeit -s'lst=[1,2,3,0,1,2]*1000' 'for i in xrange(len(lst)): elem=lst[i]' 1000 loops, best of 3: 480 usec per loop $ python -mtimeit -s'lst=[1,2,3,0,1,2]*1000' 'for i, elem in enumerate(lst): pass' 1000 loops, best of 3: 473 usec per loop </code></pre> <p>(BTW, I always recommend using <code>timeit</code> at the shell prompt like this, not within code or at the interpreter prompt as you're doing, just because the output is so nicely formatted and usable, with units of measure of time and everything).</p> <p>In your code, you have an extra assignment in the enumerate case: you assign the list item to v in the <code>for</code> header clause, then again assign <code>v</code> to <code>elem</code>; while in the xrange case you only assign the item once, to <code>elem</code>. In my case I'm also assigning only once in either case, of course; why would you WANT to assign multiple times anyway?! Whatever you're doing with <code>elem</code> and <code>i</code> in the body of the loop you can do it identically in the two forms I'm measuring, just without the redundancy that your enumerate case has.</p>
14
2009-08-29T22:09:07Z
[ "python" ]
Why does ActivePython exist?
1,352,528
<p>What's ActivePython actually about? </p> <p>From <a href="http://www.activestate.com/activepython/features/">what I've read</a> it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, sqlite3, Tkinter, ElementTree, ctypes, multiprocessing) are part of core Python distribution. </p> <p>Next up, the tag-line "ActivePython is the industry-standard Python distribution", isn't core Python distribution "industry-standard" (whatever that means?)? </p> <p>And the weirdest thing, is that ActiveState bundles it with crappy PythonWin, and not their own most-awesome Python editor/IDE, Komodo. What gives?</p> <p>I actually never got to installing ActivePython, so maybe I don't know something, but it seems pretty irrelevant, and I see the name quite often on forums or here.</p>
63
2009-08-29T22:12:56Z
1,352,533
<p>The main feature is that you can buy a paid support contract for it.</p> <p>Why does Red Hat Enterprise Linux exist when you can compile everything yourself? 8-)</p> <p>For many businesses, the combination of proven Open Source software <em>and</em> a support contract from people who build, package and test that software, is an excellent proposition.</p>
28
2009-08-29T22:17:13Z
[ "python", "activestate", "activepython", "rationale" ]
Why does ActivePython exist?
1,352,528
<p>What's ActivePython actually about? </p> <p>From <a href="http://www.activestate.com/activepython/features/">what I've read</a> it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, sqlite3, Tkinter, ElementTree, ctypes, multiprocessing) are part of core Python distribution. </p> <p>Next up, the tag-line "ActivePython is the industry-standard Python distribution", isn't core Python distribution "industry-standard" (whatever that means?)? </p> <p>And the weirdest thing, is that ActiveState bundles it with crappy PythonWin, and not their own most-awesome Python editor/IDE, Komodo. What gives?</p> <p>I actually never got to installing ActivePython, so maybe I don't know something, but it seems pretty irrelevant, and I see the name quite often on forums or here.</p>
63
2009-08-29T22:12:56Z
1,352,539
<p>It's a packaging, or "distribution", of Python, with some extras -- not (anywhere) quite as "Sumo" as Enthought's HUGE distro of "Python plus everything", but still in a similar vein (and it first appeared much earlier).</p> <p>I don't think you're missing anything in particular, except perhaps the fact that David Ascher (Python enthusiast and my coauthor in the Python Cookbook) used to be CTO at ActiveState (and so no doubt internally pushed Python to go with other dynamic languages ActiveState focuses on) but he's gone now (he's CEO at the Mozilla-owned firm that deals with email and similar forms of communication -- ThunderBird and the like, in terms of programs).</p> <p>No doubt some firms prefer to purchase a distribution with commercially available support contracts, like ActivePython, just because that's the way some purchasing departments in several enterprises (and/or their IT depts) are used to work. Unless you care about such issues, I don't think you're missing anything by giving ActiveState's Python distro a pass;-). [[I feel similarly about costly Enterprise distros of Linux, vs. Debian or Ubuntu or the like -- but then I'm not in Purchasing, nor in an IT department, nor do I work for a very traditional enterprise anyway;-)]]</p>
42
2009-08-29T22:20:10Z
[ "python", "activestate", "activepython", "rationale" ]
Why does ActivePython exist?
1,352,528
<p>What's ActivePython actually about? </p> <p>From <a href="http://www.activestate.com/activepython/features/">what I've read</a> it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, sqlite3, Tkinter, ElementTree, ctypes, multiprocessing) are part of core Python distribution. </p> <p>Next up, the tag-line "ActivePython is the industry-standard Python distribution", isn't core Python distribution "industry-standard" (whatever that means?)? </p> <p>And the weirdest thing, is that ActiveState bundles it with crappy PythonWin, and not their own most-awesome Python editor/IDE, Komodo. What gives?</p> <p>I actually never got to installing ActivePython, so maybe I don't know something, but it seems pretty irrelevant, and I see the name quite often on forums or here.</p>
63
2009-08-29T22:12:56Z
1,352,541
<p>ActiveState has a long tradition contributing Windows support to Python, Tcl, and Perl: by hiring key developers (like Mark Hammond, for some time), by fixing bugs specific to Windows, and having employees contribute fixes back, and by being sponsors of the Python Software Foundation.</p> <p>While it is true that the distribution they produce is fairly similar to mine, it's as RichieHindle says: you can get paid support from ActiveState (but not from me).</p>
31
2009-08-29T22:21:36Z
[ "python", "activestate", "activepython", "rationale" ]
Why does ActivePython exist?
1,352,528
<p>What's ActivePython actually about? </p> <p>From <a href="http://www.activestate.com/activepython/features/">what I've read</a> it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, sqlite3, Tkinter, ElementTree, ctypes, multiprocessing) are part of core Python distribution. </p> <p>Next up, the tag-line "ActivePython is the industry-standard Python distribution", isn't core Python distribution "industry-standard" (whatever that means?)? </p> <p>And the weirdest thing, is that ActiveState bundles it with crappy PythonWin, and not their own most-awesome Python editor/IDE, Komodo. What gives?</p> <p>I actually never got to installing ActivePython, so maybe I don't know something, but it seems pretty irrelevant, and I see the name quite often on forums or here.</p>
63
2009-08-29T22:12:56Z
1,354,126
<p>I've been using ActivePerl for years and when I made the switch to Python, I very naturally downloaded ActivePython. Never had any problems with the Active* distributions - they're robust, come with a few useful libraries that the vanilla core Python doesn't have. They also come bundled with a .CHM Python documentation compilation that's very useful.</p>
8
2009-08-30T15:40:47Z
[ "python", "activestate", "activepython", "rationale" ]
Why does ActivePython exist?
1,352,528
<p>What's ActivePython actually about? </p> <p>From <a href="http://www.activestate.com/activepython/features/">what I've read</a> it's just standard Python with openssl and pyWin32 (on Win). No big deal I guess, I could install them in matter of minutes, and most people don't need them anyway. All other mentioned libraries (zlib, bzip2, sqlite3, Tkinter, ElementTree, ctypes, multiprocessing) are part of core Python distribution. </p> <p>Next up, the tag-line "ActivePython is the industry-standard Python distribution", isn't core Python distribution "industry-standard" (whatever that means?)? </p> <p>And the weirdest thing, is that ActiveState bundles it with crappy PythonWin, and not their own most-awesome Python editor/IDE, Komodo. What gives?</p> <p>I actually never got to installing ActivePython, so maybe I don't know something, but it seems pretty irrelevant, and I see the name quite often on forums or here.</p>
63
2009-08-29T22:12:56Z
1,401,911
<p>Here is an email to python-list I wrote on this a long while ago:</p> <p><a href="https://mail.python.org/pipermail/python-list/2007-July/456660.html" rel="nofollow">https://mail.python.org/pipermail/python-list/2007-July/456660.html</a> </p> <p>Mostly those details are still true. Also, all the other responses I've seen to this question are fair.</p> <p>Note that as of release 2.6.3.7 ActivePython includes <a href="http://code.activestate.com/pypm/" rel="nofollow">PyPM</a> (similar to PPM for ActivePerl) to help with installing Python packages -- the hoped for benefit over "easy_install" and "pip" (and others) to be the installation of popular binary packages.</p>
5
2009-09-09T20:30:47Z
[ "python", "activestate", "activepython", "rationale" ]
Is there any way to make an asynchronous function call from Python [Django]?
1,352,678
<p>I am creating a Django application that does various long computations with uploaded files. I don't want to make the user wait for the file to be handled - I just want to show the user a page reading something like 'file is being parsed'.</p> <p>How can I make an asynchronous function call from a view?</p> <p>Something that may look like that:</p> <pre><code>def view(request): ... if form.is_valid(): form.save() async_call(handle_file) return render_to_response(...) </code></pre>
4
2009-08-29T23:59:53Z
1,352,686
<p>Unless you specifically need to use a separate process, which seems to be the gist of the other questions S.Lott is indicating as duplicate of yours, the <code>threading</code> module from the Python standard library (documented <a href="http://docs.python.org/library/threading.html" rel="nofollow">here</a>) may offer the simplest solution. Just make sure that <code>handle_file</code> is not accessing any globals that might get modified, nor especially modifying any globals itself; ideally it should communicate with the rest of your process only through <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a> instances; etc, etc, all the usual recommendations about threading;-).</p>
0
2009-08-30T00:05:55Z
[ "python", "django", "asynchronous" ]
Is there any way to make an asynchronous function call from Python [Django]?
1,352,678
<p>I am creating a Django application that does various long computations with uploaded files. I don't want to make the user wait for the file to be handled - I just want to show the user a page reading something like 'file is being parsed'.</p> <p>How can I make an asynchronous function call from a view?</p> <p>Something that may look like that:</p> <pre><code>def view(request): ... if form.is_valid(): form.save() async_call(handle_file) return render_to_response(...) </code></pre>
4
2009-08-29T23:59:53Z
1,353,400
<p>Rather than trying to manage this via subprocesses or threads, I recommend you separate it out completely. There are two approaches: the first is to set a flag in a database table somewhere, and have a cron job running regularly that checks the flag and performs the required operation.</p> <p>The second option is to use a message queue. Your file upload process sends a message on the queue, and a separate listener receives the message and does what's needed. I've used RabbitMQ for this sort of thing, but others are available.</p> <p>Either way, your user doesn't have to wait for the process to finish, and you don't have to worry about managing subprocesses.</p>
5
2009-08-30T08:02:16Z
[ "python", "django", "asynchronous" ]
Is there any way to make an asynchronous function call from Python [Django]?
1,352,678
<p>I am creating a Django application that does various long computations with uploaded files. I don't want to make the user wait for the file to be handled - I just want to show the user a page reading something like 'file is being parsed'.</p> <p>How can I make an asynchronous function call from a view?</p> <p>Something that may look like that:</p> <pre><code>def view(request): ... if form.is_valid(): form.save() async_call(handle_file) return render_to_response(...) </code></pre>
4
2009-08-29T23:59:53Z
1,355,722
<p>I have tried to do the same and failed after multiple attempt due of the nature of django and other asynchronous call.</p> <p>The solution I have come up which could be a bit over the top for you is to have another asynchronous server in the background processing messages queues from the web request and throwing some chunked javascript which get parsed directly from the browser in an asynchronous way (ie: ajax).</p> <p>Everything is made transparent for the end user via mod_proxy setting.</p>
2
2009-08-31T03:57:50Z
[ "python", "django", "asynchronous" ]
Is there any way to make an asynchronous function call from Python [Django]?
1,352,678
<p>I am creating a Django application that does various long computations with uploaded files. I don't want to make the user wait for the file to be handled - I just want to show the user a page reading something like 'file is being parsed'.</p> <p>How can I make an asynchronous function call from a view?</p> <p>Something that may look like that:</p> <pre><code>def view(request): ... if form.is_valid(): form.save() async_call(handle_file) return render_to_response(...) </code></pre>
4
2009-08-29T23:59:53Z
4,665,597
<p>threading will break runserver if I'm not mistaken. I've had good luck with multiprocess in request handlers with mod_wsgi and runserver. Maybe someone can enlighten me as to why this is bad:</p> <pre><code>def _bulk_action(action, objs): # mean ponies here def bulk_action(request, t): ... objs = model.objects.filter(pk__in=pks) if request.method == 'POST': objs.update(is_processing=True) from multiprocessing import Process p = Process(target=_bulk_action,args=(action,objs)) p.start() return HttpResponseRedirect(next_url) context = {'t': t, 'action': action, 'objs': objs, 'model': model} return render_to_response(...) </code></pre> <p><a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">http://docs.python.org/library/multiprocessing.html</a></p> <p>New in 2.6</p>
0
2011-01-12T05:22:45Z
[ "python", "django", "asynchronous" ]
Python script performance as a background process
1,352,760
<p>Im in the process of writing a python script to act as a "glue" between an application and some external devices. The script itself is quite straight forward and has three distinct processes:</p> <ol> <li>Request data (from a socket connection, via UDP)</li> <li>Receive response (from a socket connection, via UDP)</li> <li>Process response and make data available to 3rd party application</li> </ol> <p>However, this will be done repetitively, and for several (+/-200 different) devices. So once its reached device #200, it would start requesting data from device #001 again. My main concern here is not to bog down the processor whilst executing the script. </p> <p>UPDATE: I am using three threads to do the above, one thread for each of the above processes. The request/response is asynchronous as each response contains everything i need to be able to process it (including the senders details).</p> <p>Is there any way to allow the script to run in the background and consume as little system resources as possible while doing its thing? This will be running on a windows 2003 machine.</p> <p>Any advice would be appreciated.</p>
0
2009-08-30T00:58:11Z
1,352,773
<p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> -- the best async framework for Python -- would allow you do perform these tasks with the minimal hogging of system resources, most especially though not exclusively if you want to process several devices "at once" rather than just round-robin among the several hundreds (the latter might result in too long a cycle time, especially if there's a risk that some device will have very delayed answer or even fail to answer once in a while and result in a "timeout"; as a rule of thumb I'd suggest having at least half a dozens devices "in play" at any given time to avoid this excessive-delay risk).</p>
4
2009-08-30T01:07:20Z
[ "python", "performance", "process", "background" ]
Python script performance as a background process
1,352,760
<p>Im in the process of writing a python script to act as a "glue" between an application and some external devices. The script itself is quite straight forward and has three distinct processes:</p> <ol> <li>Request data (from a socket connection, via UDP)</li> <li>Receive response (from a socket connection, via UDP)</li> <li>Process response and make data available to 3rd party application</li> </ol> <p>However, this will be done repetitively, and for several (+/-200 different) devices. So once its reached device #200, it would start requesting data from device #001 again. My main concern here is not to bog down the processor whilst executing the script. </p> <p>UPDATE: I am using three threads to do the above, one thread for each of the above processes. The request/response is asynchronous as each response contains everything i need to be able to process it (including the senders details).</p> <p>Is there any way to allow the script to run in the background and consume as little system resources as possible while doing its thing? This will be running on a windows 2003 machine.</p> <p>Any advice would be appreciated.</p>
0
2009-08-30T00:58:11Z
1,352,777
<p>If you are using blocking I/O to your devices, then the script won't consume any processor while waiting for the data. How much processor you use depends on what sorts of computation you are doing with the data.</p>
5
2009-08-30T01:08:15Z
[ "python", "performance", "process", "background" ]
Optional get parameters in django?
1,352,834
<p>Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.</p> <p>Here's what I have currently:</p> <p><strong>Pattern</strong></p> <pre><code>(r'^so/(?P&lt;required&gt;\d+)/?(?P&lt;optional&gt;(.*))/?$', 'myapp.so') </code></pre> <p><strong>View</strong></p> <pre><code>def so(request, required, optional): </code></pre> <p>If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.</p> <p>How can I accomplish this?</p> <p>Thanks, Pete</p>
22
2009-08-30T01:43:34Z
1,352,841
<p>I generally make two patterns with a <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns">named url</a>:</p> <pre><code>url(r'^so/(?P&lt;required&gt;\d+)/$', 'myapp.so', name='something'), url(r'^so/(?P&lt;required&gt;\d+)/(?P&lt;optional&gt;.*)/$', 'myapp.so', name='something_else'), </code></pre>
34
2009-08-30T01:48:34Z
[ "python", "regex", "django" ]
Optional get parameters in django?
1,352,834
<p>Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.</p> <p>Here's what I have currently:</p> <p><strong>Pattern</strong></p> <pre><code>(r'^so/(?P&lt;required&gt;\d+)/?(?P&lt;optional&gt;(.*))/?$', 'myapp.so') </code></pre> <p><strong>View</strong></p> <pre><code>def so(request, required, optional): </code></pre> <p>If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.</p> <p>How can I accomplish this?</p> <p>Thanks, Pete</p>
22
2009-08-30T01:43:34Z
1,352,842
<p>Why not have two patterns:</p> <pre><code>(r'^so/(?P&lt;required&gt;\d+)/(?P&lt;optional&gt;.*)/$', view='myapp.so', name='optional'), (r'^so/(?P&lt;required&gt;\d+)/$', view='myapp.so', kwargs={'optional':None}, name='required'), </code></pre>
1
2009-08-30T01:49:33Z
[ "python", "regex", "django" ]
Optional get parameters in django?
1,352,834
<p>Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.</p> <p>Here's what I have currently:</p> <p><strong>Pattern</strong></p> <pre><code>(r'^so/(?P&lt;required&gt;\d+)/?(?P&lt;optional&gt;(.*))/?$', 'myapp.so') </code></pre> <p><strong>View</strong></p> <pre><code>def so(request, required, optional): </code></pre> <p>If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.</p> <p>How can I accomplish this?</p> <p>Thanks, Pete</p>
22
2009-08-30T01:43:34Z
1,353,956
<p>Others have demonstrated the way to handle this with two separate named URL patterns. If the repetition of part of the URL pattern bothers you, it's possible to get rid of it by using include():</p> <pre><code>url(r'^so/(?P&lt;required&gt;\d+)/', include('myapp.required_urls')) </code></pre> <p>And then add a required_urls.py file with:</p> <pre><code>url(r'^$', 'myapp.so', name='something') url(r'^(?P&lt;optional&gt;.+)/$', 'myapp.so', name='something_else') </code></pre> <p>Normally I wouldn't consider this worth it unless there's a common prefix for quite a number of URLs (certainly more than two).</p>
5
2009-08-30T14:10:49Z
[ "python", "regex", "django" ]
Optional get parameters in django?
1,352,834
<p>Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.</p> <p>Here's what I have currently:</p> <p><strong>Pattern</strong></p> <pre><code>(r'^so/(?P&lt;required&gt;\d+)/?(?P&lt;optional&gt;(.*))/?$', 'myapp.so') </code></pre> <p><strong>View</strong></p> <pre><code>def so(request, required, optional): </code></pre> <p>If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.</p> <p>How can I accomplish this?</p> <p>Thanks, Pete</p>
22
2009-08-30T01:43:34Z
6,345,264
<p>in views.py you do simple thing.</p> <pre><code>def so(request, required, optional=None): </code></pre> <p>And when you dont get <strong>optional</strong> param in url string it will be None in your code. </p> <p>Simple and elegant :)</p>
-1
2011-06-14T14:36:02Z
[ "python", "regex", "django" ]
Optional get parameters in django?
1,352,834
<p>Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.</p> <p>Here's what I have currently:</p> <p><strong>Pattern</strong></p> <pre><code>(r'^so/(?P&lt;required&gt;\d+)/?(?P&lt;optional&gt;(.*))/?$', 'myapp.so') </code></pre> <p><strong>View</strong></p> <pre><code>def so(request, required, optional): </code></pre> <p>If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.</p> <p>How can I accomplish this?</p> <p>Thanks, Pete</p>
22
2009-08-30T01:43:34Z
8,981,132
<p>Django urls are polymorphic:</p> <pre><code>url(r'^so/(?P&lt;required&gt;\d+)/$', 'myapp.so', name='sample_view'), url(r'^so/(?P&lt;required&gt;\d+)/(?P&lt;optional&gt;.*)/$', 'myapp.so', name='sample_view'), </code></pre> <p>its obious that you have to make your views like this:</p> <pre><code>def sample_view(request, required, optional = None): </code></pre> <p>so you can call it with the same name and it would work work url resolver fine. However be aware that you cant pass None as the required argument and expect that it will get you to the regexp without argument:</p> <p><strong>Wrong:</strong> </p> <pre><code>{% url sample_view required optional %} </code></pre> <p><strong>Correct:</strong></p> <pre><code>{% if optional %} {% url sample_view required optional %} {% else %} {% url sample_view required %} {% endif %} </code></pre> <p>I dont know whether this is documented anywhere - I have discovered it by accident - I forgot to rewrite the url names and it was working anyway :)</p>
16
2012-01-24T01:46:59Z
[ "python", "regex", "django" ]
Optional get parameters in django?
1,352,834
<p>Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.</p> <p>Here's what I have currently:</p> <p><strong>Pattern</strong></p> <pre><code>(r'^so/(?P&lt;required&gt;\d+)/?(?P&lt;optional&gt;(.*))/?$', 'myapp.so') </code></pre> <p><strong>View</strong></p> <pre><code>def so(request, required, optional): </code></pre> <p>If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.</p> <p>How can I accomplish this?</p> <p>Thanks, Pete</p>
22
2009-08-30T01:43:34Z
16,558,729
<p>For anyone who is still having this problem. I use Django 1.5 (updated: using 1.8) and it's still working fine. </p> <p>I use:</p> <blockquote> <p>urls.py url(r'^(?P\d+)/start/+(?P\d+)?', views.restart, name='restart')</p> </blockquote> <p>Then when I want to have the two urls</p> <blockquote> <p>/1/start/2 and /1/start</p> </blockquote> <p>I use:</p> <blockquote> <p>{% url ':start' app.id %} {% url ':start' app.id server.id %}</p> </blockquote> <p>This will create the urls</p> <blockquote> <p>/1/start/2 and /1/start/ &lt;- notice the slash.</p> </blockquote> <p>If you create a url manually you have to keep the / in mind.</p> <p>I hoop this helps anyone!</p>
1
2013-05-15T07:00:18Z
[ "python", "regex", "django" ]
Optional get parameters in django?
1,352,834
<p>Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.</p> <p>Here's what I have currently:</p> <p><strong>Pattern</strong></p> <pre><code>(r'^so/(?P&lt;required&gt;\d+)/?(?P&lt;optional&gt;(.*))/?$', 'myapp.so') </code></pre> <p><strong>View</strong></p> <pre><code>def so(request, required, optional): </code></pre> <p>If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.</p> <p>How can I accomplish this?</p> <p>Thanks, Pete</p>
22
2009-08-30T01:43:34Z
26,871,543
<p>Depending on your use case, you may simply want to pass a url parameter like so:</p> <pre><code>url/?parameter=foo </code></pre> <p>call this in your view:</p> <pre><code>request.REQUEST.get('parameter') </code></pre> <p>this will return 'foo'</p>
-2
2014-11-11T18:10:06Z
[ "python", "regex", "django" ]
Nice copying from Python Interpreter
1,352,886
<p>When I am working with a Python Interpreter, I always find it a pain to try and copy code from it because it inserts all of these >>> and ...</p> <p>Is there a Python interpreter that will let me copy code, without having to deal with this? Or alternatively, is there a way to clean the output.</p> <p>Additionally, sometimes I would like to paste code in, but the code is indented. Is there any console that can automatically indent it instead of throwing an error?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/647142/why-can-i-not-paste-the-output-of-pythons-repl-without-manual-editing">Why can I not paste the output of Pythons REPL without manual-editing?</a></li> </ul>
6
2009-08-30T02:18:40Z
1,352,900
<p>Decent text editors such as Notepad++ can make global search and replace operations that can replace >>> with nothing.</p>
0
2009-08-30T02:23:43Z
[ "python" ]
Nice copying from Python Interpreter
1,352,886
<p>When I am working with a Python Interpreter, I always find it a pain to try and copy code from it because it inserts all of these >>> and ...</p> <p>Is there a Python interpreter that will let me copy code, without having to deal with this? Or alternatively, is there a way to clean the output.</p> <p>Additionally, sometimes I would like to paste code in, but the code is indented. Is there any console that can automatically indent it instead of throwing an error?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/647142/why-can-i-not-paste-the-output-of-pythons-repl-without-manual-editing">Why can I not paste the output of Pythons REPL without manual-editing?</a></li> </ul>
6
2009-08-30T02:18:40Z
1,352,904
<p>WingIDE from <a href="http://www.wingware.com" rel="nofollow">Wingware</a> will let you evaluate any chunk of code in a separate interpreter window.</p>
3
2009-08-30T02:24:38Z
[ "python" ]
Nice copying from Python Interpreter
1,352,886
<p>When I am working with a Python Interpreter, I always find it a pain to try and copy code from it because it inserts all of these >>> and ...</p> <p>Is there a Python interpreter that will let me copy code, without having to deal with this? Or alternatively, is there a way to clean the output.</p> <p>Additionally, sometimes I would like to paste code in, but the code is indented. Is there any console that can automatically indent it instead of throwing an error?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/647142/why-can-i-not-paste-the-output-of-pythons-repl-without-manual-editing">Why can I not paste the output of Pythons REPL without manual-editing?</a></li> </ul>
6
2009-08-30T02:18:40Z
1,352,909
<p><a href="http://ipython.scipy.org/moin/" rel="nofollow">IPython</a> will let you paste Python code with leading indents without giving you an IndentationError. You can also <a href="http://ipython.scipy.org/doc/manual/html/config/customization.html#fine-tuning-your-prompt" rel="nofollow">change your prompts</a> to remove >>> and ... if you wish.</p>
1
2009-08-30T02:27:43Z
[ "python" ]
Nice copying from Python Interpreter
1,352,886
<p>When I am working with a Python Interpreter, I always find it a pain to try and copy code from it because it inserts all of these >>> and ...</p> <p>Is there a Python interpreter that will let me copy code, without having to deal with this? Or alternatively, is there a way to clean the output.</p> <p>Additionally, sometimes I would like to paste code in, but the code is indented. Is there any console that can automatically indent it instead of throwing an error?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/647142/why-can-i-not-paste-the-output-of-pythons-repl-without-manual-editing">Why can I not paste the output of Pythons REPL without manual-editing?</a></li> </ul>
6
2009-08-30T02:18:40Z
1,352,914
<p>I have a vim macro to "paste while cleaning interpreter prompts and sample output [[==stuff NOT preceded by prompts" and I'll be happy to share it if vim is what you're using. Any editor or IDE worth that name will of course be similarly easy to program for such purposes!</p>
1
2009-08-30T02:28:51Z
[ "python" ]
Nice copying from Python Interpreter
1,352,886
<p>When I am working with a Python Interpreter, I always find it a pain to try and copy code from it because it inserts all of these >>> and ...</p> <p>Is there a Python interpreter that will let me copy code, without having to deal with this? Or alternatively, is there a way to clean the output.</p> <p>Additionally, sometimes I would like to paste code in, but the code is indented. Is there any console that can automatically indent it instead of throwing an error?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/647142/why-can-i-not-paste-the-output-of-pythons-repl-without-manual-editing">Why can I not paste the output of Pythons REPL without manual-editing?</a></li> </ul>
6
2009-08-30T02:18:40Z
1,352,991
<p>IPython lets you show, save and edit your command history, for example to show the first three commands of your session without line numbers you'd type <code>%hist -n 1 4</code>.</p>
4
2009-08-30T03:17:51Z
[ "python" ]
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
1,352,922
<p>Anyone know this? I've never been able to find an answer.</p>
57
2009-08-30T02:30:30Z
1,352,927
<p>It finds 'python' also in /usr/local/bin, ~/bin, /opt/bin, ... or wherever it may hide.</p>
5
2009-08-30T02:31:52Z
[ "python", "bash" ]
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
1,352,922
<p>Anyone know this? I've never been able to find an answer.</p>
57
2009-08-30T02:30:30Z
1,352,932
<p>You may find this post to be of interest: <a href="http://mail.python.org/pipermail/python-list/2008-May/661514.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2008-May/661514.html</a></p> <p>This may be a better explanation: <a href="http://mail.python.org/pipermail/tutor/2007-June/054816.html" rel="nofollow">http://mail.python.org/pipermail/tutor/2007-June/054816.html</a></p>
3
2009-08-30T02:34:02Z
[ "python", "bash" ]
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
1,352,922
<p>Anyone know this? I've never been able to find an answer.</p>
57
2009-08-30T02:30:30Z
1,352,938
<p>If you're prone to installing python in various and interesting places on your PATH (as in <code>$PATH</code> in typical Unix shells, <code>%PATH</code> on typical Windows ones), using <code>/usr/bin/env</code> will accomodate your whim (well, in Unix-like environments at least) while going directly to <code>/usr/bin/python</code> won't. But losing control of what version of Python your scripts run under is no unalloyed bargain... if you look at my code you're more likely to see it start with, e.g., <code>#!/usr/local/bin/python2.5</code> rather than with an open and accepting <code>#!/usr/bin/env python</code> -- assuming the script is important I like to ensure it's run with the specific version I have tested and developed it with, NOT a semi-random one;-).</p>
60
2009-08-30T02:36:51Z
[ "python", "bash" ]
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
1,352,922
<p>Anyone know this? I've never been able to find an answer.</p>
57
2009-08-30T02:30:30Z
1,352,939
<p>From <a href="http://en.wikipedia.org/wiki/Shebang_%28Unix%29">wikipedia</a></p> <blockquote> <p>Shebangs specify absolute paths to system executables; this can cause problems on systems which have non-standard file system layouts</p> <p>Often, the program /usr/bin/env can be used to circumvent this limitation</p> </blockquote>
23
2009-08-30T02:36:53Z
[ "python", "bash" ]
Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
1,352,922
<p>Anyone know this? I've never been able to find an answer.</p>
57
2009-08-30T02:30:30Z
1,352,941
<p>it finds the python executable in your environment and uses that. it's more portable because python may not always be in /usr/bin/python. env is always located in /usr/bin.</p>
9
2009-08-30T02:37:13Z
[ "python", "bash" ]
Multiprocessing debug techniques
1,352,980
<p>I'm having trouble debugging a multi-process application (specifically using a process pool in python's multiprocessing module). I have an apparent deadlock and I do not know what is causing it. The stack trace is not sufficient to describe the issue, as it only displays code in the multiprocessing module.</p> <p>Are there any python tools, or otherwise general techniques used to debug deadlocks?</p>
15
2009-08-30T03:06:04Z
1,353,037
<p>Yah, debugging deadlocks is fun. You can set the logging level to be higher -- see <a href="http://docs.python.org/library/multiprocessing.html">the Python documentation</a> for a description of it, but really quickly:</p> <pre><code>import multiprocessing, logging logger = multiprocessing.log_to_stderr() logger.setLevel(multiprocessing.SUBDEBUG) </code></pre> <p>Also, add logging for anything in your code that deals with a resource or whatnot that might be in contention. Finally, shot in the dark: spawning off child processes during an import might cause a problem.</p>
28
2009-08-30T03:58:08Z
[ "python", "debugging", "deadlock", "multiprocessing" ]
Multiprocessing debug techniques
1,352,980
<p>I'm having trouble debugging a multi-process application (specifically using a process pool in python's multiprocessing module). I have an apparent deadlock and I do not know what is causing it. The stack trace is not sufficient to describe the issue, as it only displays code in the multiprocessing module.</p> <p>Are there any python tools, or otherwise general techniques used to debug deadlocks?</p>
15
2009-08-30T03:06:04Z
1,353,520
<p>In order to <em>avoid</em> deadlocks in the first place, learning good practices is useful, as parallel processing is indeed quite subtle. The (free) <a href="http://www.greenteapress.com/semaphores/" rel="nofollow">Little Book of Semaphores</a> can be a very enjoyable read!</p>
3
2009-08-30T09:46:54Z
[ "python", "debugging", "deadlock", "multiprocessing" ]
RPC for multiprocessing, design issues
1,353,055
<p>Hey everyone, what's a good way to do rpc across multiprocessing.Process'es ?</p> <p>I am also open to design advise on the following architecture: Process A * 10, Process B * 1. Each process A has to check with proces B on whether a particular item needs to be queried. </p> <p>So I was thinking of implementing multiprocessing.Pipe() object for all the As, and then have B listen to each of them. However, I realize that Multiprocessing.Pipe.recv is BLOCKING. so I don't really know how I can go about doing this. (if I use a loop to check which one has things sent through the other end that the loop will be blocked).</p> <p>There are suggestions for me to use twisted, but I am not sure how I should go about doing this in twisted: Should I create a defer on each pipe.handler from all the processes A and then when recv() receives something it goes on and complete a certain routine? I know personally twisted does not mix well with multiprocessing, but I have done some testing on twisted that are child processes of an multiprocessing implementation and I think this time it's workable.</p> <p>Any recommendations?</p>
0
2009-08-30T04:09:23Z
1,353,089
<p>Personally, I always tend to lean towards socket-based RPC, because that frees me from the confine of a single node if and when I need to expand more. Twisted offers a great way to handle socket-based communications, but of course there are other alternatives too. HTTP 1.1 is a great "transport" layer to use for such purposes, as it typically passes firewalls easily, is easily migrated into HTTPS if and when you need security, too. As for payloads over it, I may be somewhat of an eccentric for favoring JSON, but I've had a great time with it compared with XML or many other encodings. Though I have to admit that, now that Google's <a href="http://en.wikipedia.org/wiki/Protocol%5FBuffers" rel="nofollow">protobufs</a> have been open-sourced, they're tempting too (especially as they ARE what we use internally, almost exclusively -- one sure gets used to them;-). Pity no specific RPC implementation of protobufs over HTTP has been open-sourced... but it's not THAT hard to cook up one for yourself;-).</p>
6
2009-08-30T04:34:10Z
[ "python", "rpc", "multiprocessing" ]
RPC for multiprocessing, design issues
1,353,055
<p>Hey everyone, what's a good way to do rpc across multiprocessing.Process'es ?</p> <p>I am also open to design advise on the following architecture: Process A * 10, Process B * 1. Each process A has to check with proces B on whether a particular item needs to be queried. </p> <p>So I was thinking of implementing multiprocessing.Pipe() object for all the As, and then have B listen to each of them. However, I realize that Multiprocessing.Pipe.recv is BLOCKING. so I don't really know how I can go about doing this. (if I use a loop to check which one has things sent through the other end that the loop will be blocked).</p> <p>There are suggestions for me to use twisted, but I am not sure how I should go about doing this in twisted: Should I create a defer on each pipe.handler from all the processes A and then when recv() receives something it goes on and complete a certain routine? I know personally twisted does not mix well with multiprocessing, but I have done some testing on twisted that are child processes of an multiprocessing implementation and I think this time it's workable.</p> <p>Any recommendations?</p>
0
2009-08-30T04:09:23Z
1,353,698
<p>I'm satisfied with using REST-ful transaction design.</p> <p>This means using HTTP instead of pipes.</p> <p>If Process B has a queue of things for the various Process A's to do, it would work like this.</p> <p>Process B is an HTTP server, with RESTful URI's that handle queries from process A's. B is implemented using Python <a href="http://docs.python.org/library/wsgiref.html" rel="nofollow">wsgiref</a> or <a href="http://werkzeug.pocoo.org/" rel="nofollow">werkzeug</a> or some other WSGI implementation.</p> <p>Mostly, B responds to GET requests from A. Each GET request takes the next thing off the queue and responds with it. Since B will have multiple concurrent requests, some kind of single-threaded queue is essential. The easiest way to assure this is to assure that the WSGI server is single-threaded. Each request is relatively fast, so single-threaded processing works out quite nicely.</p> <p>B has to have it's queue loaded, so it probably also responds to POST requests to enqueue things, too.</p> <p>Process A is an HTTP client, making requests of the RESTful URI's that Process B provides. A is implemented using <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> to make requests of B. A makes GET requests of B to get the next thing from the queue.</p>
1
2009-08-30T11:41:22Z
[ "python", "rpc", "multiprocessing" ]
RPC for multiprocessing, design issues
1,353,055
<p>Hey everyone, what's a good way to do rpc across multiprocessing.Process'es ?</p> <p>I am also open to design advise on the following architecture: Process A * 10, Process B * 1. Each process A has to check with proces B on whether a particular item needs to be queried. </p> <p>So I was thinking of implementing multiprocessing.Pipe() object for all the As, and then have B listen to each of them. However, I realize that Multiprocessing.Pipe.recv is BLOCKING. so I don't really know how I can go about doing this. (if I use a loop to check which one has things sent through the other end that the loop will be blocked).</p> <p>There are suggestions for me to use twisted, but I am not sure how I should go about doing this in twisted: Should I create a defer on each pipe.handler from all the processes A and then when recv() receives something it goes on and complete a certain routine? I know personally twisted does not mix well with multiprocessing, but I have done some testing on twisted that are child processes of an multiprocessing implementation and I think this time it's workable.</p> <p>Any recommendations?</p>
0
2009-08-30T04:09:23Z
1,569,247
<p>Have you looked at MPI? <a href="http://en.wikipedia.org/wiki/Message%5FPassing%5FInterface" rel="nofollow">http://en.wikipedia.org/wiki/Message%5FPassing%5FInterface</a>.</p> <p>It is broadly available on UNIX/Linux/etc. I believe it can be had on Windows. Basically it provides all the plumbing that you'll have to build on top of RPC mechanisms, and it has many years of development and refinement behind it. It is a spec for an API, originally done in C so works with C++ too, and there are Python implementations of it out there too.</p>
0
2009-10-14T21:57:29Z
[ "python", "rpc", "multiprocessing" ]
Python+Django social network open source projects
1,353,097
<p>I'm looking for some open source, free to change and use project written on Pyton+Django with following features:</p> <ul> <li>Blog (for site, not for users)</li> <li>Users Registration</li> <li>User Profiles </li> <li>Adding friends, watching what friends added</li> <li>Award system for active users (carma, rating)</li> <li>Content rating</li> <li>Comments</li> <li>Probably different users levels (for automatic moderation)</li> </ul> <p>Basically all features of modern social network :) Just want to find some foundation to build site on top of it.</p>
6
2009-08-30T04:37:35Z
1,353,112
<p>Django has <a href="http://docs.djangoproject.com/en/dev/topics/auth/">authentication</a> and <a href="http://docs.djangoproject.com/en/dev/ref/contrib/comments/">commenting</a> built in, but most of the rest is covered by <a href="http://pinaxproject.com/">Pinax</a>.</p>
10
2009-08-30T04:44:12Z
[ "python", "django", "project", "social-networking" ]
Python+Django social network open source projects
1,353,097
<p>I'm looking for some open source, free to change and use project written on Pyton+Django with following features:</p> <ul> <li>Blog (for site, not for users)</li> <li>Users Registration</li> <li>User Profiles </li> <li>Adding friends, watching what friends added</li> <li>Award system for active users (carma, rating)</li> <li>Content rating</li> <li>Comments</li> <li>Probably different users levels (for automatic moderation)</li> </ul> <p>Basically all features of modern social network :) Just want to find some foundation to build site on top of it.</p>
6
2009-08-30T04:37:35Z
5,789,370
<p>There is an application that covers all of your requirements: <a href="http://www.vikuit.com" rel="nofollow">vikuit</a>.</p> <p>django, python, social network, profiles, rating, registration.... </p> <p>It's open source, so you can adapt or improve. I used their forums and SSO as a base for another app.</p>
3
2011-04-26T11:04:52Z
[ "python", "django", "project", "social-networking" ]
Encrypted Django Model Fields
1,353,128
<p>A client wants to ensure that I cannot read sensitive data from their site, which will still be administered by me. In practice, this means that I'll have database access, but it can't be possible for me to read the contents of certain Model Fields. Is there any way to make the data inaccessible to me, but still decrypted by the server to be browsed by the client?</p>
4
2009-08-30T04:55:01Z
1,353,174
<p>No, it's not possible to have data that is both in a form you can't decrypt it, and in a form where you can decrypt it to show it to the client simultaneously. The best you can do is a reversible encryption on the content so at least if your server is compromised their data is safe.</p>
4
2009-08-30T05:52:05Z
[ "python", "django", "encryption", "django-models" ]
Encrypted Django Model Fields
1,353,128
<p>A client wants to ensure that I cannot read sensitive data from their site, which will still be administered by me. In practice, this means that I'll have database access, but it can't be possible for me to read the contents of certain Model Fields. Is there any way to make the data inaccessible to me, but still decrypted by the server to be browsed by the client?</p>
4
2009-08-30T04:55:01Z
1,360,064
<p>You and your client could agree on them being obscured. A simple XOR operation or something similar will make the values unreadable in the admin and they can be decoded just in time they are needed in the site.</p> <p>This way you can safely administer the site without "accidentally" reading something.</p> <p>Make sure your client understands that it is technically possible for you to get the actual contents but that it would require active effort.</p>
0
2009-09-01T00:40:52Z
[ "python", "django", "encryption", "django-models" ]
Encrypted Django Model Fields
1,353,128
<p>A client wants to ensure that I cannot read sensitive data from their site, which will still be administered by me. In practice, this means that I'll have database access, but it can't be possible for me to read the contents of certain Model Fields. Is there any way to make the data inaccessible to me, but still decrypted by the server to be browsed by the client?</p>
4
2009-08-30T04:55:01Z
2,882,398
<p>Take a look at <a href="http://github.com/svetlyak40wt/django-fields" rel="nofollow">Django-fields</a></p>
2
2010-05-21T13:22:40Z
[ "python", "django", "encryption", "django-models" ]
Encrypted Django Model Fields
1,353,128
<p>A client wants to ensure that I cannot read sensitive data from their site, which will still be administered by me. In practice, this means that I'll have database access, but it can't be possible for me to read the contents of certain Model Fields. Is there any way to make the data inaccessible to me, but still decrypted by the server to be browsed by the client?</p>
4
2009-08-30T04:55:01Z
9,006,291
<p>This is possible with public key encryption. I have done something similar before in PHP but the idea is the same for a Django app:</p> <p>All data on this website was stored encrypted using a private key held by the system software. The corresponding public key to decrypt the data was held by the client in a text file.</p> <p>When the client wanted to access their data, they pasted the public key into an authorisation form (holding the key in the session) which unlocked the data.</p> <p>When done, they deauthorised their session.</p> <p>This protected the information against authorised access to the web app (so safe against weak username/passwords) and also from leaks at the database level.</p> <p>This is still not completely secure: if you have root access to the machine you can capture the key as it is uploaded, or inspect the session information. For that the cure could be to run the reading software on the client's machine and access the database through an API.</p> <p>I realise this is an old question but I thought I'd clarify that it is indeed possible.</p>
5
2012-01-25T16:31:02Z
[ "python", "django", "encryption", "django-models" ]
Encrypted Django Model Fields
1,353,128
<p>A client wants to ensure that I cannot read sensitive data from their site, which will still be administered by me. In practice, this means that I'll have database access, but it can't be possible for me to read the contents of certain Model Fields. Is there any way to make the data inaccessible to me, but still decrypted by the server to be browsed by the client?</p>
4
2009-08-30T04:55:01Z
22,415,648
<p>You might find <a href="https://github.com/defrex/django-encrypted-fields" rel="nofollow">Django Encrypted Fields</a> useful.</p>
0
2014-03-14T21:00:29Z
[ "python", "django", "encryption", "django-models" ]
Encrypted Django Model Fields
1,353,128
<p>A client wants to ensure that I cannot read sensitive data from their site, which will still be administered by me. In practice, this means that I'll have database access, but it can't be possible for me to read the contents of certain Model Fields. Is there any way to make the data inaccessible to me, but still decrypted by the server to be browsed by the client?</p>
4
2009-08-30T04:55:01Z
23,873,516
<p>Some other issues to consider are that the web application will then not be able to sort or easily query on the encrypted fields. It would be helpful to know what administrative functions the client wants you to have. Another approach would be to have a separate app / access channel that does not show the critical data but still allows you to perform your admin functions only.</p>
0
2014-05-26T15:35:41Z
[ "python", "django", "encryption", "django-models" ]
Issues with scoped_session in sqlalchemy - how does it work?
1,353,131
<p>I'm not really sure how scoped_session works, other than it seems to be a wrapper that hides several real sessions, keeping them separate for different requests. Does it do this with thread locals?</p> <p>Anyway the trouble is as follows:</p> <pre><code>S = elixir.session # = scoped_session(...) f = Foo(bar=1) S.add(f) # ERROR, f is already attached to session (different session) </code></pre> <p>Not sure how f ended up in a different session, I've not had problems with that before. Elsewhere I have code that looks just like that, but actually works. As you can imagine I find that very confusing.</p> <p>I just don't know anything here, f seems to be magically added to a session in the constructor, but I don't seem to have any references to the session it uses. Why would it end up in a different session? How can I get it to end up in the right session? How does this scoped_session thing work anyway? It just seems to work sometimes, and other times it just doesn't.</p> <p>I'm definitely very confused.</p>
6
2009-08-30T04:57:08Z
1,353,153
<p>It turns out elixir sets save-on-init=True on the created mappers. This can be disabled by:</p> <pre><code>using_mapper_options(save_on_init=False) </code></pre> <p>This solves the problem. Kudos to stepz on #sqlalchemy for figuring out what was going on immediately. Although I am still curious how scoped_session really works, so if someone answers that, they'll get credit for answering the question. </p>
2
2009-08-30T05:25:37Z
[ "python", "sqlalchemy", "python-elixir" ]
Issues with scoped_session in sqlalchemy - how does it work?
1,353,131
<p>I'm not really sure how scoped_session works, other than it seems to be a wrapper that hides several real sessions, keeping them separate for different requests. Does it do this with thread locals?</p> <p>Anyway the trouble is as follows:</p> <pre><code>S = elixir.session # = scoped_session(...) f = Foo(bar=1) S.add(f) # ERROR, f is already attached to session (different session) </code></pre> <p>Not sure how f ended up in a different session, I've not had problems with that before. Elsewhere I have code that looks just like that, but actually works. As you can imagine I find that very confusing.</p> <p>I just don't know anything here, f seems to be magically added to a session in the constructor, but I don't seem to have any references to the session it uses. Why would it end up in a different session? How can I get it to end up in the right session? How does this scoped_session thing work anyway? It just seems to work sometimes, and other times it just doesn't.</p> <p>I'm definitely very confused.</p>
6
2009-08-30T04:57:08Z
1,353,193
<p>Scoped session creates a proxy object that keeps a registry of (by default) per thread session objects created on demand from the passed session factory. When you access a session method such as <code>ScopedSession.add</code> it finds the session corresponding to the current thread and returns the <code>add</code> method bound to that session. The active session can be removed using the <code>ScopedSession.remove()</code> method.</p> <p>ScopedSession has a few convenience methods, one is <code>query_property</code> that creates a property that returns a query object bound to the scoped session it was created on and the class it was accessed. The other is <code>ScopedSession.mapper</code> that adds a default <code>__init__(**kwargs)</code> constructor and by default adds created objects to the scoped session the mapper was created off. This behavior can be controlled by the <code>save_on_init</code> keyword argument to the mapper. <code>ScopedSession.mapper</code> is deprecated because of exactly the problem that is in the question. This is one case where the Python "explicit is better than implicit" philosophy really applies. Unfortunately Elixir still by default uses <code>ScopedSession.mapper</code>. </p>
7
2009-08-30T06:02:18Z
[ "python", "sqlalchemy", "python-elixir" ]
Custom/Owner draw control in PyQt?
1,353,181
<p>I am learning PyQt and wonder if one can create custom/owner draw control like one show in the figure below:</p> <blockquote> <p><img src="http://lh5.ggpht.com/%5F5XDoB4MglkY/SpoT51SXR1I/AAAAAAAAFcU/ZXjzmhRyDVA/s400/SearchBox.png" alt="alt text" /></p> </blockquote> <p>The search box has magnifier icon on its right border. Is this kind of thing possible with PyQt? Thanks!</p>
1
2009-08-30T05:57:23Z
1,353,231
<p>If you only need to show an icon, an easy way is to use <a href="http://doc.trolltech.com/4.5/stylesheet.html">style-sheets</a>:</p> <pre><code>lineedit = QtGui.QLineEdit() lineedit.setStyleSheet("""QLineEdit { background-image: url(:/images/magnifier.png); background-repeat: no-repeat; background-position: right; background-clip: padding; padding-right: 16px; }""") </code></pre>
6
2009-08-30T06:25:40Z
[ "python", "user-interface", "qt", "pyqt", "ownerdrawn" ]
Custom/Owner draw control in PyQt?
1,353,181
<p>I am learning PyQt and wonder if one can create custom/owner draw control like one show in the figure below:</p> <blockquote> <p><img src="http://lh5.ggpht.com/%5F5XDoB4MglkY/SpoT51SXR1I/AAAAAAAAFcU/ZXjzmhRyDVA/s400/SearchBox.png" alt="alt text" /></p> </blockquote> <p>The search box has magnifier icon on its right border. Is this kind of thing possible with PyQt? Thanks!</p>
1
2009-08-30T05:57:23Z
1,813,358
<p>Antas Aasma - good anser! m3rLinEz Maybe its worth packing all buttons and text labels into one widget. In constructor of that widget connect all buttons. Expose only necessary signals and slots. Just to reduce code you write (and possibly increase reuse of this widget).</p>
0
2009-11-28T18:45:08Z
[ "python", "user-interface", "qt", "pyqt", "ownerdrawn" ]
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
1,353,211
<p>I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer.</p> <p>I am in a quandary putting this into practice.</p> <p><strong>I want to know specific ways that using Python or Ruby can make me a more productive .NET developer.</strong></p> <p>One specific way per answer, and even better if you can say whether I could use <strong>Python</strong> or <strong>Ruby</strong> or <strong>Both</strong> for it.</p> <p>See standard format below.</p>
4
2009-08-30T06:13:28Z
1,353,220
<h2>Quick Prototyping - Both</h2> <p>In the simplest cases when firing a python interpreter and writing a line or two is way faster than creating a new project in visual studio.</p> <p>And you can use ruby to. Or lua, or evel perl, whatever. The point is implicit typing and light-weight feel.</p>
1
2009-08-30T06:18:53Z
[ ".net", "python", "ruby", "productivity" ]
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
1,353,211
<p>I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer.</p> <p>I am in a quandary putting this into practice.</p> <p><strong>I want to know specific ways that using Python or Ruby can make me a more productive .NET developer.</strong></p> <p>One specific way per answer, and even better if you can say whether I could use <strong>Python</strong> or <strong>Ruby</strong> or <strong>Both</strong> for it.</p> <p>See standard format below.</p>
4
2009-08-30T06:13:28Z
1,353,225
<h2>IronPython / IronRuby</h2> <p><a href="http://www.manning.com/foord/" rel="nofollow">IronPython in Action</a> will do a better job explaining this (and exactly how best to use IronPython) that can possibly be accommodated in a SO answer. I'm biased -- I was a tech reviewer and am a friend of one of the authors -- but objectively think it's a great book. (No idea if IronRuby is blessed with a similarly wonderful book, yet).</p> <p>As you want "one specific way per answer" (incompatible with SO, which <strong>STRONGLY</strong> discourages a poster posting 25 different answers if they have 25 "specific ways" to indicate...!-): <strong>prototyping</strong> in order to explore some specific assembly or collection thereof that you're unfamiliar with (to check if you've understood their docs right and how to perform certain tasks) is an order of magnitude more productive in IronPython than in C#, as you can explore interactively and compilation is instantaneous and as-needed. (Have not tried IronRuby but I'll assume it can work in a roughly equivalent way and speed).</p>
5
2009-08-30T06:22:08Z
[ ".net", "python", "ruby", "productivity" ]
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
1,353,211
<p>I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer.</p> <p>I am in a quandary putting this into practice.</p> <p><strong>I want to know specific ways that using Python or Ruby can make me a more productive .NET developer.</strong></p> <p>One specific way per answer, and even better if you can say whether I could use <strong>Python</strong> or <strong>Ruby</strong> or <strong>Both</strong> for it.</p> <p>See standard format below.</p>
4
2009-08-30T06:13:28Z
1,353,228
<h2>Advanced Text Processing</h2> <p>Traditional strengths of awk and perl. You can just glue together a bunch of regular expressions to create a simple data-mining system on the go.</p>
2
2009-08-30T06:24:30Z
[ ".net", "python", "ruby", "productivity" ]
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
1,353,211
<p>I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer.</p> <p>I am in a quandary putting this into practice.</p> <p><strong>I want to know specific ways that using Python or Ruby can make me a more productive .NET developer.</strong></p> <p>One specific way per answer, and even better if you can say whether I could use <strong>Python</strong> or <strong>Ruby</strong> or <strong>Both</strong> for it.</p> <p>See standard format below.</p>
4
2009-08-30T06:13:28Z
1,353,229
<h2>Less Code</h2> <p>I think productivity is direct result on how proficient you are in a specific language. That said the terseness of a language like Python might save some time on getting certain things done.</p> <p>If I compare how much less code I have to write for simple administration scripts (e.g. clean-up of old files) compared to .NET code there is certain amount of productivity gain. (Plus it is more fun which also helps getting the job done)</p>
4
2009-08-30T06:24:34Z
[ ".net", "python", "ruby", "productivity" ]
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
1,353,211
<p>I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer.</p> <p>I am in a quandary putting this into practice.</p> <p><strong>I want to know specific ways that using Python or Ruby can make me a more productive .NET developer.</strong></p> <p>One specific way per answer, and even better if you can say whether I could use <strong>Python</strong> or <strong>Ruby</strong> or <strong>Both</strong> for it.</p> <p>See standard format below.</p>
4
2009-08-30T06:13:28Z
1,353,244
<h2>Cross platform</h2> <p>Compared to .NET a simple script Python is more easily ported to other platforms such as Linux. Although possible to achieve the same with the likes of Mono it simpler to run a Python script file on different platforms.</p>
1
2009-08-30T06:35:51Z
[ ".net", "python", "ruby", "productivity" ]
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
1,353,211
<p>I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer.</p> <p>I am in a quandary putting this into practice.</p> <p><strong>I want to know specific ways that using Python or Ruby can make me a more productive .NET developer.</strong></p> <p>One specific way per answer, and even better if you can say whether I could use <strong>Python</strong> or <strong>Ruby</strong> or <strong>Both</strong> for it.</p> <p>See standard format below.</p>
4
2009-08-30T06:13:28Z
1,353,255
<h2>Processing received Email</h2> <p>Python has built-in support for POP3 and IMAP where the standard .NET framework doesn't. Useful for automating email triggered tasks.</p>
1
2009-08-30T06:40:17Z
[ ".net", "python", "ruby", "productivity" ]
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
1,353,211
<p>I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer.</p> <p>I am in a quandary putting this into practice.</p> <p><strong>I want to know specific ways that using Python or Ruby can make me a more productive .NET developer.</strong></p> <p>One specific way per answer, and even better if you can say whether I could use <strong>Python</strong> or <strong>Ruby</strong> or <strong>Both</strong> for it.</p> <p>See standard format below.</p>
4
2009-08-30T06:13:28Z
1,353,273
<p>Learning a new language gives you knowledge that you can bring back to <em>any</em> programming language. Here are some things you'd learn.</p> <p>Add <a href="http://jonesbunch.com/articles/2008/ruby-singleton" rel="nofollow">functionality to your objects</a> on the fly. </p> <p><a href="http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/" rel="nofollow">Mix</a> in modules.</p> <p><a href="http://www.devarticles.com/c/a/Ruby-on-Rails/Code-Blocks-and-Iteration/" rel="nofollow">Pass a chunk of code</a> around.</p> <p>Figure out how to do more with <a href="http://joe.truemesh.com/blog/000390.html" rel="nofollow">less code</a>: <code>ruby -e "puts 'hello world'"</code></p> <p>C# can do some of these things, but a fresh perspective might bring you one step closer to automating your breakfast.</p>
2
2009-08-30T06:52:17Z
[ ".net", "python", "ruby", "productivity" ]
I'm a .NET Programmer. What are specific uses of Python and/or Ruby for that will make me more productive?
1,353,211
<p>I recall when I first read Pragmatic Programmer that they suggested using scripting languages to make you a more productive programmer.</p> <p>I am in a quandary putting this into practice.</p> <p><strong>I want to know specific ways that using Python or Ruby can make me a more productive .NET developer.</strong></p> <p>One specific way per answer, and even better if you can say whether I could use <strong>Python</strong> or <strong>Ruby</strong> or <strong>Both</strong> for it.</p> <p>See standard format below.</p>
4
2009-08-30T06:13:28Z
1,353,301
<h2>Embedding a script engine</h2> <p>Use of IronPython for a scripting engine inside your .NET application. For example enabling end-users of your application to change customizable parts with a full fledge language such as Python.</p> <p>A possible example might be to expose custom logic to end-users for a work flow engine.</p>
2
2009-08-30T07:08:56Z
[ ".net", "python", "ruby", "productivity" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,353,722
<p>My answer to that would be :</p> <blockquote> <p>We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.</p> </blockquote> <p><em>(Quoting Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268)</em></p> <p><br> If your application is doing anything like a query to the database, that one query will take more time than anything you can gain with those kind of small optimizations, anyway...</p> <p>And if running after performances like that, why not code in assembly language, afterall ? Because Python is easier/faster to write and maintain ? Well, if so, you are right :-)</p> <p>The most important thing is that your code is easy to maintain ; not a couple micro-seconds of CPU-time ! <br><em>Well, maybe except if you have thousands of servers -- but is it your case ?</em></p>
14
2009-08-30T11:52:06Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,353,728
<blockquote> <p>I should also say that context of the code is not a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> </blockquote> <p>Given this, I'd say that you should take your colleague's advice about writing efficient Python but ignore anything he says that goes against prioritizing readability and maintainability of the code, which will probably be more important than the speed at which it'll execute.</p>
3
2009-08-30T11:55:53Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,353,732
<p>The answer is really simple :</p> <ul> <li>Follow Python best practices, not C++ best practices.</li> <li>Readability in Python is more important that speed.</li> <li>If performance becomes an issue, measure, then start optimizing.</li> </ul>
13
2009-08-30T11:57:23Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,353,773
<blockquote> <p>In an if statement with an or always put the condition most likely to fail first, so the second will not be checked.</p> </blockquote> <p>This is generally a good advice, and also depends on the logic of your program. If it makes sense that the second statement is not evaluated if the first returns false, then do so. Doing the opposite could be a bug otherwise.</p> <blockquote> <p>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</p> </blockquote> <p>I don't really get this point. Of course you should use the library provided functions, because they are probably implemented in C, and a pure python implementation is most likely to be slower. In any case, no need to reinvent the wheel.</p> <blockquote> <p>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</p> </blockquote> <pre><code>$ cat withcall.py def square(a): return a*a for i in xrange(1,100000): i_square = square(i) $ cat withoutcall.py for i in xrange(1,100000): i_square = i*i $ time python2.3 withcall.py real 0m5.769s user 0m4.304s sys 0m0.215s $ time python2.3 withcall.py real 0m5.884s user 0m4.315s sys 0m0.206s $ time python2.3 withoutcall.py real 0m5.806s user 0m4.172s sys 0m0.209s $ time python2.3 withoutcall.py real 0m5.613s user 0m4.171s sys 0m0.216s </code></pre> <p>I mean... come on... please.</p>
2
2009-08-30T12:26:12Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,353,775
<p>This sort of premature micro-optimisation is usually a waste of time in my experience, even in C and C++. Write readable code first. If it's running too slowly, run it through a profiler, and if necessary, fix the hot-spots.</p> <p>Fundamentally, you need to think about return on investment. Is it worth the extra effort in reading and maintaining "optimised" code for the couple of microseconds it saves you? In most cases it isn't.</p> <p>(Also, compilers and runtimes are getting cleverer. Some micro-optimisations may become micro-pessimisations over time.)</p>
10
2009-08-30T12:26:37Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,353,788
<p>I agree with others: readable code first ("Performance is not a problem until performance is a problem.").</p> <p>I only want to add that when you absolutely need to write some unreadable and/or non-intuitive code, you can generally isolate it in few specific methods, for which you can write detailed comments, and keep the rest of your code highly readable. If you do so, you'll end up having easy to maintain code, and you'll only have to go through the unreadable parts when you really need to.</p>
4
2009-08-30T12:36:50Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,353,798
<p>Sure follow Python best-practices (and in fact I agree with the first two recommendations), but maintainability and efficiency are not opposites, they are mostly togethers (if that's a word).</p> <p>Statements like "always write your IF statements a certain way for performance" are a-priori, i.e. not based on knowledge of what your program spends time on, and are therefore guesses. The first (or second, or third, whatever) rule of performance tuning is <em>don't guess</em>.</p> <p>If after you measure, profile, or in my case <a href="http://stackoverflow.com/questions/926266/performance-optimization-strategies-of-last-resort/927773#927773"><em>do this</em></a>, you actually <em>know</em> that you can save much time by re-ordering tests, by all means, do. My money says that's at the 1% level or less.</p>
1
2009-08-30T12:42:44Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,354,718
<p>I think there are several related 'urban legends' here.</p> <ul> <li><p><strong>False</strong> Putting the more often-checked condition first in a conditional and similar optimizations save enough time for a typical program that it is worthy for a typical programmer.</p></li> <li><p><strong>True</strong> Some, but not many, people are using such styles in Python in the incorrect belief outlined above.</p></li> <li><p><strong>True</strong> Many people use such style in Python when they think that it improves <em>readability</em> of a Python program.</p></li> </ul> <p>About readability: I think it's indeed useful when you give the most useful conditional first, since this is what people notice first anyway. You should also use <code>''.join()</code> if you mean concatenation of strings since it's the most direct way to do it (the <code>s += x</code> operation <strong>could</strong> mean something different). </p> <p>"Call as less functions as possible" decreases readability and goes against Pythonic principle of code reuse. And so it's not a style people use in Python.</p>
2
2009-08-30T19:33:55Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,354,801
<p>Before introducing performance optimizations at the expense of readability, look into modules like psyco that will do some JIT-ish compiling of distinct functions, often with striking results, with no impairment of readability.</p> <p>Then if you really want to embark on the optimization path, you must first learn to measure and profile. Optimization MUST BE QUANTITATIVE - do not go with your gut. The hotspot profiler will show you the functions where your program is burning up the most time.</p> <p>If optimization turns up a function like this is being frequently called:</p> <pre><code>def get_order_qty(ordernumber): # look up order in database and return quantity </code></pre> <p>If there is any repetition of ordernumbers, then memoization would be a good optimization technique to learn, and it is easily packaged in an @memoize decorator so that there is little impact to program readability. The effect of memoizing is that values returned for a given set of input arguments are cached, so that the expensive function can be called only once, with subseqent calls resolved against the cache.</p> <p>Lastly, consider lifting invariants out of loops. For large multi-dimensional structures, this can save a lot of time - in fact in this case, I would argue that this optimization <em>improves</em> readability, as it often serves to make clear that some expression can be computed at a high-level dimension in the nested logic.</p> <p>(BTW, is this really what you meant? •In an if statement with an or always put the condition most likely to fail first, so the second will not be checked.</p> <p>I should think this might be the case for "and", but an "or" will short-circuit if the first value is True, saving the evaluation of the second term of the conditional. So I would change this optimization "rule" to:</p> <ul> <li>If testing "A and B", put A first if it is more likely to evaluate to<br /> False.</li> <li>If testing "A or B", put A first if it is more likely to evaluate to True.</li> </ul> <p>But often, the sequence of conditions is driven by the tests themselves:</p> <pre><code>if obj is not None and hasattr(obj,"name") and obj.name.startswith("X"): </code></pre> <p>You can't reorder these for optimization - they <em>have</em> to be in this order (or just let the exceptions fly and catch them later:</p> <pre><code>if obj.name.startswith("X"): </code></pre>
2
2009-08-30T20:16:59Z
[ "python", "performance" ]
Should I optimise my python code like C++? Does it matter?
1,353,715
<p>I had an argument with a colleague about writing python efficiently. He claimed that though you are programming python you still have to optimise the little bits of your software as much as possible, as if you are writing an efficient algorithm in C++.</p> <p>Things like:</p> <ul> <li>In an <code>if</code> statement with an <code>or</code> always put the condition most likely to fail first, so the second will not be checked.</li> <li>Use the most efficient functions for manipulating strings in common use. Not code that grinds strings, but simple things like doing joins and splits, and finding substrings.</li> <li>Call as less functions as possible, even if it comes on the expense of readability, because of the overhead this creates.</li> </ul> <p>I say, that in most cases it doesn't matter. I should also say that context of the code is <strong>not</strong> a super-efficient NOC or missile-guidance systems. We're mostly writing tests in python.</p> <p>What's your view of the matter?</p>
5
2009-08-30T11:49:35Z
1,354,833
<p>My visceral reaction is this:</p> <p>I've worked with guys like your colleague and in general I wouldn't take advice from them.</p> <p>Ask him if he's ever even used a profiler.</p>
1
2009-08-30T20:29:55Z
[ "python", "performance" ]
Handling KeyboardInterrupt in a KDE Python application?
1,353,823
<p>I'm working on a PyKDE4/PyQt4 application, <a href="http://autokey.googlecode.com/" rel="nofollow">Autokey</a>, and I noticed that when I send the program a CTRL+C, the keyboard interrupt is not processed until I interact with the application, by ie. clicking on a menu item or changing a checkbox. </p> <pre><code>lfaraone@stone:~$ /usr/bin/autokey ^C^C^C Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/autokey/ui/popupmenu.py", line 113, in on_triggered def on_triggered(self): KeyboardInterrupt ^C^C^C Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/autokey/ui/configwindow.py", line 423, in mousePressEvent def mousePressEvent(self, event): KeyboardInterrupt </code></pre> <p>This is despite having the following in /usr/bin/autokey:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import sys from autokey.autokey import Application a = Application() try: a.main() except KeyboardInterrupt: a.shutdown() sys.exit(0) </code></pre> <p>Why isn't the KeyboardInterrupt caught:</p> <ul> <li>when I issue it, rather than when I next take an action in the GUI</li> <li>by the initial try/except clause?</li> </ul> <p>Running Ubuntu 9.04 with Python 2.6.</p>
2
2009-08-30T12:58:52Z
1,357,015
<p>Try doing this:</p> <pre><code>import signal signal.signal(signal.SIGINT, signal.SIG_DFL) </code></pre> <p>before invoking <code>a.main()</code>.</p> <p><strong>Update:</strong> Remember, Ctrl-C can be used for Copy in GUI applications. It's better to use Ctrl+\ in Qt, which will cause the event loop to terminate and the application to close.</p>
4
2009-08-31T11:31:07Z
[ "python", "pyqt", "keyboardinterrupt", "pykde", "autokey" ]
Creating SVGs using Python
1,353,976
<p>I'm building a set of SVG files that include an unfortunate number of hardcoded values (they must print with some elements sized in mm, while others must be scaled as a percent, and most of the values are defined relative to each other). Rather than managing those numbers by hand (heaven forbid I want to change something), I thought I might use my trusty hammer python for the task.</p> <p>SVG 1.1 doesn't natively support any kind of variable scheme that would let me do what I want, and I'm not interested in introducing javascript or unstable w3c draft specs into the mix. One obvious solution is to use string formatting to read, parse, and replace variables in my SVG file. This seems like a bad idea for a larger document, but has the advantage of being simple and portable.</p> <p>My second though was to investigate the available python->svg libraries. Unfortunately, it seems that the few options tend to be either too new (<a href="http://codeboje.de/pysvg/" rel="nofollow">pySVG</a> still has an unstable interface), too old (not updated since 2005), or abandoned. I haven't looked closely, but my sense is that the charting applications are not flexible enough to generate my documents.</p> <p>The third option I came across was that of using some other drawing tool (cairo, for instance) that can be convinced to put out svg. This has the (potential) disadvantage of not natively supporting the absolute element sizes that are so important to me, but might include the ability to output PDF, which would be convenient.</p> <p>I've already done the googling, so I'm looking for input from people who have used any of the methods mentioned, or who might know of some other approach. Long-term stability of whatever solution is chosen is important to me (it was the original reason for the hand-coding instead of just using illustrator). </p> <p>At this point, I'm leaning towards the first solution, so recommendations on best practices for using python to parse and replace variables in XML files are welcome.</p>
5
2009-08-30T14:19:45Z
1,354,013
<p>Since SVG is XML, maybe you could use XSLT to transform a source XML file containing your variables to SVG. In your XSLT style sheet, you would have templates corresponding to various elements of your SVG illustration, that change their output depending on the values found in the source XML file.</p> <p>Or you could use a template SVG as the source and transform it into the final one, with the values passed as parameters to the XSLT processor.</p> <p>You's either use XSLT directly, or via Python if you need some logic that's easier to perform in a traditional language.</p>
0
2009-08-30T14:34:32Z
[ "python", "xml", "graphics", "svg" ]
Creating SVGs using Python
1,353,976
<p>I'm building a set of SVG files that include an unfortunate number of hardcoded values (they must print with some elements sized in mm, while others must be scaled as a percent, and most of the values are defined relative to each other). Rather than managing those numbers by hand (heaven forbid I want to change something), I thought I might use my trusty hammer python for the task.</p> <p>SVG 1.1 doesn't natively support any kind of variable scheme that would let me do what I want, and I'm not interested in introducing javascript or unstable w3c draft specs into the mix. One obvious solution is to use string formatting to read, parse, and replace variables in my SVG file. This seems like a bad idea for a larger document, but has the advantage of being simple and portable.</p> <p>My second though was to investigate the available python->svg libraries. Unfortunately, it seems that the few options tend to be either too new (<a href="http://codeboje.de/pysvg/" rel="nofollow">pySVG</a> still has an unstable interface), too old (not updated since 2005), or abandoned. I haven't looked closely, but my sense is that the charting applications are not flexible enough to generate my documents.</p> <p>The third option I came across was that of using some other drawing tool (cairo, for instance) that can be convinced to put out svg. This has the (potential) disadvantage of not natively supporting the absolute element sizes that are so important to me, but might include the ability to output PDF, which would be convenient.</p> <p>I've already done the googling, so I'm looking for input from people who have used any of the methods mentioned, or who might know of some other approach. Long-term stability of whatever solution is chosen is important to me (it was the original reason for the hand-coding instead of just using illustrator). </p> <p>At this point, I'm leaning towards the first solution, so recommendations on best practices for using python to parse and replace variables in XML files are welcome.</p>
5
2009-08-30T14:19:45Z
1,354,057
<p>A markup based templating engine, such as <a href="http://genshi.edgewall.org/" rel="nofollow">genshi</a> might be useful. It would let you do most of the authoring using a SVG tool and do the customization in the template. I'd definitely prefer it to XSLT.</p>
4
2009-08-30T15:02:22Z
[ "python", "xml", "graphics", "svg" ]
How to implement a multiprocessing priority queue in Python?
1,354,204
<p>Anybody familiar with how I can implement a multiprocessing priority queue in python?</p>
4
2009-08-30T16:17:03Z
1,354,255
<p>There is a bug that prevents true FIFO.<br /> Read <a href="http://bugs.python.org/issue4999" rel="nofollow">here</a>.</p> <p>An alternate way to build a priority queue multiprocessing setup would be certainly be great!</p>
2
2009-08-30T16:37:12Z
[ "python", "multiprocessing", "priority-queue" ]
How to implement a multiprocessing priority queue in Python?
1,354,204
<p>Anybody familiar with how I can implement a multiprocessing priority queue in python?</p>
4
2009-08-30T16:17:03Z
1,354,295
<p>Alas, it's nowhere as simple as changing queueing discipline of a good old <code>Queue.Queue</code>: the latter is in fact designed to be subclassed according to a template-method pattern, and overriding just the hook methods <code>_put</code> and/or <code>_get</code> can easily allow changing the queueing discipline (in 2.6 explicit LIFO and priority implementations are offered, but they were easy to make even in earlier versions of Python).</p> <p>For multiprocessing, in the general case (multiple readers, multiple writers), I see no solution for how to implement priority queues except to give up on the distributed nature of the queue; designate one special auxiliary process that does nothing but handle queues, send (essentially) RPCs to it to create a queue with a specified discipline, do puts and gets to it, get info about it, &amp;c. So one would get the usual problems about ensuring every process knows about the aux proc's location (host and port, say), etc (easier if the process is always spawned at startup by the main proc). A pretty large problem, especially if one wants to do it with good performance, safeguards against aux proc's crashes (requiring replication of data to slave processes, distributed "master election" among slaves if master crashes, &amp;c), and so forth. Doing it from scratch sounds like a PhD's worth of work. One might start from <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.48.5583">Johnson's</a> work, or piggyback on some very general approach like <a href="http://activemq.apache.org/index.html">ActiveMQ</a>.</p> <p>Some special cases (e.g. single reader, single writer) might be easier, and turn out to be faster for their limited area of application; but then a very specifically restricted spec should be drawn up for that limited area -- and the results would not constitute a (general purpose) "multiprocessing queue", but one applicable only to the given constrained set of requirements.</p>
5
2009-08-30T16:56:16Z
[ "python", "multiprocessing", "priority-queue" ]
How to implement a multiprocessing priority queue in Python?
1,354,204
<p>Anybody familiar with how I can implement a multiprocessing priority queue in python?</p>
4
2009-08-30T16:17:03Z
1,354,373
<p>While this isn't an answer, maybe it can help you develop an multiprocessing queue. </p> <p>Here's a simple <strong>priority queue</strong> class I wrote using Python's <strong>Array</strong>:</p> <pre><code>class PriorityQueue(): """A basic priority queue that dequeues items with the smallest priority number.""" def __init__(self): """Initializes the queue with no items in it.""" self.array = [] self.count = 0 def enqueue(self, item, priority): """Adds an item to the queue.""" self.array.append([item, priority]) self.count += 1 def dequeue(self): """Removes the highest priority item (smallest priority number) from the queue.""" max = -1 dq = 0 if(self.count &gt; 0): self.count -= 1 for i in range(len(self.array)): if self.array[i][1] != None and self.array[i][1] &gt; max: max = self.array[i][1] if max == -1: return self.array.pop(0) else: for i in range(len(self.array)): if self.array[i][1] != None and self.array[i][1] &lt;= max: max = self.array[i][1] dq = i return self.array.pop(dq) def requeue(self, item, newPrio): """Changes specified item's priority.""" for i in range(len(self.array)): if self.array[i][0] == item: self.array[i][1] = newPrio break def returnArray(self): """Returns array representation of the queue.""" return self.array def __len__(self): """Returnes the length of the queue.""" return self.count </code></pre>
1
2009-08-30T17:21:32Z
[ "python", "multiprocessing", "priority-queue" ]
How to implement a multiprocessing priority queue in Python?
1,354,204
<p>Anybody familiar with how I can implement a multiprocessing priority queue in python?</p>
4
2009-08-30T16:17:03Z
1,359,108
<p>Depending on your requirements you could use the operating system and the file system in a number of ways. How large will the queue grow and how fast does it have to be? If the queue may be big but you are willing to open a couple files for every queue access you could use a BTree implementation to store the queue and file locking to enforce exclusive access. Slowish but robust. </p> <p>If the queue will remain relatively small and you need it to be fast you might be able to use shared memory on some operating systems...</p> <p>If the queue will be small (1000s of entries) and you don't need it to be really fast you could use something as simple as a directory with files containing the data with file locking. This would be my preference if small and slow is okay.</p> <p>If the queue can be large and you want it to be fast on average, then you probably should use a dedicated server process like Alex suggests. This is a pain in the neck however.</p> <p>What are your performance and size requirements?</p>
0
2009-08-31T19:49:54Z
[ "python", "multiprocessing", "priority-queue" ]
How to implement a multiprocessing priority queue in Python?
1,354,204
<p>Anybody familiar with how I can implement a multiprocessing priority queue in python?</p>
4
2009-08-30T16:17:03Z
1,750,166
<p>I had the same use case. But with a finite number of priorities.</p> <p>What I am ending up doing is creating one Queue per priority, and my Process workers will try to get the items from those queues, starting with the most important queue to the less important one (moving from one queue to the other is done when the queue is empty)</p>
1
2009-11-17T16:43:45Z
[ "python", "multiprocessing", "priority-queue" ]
How to implement a multiprocessing priority queue in Python?
1,354,204
<p>Anybody familiar with how I can implement a multiprocessing priority queue in python?</p>
4
2009-08-30T16:17:03Z
22,471,105
<p>Inspired by @user211505's suggestion, I put together something quick and dirty. </p> <p>Note that this is not a complete solution to the difficult problem of priority queues in multiprocessing production environments. However, if you're just messing around or need something for a short project, this will likely fit the bill:</p> <pre><code>from time import sleep from datetime import datetime from Queue import Empty from multiprocessing import Queue as ProcessQueue class SimplePriorityQueue(object): ''' Simple priority queue that works with multiprocessing. Only a finite number of priorities are allowed. Adding many priorities slow things down. Also: no guarantee that this will pull the highest priority item out of the queue if many items are being added and removed. Race conditions exist where you may not get the highest priority queue item. However, if you tend to keep your queues not empty, this will be relatively rare. ''' def __init__(self, num_priorities=1, default_sleep=.2): self.queues = [] self.default_sleep = default_sleep for i in range(0, num_priorities): self.queues.append(ProcessQueue()) def __repr__(self): return "&lt;Queue with %d priorities, sizes: %s&gt;"%(len(self.queues), ", ".join(map(lambda (i, q): "%d:%d"%(i, q.qsize()), enumerate(self.queues)))) qsize = lambda(self): sum(map(lambda q: q.qsize(), self.queues)) def get(self, block=True, timeout=None): start = datetime.utcnow() while True: for q in self.queues: try: return q.get(block=False) except Empty: pass if not block: raise Empty if timeout and (datetime.utcnow()-start).total_seconds &gt; timeout: raise Empty if timeout: time_left = (datetime.utcnow()-start).total_seconds - timeout sleep(time_left/4) else: sleep(self.default_sleep) get_nowait = lambda(self): self.get(block=False) def put(self, priority, obj, block=False, timeout=None): if priority &lt; 0 or priority &gt;= len(self.queues): raise Exception("Priority %d out of range."%priority) # Block and timeout don't mean much here because we never set maxsize return self.queues[priority].put(obj, block=block, timeout=timeout) </code></pre>
0
2014-03-18T05:30:07Z
[ "python", "multiprocessing", "priority-queue" ]
Using HTML Parser with HTTPResponse in Python 3.1
1,354,338
<p>The response data from HTTPResponse object is of type bytes. </p> <pre><code>conn = http.client.HTTPConnection(www.yahoo.com) conn.request("GET","/") response = conn.getresponse(); data = response.read() type(data) </code></pre> <p>The data is of type bytes.</p> <p>I would like to use the response along with the built-in HTML parser of Python 3.1. However I find that HTMLParser.feed() requires a string (of type str). And this method does not accept data as the argument. To circumvent this problem, I have used data.decode() to continue with the parsing.</p> <p>Question:</p> <ol> <li>Is there a better way to accomplish this?</li> <li>Is there a reason why HTTP response does not return string?</li> </ol> <p>I guess the reason is this: The response of the server could be in any character set. So, the library cannot assume that it would be ASCII. But then, string in python is Unicode. The HTTP library could as well return a string. HTML tags are definitely in ASCII.</p>
0
2009-08-30T17:10:27Z
1,354,379
<blockquote> <p>Is there a reason why HTTP response does not return string?</p> </blockquote> <p>You nailed it yourself. A HTTP response isn't necessarily a string.</p> <p>It can be an image, for example, and even when it is a string it can't know the encoding. If you know the encoding (or have an encoding detection library) then it's very easy to convert a series of bytes to a string. In fact, the byte type is often used synonymously with the char type in C-based languages.</p> <blockquote> <p>HTML tags are definitely in ASCII.</p> </blockquote> <p>And if HTML tags were always ASCII, XHTML (which is recommended to be delivered as UTF-8) would have serious issues!</p> <p>Besides, HTTP != HTML.</p>
2
2009-08-30T17:25:01Z
[ "python", "html", "http" ]
Split Twitter RSS string using Python
1,354,415
<p>I am trying to parse Twitter RSS feeds and put the information in a sqlite database, using Python. Here's an example:</p> <pre><code>MiamiPete: today's "Last Call" is now up http://bit.ly/MGDzu #stocks #stockmarket #finance #money </code></pre> <p>What I want to do is create one column for the main content (<code>Miami Pete…now up</code>), one column for the URL (<code>http://bit.ly/MGDzu</code>), and four separate columns for the hashtags (stocks, stockmarket, finance, money). I've been playing around with how to do this. </p> <p>Any advice would be greatly appreciated! </p> <p>P.S. Some code I've been playing around with is below--you can see I tried initially creating a variable called "tiny_url" and splitting it, which it does seem to do, but this feeble attempt is not anywhere close to solving the problem noted above. :)</p> <pre><code>def store_feed_items(id, items): """ Takes a feed_id and a list of items and stored them in the DB """ for entry in items: c.execute('SELECT entry_id from RSSEntries WHERE url=?', (entry.link,)) tinyurl = entry.summary ### I added this in print tinyurl.split('http') ### I added this in if len(c.fetchall()) == 0: c.execute('INSERT INTO RSSEntries (id, url, title, content, tinyurl, date, tiny) VALUES (?,?,?,?,?,?,?)', (id, entry.link, entry.title, entry.summary, tinyurl, strftime("%Y-%m-%d %H:%M:%S",entry.updated_parsed), tiny )) </code></pre>
1
2009-08-30T17:38:25Z
1,354,515
<p>Twitter has an api that may be easier for you to use here, <a href="http://apiwiki.twitter.com/Twitter-API-Documentation" rel="nofollow">http://apiwiki.twitter.com/Twitter-API-Documentation</a>.</p> <p>You can get the results as JSON or XML and use one of the many Python libraries to parse the results.</p> <p>Or if you must your the RSS there are Python feed parsers like, <a href="http://www.feedparser.org/" rel="nofollow">http://www.feedparser.org/</a>.</p>
1
2009-08-30T18:20:54Z
[ "python", "string", "sqlite", "split", "bit.ly" ]
Split Twitter RSS string using Python
1,354,415
<p>I am trying to parse Twitter RSS feeds and put the information in a sqlite database, using Python. Here's an example:</p> <pre><code>MiamiPete: today's "Last Call" is now up http://bit.ly/MGDzu #stocks #stockmarket #finance #money </code></pre> <p>What I want to do is create one column for the main content (<code>Miami Pete…now up</code>), one column for the URL (<code>http://bit.ly/MGDzu</code>), and four separate columns for the hashtags (stocks, stockmarket, finance, money). I've been playing around with how to do this. </p> <p>Any advice would be greatly appreciated! </p> <p>P.S. Some code I've been playing around with is below--you can see I tried initially creating a variable called "tiny_url" and splitting it, which it does seem to do, but this feeble attempt is not anywhere close to solving the problem noted above. :)</p> <pre><code>def store_feed_items(id, items): """ Takes a feed_id and a list of items and stored them in the DB """ for entry in items: c.execute('SELECT entry_id from RSSEntries WHERE url=?', (entry.link,)) tinyurl = entry.summary ### I added this in print tinyurl.split('http') ### I added this in if len(c.fetchall()) == 0: c.execute('INSERT INTO RSSEntries (id, url, title, content, tinyurl, date, tiny) VALUES (?,?,?,?,?,?,?)', (id, entry.link, entry.title, entry.summary, tinyurl, strftime("%Y-%m-%d %H:%M:%S",entry.updated_parsed), tiny )) </code></pre>
1
2009-08-30T17:38:25Z
1,354,517
<p>It seems like your data-driven design is rather flawed. Unless all your entries have a text part, an url and up to 4 tags, it's not going to work.</p> <p>You also need to separate saving to db from parsing. Parsing could be easily done with a regexep (or even string methods):</p> <pre><code>&gt;&gt;&gt; s = your_string &gt;&gt;&gt; s.split() ['MiamiPete:', "today's", '"Last', 'Call"', 'is', 'now', 'up', 'http://bit.ly/MGDzu', '#stocks', '#stockmarket', '#finance', '#money'] &gt;&gt;&gt; url = [i for i in s.split() if i.startswith('http://')] &gt;&gt;&gt; url ['http://bit.ly/MGDzu'] &gt;&gt;&gt; tags = [i for i in s.split() if i.startswith('#')] &gt;&gt;&gt; tags ['#stocks', '#stockmarket', '#finance', '#money'] &gt;&gt;&gt; ' '.join(i for i in s.split() if i not in url+tags) 'MiamiPete: today\'s "Last Call" is now up' </code></pre> <p>Single-table db design would probably have to go, though.</p>
4
2009-08-30T18:21:40Z
[ "python", "string", "sqlite", "split", "bit.ly" ]
Split Twitter RSS string using Python
1,354,415
<p>I am trying to parse Twitter RSS feeds and put the information in a sqlite database, using Python. Here's an example:</p> <pre><code>MiamiPete: today's "Last Call" is now up http://bit.ly/MGDzu #stocks #stockmarket #finance #money </code></pre> <p>What I want to do is create one column for the main content (<code>Miami Pete…now up</code>), one column for the URL (<code>http://bit.ly/MGDzu</code>), and four separate columns for the hashtags (stocks, stockmarket, finance, money). I've been playing around with how to do this. </p> <p>Any advice would be greatly appreciated! </p> <p>P.S. Some code I've been playing around with is below--you can see I tried initially creating a variable called "tiny_url" and splitting it, which it does seem to do, but this feeble attempt is not anywhere close to solving the problem noted above. :)</p> <pre><code>def store_feed_items(id, items): """ Takes a feed_id and a list of items and stored them in the DB """ for entry in items: c.execute('SELECT entry_id from RSSEntries WHERE url=?', (entry.link,)) tinyurl = entry.summary ### I added this in print tinyurl.split('http') ### I added this in if len(c.fetchall()) == 0: c.execute('INSERT INTO RSSEntries (id, url, title, content, tinyurl, date, tiny) VALUES (?,?,?,?,?,?,?)', (id, entry.link, entry.title, entry.summary, tinyurl, strftime("%Y-%m-%d %H:%M:%S",entry.updated_parsed), tiny )) </code></pre>
1
2009-08-30T17:38:25Z
1,354,577
<p>Also, you can parse your strings using regexps:</p> <pre><code>&gt;&gt;&gt; s = (u'MiamiPete: today\'s "Last Call" is now up http://bit.ly/MGDzu ' '#stocks #stockmarket #finance #money') &gt;&gt;&gt; re.match(r'(.*) (http://[^ ]+)', s).groups() (u'MiamiPete: today\'s "Last Call" is now up', u'http://bit.ly/MGDzu') &gt;&gt;&gt; re.findall(r'(#\w+)', s) [u'#stocks', u'#stockmarket', u'#finance', u'#money'] </code></pre>
2
2009-08-30T18:41:51Z
[ "python", "string", "sqlite", "split", "bit.ly" ]
Split Twitter RSS string using Python
1,354,415
<p>I am trying to parse Twitter RSS feeds and put the information in a sqlite database, using Python. Here's an example:</p> <pre><code>MiamiPete: today's "Last Call" is now up http://bit.ly/MGDzu #stocks #stockmarket #finance #money </code></pre> <p>What I want to do is create one column for the main content (<code>Miami Pete…now up</code>), one column for the URL (<code>http://bit.ly/MGDzu</code>), and four separate columns for the hashtags (stocks, stockmarket, finance, money). I've been playing around with how to do this. </p> <p>Any advice would be greatly appreciated! </p> <p>P.S. Some code I've been playing around with is below--you can see I tried initially creating a variable called "tiny_url" and splitting it, which it does seem to do, but this feeble attempt is not anywhere close to solving the problem noted above. :)</p> <pre><code>def store_feed_items(id, items): """ Takes a feed_id and a list of items and stored them in the DB """ for entry in items: c.execute('SELECT entry_id from RSSEntries WHERE url=?', (entry.link,)) tinyurl = entry.summary ### I added this in print tinyurl.split('http') ### I added this in if len(c.fetchall()) == 0: c.execute('INSERT INTO RSSEntries (id, url, title, content, tinyurl, date, tiny) VALUES (?,?,?,?,?,?,?)', (id, entry.link, entry.title, entry.summary, tinyurl, strftime("%Y-%m-%d %H:%M:%S",entry.updated_parsed), tiny )) </code></pre>
1
2009-08-30T17:38:25Z
1,355,156
<p>I would highly recommend using the Twitter API. There are actually two APIs, one for the main twitter server and one for the search server. They are used for different things.</p> <p>You can find sample code, pytwitter on svn. Add simplejson and you can be doing very powerful things in a matter of minutes.</p> <p>Good luck</p>
1
2009-08-30T22:59:11Z
[ "python", "string", "sqlite", "split", "bit.ly" ]
Storing huge hash table in a file in Python
1,354,520
<p>Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there's no other option if the amount of data is really huge. Thanks!</p>
4
2009-08-30T18:24:09Z
1,354,533
<p>You can use the <a href="http://docs.python.org/library/shelve.html">shelve module</a> to store a dictionary like structure in a file. From the Python documentation:</p> <pre><code>import shelve d = shelve.open(filename) # open -- file may get suffix added by low-level # library d[key] = data # store data at key (overwrites old data if # using an existing key) data = d[key] # retrieve a COPY of data at key (raise KeyError if no # such key) del d[key] # delete data stored at key (raises KeyError # if no such key) flag = d.has_key(key) # true if the key exists klist = d.keys() # a list of all existing keys (slow!) # as d was opened WITHOUT writeback=True, beware: d['xx'] = range(4) # this works as expected, but... d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)! # having opened d without writeback=True, you need to code carefully: temp = d['xx'] # extracts the copy temp.append(5) # mutates the copy d['xx'] = temp # stores the copy right back, to persist it # or, d=shelve.open(filename,writeback=True) would let you just code # d['xx'].append(5) and have it work as expected, BUT it would also # consume more memory and make the d.close() operation slower. d.close() # close it </code></pre>
6
2009-08-30T18:27:40Z
[ "python", "file", "hashtable" ]
Storing huge hash table in a file in Python
1,354,520
<p>Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there's no other option if the amount of data is really huge. Thanks!</p>
4
2009-08-30T18:24:09Z
1,354,611
<p>You can also go one step down the ladder and use <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a>. <a href="http://docs.python.org/library/shelve.html#module-shelve" rel="nofollow">Shelve</a> imports from pickle (<a href="http://groups.google.com/group/comp.lang.python/msg/2913f64bc43e81bc" rel="nofollow">link</a>), so if you don't need the added functionality of shelve, this may spare you some clock cycles (although, they really don't matter to you, as you have choosen python to do large number storing)</p>
0
2009-08-30T18:52:06Z
[ "python", "file", "hashtable" ]
Storing huge hash table in a file in Python
1,354,520
<p>Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there's no other option if the amount of data is really huge. Thanks!</p>
4
2009-08-30T18:24:09Z
1,354,615
<p>For <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a>, I stored a precomputed list of primes up to 10**8 in a text file just by writing them in comma separated format. It worked well for that size, but it doesn't scale well to going much larger.</p> <p>If your huge is not really that huge, I would use something simple like me, otherwise I would go with shelve as the others have said.</p>
1
2009-08-30T18:54:37Z
[ "python", "file", "hashtable" ]
Storing huge hash table in a file in Python
1,354,520
<p>Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there's no other option if the amount of data is really huge. Thanks!</p>
4
2009-08-30T18:24:09Z
1,354,619
<p>For a list of primes up to <code>10**9</code>, why do you need a hash? What would the KEYS be?! Sounds like a perfect opportunity for a simple, straightforward binary file! By the <a href="http://en.wikipedia.org/wiki/Prime%5Fnumber%5Ftheorem">Prime Number Theorem</a>, there's about <code>10**9/ln(10**9)</code> such primes -- i.e. 50 millions or a bit less. At 4 bytes per prime, that's only 200 MB or less -- perfect for an <code>array.array("L")</code> and its methods such as <code>fromfile</code>, etc (see <a href="http://docs.python.org/library/array.html">the docs</a>). In many cases you could actually suck all of the 200 MB into memory, but, worst case, you can get a slice of those (e.g. via <a href="http://docs.python.org/library/mmap.html">mmap</a> and the <code>fromstring</code> method of <code>array.array</code>), do binary searches there (e.g. via <a href="http://docs.python.org/library/bisect.html">bisect</a>), etc, etc.</p> <p>When you DO need a <strong>huge</strong> key-values store -- gigabytes, not a paltry 200 MB!-) -- I used to recommend <code>shelve</code> but after unpleasant real-life experience with huge shelves (performance, reliability, etc), I currently recommend a database engine instead -- sqlite is good and comes with Python, PostgreSQL is even better, non-relational ones such as CouchDB can be better still, and so forth.</p>
10
2009-08-30T18:56:01Z
[ "python", "file", "hashtable" ]
Storing huge hash table in a file in Python
1,354,520
<p>Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there's no other option if the amount of data is really huge. Thanks!</p>
4
2009-08-30T18:24:09Z
1,354,632
<p>Let's see where the bottleneck is. When you're going to read a file, the hard drive has to turn enough to be able to read from it; then it reads a big block and caches the results.</p> <p>So you want some method that will guess exactly <em>what position in file you're going to read from</em> and then do it exactly once. I'm pretty much sure standard DB modules will work for you, but you can do it yourself -- just open the file in binary mode for reading/writing and store your values as, say, 30-digits (=100-bit = 13-byte) numbers.</p> <p>Then use standard <code>file</code> methods .</p>
0
2009-08-30T18:59:23Z
[ "python", "file", "hashtable" ]
Storing huge hash table in a file in Python
1,354,520
<p>Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there's no other option if the amount of data is really huge. Thanks!</p>
4
2009-08-30T18:24:09Z
1,354,750
<p>Just naively sticking a hash table onto disk will result in about 5 orders of magnitude performance loss compared to an in memory implementation (or at least 3 if you have a SSD). When dealing with hard disks you'll want to extract every bit of data-locality and caching you can get.</p> <p>The correct choice will depend on details of your use case. How much performance do you need? What kind of operations do you need on data-structure? Do you need to only check if the table contains a key or do you need to fetch a value based on the key? Can you precompute the table or do you need to be able to modify it on the fly? What kind of hit rate are you expecting? Can you filter out a significant amount of the operations using a bloom filter? Are the requests uniformly distributed or do you expect some kind of temporal locality? Can you predict the locality clusters ahead of time?</p> <p>If you don't need ultimate performance or can parallelize and throw hardware at the problem check out some <a href="http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/" rel="nofollow">distributed key-value stores</a>.</p>
1
2009-08-30T19:50:31Z
[ "python", "file", "hashtable" ]
Storing huge hash table in a file in Python
1,354,520
<p>Hey. I have a function I want to memoize, however, it has too many possible values. Is there any convenient way to store the values in a text file and make it read from them? For example, something like storing a pre-computed list of primes up to 10^9 in a text file? I know it's slow to read from a text file but there's no other option if the amount of data is really huge. Thanks!</p>
4
2009-08-30T18:24:09Z
1,354,864
<p>You could also just go with the ultimate brute force, and create a Python file with just a single statement in it:</p> <pre><code>seedprimes = [3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73, 79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173, ... </code></pre> <p>and then just import it. (Here is file with the primes up to 1e5: <a href="http://python.pastebin.com/f177ec30" rel="nofollow">http://python.pastebin.com/f177ec30</a>).</p> <pre><code>from primes_up_to_1e9 import seedprimes </code></pre>
3
2009-08-30T20:49:04Z
[ "python", "file", "hashtable" ]
python object to native c++ pointer
1,355,187
<p>Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer.</p> <p>So this is my class:</p> <pre><code>class CGEGameModeBase { public: virtual void FunctionCall()=0; virtual const char* StringReturn()=0; }; class CGEPYGameMode : public CGEGameModeBase, public boost::python::wrapper&lt;CGEPYGameMode&gt; { public: virtual void FunctionCall() { if (override f = this-&gt;get_override("FunctionCall")) f(); } virtual const char* StringReturn() { if (override f = this-&gt;get_override("StringReturn")) return f(); return "FAILED TO CALL"; } }; </code></pre> <p>Boost wrapping:</p> <pre><code>BOOST_PYTHON_MODULE(GEGameMode) { class_&lt;CGEGameModeBase, boost::noncopyable&gt;("CGEGameModeBase", no_init); class_&lt;CGEPYGameMode, bases&lt;CGEGameModeBase&gt; &gt;("CGEPYGameMode", no_init) .def("FunctionCall", &amp;CGEPYGameMode::FunctionCall) .def("StringReturn", &amp;CGEPYGameMode::StringReturn); } </code></pre> <p>and the python code:</p> <pre><code>import GEGameMode def Ident(): return "Alpha" def NewGamePlay(): return "NewAlpha" def NewAlpha(): import GEGameMode import GEUtil class Alpha(GEGameMode.CGEPYGameMode): def __init__(self): print "Made new Alpha!" def FunctionCall(self): GEUtil.Msg("This is function test Alpha!") def StringReturn(self): return "This is return test Alpha!" return Alpha() </code></pre> <p>Now i can call the first to functions fine by doing this:</p> <pre><code>const char* ident = extract&lt; const char* &gt;( GetLocalDict()["Ident"]() ); const char* newgameplay = extract&lt; const char* &gt;( GetLocalDict()["NewGamePlay"]() ); printf("Loading Script: %s\n", ident); CGEPYGameMode* m_pGameMode = extract&lt; CGEPYGameMode* &gt;( GetLocalDict()[newgameplay]() ); </code></pre> <p>However when i try and convert the Alpha class back to its base class (last line above) i get an boost error:</p> <pre><code>TypeError: No registered converter was able to extract a C++ pointer to type class CGEPYGameMode from this Python object of type Alpha </code></pre> <p>I have done alot of searching on the net but cant work out how to convert the Alpha object into its base class pointer. I could leave it as an object but rather have it as a pointer so some non python aware code can use it. Any ideas?</p>
2
2009-08-30T23:17:28Z
1,356,618
<p>Well, I am not sure whether it will help you, but I had the same problem with scripts in Lua. We created objects from Lua and wanted some c++ code to handle the objects via pointers. We did the following:</p> <ul> <li>all object stuff was written in c++, including constructors, destructors and factory method;</li> <li>lua code was calling a factory method to create an object. this factory method 1) gave the object a unique ID number and 2) registered it in the c++ map, that mapped ID numbers to native pointers;</li> <li>so, whenever lua was going to pass a pointer to c++ code, it gave an object ID instead, and the c++ code looked up the map for finding the actual pointer by ID.</li> </ul>
0
2009-08-31T09:22:47Z
[ "c++", "python", "boost", "embedded-language" ]
python object to native c++ pointer
1,355,187
<p>Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer.</p> <p>So this is my class:</p> <pre><code>class CGEGameModeBase { public: virtual void FunctionCall()=0; virtual const char* StringReturn()=0; }; class CGEPYGameMode : public CGEGameModeBase, public boost::python::wrapper&lt;CGEPYGameMode&gt; { public: virtual void FunctionCall() { if (override f = this-&gt;get_override("FunctionCall")) f(); } virtual const char* StringReturn() { if (override f = this-&gt;get_override("StringReturn")) return f(); return "FAILED TO CALL"; } }; </code></pre> <p>Boost wrapping:</p> <pre><code>BOOST_PYTHON_MODULE(GEGameMode) { class_&lt;CGEGameModeBase, boost::noncopyable&gt;("CGEGameModeBase", no_init); class_&lt;CGEPYGameMode, bases&lt;CGEGameModeBase&gt; &gt;("CGEPYGameMode", no_init) .def("FunctionCall", &amp;CGEPYGameMode::FunctionCall) .def("StringReturn", &amp;CGEPYGameMode::StringReturn); } </code></pre> <p>and the python code:</p> <pre><code>import GEGameMode def Ident(): return "Alpha" def NewGamePlay(): return "NewAlpha" def NewAlpha(): import GEGameMode import GEUtil class Alpha(GEGameMode.CGEPYGameMode): def __init__(self): print "Made new Alpha!" def FunctionCall(self): GEUtil.Msg("This is function test Alpha!") def StringReturn(self): return "This is return test Alpha!" return Alpha() </code></pre> <p>Now i can call the first to functions fine by doing this:</p> <pre><code>const char* ident = extract&lt; const char* &gt;( GetLocalDict()["Ident"]() ); const char* newgameplay = extract&lt; const char* &gt;( GetLocalDict()["NewGamePlay"]() ); printf("Loading Script: %s\n", ident); CGEPYGameMode* m_pGameMode = extract&lt; CGEPYGameMode* &gt;( GetLocalDict()[newgameplay]() ); </code></pre> <p>However when i try and convert the Alpha class back to its base class (last line above) i get an boost error:</p> <pre><code>TypeError: No registered converter was able to extract a C++ pointer to type class CGEPYGameMode from this Python object of type Alpha </code></pre> <p>I have done alot of searching on the net but cant work out how to convert the Alpha object into its base class pointer. I could leave it as an object but rather have it as a pointer so some non python aware code can use it. Any ideas?</p>
2
2009-08-30T23:17:28Z
1,356,622
<p>May not be the answer you are looking for, but take a look at <a href="http://www.chaiscript.com/" rel="nofollow">ChaiScript</a> for embedding in your C++ application.</p> <p>According to their website,</p> <blockquote> <p>ChaiScript is the first and only scripting language designed from the ground up with C++ compatibility in mind. It is an ECMAScript-inspired, embedded functional-like language.</p> <p>ChaiScript has no meta-compiler, no library dependencies, no build system requirements and no legacy baggage of any kind. At can work seamlessly with any C++ functions you expose to it. It does not have to be told explicitly about any type, it is function centric.</p> <p>With ChaiScript you can literally begin scripting your application by adding three lines of code to your program and not modifying your build steps at all.</p> </blockquote>
0
2009-08-31T09:23:25Z
[ "c++", "python", "boost", "embedded-language" ]
python object to native c++ pointer
1,355,187
<p>Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer.</p> <p>So this is my class:</p> <pre><code>class CGEGameModeBase { public: virtual void FunctionCall()=0; virtual const char* StringReturn()=0; }; class CGEPYGameMode : public CGEGameModeBase, public boost::python::wrapper&lt;CGEPYGameMode&gt; { public: virtual void FunctionCall() { if (override f = this-&gt;get_override("FunctionCall")) f(); } virtual const char* StringReturn() { if (override f = this-&gt;get_override("StringReturn")) return f(); return "FAILED TO CALL"; } }; </code></pre> <p>Boost wrapping:</p> <pre><code>BOOST_PYTHON_MODULE(GEGameMode) { class_&lt;CGEGameModeBase, boost::noncopyable&gt;("CGEGameModeBase", no_init); class_&lt;CGEPYGameMode, bases&lt;CGEGameModeBase&gt; &gt;("CGEPYGameMode", no_init) .def("FunctionCall", &amp;CGEPYGameMode::FunctionCall) .def("StringReturn", &amp;CGEPYGameMode::StringReturn); } </code></pre> <p>and the python code:</p> <pre><code>import GEGameMode def Ident(): return "Alpha" def NewGamePlay(): return "NewAlpha" def NewAlpha(): import GEGameMode import GEUtil class Alpha(GEGameMode.CGEPYGameMode): def __init__(self): print "Made new Alpha!" def FunctionCall(self): GEUtil.Msg("This is function test Alpha!") def StringReturn(self): return "This is return test Alpha!" return Alpha() </code></pre> <p>Now i can call the first to functions fine by doing this:</p> <pre><code>const char* ident = extract&lt; const char* &gt;( GetLocalDict()["Ident"]() ); const char* newgameplay = extract&lt; const char* &gt;( GetLocalDict()["NewGamePlay"]() ); printf("Loading Script: %s\n", ident); CGEPYGameMode* m_pGameMode = extract&lt; CGEPYGameMode* &gt;( GetLocalDict()[newgameplay]() ); </code></pre> <p>However when i try and convert the Alpha class back to its base class (last line above) i get an boost error:</p> <pre><code>TypeError: No registered converter was able to extract a C++ pointer to type class CGEPYGameMode from this Python object of type Alpha </code></pre> <p>I have done alot of searching on the net but cant work out how to convert the Alpha object into its base class pointer. I could leave it as an object but rather have it as a pointer so some non python aware code can use it. Any ideas?</p>
2
2009-08-30T23:17:28Z
1,357,350
<p>Thanks to Stefan from the python c++ mailling list, i was missing </p> <pre><code>super(Alpha, self).__init__() </code></pre> <p>from the constructor call meaning it never made the parent class. Thought this would of been automatic :D</p> <p>Only other issue i had was saving the new class instance as a global var otherwise it got cleaned up as it went out of scope.</p> <p>So happy now</p>
1
2009-08-31T13:00:16Z
[ "c++", "python", "boost", "embedded-language" ]
How to tell if a full-screen application is running?
1,355,206
<p>Is it possible in python to tell if a full screen application on linux is running? I have a feeling it might be possible using Xlib but I haven't found a way.</p> <p><strong>EDIT:</strong> By full screen I mean the WHOLE screen nothing else but the application, such as a full-screen game.</p>
6
2009-08-30T23:26:39Z
1,355,332
<p>If all Window Managers you're interested in running under support <a href="http://standards.freedesktop.org/wm-spec/1.3/index.html#id2463334" rel="nofollow">EWMH</a>, the Extended Window Manager Hints standard, there are elegant ways to perform this (speaking to Xlib via ctypes, for example). The <code>_NET_ACTIVE_WINDOW</code> property of the root window (see <a href="http://standards.freedesktop.org/wm-spec/1.3/ar01s03.html" rel="nofollow">here</a>) tells you which window is active (if any); the <code>_NET_WM_STATE</code> property of the active window is then a list of atoms describing its state which will include <code>_NET_WM_STATE_FULLSCREEN</code> if that window is fullscreen. (If you have multiple monitors of course a window could be fullscreen on one of them without being active; I believe other cases may exist in which a window may be fullscreen without being active -- I don't think there's any way to cover them all without essentially checking <code>_NET_WM_STATE</code> for every window, though).</p>
4
2009-08-31T00:36:33Z
[ "python", "linux", "x11" ]
How to tell if a full-screen application is running?
1,355,206
<p>Is it possible in python to tell if a full screen application on linux is running? I have a feeling it might be possible using Xlib but I haven't found a way.</p> <p><strong>EDIT:</strong> By full screen I mean the WHOLE screen nothing else but the application, such as a full-screen game.</p>
6
2009-08-30T23:26:39Z
1,360,522
<p>Found a solution:</p> <pre><code>import Xlib.display screen = Xlib.display.Display().screen() root_win = screen.root num_of_fs = 0 for window in root_win.query_tree()._data['children']: window_name = window.get_wm_name() width = window.get_geometry()._data["width"] height = window.get_geometry()._data["height"] if width == screen.width_in_pixels and height == screen.height_in_pixels: num_of_fs += 1 print num_of_fs </code></pre> <p>This prints out the number of fullscreen windows which for me is normally one. When playing a full screen game its 2.</p>
3
2009-09-01T04:27:22Z
[ "python", "linux", "x11" ]
Python code to download a webpage using JavaScript
1,355,244
<p>Im trying to download share data from a stock exchange using python. The problem is that there is no direct download link, but rather a javascript to export the data.</p> <p>The data page url: </p> <pre><code>http://tase.co.il/TASE/Templates/Company/CompanyHistory.aspx?NRMODE=Published&amp;NRORIGINALURL=%2fTASEEng%2fGeneral%2fCompany%2fcompanyHistoryData.htm%3fcompanyID%3d001216%26ShareID%3d01091248%26subDataType%3d0%26&amp;NRNODEGUID={045D6005-5C86-4A8E-ADD4-C151A77EC14B}&amp;NRCACHEHINT=Guest&amp;shareID=01820083&amp;companyID=000182&amp;subDataType=0 </code></pre> <p>When I open the data page in a browser and then the download page, it works like a charm. When I just open the download page, it doen't download anything. I guess this is because the data page injects the actual data to the variables Columns, Titles etc.</p> <p>I've tried to mimic this behaviour in a python script, but without success.</p> <pre><code>def download_CSV (shareID, compID): data_url ="http://tase.co.il/TASE/Templates/Company/CompanyHistory.aspx?NRMODE=Published&amp;NRORIGINALURL=%2fTASEEng%2fGeneral%2fCompany%2fcompanyHistoryData.htm%3fsubDataType%3d0%26shareID%3d00759019&amp;NRNODEGUID={045D6005-5C86-4A8E-ADD4-C151A77EC14B}&amp;NRCACHEHINT=Guest&amp;shareID="+shareID+"&amp;companyID="+compID+"&amp;subDataType=0" import urllib2 response = urllib2.urlopen(data_url) html = response.read() down_url ="http://tase.co.il/TASE/Pages/Export.aspx?tbl=0&amp;Columns=AddColColumnsHistory&amp;Titles=AddColTitlesHistory&amp;sn=dsHistory&amp;enumTblType=GridHistorydaily&amp;ExportType=3" import urllib urllib.urlretrieve (down_url, "test.csv") </code></pre> <p>Thanks a lot</p>
1
2009-08-30T23:52:45Z
1,355,294
<p>You could use <a href="http://seleniumhq.org/" rel="nofollow">Selenium</a> or other ways to automate a browser to take advantage of the browser's built-in Javascript interpreter -- to control Selenium with Python, see e.g. <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html" rel="nofollow">here</a>.</p>
1
2009-08-31T00:15:31Z
[ "javascript", "python" ]
Latin letters with acute : DjangoUnicodeDecodeError
1,355,285
<p>I have a problem reading a txt file to insert in the mysql db table, te sniped of this code:</p> <p>file contains the in first line: "<b>aclaración</b>"</p> <blockquote> <p>archivo = open('file.txt',"r") <br> for line in archivo.readlines():<br> ....body = body + line<br> model = MyModel(body=body)<br> model.save()</p> </blockquote> <p>i get a DjangoUnicodeDecodeError:</p> <p>'utf8' codec can't decode bytes in position 8: invalid data. You passed in 'aclaraci\xf3n' (type 'str') Unicode error hint</p> <p>The string that could not be encoded/decoded was: araci�n.<br><br></p> <p>I tried to body.decode('utf-8'), body.decode('latin-1'), body.decode('iso-8859-1') without solution.</p> <p>Can you help me please? Any hint is apreciated :)</p>
1
2009-08-31T00:11:44Z
1,355,303
<p>Judging from the <code>\xf3</code> code for 'ó', it does look like the data is encoded in ISO-8859-1 (or some close relative). So <code>body.decode('iso-8859-1')</code> should be a valid Unicode string (you don't specify what "without solution" means -- what error message do you get, and where?); if what you need is a utf-8 encoded bytestring instead, <code>body.decode('iso-8859-1').encode('utf-8')</code> should give you one!</p>
5
2009-08-31T00:20:06Z
[ "python", "django", "utf-8", "character-encoding" ]
Python classes -- mutability
1,355,555
<p>Im having a problem with python.. I have a binary tree node type:</p> <pre><code>class NODE: element = 0 leftchild = None rightchild = None </code></pre> <p>And I had to implement a function deletemin:</p> <pre><code>def DELETEMIN( A ): if A.leftchild == None: retval = A.element A = A.rightchild return retval else: return DELETEMIN( A.leftchild ) </code></pre> <p>Yet, when I try to test this on the binary tree:</p> <pre><code> 1 / \ 0 2 </code></pre> <p>It should delete 0, by just setting it to null but instead, i get this:</p> <pre><code> 0 / \ 0 2 </code></pre> <p>Why can I not nullify a node within a function in python? Is their a way to do this? </p>
1
2009-08-31T02:26:42Z
1,355,568
<p>Python passes arguments by object-reference, just like java, not by variable-reference. When you assign to a local variable (including an argument) to a new value, you're changing only the local variable, nothing else (don't confuse that with calling mutators or assigning to ATTRIBUTES of objects: we're talking about assignments to barenames).</p> <p>The preferred solution in Python is generally to return multiple values, as many as you need, and assign them appropriately in the caller. So deletemin would return two values, the current returnval and the modified node, and the caller would assign the latter as needed. I.e.:</p> <pre><code>def DELETEMIN( A ): if A.leftchild is None: return A.element, A.rightchild else: return DELETEMIN( A.leftchild ) </code></pre> <p>and in the caller, where you previously had <code>foo = DELETEMIN( bar )</code>, you'd use instead</p> <pre><code>foo, bar = DELETEMIN( bar ) </code></pre> <p>Peculiar capitalization and spacing within parentheses, BTW, but that's another issue;-).</p> <p>There is no way to get "a pointer or reference to a caller's barename" (in either Python or Java) in the way you could, e.g., in C or C++. There are other alternative approaches, but they require different arrangements than you appear to prefer, so I recommend the multiple return values approach as here indicated.</p>
2
2009-08-31T02:31:26Z
[ "python", "class" ]