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
Better to install MySQL 32bit or 64bit on my 64bit Intel-based Mac (Perl/Python user)?
1,436,422
<p>I have had numerous headaches trying to get the MySQL APIs for Perl and Python working on my 64 bit Macbook Pro (Leopard). I installed the 64 bit version of MySQL, but Googling around now I have the impression that this could be the source of my pain. None of the various blogs and SO answers quite seem to work (for example <a href="http://stackoverflow.com/questions/395509/how-do-i-install-mysql-and-the-python-mysql-package-on-osx-leopard-or-how-do-i">here on SO</a>)</p> <p>Could the 64 bit MySQL install be the culprit? Can anyone confirm that they have MySQL access via Perl and/or Python on a 64 bit Mac using 64 bit MySQL? Did you do anything special or face some similar problems?</p>
5
2009-09-17T02:23:39Z
1,436,434
<p>32-bit and 64-bit libraries don't play nice together. So, it depends whether you're using 32-bit Perl/Python or not.</p> <p>If you are, you'll need 32-bit MySQL. Chances are your Python, at least, is 32-bit, since both the Apple-shipped Python and the binaries from python.org are 32-bit only. You can build 64-bit Python (or- <em>gasp</em>- a 4-way i386/x86_64/ppc/ppc64 Universal Binary) from source, but unless you really need to work with absolutely huge disk files/amounts of memory (I'm talking multi-gigabyte memory maps, for example), chances are you do not need 64-bit anything right now.</p>
4
2009-09-17T02:29:48Z
[ "python", "mysql", "perl" ]
Better to install MySQL 32bit or 64bit on my 64bit Intel-based Mac (Perl/Python user)?
1,436,422
<p>I have had numerous headaches trying to get the MySQL APIs for Perl and Python working on my 64 bit Macbook Pro (Leopard). I installed the 64 bit version of MySQL, but Googling around now I have the impression that this could be the source of my pain. None of the various blogs and SO answers quite seem to work (for example <a href="http://stackoverflow.com/questions/395509/how-do-i-install-mysql-and-the-python-mysql-package-on-osx-leopard-or-how-do-i">here on SO</a>)</p> <p>Could the 64 bit MySQL install be the culprit? Can anyone confirm that they have MySQL access via Perl and/or Python on a 64 bit Mac using 64 bit MySQL? Did you do anything special or face some similar problems?</p>
5
2009-09-17T02:23:39Z
1,437,190
<p>You <strong>will</strong> need the 32vit vs 64bit of the MySQL <em>client libraries</em> to match the application you're trying to link them with. However, this not prevent you from connecting to a 64-bit install of MySQL <em>server</em>.</p> <p>In Unix, the MySQL client libraries support multiple versions of themselves lying around; you just have to make sure the application is loading the correct one. This should be true to the Mac.</p>
2
2009-09-17T07:15:51Z
[ "python", "mysql", "perl" ]
Python: Passing a class name as a parameter to a function?
1,436,444
<pre><code>class TestSpeedRetrieval(webapp.RequestHandler): """ Test retrieval times of various important records in the BigTable database """ def get(self): commandValidated = True beginTime = time() itemList = Subscriber.all().fetch(1000) for item in itemList: pass endTime = time() self.response.out.write("&lt;br/&gt;Subscribers count=" + str(len(itemList)) + " Duration=" + duration(beginTime,endTime)) </code></pre> <p>How can I turn the above into a function where I pass the name of the class? In the above example, Subscriber is a class name. </p> <p>I want to do something like this: </p> <pre><code> TestRetrievalOfClass(Subscriber) or TestRetrievalOfClass("Subscriber") </code></pre> <p>Thanks, Neal Walters </p>
21
2009-09-17T02:32:43Z
1,436,461
<pre><code>class TestSpeedRetrieval(webapp.RequestHandler): """ Test retrieval times of various important records in the BigTable database """ def __init__(self, cls): self.cls = cls def get(self): commandValidated = True beginTime = time() itemList = self.cls.all().fetch(1000) for item in itemList: pass endTime = time() self.response.out.write("&lt;br/&gt;%s count=%d Duration=%s" % (self.cls.__name__, len(itemList), duration(beginTime,endTime)) TestRetrievalOfClass(Subscriber) </code></pre>
13
2009-09-17T02:37:09Z
[ "python", "function" ]
Python: Passing a class name as a parameter to a function?
1,436,444
<pre><code>class TestSpeedRetrieval(webapp.RequestHandler): """ Test retrieval times of various important records in the BigTable database """ def get(self): commandValidated = True beginTime = time() itemList = Subscriber.all().fetch(1000) for item in itemList: pass endTime = time() self.response.out.write("&lt;br/&gt;Subscribers count=" + str(len(itemList)) + " Duration=" + duration(beginTime,endTime)) </code></pre> <p>How can I turn the above into a function where I pass the name of the class? In the above example, Subscriber is a class name. </p> <p>I want to do something like this: </p> <pre><code> TestRetrievalOfClass(Subscriber) or TestRetrievalOfClass("Subscriber") </code></pre> <p>Thanks, Neal Walters </p>
21
2009-09-17T02:32:43Z
1,436,462
<p>If you pass the class object directly, as in your code between "like this" and "or", you can get its name as the <code>__name__</code> attribute.</p> <p>Starting with the name (as in your code <em>after</em> "or") makes it REALLY hard (and not unambiguous) to retrieve the class object unless you have some indication about where the class object may be contained -- so why not pass the class object instead?!</p>
9
2009-09-17T02:37:23Z
[ "python", "function" ]
Python: Passing a class name as a parameter to a function?
1,436,444
<pre><code>class TestSpeedRetrieval(webapp.RequestHandler): """ Test retrieval times of various important records in the BigTable database """ def get(self): commandValidated = True beginTime = time() itemList = Subscriber.all().fetch(1000) for item in itemList: pass endTime = time() self.response.out.write("&lt;br/&gt;Subscribers count=" + str(len(itemList)) + " Duration=" + duration(beginTime,endTime)) </code></pre> <p>How can I turn the above into a function where I pass the name of the class? In the above example, Subscriber is a class name. </p> <p>I want to do something like this: </p> <pre><code> TestRetrievalOfClass(Subscriber) or TestRetrievalOfClass("Subscriber") </code></pre> <p>Thanks, Neal Walters </p>
21
2009-09-17T02:32:43Z
1,436,624
<p>A slight variation of Ned's code that I used. This is a web application, so I start it by running the get routine via a URL: <a href="http://localhost:8080/TestSpeedRetrieval" rel="nofollow">http://localhost:8080/TestSpeedRetrieval</a>. I didn't see the need of the <strong>init</strong>. </p> <pre><code>class TestSpeedRetrieval(webapp.RequestHandler): """ Test retrieval times of various important records in the BigTable database """ def speedTestForRecordType(self, recordTypeClassname): beginTime = time() itemList = recordTypeClassname.all().fetch(1000) for item in itemList: pass # just because we almost always loop through the records to put them somewhere endTime = time() self.response.out.write("&lt;br/&gt;%s count=%d Duration=%s" % (recordTypeClassname.__name__, len(itemList), duration(beginTime,endTime))) def get(self): self.speedTestForRecordType(Subscriber) self.speedTestForRecordType(_AppEngineUtilities_SessionData) self.speedTestForRecordType(CustomLog) </code></pre> <p>Output: </p> <pre><code>Subscriber count=11 Duration=0:2 _AppEngineUtilities_SessionData count=14 Duration=0:1 CustomLog count=5 Duration=0:2 </code></pre>
0
2009-09-17T03:47:30Z
[ "python", "function" ]
Sharing widgets between PyQT and Boost.Python
1,436,514
<p>I was wondering if it was possible to share widgets between PyQt and Boost.Python.</p> <p>I will be embedding a Python interpreter into an application of mine that uses Qt. I would like users of my application to be able to embed their own UI widgets into UI widgets programmed in C++ and exposed via Boost.Python.</p> <p>Is this possible and how would one go about doing this?</p>
3
2009-09-17T02:59:18Z
1,530,455
<p>I've tried to write some proxying for this, but I haven't succeeded completely. Here's a start that tries to solve this, but the dir() won't work. Calling functions directly works somewhat.</p> <p>The idea was to create an additional python object wrapped in SIP and forward any calls/attributes to that object if the original boost.python object does not have any matching attribute.</p> <p>I'm not enough of a Python guru to make this work properly, though. :(</p> <p>(I'm turning this into a wiki, so ppl can edit and update here, as this code is just half-baked boilerplate.)</p> <p>c++:</p> <pre><code>#include "stdafx.h" #include &lt;QtCore/QTimer&gt; class MyWidget : public QTimer { public: MyWidget() {} void foo() { std::cout &lt;&lt; "yar\n"; } unsigned long myself() { return reinterpret_cast&lt;unsigned long&gt;(this); } }; #ifdef _DEBUG BOOST_PYTHON_MODULE(PyQtBoostPythonD) #else BOOST_PYTHON_MODULE(PyQtBoostPython) #endif { using namespace boost::python; class_&lt;MyWidget, bases&lt;&gt;, MyWidget*, boost::noncopyable&gt;("MyWidget"). def("foo", &amp;MyWidget::foo). def("myself", &amp;MyWidget::myself); } </code></pre> <p>Python:</p> <pre><code>from PyQt4.Qt import * import sys import sip from PyQtBoostPythonD import * # the module compiled from cpp file above a = QApplication(sys.argv) w = QWidget() f = MyWidget() def _q_getattr(self, attr): if type(self) == type(type(MyWidget)): raise AttributeError else: print "get %s" % attr value = getattr(sip.wrapinstance(self.myself(), QObject), attr) print "get2 %s returned %s" % (attr, value) return value MyWidget.__getattr__ = _q_getattr def _q_dir(self): r = self.__dict__ r.update(self.__class__.__dict__) wrap = sip.wrapinstance(self.myself(), QObject) r.update(wrap.__dict__) r.update(wrap.__class__.__dict__) return r MyWidget.__dir__ = _q_dir f.start() f.foo() print dir(f) </code></pre>
2
2009-10-07T09:13:36Z
[ "python", "qt", "pyqt", "sip", "boost-python" ]
GAE - How Do i edit / update the datastore in python
1,436,545
<p>I have this datastore model</p> <pre><code>class Project(db.Model) projectname = db.StringProperty() projecturl = db.StringProperty() class Task(db.Model) project = db.ReferenceProperty(Project) taskname= db.StringProperty() taskdesc = db.StringProperty() </code></pre> <p>How do I edit the value of taskname ? say I have task1 and i want to change it to task1-project</p>
2
2009-09-17T03:12:28Z
1,436,553
<p>Given an instance <code>t</code> of <code>Task</code> (e.g. from some <code>get</code> operation on the <code>db</code>) you can perform the alteration you want e.g. by <code>t.taskname = t.taskname + '-project'</code> (if what you want is to "append <code>'-project'</code> to whatever was there before). Eventually, you also probably need to <code>.put</code> <code>t</code> back into the store, of course (but if you make multiple changes you don't need to put it back after each and every change -- only when you're done changing it!-).</p>
1
2009-09-17T03:18:19Z
[ "python", "google-app-engine", "gql", "gqlquery" ]
GAE - How Do i edit / update the datastore in python
1,436,545
<p>I have this datastore model</p> <pre><code>class Project(db.Model) projectname = db.StringProperty() projecturl = db.StringProperty() class Task(db.Model) project = db.ReferenceProperty(Project) taskname= db.StringProperty() taskdesc = db.StringProperty() </code></pre> <p>How do I edit the value of taskname ? say I have task1 and i want to change it to task1-project</p>
2
2009-09-17T03:12:28Z
1,436,563
<p>Probably the easiest way is to use the admin console. Locally it's:</p> <pre><code>http://localhost:8080/_ah/admin </code></pre> <p>and if you've uploaded it, it's the dashboard:</p> <pre><code>http://appengine.google.com/dashboard?&amp;app_id=****** </code></pre> <p><a href="http://code.google.com/appengine/docs/python/tools/devserver.html#The%5FDevelopment%5FConsole" rel="nofollow">Here's</a> a link:</p>
-1
2009-09-17T03:20:05Z
[ "python", "google-app-engine", "gql", "gqlquery" ]
GAE - How Do i edit / update the datastore in python
1,436,545
<p>I have this datastore model</p> <pre><code>class Project(db.Model) projectname = db.StringProperty() projecturl = db.StringProperty() class Task(db.Model) project = db.ReferenceProperty(Project) taskname= db.StringProperty() taskdesc = db.StringProperty() </code></pre> <p>How do I edit the value of taskname ? say I have task1 and i want to change it to task1-project</p>
2
2009-09-17T03:12:28Z
1,442,200
<p>oops sorry, Here is the formatted code:</p> <p>taskkey = self.request.get("taskkey") <br/> taskid = Task.get(taskkey)<br/> query = db.GqlQuery("SELECt * FROM Task WHERE key =:taskid", taskid=taskid)<br/></p> <p>if query.count() > 0:<br/> task = Task()<br/> task.taskname = "task1-project"<br/> task.put()</p> <p>by the way I get it now. I changed the task=Task() into task = query.get() and it worked. </p> <p>Thanks for helping by the way.</p>
2
2009-09-18T01:30:39Z
[ "python", "google-app-engine", "gql", "gqlquery" ]
unique pin generator
1,436,552
<p>The task is to generate a given number of numeric pins of a given length. Here's the code I came up with for a particular case of numeric pins that don't start with 0:</p> <pre><code>def generate_pins(length, count): return random.sample(range(int('1' + '0' * (length - 1)), int('9' * length)), count) </code></pre> <p>How would you implement it?</p> <p>EDIT: Pins shouldn't repeat.</p> <p>EDIT2: Probably let's extend this example so that pin can contain any alphanumeric symbol.</p>
0
2009-09-17T03:17:49Z
1,436,574
<p><code>random.sample</code> guarantees no repetition ("sampling without replacement", per <a href="http://docs.python.org/library/random.html?highlight=random.sample#random.sample" rel="nofollow">the docs</a>); is this condition part of your specs?</p> <p>As expressed (without any word "<strong>distinct</strong>" to indicate lack of repetition), I'd do:</p> <pre><code>import random import string def generate_pins(length, count): return [''.join(random.choice(string.digits) for x in xrange(length)) for x in xrange(count)] </code></pre> <p><em>With</em> an additional condition that all the pins returned be unique:</p> <pre><code>def generate_pins(length, count, alphabet=string.digits): alphabet = ''.join(set(alphabet)) if count &gt; len(alphabet)**length: raise ValueError("Can't generate more than %s &gt; %s pins of length %d out of %r" % count, len(alphabet)**length, length, alphabet) def onepin(length): return ''.join(random.choice(alphabet) for x in xrange(length)) result = set(onepin(length) for x in xrange(count)) while len(result) &lt; count: result.add(onepin(length)) return list(result) </code></pre> <p>assuming that the specs require you to return a list.</p> <p><strong>Edit</strong>: given the OP's late clarification and spec changes, the second answer looks good, except <code>string.ascii_lowercase + string.digits</code> (or some variants thereof e.g. if both lowercase and uppercase ASCII letters are desired) should be used in <code>onepin</code>. You should specify better exactly what "alphabet" string you want to draw characters from (maybe pass it to <code>generate_pins</code> as an argument, with <code>None</code> indicating <code>generate_pins</code> should pick a default alphabet such as e.g. <code>string.digits</code>).</p> <p><strong>Further edit</strong>: added optional alphabet argument and checks about number of distinct pins that can be generated given length and that alphabet.</p>
6
2009-09-17T03:25:25Z
[ "python" ]
unique pin generator
1,436,552
<p>The task is to generate a given number of numeric pins of a given length. Here's the code I came up with for a particular case of numeric pins that don't start with 0:</p> <pre><code>def generate_pins(length, count): return random.sample(range(int('1' + '0' * (length - 1)), int('9' * length)), count) </code></pre> <p>How would you implement it?</p> <p>EDIT: Pins shouldn't repeat.</p> <p>EDIT2: Probably let's extend this example so that pin can contain any alphanumeric symbol.</p>
0
2009-09-17T03:17:49Z
1,436,698
<p>As OP haven't said random PINs, only criteria seems to be unique pins here is the fastest way</p> <pre><code>def generate_pins(length, count): start=10**length return range(start,start+count,1) </code></pre> <p>also you can not always guarantee uniqeness, same length and count at same time e.g. try generate_pins(1,11) for Alex's answer.</p>
1
2009-09-17T04:25:02Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
1,436,706
<p>From <a href="http://pyref.infogami.com/%5F%5Fstr%5F%5F" rel="nofollow">http://pyref.infogami.com/%5F%5Fstr%5F%5F</a> by effbot:</p> <p><code>__str__</code> "computes the "informal" string representation of an object. This differs from <code>__repr__</code> in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead."</p>
4
2009-09-17T04:28:52Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
1,436,721
<p><strong><code>__repr__</code></strong>: representation of python object usually eval will convert it back to that object</p> <p><strong><code>__str__</code></strong>: is whatever you think is that object in text form</p> <p>e.g.</p> <pre><code>&gt;&gt;&gt; s="""w'o"w""" &gt;&gt;&gt; repr(s) '\'w\\\'o"w\'' &gt;&gt;&gt; str(s) 'w\'o"w' &gt;&gt;&gt; eval(str(s))==s Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;string&gt;", line 1 w'o"w ^ SyntaxError: EOL while scanning single-quoted string &gt;&gt;&gt; eval(repr(s))==s True </code></pre>
99
2009-09-17T04:35:36Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
1,436,756
<p>Unless you specifically act to ensure otherwise, most classes don't have helpful results for either:</p> <pre><code>&gt;&gt;&gt; class Sic(object): pass ... &gt;&gt;&gt; print str(Sic()) &lt;__main__.Sic object at 0x8b7d0&gt; &gt;&gt;&gt; print repr(Sic()) &lt;__main__.Sic object at 0x8b7d0&gt; &gt;&gt;&gt; </code></pre> <p>As you see -- no difference, and no info beyond the class and object's <code>id</code>. If you only override one of the two...:</p> <pre><code>&gt;&gt;&gt; class Sic(object): ... def __repr__(object): return 'foo' ... &gt;&gt;&gt; print str(Sic()) foo &gt;&gt;&gt; print repr(Sic()) foo &gt;&gt;&gt; class Sic(object): ... def __str__(object): return 'foo' ... &gt;&gt;&gt; print str(Sic()) foo &gt;&gt;&gt; print repr(Sic()) &lt;__main__.Sic object at 0x2617f0&gt; &gt;&gt;&gt; </code></pre> <p>as you see, if you override <code>__repr__</code>, that's ALSO used for <code>__str__</code>, but not vice versa.</p> <p>Other crucial tidbits to know: <code>__str__</code> on a built-on container uses the <code>__repr__</code>, NOT the <code>__str__</code>, for the items it contains. And, despite the words on the subject found in typical docs, hardly anybody bothers making the <code>__repr__</code> of objects be a string that <code>eval</code> may use to build an equal object (it's just too hard, AND not knowing how the relevant module was actually imported makes it actually flat out impossible).</p> <p>So, my advice: focus on making <code>__str__</code> reasonably human-readable, and <code>__repr__</code> as unambiguous as you possibly can, even if that interferes with the fuzzy unattainable goal of making <code>__repr__</code>'s returned value acceptable as input to <code>__eval__</code>!</p>
215
2009-09-17T04:49:40Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
1,438,297
<p>My rule of thumb: <code>__repr__</code> is for developers, <code>__str__</code> is for customers.</p>
205
2009-09-17T11:35:13Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
2,626,364
<p>Alex summarized well but, surprisingly, was too succinct.</p> <p>First, let me reiterate the main points in Alex’s post:</p> <ul> <li>The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah)</li> <li><code>__repr__</code> goal is to be unambiguous</li> <li><code>__str__</code> goal is to be readable</li> <li>Container’s <code>__str__</code> uses contained objects’ <code>__repr__</code></li> </ul> <p><strong>Default implementation is useless</strong></p> <p>This is mostly a surprise because Python’s defaults tend to be fairly useful. However, in this case, having a default for <code>__repr__</code> which would act like:</p> <pre><code>return "%s(%r)" % (self.__class__, self.__dict__) </code></pre> <p>would have been too dangerous (for example, too easy to get into infinite recursion if objects reference each other). So Python cops out. Note that there is one default which is true: if <code>__repr__</code> is defined, and <code>__str__</code> is not, the object will behave as though <code>__str__=__repr__</code>.</p> <p>This means, in simple terms: almost every object you implement should have a functional <code>__repr__</code> that’s usable for understanding the object. Implementing <code>__str__</code> is optional: do that if you need a “pretty print” functionality (for example, used by a report generator).</p> <p><strong>The goal of <code>__repr__</code> is to be unambiguous</strong></p> <p>Let me come right out and say it — I do not believe in debuggers. I don’t really know how to use any debugger, and have never used one seriously. Furthermore, I believe that the big fault in debuggers is their basic nature — most failures I debug happened a long long time ago, in a galaxy far far away. This means that I do believe, with religious fervor, in logging. Logging is the lifeblood of any decent fire-and-forget server system. Python makes it easy to log: with maybe some project specific wrappers, all you need is a</p> <pre><code>log(INFO, "I am in the weird function and a is", a, "and b is", b, "but I got a null C — using default", default_c) </code></pre> <p>But you have to do the last step — make sure every object you implement has a useful repr, so code like that can just work. This is why the “eval” thing comes up: if you have enough information so <code>eval(repr(c))==c</code>, that means you know everything there is to know about <code>c</code>. If that’s easy enough, at least in a fuzzy way, do it. If not, make sure you have enough information about <code>c</code> anyway. I usually use an eval-like format: <code>"MyClass(this=%r,that=%r)" % (self.this,self.that)</code>. It does not mean that you can actually construct MyClass, or that those are the right constructor arguments — but it is a useful form to express “this is everything you need to know about this instance”.</p> <p>Note: I used <code>%r</code> above, not <code>%s</code>. You always want to use <code>repr()</code> [or <code>%r</code> formatting character, equivalently] inside <code>__repr__</code> implementation, or you’re defeating the goal of repr. You want to be able to differentiate <code>MyClass(3)</code> and <code>MyClass("3")</code>.</p> <p><strong>The goal of <code>__str__</code> is to be readable</strong></p> <p>Specifically, it is not intended to be unambiguous — notice that <code>str(3)==str("3")</code>. Likewise, if you implement an IP abstraction, having the str of it look like 192.168.1.1 is just fine. When implementing a date/time abstraction, the str can be "2010/4/12 15:35:22", etc. The goal is to represent it in a way that a user, not a programmer, would want to read it. Chop off useless digits, pretend to be some other class — as long is it supports readability, it is an improvement.</p> <p><strong>Container’s <code>__str__</code> uses contained objects’ <code>__repr__</code></strong></p> <p>This seems surprising, doesn’t it? It is a little, but how readable would</p> <pre><code>[moshe is, 3, hello world, this is a list, oh I don't know, containing just 4 elements] </code></pre> <p>be? Not very. Specifically, the strings in a container would find it way too easy to disturb its string representation. In the face of ambiguity, remember, Python resists the temptation to guess. If you want the above behavior when you’re printing a list, just</p> <pre><code>print "["+", ".join(l)+"]" </code></pre> <p>(you can probably also figure out what to do about dictionaries.</p> <p><strong>Summary</strong></p> <p>Implement <code>__repr__</code> for any class you implement. This should be second nature. Implement <code>__str__</code> if you think it would be useful to have a string version which errs on the side of more readability in favor of more ambiguity.</p>
1,475
2010-04-13T00:56:52Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
13,395,755
<p>In all honesty, <code>eval(repr(obj))</code> is never used. If you find yourself using it, you should stop, because <code>eval</code> is dangerous, and strings are a very inefficient way to serialize your objects (use <code>pickle</code> instead). </p> <p>Therefore, I would recommend setting <code>__repr__ = __str__</code>. The reason is that <code>str(list)</code> calls <code>repr</code> on the elements (I consider this to be one of the biggest design flaws of Python that was not addressed by Python 3). An actual <code>repr</code> will probably not be very helpful as the output of <code>print [your, objects]</code>. </p> <p>To qualify this, in my experience, the most useful use case of the <code>repr</code> function is to put a string inside another string (using string formatting). This way, you don't have to worry about escaping quotes or anything. But note that there is no <code>eval</code> happening here. </p>
6
2012-11-15T10:39:22Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
19,597,196
<blockquote> <p>In short, the goal of <code>__repr__</code> is to be unambiguous and <code>__str__</code> is to be readable.</p> </blockquote> <p>Here is a good example:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; today = datetime.datetime.now() &gt;&gt;&gt; str(today) '2012-03-14 09:21:58.130922' &gt;&gt;&gt; repr(today) 'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)' </code></pre> <p>Read this documentation for repr:</p> <blockquote> <p><code>repr(object)</code></p> <p>Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to <code>eval()</code>, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a <code>__repr__()</code> method.</p> </blockquote> <p>Here is the documentation for str:</p> <blockquote> <p><code>str(object='')</code></p> <p>Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with <code>repr(object)</code> is that <code>str(object)</code> does not always attempt to return a string that is acceptable to <code>eval()</code>; its goal is to return a printable string. If no argument is given, returns the empty string, <code>''</code>.</p> </blockquote>
55
2013-10-25T18:38:52Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
28,132,458
<blockquote> <h1>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</h1> </blockquote> <p><code>__str__</code> (read as "dunder (double-underscore) string") and <code>__repr__</code> (read as "dunder-repper" (for "representation")) are both special methods that return strings based on the state of the object. </p> <p><code>__repr__</code> provides backup behavior if <code>__str__</code> is missing. </p> <p>So one should first write a <code>__repr__</code> that allows you to reinstantiate an equivalent object from the string it returns e.g. using <code>eval</code> or by typing it in character-for-character in a Python shell. </p> <p>At any time later, one can write a <code>__str__</code> for a user-readable string representation of the instance, when one believes it to be necessary.</p> <h1><code>__str__</code></h1> <p>If you print an object, or pass it to <code>format</code>, <code>str.format</code>, or <code>str</code>, then if a <code>__str__</code> method is defined, that method will be called, otherwise, <code>__repr__</code> will be used. </p> <h1><code>__repr__</code></h1> <p>The <code>__repr__</code> method is called by the builtin function <code>repr</code> and is what is echoed on your python shell when it evaluates an expression that returns an object. </p> <p>Since it provides a backup for <code>__str__</code>, if you can only write one, start with <code>__repr__</code></p> <p>Here's the builtin help on <code>repr</code>:</p> <pre><code>repr(...) repr(object) -&gt; string Return the canonical string representation of the object. For most object types, eval(repr(object)) == object. </code></pre> <p>That is, for most objects, if you type in what is printed by <code>repr</code>, you should be able to create an equivalent object. <em>But this is not the default implementation.</em></p> <h1>Default Implementation of <code>__repr__</code></h1> <p>The default object <code>__repr__</code> is (<a href="https://hg.python.org/cpython/file/2.7/Objects/object.c#l377">C Python source</a>) something like:</p> <pre><code>def __repr__(self): return '&lt;{0}.{1} object at {2}&gt;'.format( self.__module__, type(self).__name__, hex(id(self))) </code></pre> <p>That means by default you'll print the module the object is from, the class name, and the hexadecimal representation of its location in memory - for example:</p> <pre><code>&lt;__main__.Foo object at 0x7f80665abdd0&gt; </code></pre> <p>This information isn't very useful, but there's no way to derive how one might accurately create a canonical representation of any given instance, and it's better than nothing, at least telling us how we might uniquely identify it in memory.</p> <h1>How can <code>__repr__</code> be useful?</h1> <p>Let's look at how useful it can be, using the Python shell and <code>datetime</code> objects. First we need to import the <code>datetime</code> module:</p> <pre><code>import datetime </code></pre> <p>If we call <code>datetime.now</code> in the shell, we'll see everything we need to recreate an equivalent datetime object. This is created by the datetime <code>__repr__</code>:</p> <pre><code>&gt;&gt;&gt; datetime.datetime.now() datetime.datetime(2015, 1, 24, 20, 5, 36, 491180) </code></pre> <p>If we print a datetime object, we see a nice human readable (in fact, ISO) format. This is implemented by datetime's <code>__str__</code>:</p> <pre><code>&gt;&gt;&gt; print(datetime.datetime.now()) 2015-01-24 20:05:44.977951 </code></pre> <p>It is a simple matter to recreate the object we lost because we didn't assign it to a variable by copying and pasting from the <code>__repr__</code> output, and then printing it, and we get it in the same human readable output as the other object:</p> <pre><code>&gt;&gt;&gt; the_past = datetime.datetime(2015, 1, 24, 20, 5, 36, 491180) &gt;&gt;&gt; print(the_past) 2015-01-24 20:05:36.491180 </code></pre> <h1>How do I implement them?</h1> <p>As you're developing, you'll want to be able to reproduce objects in the same state, if possible. This, for example, is how the datetime object defines <code>__repr__</code> (<a href="https://hg.python.org/cpython/file/3.4/Lib/datetime.py#l1570">Python source</a>). It is fairly complex, because of all of the attributes needed to reproduce such an object:</p> <pre><code>def __repr__(self): """Convert to formal string, for repr().""" L = [self._year, self._month, self._day, # These are never zero self._hour, self._minute, self._second, self._microsecond] if L[-1] == 0: del L[-1] if L[-1] == 0: del L[-1] s = ", ".join(map(str, L)) s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s) if self._tzinfo is not None: assert s[-1:] == ")" s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")" return s </code></pre> <p>If you want your object to have a more human readable representation, you can implement <code>__str__</code> next. Here's how the datetime object (<a href="https://hg.python.org/cpython/file/3.4/Lib/datetime.py#l1585">Python source</a>) implements <code>__str__</code>, which it easily does because it already has a function to display it in ISO format:</p> <pre><code>def __str__(self): "Convert to string, for str()." return self.isoformat(sep=' ') </code></pre> <h1>Conclusion</h1> <p>Define <code>__repr__</code> for objects you write so you and other developers have a reproducible example when using it as you develop. Define <code>__str__</code> when you need a human readable string representation of it. </p>
38
2015-01-25T02:01:30Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
31,427,937
<pre><code>&gt;&gt;&gt; print(decimal.Decimal(23) / decimal.Decimal("1.05")) 21.90476190476190476190476190 &gt;&gt;&gt; decimal.Decimal(23) / decimal.Decimal("1.05") Decimal('21.90476190476190476190476190') </code></pre> <p>When print() is called on the result of decimal.Decimal(23) / deci- mal.Decimal("1.05") the raw number is printed; this output is in <strong>string form</strong> which can be achieved with __str __(). If we simply enter the expression we get a decimal.Decimal output—this output is in <strong>representational form</strong> which can be achieved with __repr __(). All Python objects have two output forms. String form is designed to be human-readable. Representational form is designed to produce output that if fed to a Python interpreter would (when possible) re- produce the represented object</p>
1
2015-07-15T10:30:35Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
33,421,226
<p>Excellent answers are already cover the difference between <code>__str__</code> and <code>__repr__</code>, which for me boils down to the former being readable even by an end user, and the latter being as useful as possible to developers. Given that, I find that the default implementation of <code>__repr__</code> often fails to achieve this goal because it <em>omits</em> information useful to developers.</p> <p>For this reason, if I have a simple enough <code>__str__</code>, I generally just try to get the best of both worlds with something like:</p> <pre><code>def __repr__(self): return '{0} ({1})'.format(object.__repr__(self), str(self)) </code></pre>
0
2015-10-29T17:46:48Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
33,727,876
<blockquote> <p>One important thing to keep in mind is that container's <code>__str__</code> uses contained objects' <code>__repr__</code>.</p> </blockquote> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; print (Decimal('52'), datetime.now()) (Decimal('52'), datetime.datetime(2015, 11, 16, 10, 51, 26, 185000)) &gt;&gt;&gt; str((Decimal('52'), datetime.now())) "(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 52, 22, 176000))" </code></pre> <p><em>Python favors unambiguity over readability</em>, the <code>__str__</code> call of a <code>tuple</code> calls the contained objects' <code>__repr__</code>, the <em>"formal"</em> representation of an object. Although the formal representation is harder to read than an informal one, it is unambiguous and more robust against bugs.</p>
0
2015-11-16T03:02:21Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
34,734,815
<p>To put it simply:</p> <p><code>__str__</code> is used in to show a string representation of your object <strong>to be read easily</strong> by others.</p> <p><code>__repr__</code> is used to show a string representation of <strong>the</strong> object.</p> <p>Let's say I want to create a <code>Fraction</code> class where the string representation of a fraction is '(1/2)' and the object (Fraction class) is to be represented as 'Fraction (1,2)'</p> <p>So we can create a simple Fraction class:</p> <pre><code>class Fraction: def __init__(self, num, den): self.__num = num self.__den = den def __str__(self): return '(' + str(self.__num) + '/' + str(self.__den) + ')' def __repr__(self): return 'Fraction (' + str(self.__num) + ',' + str(self.__den) + ')' f = Fraction(1,2) print('I want to represent the Fraction STRING as ' + str(f)) # (1/2) print('I want to represent the Fraction OBJECT as ', repr(f)) # Fraction (1,2) </code></pre>
1
2016-01-12T02:53:49Z
[ "python" ]
Difference between __str__ and __repr__ in Python
1,436,703
<p>What is the difference between <code>__str__</code> and <code>__repr__</code> in Python?</p>
1,363
2009-09-17T04:27:45Z
39,382,137
<p>Apart from all the answers given, I would like to add few points :-</p> <p>1) <code>__str__()</code> is invoked when you use object with print statement. In case, if <code>__str__</code> is missing, then print invokes <code>__repr__()</code> of object.</p> <p>2) <code>__repr__()</code> is invoked when you simply write object's name on interactive python console and press enter.</p> <p>3) <code>__str__()</code> of containers, when invoked will execute <code>__repr__()</code> method of its contained elements.</p>
0
2016-09-08T03:27:45Z
[ "python" ]
Python sort() method on list vs builtin sorted() function
1,436,962
<p>I know that <code>__builtin__</code> sorted() function works on any iterable. But can someone explain this huge (10x) performance difference between anylist.sort() vs sorted(anylist) ? Also, please point out if I am doing anything wrong with way this is measured. </p> <pre> """ Example Output: $ python list_sort_timeit.py Using sort method: 20.0662879944 Using sorted builin method: 259.009809017 """ import random import timeit print 'Using sort method:', x = min(timeit.Timer("test_list1.sort()","import random;test_list1=random.sample(xrange(1000),1000)").repeat()) print x print 'Using sorted builin method:', x = min(timeit.Timer("sorted(test_list2)","import random;test_list2=random.sample(xrange(1000),1000)").repeat()) print x </pre> <p><hr> As the title says, I was interested in comparing list.sort() vs sorted(list). The above snippet showed something interesting that, python's sort function behaves very well for already sorted data. As pointed out by Anurag, in the first case, the sort method is working on already sorted data and while in second sorted it is working on fresh piece to do work again and again. </p> <p>So I wrote this one to test and yes, they are very close.</p> <pre> """ Example Output: $ python list_sort_timeit.py Using sort method: 19.0166599751 Using sorted builin method: 23.203567028 """ import random import timeit print 'Using sort method:', x = min(timeit.Timer("test_list1.sort()","import random;test_list1=random.sample(xrange(1000),1000);test_list1.sort()").repeat()) print x print 'Using sorted builin method:', x = min(timeit.Timer("sorted(test_list2)","import random;test_list2=random.sample(xrange(1000),1000);test_list2.sort()").repeat()) print x </pre> <p>Oh, I see Alex Martelli with a response, as I was typing this one.. ( I shall leave the edit, as it might be useful).</p>
26
2009-09-17T06:07:36Z
1,436,981
<p>Well, the <code>.sort()</code> method of lists sorts the list in place, while <code>sorted()</code> creates a new list. So if you have a large list, part of your performance difference will be due to copying.</p> <p>Still, an order of magnitude difference seems larger than I'd expect. Perhaps <code>list.sort()</code> has some special-cased optimization that <code>sorted()</code> can't make use of. For example, since the <code>list</code> class already has an internal <code>Py_Object*[]</code> array of the right size, perhaps it can perform swaps more efficiently.</p> <p><strong>Edit</strong>: Alex and Anurag are right, the order of magnitude difference is due to you accidentally sorting an already-sorted list in your test case. However, as Alex's benchmarks show, <code>list.sort()</code> is about 2% faster than <code>sorted()</code>, which would make sense due to the copying overhead.</p>
5
2009-09-17T06:13:47Z
[ "python", "sorting" ]
Python sort() method on list vs builtin sorted() function
1,436,962
<p>I know that <code>__builtin__</code> sorted() function works on any iterable. But can someone explain this huge (10x) performance difference between anylist.sort() vs sorted(anylist) ? Also, please point out if I am doing anything wrong with way this is measured. </p> <pre> """ Example Output: $ python list_sort_timeit.py Using sort method: 20.0662879944 Using sorted builin method: 259.009809017 """ import random import timeit print 'Using sort method:', x = min(timeit.Timer("test_list1.sort()","import random;test_list1=random.sample(xrange(1000),1000)").repeat()) print x print 'Using sorted builin method:', x = min(timeit.Timer("sorted(test_list2)","import random;test_list2=random.sample(xrange(1000),1000)").repeat()) print x </pre> <p><hr> As the title says, I was interested in comparing list.sort() vs sorted(list). The above snippet showed something interesting that, python's sort function behaves very well for already sorted data. As pointed out by Anurag, in the first case, the sort method is working on already sorted data and while in second sorted it is working on fresh piece to do work again and again. </p> <p>So I wrote this one to test and yes, they are very close.</p> <pre> """ Example Output: $ python list_sort_timeit.py Using sort method: 19.0166599751 Using sorted builin method: 23.203567028 """ import random import timeit print 'Using sort method:', x = min(timeit.Timer("test_list1.sort()","import random;test_list1=random.sample(xrange(1000),1000);test_list1.sort()").repeat()) print x print 'Using sorted builin method:', x = min(timeit.Timer("sorted(test_list2)","import random;test_list2=random.sample(xrange(1000),1000);test_list2.sort()").repeat()) print x </pre> <p>Oh, I see Alex Martelli with a response, as I was typing this one.. ( I shall leave the edit, as it might be useful).</p>
26
2009-09-17T06:07:36Z
1,436,999
<p>Because list.sort does in place sorting, so first time it sorts but next time you are sorting the sorted list.</p> <p>e.g. try this and you will get same results in timeit case most of the time is spent is copying and sorted also does one more copy</p> <pre><code>import time import random test_list1=random.sample(xrange(1000),1000) test_list2=random.sample(xrange(1000),1000) s=time.time() for i in range(100): test_list1.sort() print time.time()-s s=time.time() for i in range(100): test_list2=sorted(test_list2) print time.time()-s </code></pre>
7
2009-09-17T06:20:30Z
[ "python", "sorting" ]
Python sort() method on list vs builtin sorted() function
1,436,962
<p>I know that <code>__builtin__</code> sorted() function works on any iterable. But can someone explain this huge (10x) performance difference between anylist.sort() vs sorted(anylist) ? Also, please point out if I am doing anything wrong with way this is measured. </p> <pre> """ Example Output: $ python list_sort_timeit.py Using sort method: 20.0662879944 Using sorted builin method: 259.009809017 """ import random import timeit print 'Using sort method:', x = min(timeit.Timer("test_list1.sort()","import random;test_list1=random.sample(xrange(1000),1000)").repeat()) print x print 'Using sorted builin method:', x = min(timeit.Timer("sorted(test_list2)","import random;test_list2=random.sample(xrange(1000),1000)").repeat()) print x </pre> <p><hr> As the title says, I was interested in comparing list.sort() vs sorted(list). The above snippet showed something interesting that, python's sort function behaves very well for already sorted data. As pointed out by Anurag, in the first case, the sort method is working on already sorted data and while in second sorted it is working on fresh piece to do work again and again. </p> <p>So I wrote this one to test and yes, they are very close.</p> <pre> """ Example Output: $ python list_sort_timeit.py Using sort method: 19.0166599751 Using sorted builin method: 23.203567028 """ import random import timeit print 'Using sort method:', x = min(timeit.Timer("test_list1.sort()","import random;test_list1=random.sample(xrange(1000),1000);test_list1.sort()").repeat()) print x print 'Using sorted builin method:', x = min(timeit.Timer("sorted(test_list2)","import random;test_list2=random.sample(xrange(1000),1000);test_list2.sort()").repeat()) print x </pre> <p>Oh, I see Alex Martelli with a response, as I was typing this one.. ( I shall leave the edit, as it might be useful).</p>
26
2009-09-17T06:07:36Z
1,437,009
<p>Your error in measurement is as follows: after your first call of <code>test_list1.sort()</code>, that list object IS sorted -- and Python's sort, aka <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">timsort</a>, is <strong>wickedly fast</strong> on already sorted lists!!! That's the most frequent error in using <code>timeit</code> -- inadvertently getting side effects and not accounting for them.</p> <p>Here's a good set of measurements, using <code>timeit</code> from the command line as it's best used:</p> <pre><code>$ python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' ' &gt; y=list(x); y.sort()' 1000 loops, best of 3: 452 usec per loop $ python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' ' x.sort()' 10000 loops, best of 3: 37.4 usec per loop $ python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' ' sorted(x)' 1000 loops, best of 3: 462 usec per loop $ </code></pre> <p>As you see, <code>y.sort()</code> and <code>sorted(x)</code> are neck and neck, but <code>x.sort()</code> thanks to the side effects gains over an order of magnitude's advantage -- just because of your measurement error, though: this tells you nothing about <code>sort</code> vs <code>sorted</code> per se!-)</p>
40
2009-09-17T06:23:30Z
[ "python", "sorting" ]
Python HTML Minimizer
1,437,357
<p>I have a cherrypy web server that uses larges amounts of HTML data. Is there anyway in Python to minimize the HTML so that all comments, spaces, ext, are removed?</p>
1
2009-09-17T07:59:39Z
1,437,384
<p><a href="http://tidy.sourceforge.net/" rel="nofollow">HTML Tidy's libtidy</a> doesn't seem to have python bindings (bit it does have perl and c++ etc), but ought to be easy to run as an exe in a pipe.</p> <p>Or ideally, use it to 'tidy' all static html files once so they don't need to be tidied each time they are served.</p>
0
2009-09-17T08:05:08Z
[ "python", "html", "minimize" ]
Python HTML Minimizer
1,437,357
<p>I have a cherrypy web server that uses larges amounts of HTML data. Is there anyway in Python to minimize the HTML so that all comments, spaces, ext, are removed?</p>
1
2009-09-17T07:59:39Z
1,437,464
<p>Not what you mean, but: <a href="http://www.cherrypy.org/wiki/GzipFilter#Gzip" rel="nofollow">Gzip</a>. (Assuming you aren't already serving through a compressing front-end.) Compression will zip away whitespace to almost nothing; unless you have excessively large comments this will be more effective than minification.</p>
4
2009-09-17T08:27:18Z
[ "python", "html", "minimize" ]
Python HTML Minimizer
1,437,357
<p>I have a cherrypy web server that uses larges amounts of HTML data. Is there anyway in Python to minimize the HTML so that all comments, spaces, ext, are removed?</p>
1
2009-09-17T07:59:39Z
1,531,684
<p>there are bindings to tidy for python, called mxTidy from eGenix (Marc André Lemburg)</p>
2
2009-10-07T13:35:25Z
[ "python", "html", "minimize" ]
How to install iPython on Snow Leopard
1,437,402
<p>Does iPython work on Mac OS X 10.6.1 Snow Leopard? I'm python noob, how can I install iPython on my Mac? Links? suggestions?</p> <p>Thanks</p>
10
2009-09-17T08:11:26Z
1,437,514
<p>To install with the Apple-supplied Python in 10.6:</p> <pre><code>$ sudo /usr/bin/easy_install-2.6 ipython </code></pre> <p>To use:</p> <pre><code>$ ipython </code></pre>
21
2009-09-17T08:37:58Z
[ "python", "osx", "ipython" ]
How to install iPython on Snow Leopard
1,437,402
<p>Does iPython work on Mac OS X 10.6.1 Snow Leopard? I'm python noob, how can I install iPython on my Mac? Links? suggestions?</p> <p>Thanks</p>
10
2009-09-17T08:11:26Z
1,466,858
<p>Though ipython installs and is runnable using easy_install, I found that there were some rendering problems which could only be solved by installing pyreadline as well. However, i found that there were some problems with pyreadline's installation using easy_install. The solution i've gone with involves manually extracting the python package and editing the version of gnu-readline which pyreadline tries to compile. I've posted a more in depth guide <a href="http://www.sinjax.net/wordpress/?p=1705" rel="nofollow">on my blog</a></p> <p>Cheers</p> <p>-- Sina</p>
0
2009-09-23T15:46:12Z
[ "python", "osx", "ipython" ]
How to install iPython on Snow Leopard
1,437,402
<p>Does iPython work on Mac OS X 10.6.1 Snow Leopard? I'm python noob, how can I install iPython on my Mac? Links? suggestions?</p> <p>Thanks</p>
10
2009-09-17T08:11:26Z
2,341,928
<p>I may add that running </p> <pre><code>$ sudo /usr/bin/easy_install-2.6 readline ipython </code></pre> <p>gives you the ability to use tab completion to see the attributes of a module....</p>
8
2010-02-26T13:32:49Z
[ "python", "osx", "ipython" ]
How to install iPython on Snow Leopard
1,437,402
<p>Does iPython work on Mac OS X 10.6.1 Snow Leopard? I'm python noob, how can I install iPython on my Mac? Links? suggestions?</p> <p>Thanks</p>
10
2009-09-17T08:11:26Z
21,849,341
<p>As with other python extensions, <a href="http://www.pip-installer.org/en/latest/" rel="nofollow">pip</a> makes it quite easy:</p> <pre><code>sudo pip install ipython </code></pre>
0
2014-02-18T09:30:09Z
[ "python", "osx", "ipython" ]
What are the risks (if any) of mixing Psyco into my project?
1,437,403
<p>I work on a large financial pricing application in which some long running calculations. We have identified some functions which can be sped up by the selective application of psyco. My management have requested an assessment of the costs &amp; benefits of adding psyco into our stack. </p> <p>Given the critical nature of my project, it's not acceptable if a "performance enhancement" can potentially reduce reliability. I've read that using psyco gets additional performance at the cost of more memory used. I'm worried that this could be a problem. </p> <p>I'm doing it like this:</p> <pre><code>@psyco.proxy def my_slow_function(xxx): </code></pre> <p>In all, we expect to apply psyco to no more than 15 functions - these are used very heavily. There are thousands of functions in this library, so this is only affecting a tiny sub-set of of our code. All of the functions are small, mathematical and stateless. </p> <ul> <li>Is there likely to be a risk that this will use substantially more memory </li> <li>Are there any other problems we might encounter when adding this component to our long established library?</li> </ul> <p>FYI, platform is Python 2.4.4 on Windows 32bit XP</p> <p>UPDATE: It seems that the main potential risk is due to a program requiring more memory to run than before psyco was added, so ideally I'd like to find a way to see if adding psyco dramatically changes the memory requirements of the system.</p>
2
2009-09-17T08:11:55Z
1,437,437
<p>Psyco is a JIT compiler. If your function are stateless, then there should be almost no draw back except more memory.</p>
2
2009-09-17T08:20:41Z
[ "python", "psyco" ]
What are the risks (if any) of mixing Psyco into my project?
1,437,403
<p>I work on a large financial pricing application in which some long running calculations. We have identified some functions which can be sped up by the selective application of psyco. My management have requested an assessment of the costs &amp; benefits of adding psyco into our stack. </p> <p>Given the critical nature of my project, it's not acceptable if a "performance enhancement" can potentially reduce reliability. I've read that using psyco gets additional performance at the cost of more memory used. I'm worried that this could be a problem. </p> <p>I'm doing it like this:</p> <pre><code>@psyco.proxy def my_slow_function(xxx): </code></pre> <p>In all, we expect to apply psyco to no more than 15 functions - these are used very heavily. There are thousands of functions in this library, so this is only affecting a tiny sub-set of of our code. All of the functions are small, mathematical and stateless. </p> <ul> <li>Is there likely to be a risk that this will use substantially more memory </li> <li>Are there any other problems we might encounter when adding this component to our long established library?</li> </ul> <p>FYI, platform is Python 2.4.4 on Windows 32bit XP</p> <p>UPDATE: It seems that the main potential risk is due to a program requiring more memory to run than before psyco was added, so ideally I'd like to find a way to see if adding psyco dramatically changes the memory requirements of the system.</p>
2
2009-09-17T08:11:55Z
1,437,658
<p>Why not try profiling it? Psyco has a pretty detailed <a href="http://psyco.sourceforge.net/psycoguide/node23.html" rel="nofollow">logging</a> facility:</p> <blockquote> <p><strong>memory usage: x+ kb</strong></p> <p>Psyco's current notion of how much memory is consumes for the emitted machine code and supporting data structures. This is a rouch estimation of the memory overhead (the + sign is supposed to remind you that this figure is highly underestimated). Use this info to tune the memory limits (section 3.2.2). </p> </blockquote> <p>Note also that the <a href="http://psyco.sourceforge.net/psycoguide/memlimits.html#memlimits" rel="nofollow">memory usage is configurable</a>:</p> <blockquote> <p><strong>memorymax</strong></p> <p>Stop when the memory consumed by Psyco reached the limit (in kilobytes). This limit includes the memory consumed before this profiler started. </p> </blockquote>
3
2009-09-17T09:10:51Z
[ "python", "psyco" ]
Encoding problems in PyQt
1,437,838
<p>My program stores file index in file packed by cPickle. There are non-english filenames. When I just do this</p> <pre><code>print f [0] </code></pre> <p>where f [0] is "\xc2\xe8\xf1\xee\xea\xee\xf1\xed\xfb\xe9 \xe3\xee\xe4" ("Високосный год" in normal view), it prints the string in proper way — in russian.</p> <p>When the program manually adds the string u'Високосный год' to QTreeView, everything is fine.</p> <p>But when the program puts this string ("\xe3\xee\xe4" etc.) straight from unpickled file to QTreeView, it becomes like that:</p> <p><img src="http://img170.imageshack.us/img170/9226/encoding.png" alt="alt text" /></p> <p>Is there any way to solve that?</p>
0
2009-09-17T10:02:00Z
1,437,872
<p>Have you run <code>decode</code> on the unpickled string using the correct encoding ("cp1251" by the look of it)? If not, you need to do this to make sure you're passing a Unicode string to the GUI.</p>
2
2009-09-17T10:12:13Z
[ "python", "encoding", "pyqt" ]
Why does Psyco use a lot of memory?
1,438,220
<p><a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a> is a specialising compiler for Python. The <a href="http://psyco.sourceforge.net/psycoguide/memlimits.html" rel="nofollow">documentation states</a></p> <blockquote> <p>Psyco can and will use large amounts of memory.</p> </blockquote> <p>What are the main reasons for this memory usage? Is substantial memory overhead a feature of JIT compilers in general?</p> <p><strong>Edit:</strong> Thanks for the answers so far. There are three likely contenders.</p> <ul> <li>Writing multiple specialised blocks, each of which require memory</li> <li>Overhead due to compiling source on the fly</li> <li>Overhead due to capturing enough data to do dynamic profiling</li> </ul> <p>The question is, which one is the <strong>dominant</strong> factor in memory usage? I have my own opinion. But I'm adding a bounty, because I'd like to accept the answer that's actually correct! If anyone can demonstrate or prove where the majority of the memory is used, I'll accept it. Otherwise whoever the community votes for will be auto-accepted at the end of the bounty.</p>
5
2009-09-17T11:18:42Z
1,438,250
<blockquote> <p>The memory overhead of Psyco is currently large. I has been reduced a bit over time, but it is still an overhead. <strong>This overhead is proportional to the amount of Python code that Psyco rewrites</strong>; thus if your application has a few algorithmic "core" functions, these are the ones you will want Psyco to accelerate --- not the whole program.</p> </blockquote> <p>So I would think the large memory requirements are due to the fact that it's loading source into memory and then compiling it as it goes. The more source you try and compile the more it's going to need. I'd guess that if it's trying to optomise it on top of that, it'll look at multiple possible solutions to try and identify the best case. </p>
2
2009-09-17T11:25:24Z
[ "python", "memory", "compiler-construction", "jit", "psyco" ]
Why does Psyco use a lot of memory?
1,438,220
<p><a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a> is a specialising compiler for Python. The <a href="http://psyco.sourceforge.net/psycoguide/memlimits.html" rel="nofollow">documentation states</a></p> <blockquote> <p>Psyco can and will use large amounts of memory.</p> </blockquote> <p>What are the main reasons for this memory usage? Is substantial memory overhead a feature of JIT compilers in general?</p> <p><strong>Edit:</strong> Thanks for the answers so far. There are three likely contenders.</p> <ul> <li>Writing multiple specialised blocks, each of which require memory</li> <li>Overhead due to compiling source on the fly</li> <li>Overhead due to capturing enough data to do dynamic profiling</li> </ul> <p>The question is, which one is the <strong>dominant</strong> factor in memory usage? I have my own opinion. But I'm adding a bounty, because I'd like to accept the answer that's actually correct! If anyone can demonstrate or prove where the majority of the memory is used, I'll accept it. Otherwise whoever the community votes for will be auto-accepted at the end of the bounty.</p>
5
2009-09-17T11:18:42Z
1,438,279
<p>From psyco website "The difference with the traditional approach to JIT compilers is that Psyco writes <strong>several version of the same blocks</strong> (a block is a bit of a function), which are optimized by being specialized to some kinds of variables (a "kind" can mean a type, but it is more general)"</p>
10
2009-09-17T11:31:48Z
[ "python", "memory", "compiler-construction", "jit", "psyco" ]
Why does Psyco use a lot of memory?
1,438,220
<p><a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a> is a specialising compiler for Python. The <a href="http://psyco.sourceforge.net/psycoguide/memlimits.html" rel="nofollow">documentation states</a></p> <blockquote> <p>Psyco can and will use large amounts of memory.</p> </blockquote> <p>What are the main reasons for this memory usage? Is substantial memory overhead a feature of JIT compilers in general?</p> <p><strong>Edit:</strong> Thanks for the answers so far. There are three likely contenders.</p> <ul> <li>Writing multiple specialised blocks, each of which require memory</li> <li>Overhead due to compiling source on the fly</li> <li>Overhead due to capturing enough data to do dynamic profiling</li> </ul> <p>The question is, which one is the <strong>dominant</strong> factor in memory usage? I have my own opinion. But I'm adding a bounty, because I'd like to accept the answer that's actually correct! If anyone can demonstrate or prove where the majority of the memory is used, I'll accept it. Otherwise whoever the community votes for will be auto-accepted at the end of the bounty.</p>
5
2009-09-17T11:18:42Z
1,438,422
<blockquote> <p>"Psyco uses the actual run-time data that your program manipulates to write potentially several versions of the machine code, each differently specialized for different kinds of data." <a href="http://psyco.sourceforge.net/introduction.html" rel="nofollow">http://psyco.sourceforge.net/introduction.html</a></p> </blockquote> <p>Many JIT compilers work with statically typed languages, so they know what the types are so can create machine code for just the known types. The better ones do dynamic profiling if the types are polymorphic and optimise the more commonly encountered paths; this is also commonly done with languages featuring dynamic types&dagger;. Psyco appears to hedge its bets in order to avoid doing a full program analysis to decide what the types could be, or profiling to find what the types in use are.</p> <p><sub> &dagger; I've never gone deep enough into Python to work out whether it does or doesn't have dynamic types or not ( types whose structure can be changed at runtime after objects have been created with that type ), or just the common implementations only check types at runtime; most of the articles just rave about dynamic typing without actually defining it in the context of Python.</sub></p>
5
2009-09-17T12:03:45Z
[ "python", "memory", "compiler-construction", "jit", "psyco" ]
Why does Psyco use a lot of memory?
1,438,220
<p><a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a> is a specialising compiler for Python. The <a href="http://psyco.sourceforge.net/psycoguide/memlimits.html" rel="nofollow">documentation states</a></p> <blockquote> <p>Psyco can and will use large amounts of memory.</p> </blockquote> <p>What are the main reasons for this memory usage? Is substantial memory overhead a feature of JIT compilers in general?</p> <p><strong>Edit:</strong> Thanks for the answers so far. There are three likely contenders.</p> <ul> <li>Writing multiple specialised blocks, each of which require memory</li> <li>Overhead due to compiling source on the fly</li> <li>Overhead due to capturing enough data to do dynamic profiling</li> </ul> <p>The question is, which one is the <strong>dominant</strong> factor in memory usage? I have my own opinion. But I'm adding a bounty, because I'd like to accept the answer that's actually correct! If anyone can demonstrate or prove where the majority of the memory is used, I'll accept it. Otherwise whoever the community votes for will be auto-accepted at the end of the bounty.</p>
5
2009-09-17T11:18:42Z
1,611,658
<p>Definitely psyco memory usage comes from compiled assembler blocks. Psyco suffers sometimes from overspecialization of functions, which means there are multiple versions of assembler blocks. Also, which is also very important, psyco never frees once allocated assembler blocks even if the code assosciated with it is dead.</p> <p>If you run your program under linux you can look at /proc/xxx/smaps to see a growing block of anonymous memory, which is in different region than heap. That's anonymously mmap'ed part for writing down assembler, which of course disappears when running without psyco.</p>
2
2009-10-23T06:17:47Z
[ "python", "memory", "compiler-construction", "jit", "psyco" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
1,438,288
<p>Do you have <a href="http://developer.apple.com/technology/xcode.html" rel="nofollow">XCode</a> (comes on the Snow Leopard disc) installed? There are some key components (most notably <a href="http://gcc.gnu.org/" rel="nofollow">GCC</a>) that need to be installed which XCode handles for you.</p>
0
2009-09-17T11:32:52Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
1,438,358
<p>IT seems to me that the "No such file" is conjunction with stdarg.h is the most interesting error. There seems to be a header file missing. I don't know how to make sure it's installed on OS X, so this only half an answer, sorry about that, but maybe it pushes you in the right direction.</p>
1
2009-09-17T11:46:43Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
1,438,551
<p>May be you should try pre-build universal binaries from pythonmac site</p> <p><a href="http://pythonmac.org/packages/py25-fat/index.html" rel="nofollow">http://pythonmac.org/packages/py25-fat/index.html</a></p> <p>These are for python2.5 , with python2.5 included(so may or may not be usable for you), I have been using it since I had problem using self build PIL with py2app.</p>
1
2009-09-17T12:26:29Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
1,439,772
<p>The python.org Python was built with an earlier gcc. Try using gcc-4.0 instead of SL's default of 4.2:</p> <pre><code>export CC=/usr/bin/gcc-4.0 </code></pre> <p>See similar problem <a href="http://thread.gmane.org/gmane.comp.python.apple/16087" rel="nofollow">here</a>.</p> <p>That gets past the stdarg problem. You may then run into later build problems with various dependent libraries.</p> <p>BTW, gcc-4.0 and gcc-4.2 are both included with Snow Leopard's Xcode <em>3</em> so no additional installs are needed.</p> <p>UPDATED 2011-05: Note, that the newer Xcode <em>4</em>, released for experimental use with 10.6 and expected to be standard with 10.7, no longer includes PPC support so, if you install Xcode 4, this suggestion will not work. Options include using the newer 64-bit/32-bin Python 2.7.x installers from python.org or installing a newer Python 2.6 and PIL and the various 3rd-party libs using MacPorts, Homebrew, or Fink.</p>
11
2009-09-17T16:02:09Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
1,439,865
<h1>Modified Answer</h1> <p>Here are the steps that I took to successfully install PIL on Mac OS X 10.6 (without using MacPorts or Fink).</p> <ol> <li><p>Install readline</p> <pre><code>cd ~/src curl -O ftp://ftp.cwru.edu/pub/bash/readline-6.0.tar.gz tar -xvzf readline-6.0.tar.gz cd readline-6.0 ./configure make sudo make install </code></pre></li> <li><p>Install gbdm</p> <pre><code>cd ~/src curl -O ftp://mirror.anl.gov/pub/gnu/gdbm/gdbm-1.8.3.tar.gz tar -xvzf gbdm-1.8.3.tar.gz cd gdbm-1.8.3 # Need to modify Makefile.in perl -pi -e 's/BINOWN = bin/BINOWN = root/' Makefile.in perl -pi -e 's/BINGRP = bin/BINGRP = wheel/' Makefile.in ./configure make sudo make install </code></pre></li> <li><p>Compile the latest Python 2.6.2+ from the Mercurial Repo</p> <pre><code>cd ~/development hg clone http://code.python.org/hg/branches/release2.6-maint/ python-release2.6-maint.hg cd python-release2.6-main.hg ./configure --enable-framework MACOSX_DEPLOYMENT_TARGET=10.6 make sudo make frameworkinstall </code></pre> <p><strong>Note</strong>: I did receive the following errors after running <code>make</code>. However, I continued on as I wasn't worried about missing these modules, and I was able to successfully install PIL.</p> <pre><code>Failed to find the necessary bits to build these modules: _bsddb dl imageop linuxaudiodev ossaudiodev spwd sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. Failed to build these modules: Nav running build_scripts </code></pre></li> <li><p>Update .bash_profile for the new Python 2.6.2+ and for virtualenvwrapper</p> <pre><code># Set PATH for MacPython 2.6 if Python2.6 is installed if [ -x /Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 ]; then PATH="/Library/Frameworks/Python.framework/Versions/2.6/bin:${PATH}" export PATH fi # MDR April 23, 2009: Added for virtualenvwrapper if [ -x /Library/Frameworks/Python.framework/Versions/2.6/bin/virtualenvwrapper_bashrc ]; then export WORKON_HOME=$HOME/.virtualenvs export PIP_VIRTUALENV_BASE=$WORKON_HOME source /Library/Frameworks/Python.framework/Versions/2.6/bin/virtualenvwrapper_bashrc fi </code></pre></li> <li><p>Install easy_install, pip, virtualenv, and virtualenvwrapper for Python 2.6.2+</p> <pre><code>curl -O http://peak.telecommunity.com/dist/ez_setup.py sudo python ez_setup.py sudo easy_install pip sudo easy_install virtualenv sudo easy_install virtualenvwrapper </code></pre></li> <li><p>Create a virtualenv and then use pip to install PIL</p> <pre><code>mkvirtualenv pil-test cdvirtualenv easy_install pip pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz </code></pre></li> </ol> <p><strong>Note</strong>: I was not able to install PIL using <code>pip install pil</code>, so I installed from the URL as shown above.</p> <h1>Original Answer</h1> <p>From what I can see in your <a href="http://drop.io/gi2bgw6">pip-log.txt</a> file it appears that you installed Python 2.6.2 using the <a href="http://www.python.org/ftp/python/2.6.2/python-2.6.2-macosx2009-04-16.dmg">Mac Installer Disk Image</a> from Python.org released on April 16, 2009. Can you confirm this?</p> <p>From the pip log, gcc failed with exit status 1. The offending <code>gcc</code> command from your pip log is as follows:</p> <pre><code>gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -DHAVE_LIBJPEG -DHAVE_LIBZ -I/System/Library/Frameworks/Tcl.framework/Headers -I/System/Library/Frameworks/Tk.framework/Headers -IlibImaging -I/Library/Frameworks/Python.framework/Versions/2.6/include -I/usr/local/include -I/usr/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _imaging.c -o build/temp.macosx-10.3-fat-2.6/_imaging.o </code></pre> <p>This appears to be a problem related to Snow Leopard changing the default value for the -arch flag from <code>i386</code> to <code>x86-64</code> according to Ronald Oussoren in <a href="http://bugs.python.org/issue6802#msg92083">Message 92083</a> of <a href="http://bugs.python.org/issue6802">Python Issue 6802</a>. There is a patch available Python 2.6.2, but it has not been integrated into the Mac Installer Disk Image.</p> <p>Your best solution that doesn't involve MacPorts or Fink would probably be to compile and install Python from the 2.6 release branch from either the <a href="http://code.python.org/hg/branches/release2.6-maint/">Mercurial Python Repository</a> or the <a href="http://svn.python.org/view/python/branches/release26-maint/">Subversion Python Repository</a>. According to <a href="http://bugs.python.org/issue6802#msg92315">Message 92315</a> of <a href="http://bugs.python.org/issue6802">Issue 6802</a>, Ronald Oussoren fixed this in <a href="http://svn.python.org/view?view=rev&amp;revision=74686">Revision r74686</a>. </p> <p>I've been seeing similar errors using Python 2.6.2 installed from the Mac Disk Image while trying to then install Fabric in a virtualenv, so I plan to compile and install from the 2.6 release maintenance branch. If you want, I'll update when successful.</p>
7
2009-09-17T16:19:14Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
1,454,806
<p>I found a simpler method. sudo port install python26 sudo port install python_select</p> <p>Then use python_select set python26 as default.</p> <p>Then just install PIL as normal.</p>
1
2009-09-21T14:27:13Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
1,485,751
<p>I was able to get PIP installed with SL's Python using these instructions:</p> <p><a href="http://jetfar.com/libjpeg-and-python-imaging-pil-on-snow-leopard/" rel="nofollow">http://jetfar.com/libjpeg-and-python-imaging-pil-on-snow-leopard/</a></p>
1
2009-09-28T06:56:18Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
2,222,294
<p>The problem I ran into was that PIL was being compiled against PowerPC architecture (-arch ppc).</p> <p>Do this before setup/build/compile:</p> <pre><code>export ARCHFLAGS="-arch i386" </code></pre> <p>(Assuming you're on i386)</p>
18
2010-02-08T14:42:02Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
4,466,057
<p>10.6 Snow Leopard install PIL without the hassle and without keeping MacPorts :)<br> <br> Step 1: Install MacPorts<br> Step 2: sudo port install py26-pil<br> Step 3: mv /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/* /Library/Python/2.6/site-packages/<br> Step 4: Uninstall MacPorts<br> <br> Best of both worlds?</p>
3
2010-12-16T22:37:04Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
6,898,875
<p>Following steps worked for me:</p> <pre><code>$ brew install pip $ export ARCHFLAGS="-arch i386 -arch x86_64" $ pip install pil </code></pre>
2
2011-08-01T13:10:56Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
8,880,459
<p><strong>Solved in 2 steps:</strong></p> <p><strong>Step 1:</strong> Uninstalled and Installed Xcode, suggested here: <a href="http://binarylionstudios.com/blog/2011/01/30/error-stdarg.h-no-such-file-or-directory/" rel="nofollow">http://binarylionstudios.com/blog/2011/01/30/error-stdarg.h-no-such-file-or-directory/</a></p> <p>to remove Xcode properlly follow this answer: <a href="http://stackoverflow.com/questions/5255959/how-to-fully-remove-xcode-4">How to fully remove Xcode 4</a></p> <blockquote> <p>sudo /Developer/Library/uninstall-devtools --mode=all</p> </blockquote> <p>use the install Xcode.app after you restart your mac</p> <p><strong>Step 2:</strong> after xcode was reinstalled, the installation failed </p> <blockquote> <p>unable to execute gcc-4.2: No such file or directory PIL</p> </blockquote> <p>to resolve that i followed this post: <a href="http://aravir-rose.blogspot.com/2011/12/installing-python-27s-imaging-library.html" rel="nofollow">http://aravir-rose.blogspot.com/2011/12/installing-python-27s-imaging-library.html</a></p> <p>Good luck!</p>
0
2012-01-16T13:08:28Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2
1,438,270
<p>I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.</p> <p>I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:</p> <ol> <li><code>easy_install</code></li> <li><code>pip</code></li> <li>downloading source and running <code>python setup.py build</code> manually.</li> </ol> <p>All yield the same error (link to <code>pip</code> log: <a href="http://drop.io/gi2bgw6" rel="nofollow">http://drop.io/gi2bgw6</a>). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.</p>
26
2009-09-17T11:29:17Z
10,029,954
<p>On OS X Lion with current XCode and no gcc-4.0 I'm able to get around the missing stdard.h error by setting the follow environment variables:</p> <blockquote> <p>export CC="/usr/bin/llvm-gcc-4.2"</p> </blockquote> <p>I can't say I understand why this works.</p> <p>By the way this works for the Pillow fork of PIL too.</p>
0
2012-04-05T13:54:00Z
[ "python", "osx-snow-leopard", "python-imaging-library" ]
pygresql - insert and return serial
1,438,430
<p>I'm using <a href="http://www.pygresql.org/pg.html" rel="nofollow">PyGreSQL</a> to access my DB. In the use-case I'm currently working on; I am trying to insert a record into a table and return the last rowid... aka the value that the DB created for my ID field:</p> <pre><code>create table job_runners ( id SERIAL PRIMARY KEY, hostname varchar(100) not null, is_available boolean default FALSE ); sql = "insert into job_runners (hostname) values ('localhost')" </code></pre> <p>When I used the db.insert(), which made the most sense, I received an "AttributeError". And when I tried db.query(sql) I get nothing but an OID.</p> <p>Q: Using PyGreSQL what is the best way to insert records and return the value of the ID field without doing any additional reads or queries?</p>
1
2009-09-17T12:05:16Z
1,438,455
<pre><code>INSERT INTO job_runners (hostname,is_available) VALUES ('localhost',true) RETURNING id </code></pre> <p>That said, I have no idea about pygresql, but by what you've already written, I guess it's <code>db.query()</code> that you want to use here.</p>
1
2009-09-17T12:09:20Z
[ "python", "postgresql", "pygresql" ]
pygresql - insert and return serial
1,438,430
<p>I'm using <a href="http://www.pygresql.org/pg.html" rel="nofollow">PyGreSQL</a> to access my DB. In the use-case I'm currently working on; I am trying to insert a record into a table and return the last rowid... aka the value that the DB created for my ID field:</p> <pre><code>create table job_runners ( id SERIAL PRIMARY KEY, hostname varchar(100) not null, is_available boolean default FALSE ); sql = "insert into job_runners (hostname) values ('localhost')" </code></pre> <p>When I used the db.insert(), which made the most sense, I received an "AttributeError". And when I tried db.query(sql) I get nothing but an OID.</p> <p>Q: Using PyGreSQL what is the best way to insert records and return the value of the ID field without doing any additional reads or queries?</p>
1
2009-09-17T12:05:16Z
1,440,041
<p>The documentation in PyGreSQL says that if you call dbconn.query() with and insert/update statement that it will return the OID. It goes on to say something about lists of OIDs when there are multiple rows involved.</p> <p>First of all; I found that the OID features did not work. I suppose knowing the version numbers of the libs and tools would have helped, however, I was not trying to return the OID.</p> <p>Finally; by appending "returning id", as suggested by @hacker, pygresql simply did the right thing and returned a record-set with the ID in the resulting dictionary (see code below).</p> <pre><code>sql = "insert into job_runners (hostname) values ('localhost') returning id" rv = dbconn.query(sql) id = rv.dictresult()[0]['id'] </code></pre>
0
2009-09-17T16:52:05Z
[ "python", "postgresql", "pygresql" ]
pygresql - insert and return serial
1,438,430
<p>I'm using <a href="http://www.pygresql.org/pg.html" rel="nofollow">PyGreSQL</a> to access my DB. In the use-case I'm currently working on; I am trying to insert a record into a table and return the last rowid... aka the value that the DB created for my ID field:</p> <pre><code>create table job_runners ( id SERIAL PRIMARY KEY, hostname varchar(100) not null, is_available boolean default FALSE ); sql = "insert into job_runners (hostname) values ('localhost')" </code></pre> <p>When I used the db.insert(), which made the most sense, I received an "AttributeError". And when I tried db.query(sql) I get nothing but an OID.</p> <p>Q: Using PyGreSQL what is the best way to insert records and return the value of the ID field without doing any additional reads or queries?</p>
1
2009-09-17T12:05:16Z
2,345,736
<p>Assuming you have a cursor object <code>cur</code>:</p> <pre><code>cur.execute("INSERT INTO job_runners (hostname) VALUES (%(hostname)s) RETURNING id", {'hostname': 'localhost'}) id = cur.fetchone()[0] </code></pre> <p>This ensures PyGreSQL correctly escapes the input string, preventing SQL injection.</p>
0
2010-02-27T00:40:03Z
[ "python", "postgresql", "pygresql" ]
Google App Engine urlfetch to POST files
1,438,542
<p>I am trying to send a file to torrage.com from an app in GAE. the file is stored in memory after being received from a user upload.</p> <p>I would like to be able to post this file using the API available here: <a href="http://torrage.com/automation.php">http://torrage.com/automation.php</a> but i am having some problems undestanding how the body of the post should be encoded, the most i got from the API is a "file empty" message.</p>
5
2009-09-17T12:25:31Z
1,438,614
<p>Why not just use Python's <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> module to create a POST request, like they show in an example for PHP. It would be something like this:</p> <pre><code>import urrlib, urllib2 data = ( ('name', 'torrent'), ('type', 'application/x-bittorrent'), ('file', '/path/to/your/file.torrent'), ) request = urllib2.urlopen('http://torrage.com/autoupload.php', urllib.urlencode(data)) </code></pre>
0
2009-09-17T12:39:29Z
[ "python", "http", "google-app-engine" ]
Google App Engine urlfetch to POST files
1,438,542
<p>I am trying to send a file to torrage.com from an app in GAE. the file is stored in memory after being received from a user upload.</p> <p>I would like to be able to post this file using the API available here: <a href="http://torrage.com/automation.php">http://torrage.com/automation.php</a> but i am having some problems undestanding how the body of the post should be encoded, the most i got from the API is a "file empty" message.</p>
5
2009-09-17T12:25:31Z
1,439,945
<p>I find torrage's API docs on the POST interface (as opposed to the SOAP one) pretty confusing and conflicting with the sample C code they also supply. It seems to me that in their online example of PHP post they are not sending the file's contents (just like @kender's answer above is not sending it) while they ARE sending it in the SOAP examples and in the example C code.</p> <p>The relevant part of the C sample (how they compute the headers that you'd be passing to <code>urlfetch.fetch</code>) is:</p> <pre><code> snprintf(formdata_header, sizeof(formdata_header) - 1, "Content-Disposition: form-data; name=\"torrent\"; filename=\"%s\"\n" "Content-Type: " HTTP_UPLOAD_CONTENT_TYPE "\n" "\n", torrent_file); http_content_len = 2 + strlen(content_boundary) + 1 + strlen(formdata_header) + st.st_size + 1 + 2 + strlen(content_boundary) + 3; LTdebug("http content len %u\n", http_content_len); snprintf(http_req, sizeof(http_req) - 1, "POST /%s HTTP/1.1\n" "Host: %s\n" "User-Agent: libtorrage/" LTVERSION "\n" "Connection: close\n" "Content-Type: multipart/form-data; boundary=%s\n" "Content-Length: %u\n" "\n", cache_uri, cache_host, content_boundary, http_content_len); </code></pre> <p>"application/x-bittorrent" is the <code>HTTP_UPLOAD_CONTENT_TYPE</code>. <code>st.st_size</code> is the number of bytes in the memory buffer with all the file's data (the C sample reads that data from file, but it doesn't matter how you got it into memory, as long as you know its size). <code>content_boundary</code> is a string that's NOT present in the file's contents, they build it as <code>"---------------------------%u%uLT"</code> with each <code>%u</code> substituted by a random number (repeating until that string hits upon two random numbers that make it not present in the file). Finally, the post body (after opening the HTTP socket and sending the other headers) they write as follows:</p> <pre><code> if (write_error == 0) if (write(sock, "--", 2) &lt;= 0) write_error = 1; if (write_error == 0) if (write(sock, content_boundary, strlen(content_boundary)) &lt;= 0) write_error = 1; if (write_error == 0) if (write(sock, "\n", 1) &lt;= 0) write_error = 1; if (write_error == 0) if (write(sock, formdata_header, strlen(formdata_header)) &lt;= 0) write_error = 1; if (write_error == 0) if (write(sock, filebuf, st.st_size) &lt;= 0) write_error = 1; if (write_error == 0) if (write(sock, "\n--", 3) &lt;= 0) write_error = 1; if (write_error == 0) if (write(sock, content_boundary, strlen(content_boundary)) &lt;= 0) write_error = 1; if (write_error == 0) if (write(sock, "--\n", 3) &lt;= 0) write_error = 1; </code></pre> <p>where <code>filebuf</code> is the buffer with the file's contents.</p> <p>Hardly sharp and simple, but I hope there's enough info here to work out a way to build the arguments for a <code>urlfetch.fetch</code> (building them for a <code>urllib.urlopen</code> would be just as hard, since the problem is the scarcity of documentation about exactly what headers and what content and how encoded you need -- and that not-well-documented info needs to be reverse engineered from what I'm presenting here, I think).</p> <p>Alternatively, it may be possible to hack a SOAP request via urlfetch; see <a href="http://www.ioncannon.net/programming/180/soap-on-the-google-app-engine-platform/" rel="nofollow">here</a> for Carson's long post of his attempts, difficulties and success in the matter. And, good luck!</p>
2
2009-09-17T16:36:11Z
[ "python", "http", "google-app-engine" ]
Google App Engine urlfetch to POST files
1,438,542
<p>I am trying to send a file to torrage.com from an app in GAE. the file is stored in memory after being received from a user upload.</p> <p>I would like to be able to post this file using the API available here: <a href="http://torrage.com/automation.php">http://torrage.com/automation.php</a> but i am having some problems undestanding how the body of the post should be encoded, the most i got from the API is a "file empty" message.</p>
5
2009-09-17T12:25:31Z
1,440,042
<p>Judging from the C code, it's using the "multipart/form-data" format, which is very complex and it's very easy to get something wrong. I wouldn't hand-code the post body like that. </p> <p>I used the function from this blog and it worked for me from stand-alone program. You might want give it a try in app engine,</p> <p><a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html" rel="nofollow">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
0
2009-09-17T16:52:06Z
[ "python", "http", "google-app-engine" ]
How can I measure the overall memory requirements of a Python program
1,438,773
<p>I have a financial pricing application written in Python 2.4.4 which runs as an Excel plugin. Excel has a 1GB memory limit for all addins, so if any addin process tries to allocate more than 1Gb in total it will cause Excel to crash. </p> <p>I've recently made a change to the program which may have changed the overall memory requirements of the program. I'd like to work out if anything has changed sigifnicantly, and if not I can reassure my management that there's no chance of a failure due to an increase in memory usage.</p> <p>Incidentally, it's possible to run the same function which runs in Excel from a command-line:</p> <p>Effectively I can provide all the arguments that would be generated from Excel from the regular windows prompt. This means that if I have a method to discover the memory requirements of the process on it's own I can safely infer that it will use a similar amount when run from Excel. </p> <p>I'm not interested in the detail that a memory profiler might give: I do not need to know how much memory each function tries to allocate. What I do need to know is the smallest amount of memory that the program will require in order to run and I need to guarantee that if the program is run within a limit of 1Gb it will run OK.</p> <p>Any suggestions as to how I can do this?</p> <p>Platform is Windows XP 32bit, python 2.4.4</p>
2
2009-09-17T13:07:13Z
1,438,830
<p>Simplest solution might just be to run your app from the command line and use Task Manager to see how much memory it's using.</p> <p>Edit: For something more complicated have a look at this question / answer <a href="http://stackoverflow.com/questions/282194/how-to-get-memory-usage-under-windows-in-c">http://stackoverflow.com/questions/282194/how-to-get-memory-usage-under-windows-in-c</a></p> <p>Edit: Another option. Get <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow">Process Explorer</a>. It's basically Task Manager on steroids. It'll record peak usage of a process for you. (it's free so you don't have to worry about cost)</p>
1
2009-09-17T13:15:51Z
[ "python" ]
How can I measure the overall memory requirements of a Python program
1,438,773
<p>I have a financial pricing application written in Python 2.4.4 which runs as an Excel plugin. Excel has a 1GB memory limit for all addins, so if any addin process tries to allocate more than 1Gb in total it will cause Excel to crash. </p> <p>I've recently made a change to the program which may have changed the overall memory requirements of the program. I'd like to work out if anything has changed sigifnicantly, and if not I can reassure my management that there's no chance of a failure due to an increase in memory usage.</p> <p>Incidentally, it's possible to run the same function which runs in Excel from a command-line:</p> <p>Effectively I can provide all the arguments that would be generated from Excel from the regular windows prompt. This means that if I have a method to discover the memory requirements of the process on it's own I can safely infer that it will use a similar amount when run from Excel. </p> <p>I'm not interested in the detail that a memory profiler might give: I do not need to know how much memory each function tries to allocate. What I do need to know is the smallest amount of memory that the program will require in order to run and I need to guarantee that if the program is run within a limit of 1Gb it will run OK.</p> <p>Any suggestions as to how I can do this?</p> <p>Platform is Windows XP 32bit, python 2.4.4</p>
2
2009-09-17T13:07:13Z
1,439,782
<p>I don't believe XP keeps track of the peak memory requirements of a process (the way Linux does in /proc/pid/status for example). You can use third-party utilities such as <a href="http://www.loriotpro.com/ServiceAndSupport/How%5Fto/How%5Fto%5Fcontrol%5FMemory%5Fusage.php" rel="nofollow">this one</a> and set it to "poll" the process very frequently to get a good chance of grabbing the correct peak.</p> <p>A better approach, though it doesn't answer your title question, is to try running the process under a <a href="http://msdn.microsoft.com/en-us/library/ms684161%28VS.85%29.aspx" rel="nofollow">job object</a> with a <a href="http://msdn.microsoft.com/en-us/library/ms686216%28VS.85%29.aspx" rel="nofollow">SetInformationJobObject</a> with a <a href="http://msdn.microsoft.com/en-us/library/ms684156%28VS.85%29.aspx" rel="nofollow"><code>JOBOBJECT_EXTENDED_LIMIT_INFORMATION</code></a> structure having a suitable <code>ProcessMemoryLimit</code> (e.g 1GB max virtual memory) and the right flag in <code>JOBOBJECT_BASIC_LIMIT_INFORMATION</code> to activate that limit. This way, if the process runs correctly, you will KNOW it has never used more than 1 GB of virtual memory -- otherwise, it will crash with an out-of-memory error. </p> <p>This programmatic approach also allows measurement of peak values, but it's complicated enough, compared with using already packaged tools, that I don't think it can be recommended for that purpose. I do not know of packaged tools that allow you to use job objects to specifically limit the resources available to processes (though I wouldn't be surprised to hear that some are available, be that freely or commercially, I've never come upon one myself).</p>
2
2009-09-17T16:03:58Z
[ "python" ]
Finding closest match in collection of strings representing numbers
1,438,924
<p>I have a sorted list of datetimes in text format. The format of each entry is '2009-09-10T12:00:00'.</p> <p>I want to find the entry closest to a target. There are many more entries than the number of searches I would have to do.</p> <p>I could change each entry to a number, then search numerically (for example <a href="http://stackoverflow.com/questions/445782/finding-closest-match-in-collection-of-numbers">these</a> approaches), but that would seem excess effort. </p> <p>Is there a better way than this:</p> <pre><code>def mid(res, target): #res is a list of entries, sorted by dt (dateTtime) #each entry is a dict with a dt and some other info n = len(res) low = 0 high = n-1 # find the first res greater than target while low &lt; high: mid = (low + high)/2 t = res[int(mid)]['dt'] if t &lt; target: low = mid + 1 else: high = mid # check if the prior value is closer i = max(0, int(low)-1) a = dttosecs(res[i]['dt']) b = dttosecs(res[int(low)]['dt']) t = dttosecs(target) if abs(a-t) &lt; abs(b-t): return int(low-1) else: return int(low) import time def dttosecs(dt): # string to seconds since the beginning date,tim = dt.split('T') y,m,d = date.split('-') h,mn,s = tim.split(':') y = int(y) m = int(m) d = int(d) h = int(h) mn = int(mn) s = min(59,int(float(s)+0.5)) # round to neatest second s = int(s) secs = time.mktime((y,m,d,h,mn,s,0,0,-1)) return secs </code></pre>
2
2009-09-17T13:33:42Z
1,439,018
<p>You want the <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect module</a> from the standard library. It will do a binary search and tell you the correct insertion point for a new value into an already sorted list. Here's an example that will print the place in the list where <code>target</code> would be inserted:</p> <pre><code>from bisect import bisect dates = ['2009-09-10T12:00:00', '2009-09-11T12:32:00', '2009-09-11T12:43:00'] target = '2009-09-11T12:40:00' print bisect(dates, target) </code></pre> <p>From there you can just compare to the thing before and after your insertion point, which in this case would be <code>dates[i-1]</code> and <code>dates[i]</code> to see which one is closest to your <code>target</code>.</p>
4
2009-09-17T13:52:23Z
[ "python", "search" ]
Finding closest match in collection of strings representing numbers
1,438,924
<p>I have a sorted list of datetimes in text format. The format of each entry is '2009-09-10T12:00:00'.</p> <p>I want to find the entry closest to a target. There are many more entries than the number of searches I would have to do.</p> <p>I could change each entry to a number, then search numerically (for example <a href="http://stackoverflow.com/questions/445782/finding-closest-match-in-collection-of-numbers">these</a> approaches), but that would seem excess effort. </p> <p>Is there a better way than this:</p> <pre><code>def mid(res, target): #res is a list of entries, sorted by dt (dateTtime) #each entry is a dict with a dt and some other info n = len(res) low = 0 high = n-1 # find the first res greater than target while low &lt; high: mid = (low + high)/2 t = res[int(mid)]['dt'] if t &lt; target: low = mid + 1 else: high = mid # check if the prior value is closer i = max(0, int(low)-1) a = dttosecs(res[i]['dt']) b = dttosecs(res[int(low)]['dt']) t = dttosecs(target) if abs(a-t) &lt; abs(b-t): return int(low-1) else: return int(low) import time def dttosecs(dt): # string to seconds since the beginning date,tim = dt.split('T') y,m,d = date.split('-') h,mn,s = tim.split(':') y = int(y) m = int(m) d = int(d) h = int(h) mn = int(mn) s = min(59,int(float(s)+0.5)) # round to neatest second s = int(s) secs = time.mktime((y,m,d,h,mn,s,0,0,-1)) return secs </code></pre>
2
2009-09-17T13:33:42Z
1,439,436
<pre><code>import bisect def mid(res, target): keys = [r['dt'] for r in res] return res[bisect.bisect_left(keys, target)] </code></pre>
2
2009-09-17T15:01:40Z
[ "python", "search" ]
Finding closest match in collection of strings representing numbers
1,438,924
<p>I have a sorted list of datetimes in text format. The format of each entry is '2009-09-10T12:00:00'.</p> <p>I want to find the entry closest to a target. There are many more entries than the number of searches I would have to do.</p> <p>I could change each entry to a number, then search numerically (for example <a href="http://stackoverflow.com/questions/445782/finding-closest-match-in-collection-of-numbers">these</a> approaches), but that would seem excess effort. </p> <p>Is there a better way than this:</p> <pre><code>def mid(res, target): #res is a list of entries, sorted by dt (dateTtime) #each entry is a dict with a dt and some other info n = len(res) low = 0 high = n-1 # find the first res greater than target while low &lt; high: mid = (low + high)/2 t = res[int(mid)]['dt'] if t &lt; target: low = mid + 1 else: high = mid # check if the prior value is closer i = max(0, int(low)-1) a = dttosecs(res[i]['dt']) b = dttosecs(res[int(low)]['dt']) t = dttosecs(target) if abs(a-t) &lt; abs(b-t): return int(low-1) else: return int(low) import time def dttosecs(dt): # string to seconds since the beginning date,tim = dt.split('T') y,m,d = date.split('-') h,mn,s = tim.split(':') y = int(y) m = int(m) d = int(d) h = int(h) mn = int(mn) s = min(59,int(float(s)+0.5)) # round to neatest second s = int(s) secs = time.mktime((y,m,d,h,mn,s,0,0,-1)) return secs </code></pre>
2
2009-09-17T13:33:42Z
1,439,519
<p>First, change to this.</p> <pre><code>import datetime def parse_dt(dt): return datetime.strptime( dt, "%Y-%m-%dT%H:%M:%S" ) </code></pre> <p>This removes much of the "effort".</p> <p>Consider this as the search.</p> <pre><code>def mid( res, target ): """res is a list of entries, sorted by dt (dateTtime) each entry is a dict with a dt and some other info """ times = [ parse_dt(r['dt']) for r in res ] index= bisect( times, parse_dt(target) ) return times[index] </code></pre> <p>This doesn't seem like very much "effort". This does not depend on your timestamps being formatted properly, either. You can change to any timestamp format and be assured that this will always work.</p>
1
2009-09-17T15:16:39Z
[ "python", "search" ]
Finding closest match in collection of strings representing numbers
1,438,924
<p>I have a sorted list of datetimes in text format. The format of each entry is '2009-09-10T12:00:00'.</p> <p>I want to find the entry closest to a target. There are many more entries than the number of searches I would have to do.</p> <p>I could change each entry to a number, then search numerically (for example <a href="http://stackoverflow.com/questions/445782/finding-closest-match-in-collection-of-numbers">these</a> approaches), but that would seem excess effort. </p> <p>Is there a better way than this:</p> <pre><code>def mid(res, target): #res is a list of entries, sorted by dt (dateTtime) #each entry is a dict with a dt and some other info n = len(res) low = 0 high = n-1 # find the first res greater than target while low &lt; high: mid = (low + high)/2 t = res[int(mid)]['dt'] if t &lt; target: low = mid + 1 else: high = mid # check if the prior value is closer i = max(0, int(low)-1) a = dttosecs(res[i]['dt']) b = dttosecs(res[int(low)]['dt']) t = dttosecs(target) if abs(a-t) &lt; abs(b-t): return int(low-1) else: return int(low) import time def dttosecs(dt): # string to seconds since the beginning date,tim = dt.split('T') y,m,d = date.split('-') h,mn,s = tim.split(':') y = int(y) m = int(m) d = int(d) h = int(h) mn = int(mn) s = min(59,int(float(s)+0.5)) # round to neatest second s = int(s) secs = time.mktime((y,m,d,h,mn,s,0,0,-1)) return secs </code></pre>
2
2009-09-17T13:33:42Z
1,439,712
<p>"Copy and paste coding" (getting <code>bisect</code>'s sources into your code) is not recommended as it carries all sorts of costs down the road (lot of extra source code for you to test and maintain, difficulties dealing with upgrades in the upstream code you've copied, etc, etc); the best way to reuse standard library modules is simply to import them and use them.</p> <p>However, to do one pass transforming the dictionaries into meaningfully comparable entries is O(N), which (even though each step of the pass is simple) will eventually swamp the O(log N) time of the search proper. Since <code>bisect</code> can't support a <code>key=</code> key extractor like <code>sort</code> does, what the solution to this dilemma -- how can you reuse <code>bisect</code> by import and call, without a preliminary O(N) step...?</p> <p>As quoted <a href="http://en.wikipedia.org/wiki/Indirection%5F%28programming%29" rel="nofollow">here</a>, the solution is in David Wheeler's famous saying, "All problems in computer science can be solved by another level of indirection". Consider e.g....:</p> <pre><code>import bisect listofdicts = [ {'dt': '2009-%2.2d-%2.2dT12:00:00' % (m,d) } for m in range(4,9) for d in range(1,30) ] class Indexer(object): def __init__(self, lod, key): self.lod = lod self.key = key def __len__(self): return len(self.lod) def __getitem__(self, idx): return self.lod[idx][self.key] lookfor = listofdicts[len(listofdicts)//2]['dt'] def mid(res=listofdicts, target=lookfor): keys = [r['dt'] for r in res] return res[bisect.bisect_left(keys, target)] def midi(res=listofdicts, target=lookfor): wrap = Indexer(res, 'dt') return res[bisect.bisect_left(wrap, target)] if __name__ == '__main__': print '%d dicts on the list' % len(listofdicts) print 'Looking for', lookfor print mid(), midi() assert mid() == midi() </code></pre> <p>The output (just running this <code>indexer.py</code> as a check, then with <code>timeit</code>, two ways):</p> <pre><code>$ python indexer.py 145 dicts on the list Looking for 2009-06-15T12:00:00 {'dt': '2009-06-15T12:00:00'} {'dt': '2009-06-15T12:00:00'} $ python -mtimeit -s'import indexer' 'indexer.mid()' 10000 loops, best of 3: 27.2 usec per loop $ python -mtimeit -s'import indexer' 'indexer.midi()' 100000 loops, best of 3: 9.43 usec per loop </code></pre> <p>As you see, even in a modest task with 145 entries in the list, the indirection approach can have a performance that's three times better than the "key-extraction pass" approach. Since we're comparing O(N) vs O(log N), the advantage of the indirection approach grows without bounds as N increases. (For very small N, the higher multiplicative constants due to the indirection make the key-extraction approach faster, but this is soon surpassed by the big-O difference). Admittedly, the Indexer class is extra code -- however, it's reusable over ALL tasks of binary searching a list of dicts sorted by one entry in each dict, so having it in your "container-utilities back of tricks" offers good return on that investment.</p> <p>So much for the main search loop. For the secondary task of converting two entries (the one just below and the one just above the target) and the target to a number of seconds, consider, again, a higher-reuse approach, namely:</p> <pre><code>import time adt = '2009-09-10T12:00:00' def dttosecs(dt=adt): # string to seconds since the beginning date,tim = dt.split('T') y,m,d = date.split('-') h,mn,s = tim.split(':') y = int(y) m = int(m) d = int(d) h = int(h) mn = int(mn) s = min(59,int(float(s)+0.5)) # round to neatest second s = int(s) secs = time.mktime((y,m,d,h,mn,s,0,0,-1)) return secs def simpler(dt=adt): return time.mktime(time.strptime(dt, '%Y-%m-%dT%H:%M:%S')) if __name__ == '__main__': print adt, dttosecs(), simpler() assert dttosecs() == simpler() </code></pre> <p>Here, there is no performance advantage to the reuse approach (indeed, and on the contrary, <code>dttosecs</code> is faster) -- but then, you only need to perform three conversions per search, no matter how many entries are on your list of dicts, so it's not clear whether that performance issue is germane. Meanwhile, with <code>simpler</code> you only have to write, test and maintain one simple line of code, while <code>dttosecs</code> is a dozen lines; given this ratio, in most situations (i.e., excluding absolute bottlenecks), I would prefer <code>simpler</code>. The important thing is to be aware of both approaches and of the tradeoffs between them so as to ensure the choice is made wisely.</p>
4
2009-09-17T15:51:43Z
[ "python", "search" ]
How to catch exit() in embedded C++ module from python code?
1,439,533
<p>I am embedding a c++ library (binding done with SIP) in my python application. Under certain circonstances (error cases), this library uses exit(), which causes my entire application to exit. Is there a way to catch this event, or do I need to modify the library to handle error cases differently ? </p> <p>Thank you very much,</p>
4
2009-09-17T15:19:36Z
1,439,585
<p>You must modify the source of the library. There is no "exception handling" in C and <code>exit()</code> does not return to the calling code under any circumstances.</p>
6
2009-09-17T15:27:46Z
[ "python", "exception", "binding", "exit" ]
How to catch exit() in embedded C++ module from python code?
1,439,533
<p>I am embedding a c++ library (binding done with SIP) in my python application. Under certain circonstances (error cases), this library uses exit(), which causes my entire application to exit. Is there a way to catch this event, or do I need to modify the library to handle error cases differently ? </p> <p>Thank you very much,</p>
4
2009-09-17T15:19:36Z
8,099,938
<p>You can override the library linking with LD_LIBRARY_PATH and make your own exit function. Works fine.</p>
0
2011-11-11T21:03:01Z
[ "python", "exception", "binding", "exit" ]
have you seen? _mysql_exceptions.OperationalError "Lost connection to MySQL server during query" being ignored
1,439,616
<p>I am just starting out with the MySQLdb module for python, and upon running some SELECT and UPDATE queries, the following gets output:</p> <blockquote> <p>Exception _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') in bound method Cursor.<strong>del</strong> of MySQLdb.cursors.Cursor object at 0x8c0188c ignored</p> </blockquote> <p>The exception is apparently getting caught (and "ignored") by MySQLdb itself, so I guess this is not a major issue. Also, the SELECTs generate results and the table gets modified by UPDATE.</p> <p>But, since I am just getting my feet wet with this, I want to ask: does this message suggest I am doing something wrong? Or have you seen these warnings before in harmless situations?</p> <p>Thanks for any insight,</p> <p>lara</p>
0
2009-09-17T15:33:15Z
1,439,734
<p>Ha! Just realized I was trying to use the cursor <em>after</em> having closed the connection! In any case, it was nice writing! : )</p> <p>l</p>
0
2009-09-17T15:54:52Z
[ "python", "mysql" ]
What is the builtin name of the 'type' of functions, in Python?
1,439,815
<p>What Python builtin returns <code>&lt;type 'function'&gt;</code>?</p> <pre><code>&gt;&gt;&gt; type(lambda: None) &lt;type 'function'&gt; </code></pre> <p>Is there way of avoiding creating this lambda function, in order to get the type of functions in general?</p> <p>See <a href="http://www.finalcog.com/python-memoise-memoize-function-type" rel="nofollow">http://www.finalcog.com/python-memoise-memoize-function-type</a> for more details.</p> <p>Thanks,</p> <p>Chris.</p>
0
2009-09-17T16:11:24Z
1,439,824
<p>built-ins are not <code>function</code>s they are: <code>builtin_function_or_method</code>. Isn't it the whole point of naming?</p> <p>you can get by doing something like:</p> <pre><code>&gt;&gt;&gt; type(len) &lt;class 'builtin_function_or_method'&gt; </code></pre>
0
2009-09-17T16:12:54Z
[ "python", "types" ]
What is the builtin name of the 'type' of functions, in Python?
1,439,815
<p>What Python builtin returns <code>&lt;type 'function'&gt;</code>?</p> <pre><code>&gt;&gt;&gt; type(lambda: None) &lt;type 'function'&gt; </code></pre> <p>Is there way of avoiding creating this lambda function, in order to get the type of functions in general?</p> <p>See <a href="http://www.finalcog.com/python-memoise-memoize-function-type" rel="nofollow">http://www.finalcog.com/python-memoise-memoize-function-type</a> for more details.</p> <p>Thanks,</p> <p>Chris.</p>
0
2009-09-17T16:11:24Z
1,439,852
<p>You should be able to use <code>types.FunctionType</code> to do what you want:</p> <pre> Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import types >>> help(types.FunctionType) Help on class function in module __builtin__: class function(object) | function(code, globals[, name[, argdefs[, closure]]]) | | Create a function object from a code object and a dictionary. | The optional name string overrides the name from the code object. | The optional argdefs tuple specifies the default argument values. | The optional closure tuple supplies the bindings for free variables. </pre> <p>But generally, <code>def</code> is considered the default constructor for the <code>function</code> type.</p>
5
2009-09-17T16:16:51Z
[ "python", "types" ]
What is the builtin name of the 'type' of functions, in Python?
1,439,815
<p>What Python builtin returns <code>&lt;type 'function'&gt;</code>?</p> <pre><code>&gt;&gt;&gt; type(lambda: None) &lt;type 'function'&gt; </code></pre> <p>Is there way of avoiding creating this lambda function, in order to get the type of functions in general?</p> <p>See <a href="http://www.finalcog.com/python-memoise-memoize-function-type" rel="nofollow">http://www.finalcog.com/python-memoise-memoize-function-type</a> for more details.</p> <p>Thanks,</p> <p>Chris.</p>
0
2009-09-17T16:11:24Z
1,439,853
<p>"What Python builtin returns <code>&lt;type 'function'&gt;</code>?"</p> <p>Functions.</p> <p>"Is there way of avoiding creating this lambda function, in order to get the type of functions in general?"</p> <p>Yes, types.FunctionType. or just type(anyfunction)</p> <p>If you are asking how to get rid of lambdas (but a reread tells me you probably are not) you can if define a function instead of the lambda.</p> <p>So instead of:</p> <pre><code>&gt;&gt;&gt; somemethod(lambda x: x+x) </code></pre> <p>You do</p> <pre><code>&gt;&gt;&gt; def thefunction(x): ... return x+x &gt;&gt;&gt; somemethod(thefunction) </code></pre>
1
2009-09-17T16:16:55Z
[ "python", "types" ]
What is the builtin name of the 'type' of functions, in Python?
1,439,815
<p>What Python builtin returns <code>&lt;type 'function'&gt;</code>?</p> <pre><code>&gt;&gt;&gt; type(lambda: None) &lt;type 'function'&gt; </code></pre> <p>Is there way of avoiding creating this lambda function, in order to get the type of functions in general?</p> <p>See <a href="http://www.finalcog.com/python-memoise-memoize-function-type" rel="nofollow">http://www.finalcog.com/python-memoise-memoize-function-type</a> for more details.</p> <p>Thanks,</p> <p>Chris.</p>
0
2009-09-17T16:11:24Z
1,439,902
<p>You should get away from the idea of 'types' in Python. Most of the time you don't want to check the 'type' of something. Explicitly checking types is prone to breakage, for example:</p> <pre><code>&gt;&gt;&gt; s1 = 'hello' &gt;&gt;&gt; s2 = u'hello' &gt;&gt;&gt; type(s1) == type(s2) False </code></pre> <p>What you want to do is check if the object supports whatever operation you're trying to perform on it.</p> <p>If you want to see if a given object is a function, do this:</p> <pre><code>&gt;&gt;&gt; func = lambda x: x*2 &gt;&gt;&gt; something_else = 'not callable' &gt;&gt;&gt; callable(func) True &gt;&gt;&gt; callable(something_else) False </code></pre> <p>Or just try calling it, and catch the exception!</p>
3
2009-09-17T16:27:26Z
[ "python", "types" ]
How do i return a quoted string from a tuple?
1,439,862
<p>I have a tuple of strings that i would want to extract the contents as a quoted string, i.e.</p> <pre><code>tup=('string1', 'string2', 'string3') when i do this main_str = ",".join(tup) #i get main_str = 'string1, string2, string3' #I want the main_str to have something like this main_str = '"string1", "string2", "string3"' </code></pre> <p>Gath</p>
1
2009-09-17T16:18:59Z
1,439,879
<pre><code>", ".join('"{0}"'.format(i) for i in tup) </code></pre> <p>or</p> <pre><code>", ".join('"%s"' % i for i in tup) </code></pre>
9
2009-09-17T16:21:51Z
[ "python", "tuples" ]
How do i return a quoted string from a tuple?
1,439,862
<p>I have a tuple of strings that i would want to extract the contents as a quoted string, i.e.</p> <pre><code>tup=('string1', 'string2', 'string3') when i do this main_str = ",".join(tup) #i get main_str = 'string1, string2, string3' #I want the main_str to have something like this main_str = '"string1", "string2", "string3"' </code></pre> <p>Gath</p>
1
2009-09-17T16:18:59Z
1,439,880
<p>Well, one answer would be:</p> <pre><code>', '.join([repr(x) for x in tup]) </code></pre> <p>or</p> <pre><code>repr(tup)[1:-1] </code></pre> <p>But that's not really nice. ;)</p> <p>Updated: Although, noted, you will not be able to control if resulting string starts with '" or '". If that matters, you need to be more explicit, like the other answers here are:</p> <pre><code>', '.join(['"%s"' % x for x in tup]) </code></pre>
2
2009-09-17T16:21:59Z
[ "python", "tuples" ]
How do i return a quoted string from a tuple?
1,439,862
<p>I have a tuple of strings that i would want to extract the contents as a quoted string, i.e.</p> <pre><code>tup=('string1', 'string2', 'string3') when i do this main_str = ",".join(tup) #i get main_str = 'string1, string2, string3' #I want the main_str to have something like this main_str = '"string1", "string2", "string3"' </code></pre> <p>Gath</p>
1
2009-09-17T16:18:59Z
1,439,889
<p>Here's one way to do it:</p> <pre><code>&gt;&gt;&gt; t = ('s1', 's2', 's3') &gt;&gt;&gt; ", ".join( s.join(['"','"']) for s in t) '"s1", "s2", "s3"' </code></pre>
0
2009-09-17T16:23:56Z
[ "python", "tuples" ]
possible to intercept and rewrite email on outlook client side using ironpython?
1,440,233
<p>I want to intercept and transform some automated emails into a more readable format. I believe this is possible using VBA, but I would prefer to manipulate the text with Python. Can I create an ironpython client-side script to pre-process certain emails?</p> <p>EDIT: I believe this can be done with outlook rules. In Outlook 2007, you can do: Tools->Rules -> New Rule</p> <p>"check messages when they arrive"</p> <p>next</p> <p>[filter which emails to process]</p> <p>next</p> <p>"run a script"</p> <p>In the "run a script" it allows you to use a VBA script.</p>
1
2009-09-17T17:31:22Z
1,441,330
<p>I can only offer you a pointer. Years ago, I used a Bayesian spam filter with Outlook. It was written in Python, and provided an Outlook plug-in that would filter incoming mail. The name of the software was <a href="http://spambayes.sourceforge.net/" rel="nofollow"><em>SpamBayes</em></a>, and the project is still online. As it is open source, you will probably find all necessary information how to plug a mail filter into Outlook. This should give you enough background to add code that will actually be able to transform mail content. My understanding was it was written in vanilla Python (CPython), but if you are more comfortable with IronPython, it shouldn't be hard to translate. Give it a go.</p>
2
2009-09-17T21:01:27Z
[ "python", "vba", "outlook", "ironpython" ]
possible to intercept and rewrite email on outlook client side using ironpython?
1,440,233
<p>I want to intercept and transform some automated emails into a more readable format. I believe this is possible using VBA, but I would prefer to manipulate the text with Python. Can I create an ironpython client-side script to pre-process certain emails?</p> <p>EDIT: I believe this can be done with outlook rules. In Outlook 2007, you can do: Tools->Rules -> New Rule</p> <p>"check messages when they arrive"</p> <p>next</p> <p>[filter which emails to process]</p> <p>next</p> <p>"run a script"</p> <p>In the "run a script" it allows you to use a VBA script.</p>
1
2009-09-17T17:31:22Z
1,441,579
<p>You can reference the outlook object model here: <a href="http://msdn.microsoft.com/en-us/library/ms268893.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms268893.aspx</a></p> <p>Connect to outlook through COM, you'll need <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a>.</p> <p>There's no python reference that I know of, but you can reference the sample scripts and 'translate' to python. It's difficult at first, but once you understand the objects and their usage in python it's not hard. </p> <p>Looks like you want to look at:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms268998.aspx" rel="nofollow">How to: Perform Actions When an E-Mail Message Is Received</a></p>
2
2009-09-17T22:10:01Z
[ "python", "vba", "outlook", "ironpython" ]
possible to intercept and rewrite email on outlook client side using ironpython?
1,440,233
<p>I want to intercept and transform some automated emails into a more readable format. I believe this is possible using VBA, but I would prefer to manipulate the text with Python. Can I create an ironpython client-side script to pre-process certain emails?</p> <p>EDIT: I believe this can be done with outlook rules. In Outlook 2007, you can do: Tools->Rules -> New Rule</p> <p>"check messages when they arrive"</p> <p>next</p> <p>[filter which emails to process]</p> <p>next</p> <p>"run a script"</p> <p>In the "run a script" it allows you to use a VBA script.</p>
1
2009-09-17T17:31:22Z
1,719,000
<p>This is a work in progress, but I've figured out part of the answer with the help of the other posts. Here are the instructions for re-writing specified emails by running a script. I'm using Outlook 2007.</p> <ol> <li><p>Download and install <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a></p></li> <li><p>Download and install <a href="http://support.microsoft.com/kb/945835" rel="nofollow">ExchangeCdo.exe</a></p></li> <li><p>Put this code in a file and run it from <code>cmd</code>:</p></li> </ol> <p><code></code></p> <pre><code>import os, sys, re import win32com.client session = win32com.client.gencache.EnsureDispatch("MAPI.session") win32com.client.gencache.EnsureDispatch("Outlook.Application") outlook = win32com.client.Dispatch("Outlook.Application") #print '\n'.join(dir(outlook)) mapi = outlook.GetNamespace('MAPI') inbox = mapi.GetDefaultFolder(win32com.client.constants.olFolderInbox) items = inbox.Items #items.Restrict("[Unread] = true") #print '\n'.join(dir(items)) while True: item = items.GetNext() if item == None: break #print '\n'.join(dir(item)) if re.compile(r'crazy email').search(item.Subject): print item.Subject print item.Body # works VVVV item.Body = 'whoya!' item.Save() break </code></pre>
1
2009-11-12T00:15:24Z
[ "python", "vba", "outlook", "ironpython" ]
possible to intercept and rewrite email on outlook client side using ironpython?
1,440,233
<p>I want to intercept and transform some automated emails into a more readable format. I believe this is possible using VBA, but I would prefer to manipulate the text with Python. Can I create an ironpython client-side script to pre-process certain emails?</p> <p>EDIT: I believe this can be done with outlook rules. In Outlook 2007, you can do: Tools->Rules -> New Rule</p> <p>"check messages when they arrive"</p> <p>next</p> <p>[filter which emails to process]</p> <p>next</p> <p>"run a script"</p> <p>In the "run a script" it allows you to use a VBA script.</p>
1
2009-09-17T17:31:22Z
15,686,621
<p>There is an answer here: <a href="http://stackoverflow.com/questions/13265861/how-to-trigger-a-python-script-in-outlook-using-rules">how to trigger a python script in outlook using rules?</a> that may help you. You can make a simple VBA script to trigger the python script.</p>
0
2013-03-28T16:02:23Z
[ "python", "vba", "outlook", "ironpython" ]
How to use Python plugin reCaptcha client for validation?
1,440,239
<p>I want to make a captcha validation.</p> <p>I get the key from the <a href="http://recaptcha.net/">recaptcha website</a> and already succeed to put the public key to load the webpage with the challenge.</p> <pre><code>&lt;script type="text/javascript" src="http://api.recaptcha.net/challenge?k=&lt;your_public_key&gt;"&gt; &lt;/script&gt; &lt;noscript&gt; &lt;iframe src="http://api.recaptcha.net/noscript?k=&lt;your_public_key&gt;" height="300" width="500" frameborder="0"&gt;&lt;/iframe&gt;&lt;br&gt; &lt;textarea name="recaptcha_challenge_field" rows="3" cols="40"&gt; &lt;/textarea&gt; &lt;input type="hidden" name="recaptcha_response_field" value="manual_challenge"&gt; &lt;/noscript&gt; </code></pre> <p>I download <a href="http://pypi.python.org/pypi/recaptcha-client">the reCaptcha Python plugin</a> but I can not find any documentation on how to use it. </p> <p>Does anyone have any idea on how to use this Python plugin? recaptcha-client-1.0.4.tar.gz (md5)</p>
15
2009-09-17T17:32:07Z
1,440,429
<p>It is quite straightforward. This is an example from a trivial trac plugin I'm using:</p> <pre><code>from recaptcha.client import captcha if req.method == 'POST': response = captcha.submit( req.args['recaptcha_challenge_field'], req.args['recaptcha_response_field'], self.private_key, req.remote_addr, ) if not response.is_valid: say_captcha_is_invalid() else: do_something_useful() else: data['recaptcha_javascript'] = captcha.displayhtml(self.public_key) data['recaptcha_theme'] = self.theme return 'recaptchaticket.html', data, n </code></pre>
24
2009-09-17T18:06:28Z
[ "python", "validation", "plugins", "captcha", "recaptcha" ]
How to use Python plugin reCaptcha client for validation?
1,440,239
<p>I want to make a captcha validation.</p> <p>I get the key from the <a href="http://recaptcha.net/">recaptcha website</a> and already succeed to put the public key to load the webpage with the challenge.</p> <pre><code>&lt;script type="text/javascript" src="http://api.recaptcha.net/challenge?k=&lt;your_public_key&gt;"&gt; &lt;/script&gt; &lt;noscript&gt; &lt;iframe src="http://api.recaptcha.net/noscript?k=&lt;your_public_key&gt;" height="300" width="500" frameborder="0"&gt;&lt;/iframe&gt;&lt;br&gt; &lt;textarea name="recaptcha_challenge_field" rows="3" cols="40"&gt; &lt;/textarea&gt; &lt;input type="hidden" name="recaptcha_response_field" value="manual_challenge"&gt; &lt;/noscript&gt; </code></pre> <p>I download <a href="http://pypi.python.org/pypi/recaptcha-client">the reCaptcha Python plugin</a> but I can not find any documentation on how to use it. </p> <p>Does anyone have any idea on how to use this Python plugin? recaptcha-client-1.0.4.tar.gz (md5)</p>
15
2009-09-17T17:32:07Z
12,045,423
<p>Sorry to say, but this module, while it works just fine, is almost entirely undocumented, and it's layout is a tad confusing for those of us who prefer using ">> help(modulename)" after installation. I'll give an example using cherrypy, and make some cgi-related comments afterwards.</p> <p>captcha.py contains two functions and a class:</p> <ul> <li><p>display_html: which returns the familiar "reCaptcha box"</p></li> <li><p>submit: which submits the values entered by the user in the background</p></li> <li><p>RecapchaResponse: which is a container class that contains the response from reCaptcha</p></li> </ul> <p>You'll first need to import the complete path to capcha.py, then create a couple of functions that handle displaying and dealing with the response.</p> <pre><code>from recaptcha.client import captcha class Main(object): @cherrypy.expose def display_recaptcha(self, *args, **kwargs): public = "public_key_string_you_got_from_recaptcha" captcha_html = captcha.displayhtml( public, use_ssl=False, error="Something broke!") # You'll probably want to add error message handling here if you # have been redirected from a failed attempt return """ &lt;form action="validate"&gt; %s &lt;input type=submit value="Submit Captcha Text" \&gt; &lt;/form&gt; """%captcha_html # send the recaptcha fields for validation @cherrypy.expose def validate(self, *args, **kwargs): # these should be here, in the real world, you'd display a nice error # then redirect the user to something useful if not "recaptcha_challenge_field" in kwargs: return "no recaptcha_challenge_field" if not "recaptcha_response_field" in kwargs: return "no recaptcha_response_field" recaptcha_challenge_field = kwargs["recaptcha_challenge_field"] recaptcha_response_field = kwargs["recaptcha_response_field"] # response is just the RecaptchaResponse container class. You'll need # to check is_valid and error_code response = captcha.submit( recaptcha_challenge_field, recaptcha_response_field, "private_key_string_you_got_from_recaptcha", cherrypy.request.headers["Remote-Addr"],) if response.is_valid: #redirect to where ever we want to go on success raise cherrypy.HTTPRedirect("success_page") if response.error_code: # this tacks on the error to the redirect, so you can let the # user knowwhy their submission failed (not handled above, # but you are smart :-) ) raise cherrypy.HTTPRedirect( "display_recaptcha?error=%s"%response.error_code) </code></pre> <p>It'll be pretty much the same if using cgi, just use the REMOTE_ADDR environment variable where I used cherrypy's request.headers and use field storage to do your checks.</p> <p>There is no magic, the module just follows the docs: <a href="https://developers.google.com/recaptcha/docs/display" rel="nofollow">https://developers.google.com/recaptcha/docs/display</a></p> <p>Validation errors you might need to handle: <a href="https://developers.google.com/recaptcha/docs/verify" rel="nofollow">https://developers.google.com/recaptcha/docs/verify</a></p>
4
2012-08-20T21:24:30Z
[ "python", "validation", "plugins", "captcha", "recaptcha" ]
How do I disable psycopg2 connection pooling?
1,440,245
<p>I have configured pgpool-II for postgres connection pooling and I want to disable psycopg2 connection pooling. How do I do this?</p> <p>Thanks!</p>
0
2009-09-17T17:34:01Z
1,443,845
<p>I don't think you can. Dan McKinley bemoaned this fact (among some other interesting issues) in his blog post <a href="http://mcfunley.com/445/python-postgresql-driver-authors-hate-you" rel="nofollow">Python PostgreSQL Driver Authors Hate You</a>.</p>
-1
2009-09-18T11:00:36Z
[ "python", "psycopg2" ]
How do I disable psycopg2 connection pooling?
1,440,245
<p>I have configured pgpool-II for postgres connection pooling and I want to disable psycopg2 connection pooling. How do I do this?</p> <p>Thanks!</p>
0
2009-09-17T17:34:01Z
1,492,172
<p><code>psycopg2</code> doesn't pool connections unless you explicitely use the <code>psycopg.pool</code> module.</p>
6
2009-09-29T12:11:38Z
[ "python", "psycopg2" ]
How to create simplest p2p remote desktop OR any Robot(Java) equivalent in python
1,440,323
<p>I want to create a simplest remote desktop application using p2p communication. I did created one small p2p program in python.</p> <p>My Idea is-</p> <ul> <li><p>Transmit screenshots of remote computer periodically</p></li> <li><p>Transmit keyboard and mouse events wrapped in xml to remote desktop.</p></li> </ul> <p>Problem-</p> <p>I could transmit a information for keyboard and mouse events to remote computer and it will be received. But how should remote program reflect those events to remote machine. I mean how should remote program communicate with operating system. </p> <p>OS: windows xp</p> <p>Ok is there any equivalent of <a href="http://java.sun.com/j2se/1.3/docs/api/java/awt/Robot.html" rel="nofollow">Robot</a>(Java) in python to control mouse and keyboard events</p>
0
2009-09-17T17:47:55Z
1,440,831
<p>You can control the keyboard and the mouse with python on Windows by calling the win32 apis: <a href="http://msdn.microsoft.com/en-us/library/ms646304%28VS.85%29.aspx" rel="nofollow"><code>keybd_event</code></a> and <a href="http://msdn.microsoft.com/en-us/library/ms646260%28VS.85%29.aspx" rel="nofollow"><code>mouse_event</code></a> thanks to ctypes </p>
1
2009-09-17T19:18:35Z
[ "python", "operating-system", "remote-desktop", "p2p" ]
Class usage in Python
1,440,434
<p>I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot...</p> <p>Rather than just writing a procedure, would there be an benefits of using a Class? I can bury the actual analysis into functions so I can pass the data to the function and let it do it's thing but the functions are not contained in a Class. </p> <p>What sort of drawbacks would a Class over come and what would be the purpose of using a Class if it can be written procedurally?</p> <p>If this has been posted before my apologies, just point me in that direction.</p>
7
2009-09-17T18:07:33Z
1,440,467
<p>By using Object Oriented Programming, you will have objects, that have associated functions, that are (should) be the only way to modify its properties (internal variables).</p> <p>It was common to have functions called <code>trim_string(string)</code>, while with a <code>string</code> class you could do <code>string.trim()</code>. The difference is noticeable mainly when doing big complex modules, where you need to do all you can to minify the coupling between individual components.</p> <p>There are other concepts that encompass OOP, like inheritance, but the real important thing to know, is that OOP is about making you think about <em>objects</em> that have operations and message passing (methods/verbs), instead of thinking in term of operations (functions/verbs) and basic elements (variables)</p> <blockquote> <p><a href="http://stackoverflow.com/questions/530741/whats-the-difference-between-a-procedural-program-and-an-object-oriented-program/530930#530930">The importance</a> of the object oriented paradigm is not as much in the language mechanism as it is in the thinking and design process.</p> </blockquote> <p>Also take a look at <a href="http://stackoverflow.com/questions/530741/whats-the-difference-between-a-procedural-program-and-an-object-oriented-program">this question</a>.</p> <p><strong>There is nothing inherently <em>wrong</em> about Structured Programming, it's just that <em>some</em> problems map better to an Object Oriented design.</strong></p> <p>For example you could have in a SP language:</p> <pre><code>#Pseudocode!!! function talk(dog): if dog is aDog: print "bark!" raise "IS NOT A SUPPORTED ANIMAL!!!" &gt;&gt;var dog as aDog &gt;&gt;talk(dog) "bark!" &gt;&gt;var cat as aCat &gt;&gt;talk(cat) EXCEPTION: IS NOT A SUPPORTED ANIMAL!!! # Lets add the cat function talk(animal): if animal is aDog: print "bark!" if animal is aCat: print "miau!" raise "IS NOT A SUPPORTED ANIMAL!!!" </code></pre> <p>While on an OOP you'd have:</p> <pre><code>class Animal: def __init__(self, name="skippy"): self.name = name def talk(self): raise "MUTE ANIMAL" class Dog(Animal): def talk(self): print "bark!" class Cat(Animal): def talk(self): print "miau!" &gt;&gt;dog = new Dog() &gt;&gt;dog.talk() "bark!" &gt;&gt;cat = new Cat() &gt;&gt;cat.talk() "miau!" </code></pre> <p>You can see that with SP, every animal that you add, you'd have to add another <code>if</code> to <code>talk</code>, add another variable to store the name of the animal, touch potentially every function in the module, while on OOP, you can consider your class as independent to the rest. When there is a global change, you change the <code>Animal</code>, when it's a narrow change, you just have to look at the class definition.</p> <p>For simple, sequential, and possibly throwaway code, it's ok to use structured programming.</p>
15
2009-09-17T18:13:28Z
[ "python", "oop", "class-design", "procedural-programming" ]
Class usage in Python
1,440,434
<p>I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot...</p> <p>Rather than just writing a procedure, would there be an benefits of using a Class? I can bury the actual analysis into functions so I can pass the data to the function and let it do it's thing but the functions are not contained in a Class. </p> <p>What sort of drawbacks would a Class over come and what would be the purpose of using a Class if it can be written procedurally?</p> <p>If this has been posted before my apologies, just point me in that direction.</p>
7
2009-09-17T18:07:33Z
1,440,655
<p>You don't <em>need</em> to use classes in Python - it doesn't force you to do OOP. If you're more comfortable with the functional style, that's fine. I use classes when I want to model some abstraction which has variations, and I want to model those variations using classes. As the word "class" implies, they're useful mainly when the stuff you are working with falls naturally into various classes. When just manipulating large datasets, I've not found an overarching need to follow an OOP paradigm just for the sake of it.</p>
4
2009-09-17T18:46:28Z
[ "python", "oop", "class-design", "procedural-programming" ]
Class usage in Python
1,440,434
<p>I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot...</p> <p>Rather than just writing a procedure, would there be an benefits of using a Class? I can bury the actual analysis into functions so I can pass the data to the function and let it do it's thing but the functions are not contained in a Class. </p> <p>What sort of drawbacks would a Class over come and what would be the purpose of using a Class if it can be written procedurally?</p> <p>If this has been posted before my apologies, just point me in that direction.</p>
7
2009-09-17T18:07:33Z
1,440,684
<p>"but the functions are not contained in a Class."</p> <p>They could be.</p> <pre><code>class Linear( object ): a= 2. b= 3. def calculate( self, somePoint ): somePoint['line']= b + somePoint['x']*a class Exponential( object ): a = 1.05 b = 3.2 def calculate( self, somePoint ): somePoint['exp']= b * somePoint['x']**a class Mapping( object ): def __init__( self ): self.funcs = ( Linear(), Exponential() ) def apply( self, someData ): for row in someData: for f in self.funcs: f.calculate( row ) </code></pre> <p>Now your calculations are wrapped in classes. You can use design patterns like <strong>Delegation</strong>, <strong>Composition</strong> and <strong>Command</strong> to simplify your scripts.</p>
1
2009-09-17T18:54:19Z
[ "python", "oop", "class-design", "procedural-programming" ]
Class usage in Python
1,440,434
<p>I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot...</p> <p>Rather than just writing a procedure, would there be an benefits of using a Class? I can bury the actual analysis into functions so I can pass the data to the function and let it do it's thing but the functions are not contained in a Class. </p> <p>What sort of drawbacks would a Class over come and what would be the purpose of using a Class if it can be written procedurally?</p> <p>If this has been posted before my apologies, just point me in that direction.</p>
7
2009-09-17T18:07:33Z
1,440,734
<p>OOP lends itself well to complex programs. It's great for capturing the state and behavior of real world concepts and orchestrating the interplay between them. Good OO code is easy to read/understand, protects your data's integrity, and maximizes code reuse. I'd say code reuse is one big advantage to keeping your frequently used calculations in a class.</p>
1
2009-09-17T19:01:28Z
[ "python", "oop", "class-design", "procedural-programming" ]
Class usage in Python
1,440,434
<p>I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot...</p> <p>Rather than just writing a procedure, would there be an benefits of using a Class? I can bury the actual analysis into functions so I can pass the data to the function and let it do it's thing but the functions are not contained in a Class. </p> <p>What sort of drawbacks would a Class over come and what would be the purpose of using a Class if it can be written procedurally?</p> <p>If this has been posted before my apologies, just point me in that direction.</p>
7
2009-09-17T18:07:33Z
1,447,527
<ul> <li><p>Object-oriented programming isn't the solution to every coding problem.</p></li> <li><p>In Python, functions are objects. You can mix as many objects and functions as you want.</p></li> <li><p>Modules with functions are already objects with properties.</p></li> <li><p>If you find yourself passing a lot of the same variables around — <em>state</em> — an object is probably better suited. If you have a lot of classes with class methods, or methods that don't use <code>self</code> very much, then functions are probably better.</p></li> </ul>
1
2009-09-19T02:16:08Z
[ "python", "oop", "class-design", "procedural-programming" ]
Maximum size of object that can be saved in memcached with memcache.py
1,440,722
<p>I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<a href="http://www.sample.com/mybigfile.exe">http://www.sample.com/mybigfile.exe</a>); instead it must be accessed through code.</p> <p>Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good idea, let me know). Everything seems to work, fine (no errors), but when I try to retrieve the file from memcached I always get None, as if the file wasn't cached. </p> <p>Is there a size limit to what can be saved?</p> <p>Here's the code:</p> <pre><code>def download_demo(): """ Returns the demo file """ KEY = "xyz" TIME = 86400 #24 hours buff = memc.get(KEY) if not buff: file = open(FILENAME, 'r') buff = file.read() memc.set(KEY, buff, TIME) print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre>
20
2009-09-17T19:00:13Z
1,440,765
<p>The maximum data size is 1mb per item</p> <p><a href="http://code.google.com/p/memcached/wiki/FAQ#What_is_the_maximum_data_size_you_can_store?_%281_megabyte%29" rel="nofollow">http://code.google.com/p/memcached/wiki/FAQ#What_is_the_maximum_data_size_you_can_store?_%281_megabyte%29</a></p> <p>Update: This is a 2009 answer. And in that date the info was accurate and the source was official. Now in 2014 memcached can store 128mb instead of 1mb (but the developers didn't bother to update the official FAQ). The only reference someone could find id an obscure page that probably will be dead in one year.</p>
0
2009-09-17T19:06:35Z
[ "python", "memcached" ]
Maximum size of object that can be saved in memcached with memcache.py
1,440,722
<p>I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<a href="http://www.sample.com/mybigfile.exe">http://www.sample.com/mybigfile.exe</a>); instead it must be accessed through code.</p> <p>Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good idea, let me know). Everything seems to work, fine (no errors), but when I try to retrieve the file from memcached I always get None, as if the file wasn't cached. </p> <p>Is there a size limit to what can be saved?</p> <p>Here's the code:</p> <pre><code>def download_demo(): """ Returns the demo file """ KEY = "xyz" TIME = 86400 #24 hours buff = memc.get(KEY) if not buff: file = open(FILENAME, 'r') buff = file.read() memc.set(KEY, buff, TIME) print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre>
20
2009-09-17T19:00:13Z
1,440,773
<p>There are two entries about that in the <a href="http://docs.oracle.com/cd/E17952_01/refman-5.6-en/ha-memcached-faq.html">memcached FAQ</a> :</p> <ul> <li><a href="http://docs.oracle.com/cd/E17952_01/refman-5.6-en/ha-memcached-faq.html#qandaitem-17-6-5-1-2">What is the maximum size of an object you can store in memcached? Is that configurable?</a></li> </ul> <p>The answer to the first one is <em>(quoting, emphasis mine)</em> :</p> <blockquote> <p><strong>The maximum size of a value you can store in memcached is 1 megabyte</strong>. If your data is larger, consider clientside compression or splitting the value up into multiple keys.</p> </blockquote> <p>So I'm guessing your 11MB file is quite too big to fit in one memcached entry.</p> <p>Increasing the size of an object is possible, as per other answers.</p>
30
2009-09-17T19:07:28Z
[ "python", "memcached" ]
Maximum size of object that can be saved in memcached with memcache.py
1,440,722
<p>I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<a href="http://www.sample.com/mybigfile.exe">http://www.sample.com/mybigfile.exe</a>); instead it must be accessed through code.</p> <p>Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good idea, let me know). Everything seems to work, fine (no errors), but when I try to retrieve the file from memcached I always get None, as if the file wasn't cached. </p> <p>Is there a size limit to what can be saved?</p> <p>Here's the code:</p> <pre><code>def download_demo(): """ Returns the demo file """ KEY = "xyz" TIME = 86400 #24 hours buff = memc.get(KEY) if not buff: file = open(FILENAME, 'r') buff = file.read() memc.set(KEY, buff, TIME) print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre>
20
2009-09-17T19:00:13Z
11,730,559
<p>As of memcache 1.4.2, this is a user-configurable parameter:</p> <p><a href="http://code.google.com/p/memcached/wiki/ReleaseNotes142">http://code.google.com/p/memcached/wiki/ReleaseNotes142</a></p> <blockquote> <p>Configurable maximum item size</p> <p>Many people have asked for memcached to be able to store items larger than 1MB, while it's generally recommended that one not do this, it is now supported on the commandline.</p> <p>A few enlightened folk have also asked for memcached to reduce the maximum item size. That is also an option.</p> <p>The new -I parameter allows you to specify the maximum item size at runtime. It supports a unit postfix to allow for natural expression of item size.</p> <p>Examples:</p> <p>memcached -I 128k # Refuse items larger than 128k. </p> <p>memcached -I 10m # Allow objects up to 10MB</p> </blockquote>
27
2012-07-30T22:22:29Z
[ "python", "memcached" ]
Maximum size of object that can be saved in memcached with memcache.py
1,440,722
<p>I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<a href="http://www.sample.com/mybigfile.exe">http://www.sample.com/mybigfile.exe</a>); instead it must be accessed through code.</p> <p>Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good idea, let me know). Everything seems to work, fine (no errors), but when I try to retrieve the file from memcached I always get None, as if the file wasn't cached. </p> <p>Is there a size limit to what can be saved?</p> <p>Here's the code:</p> <pre><code>def download_demo(): """ Returns the demo file """ KEY = "xyz" TIME = 86400 #24 hours buff = memc.get(KEY) if not buff: file = open(FILENAME, 'r') buff = file.read() memc.set(KEY, buff, TIME) print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre>
20
2009-09-17T19:00:13Z
18,182,563
<p>To summarise the necessary steps:</p> <p>1) Update Memcache to version 1.4.2 or later.</p> <p>2) Add the flag -I 15M (or however many megabytes) to your memcache run command.</p> <p>That's either command line, or in Ubuntu, add the line</p> <pre><code>-I 15M </code></pre> <p>to anywhere in /etc/memcached.conf and restart the service.</p> <p>3) Add the necessary flag to the client in memcache.</p> <pre><code>import memcache memc = memcache.Client(['localhost'], server_max_value_length=1024*1024*15) memc.set(KEY, buff, TIME) </code></pre> <p>If you don't have direct access to the memcache client (i.e. working through a framework), then just hack the memcache code directly.</p> <p>On Ubuntu, it's /usr/local/lib/python2.7/dist-packages/memcache.py. Change the line:</p> <p>SERVER_MAX_ITEM_LENGTH = 1024 * 1024 </p> <p>to </p> <p>SERVER_MAX_ITEM_LENGTH = 1024 * 1024 * 15</p> <p>Obviously, you'll need to do this hack over again if you update memcache, but it's a very simple and quick fix.</p>
18
2013-08-12T08:32:25Z
[ "python", "memcached" ]
Maximum size of object that can be saved in memcached with memcache.py
1,440,722
<p>I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<a href="http://www.sample.com/mybigfile.exe">http://www.sample.com/mybigfile.exe</a>); instead it must be accessed through code.</p> <p>Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good idea, let me know). Everything seems to work, fine (no errors), but when I try to retrieve the file from memcached I always get None, as if the file wasn't cached. </p> <p>Is there a size limit to what can be saved?</p> <p>Here's the code:</p> <pre><code>def download_demo(): """ Returns the demo file """ KEY = "xyz" TIME = 86400 #24 hours buff = memc.get(KEY) if not buff: file = open(FILENAME, 'r') buff = file.read() memc.set(KEY, buff, TIME) print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre>
20
2009-09-17T19:00:13Z
30,076,502
<p>Following article explained why it limit max size of a single file to 1M.</p> <p><a href="http://www.mikeperham.com/2009/06/22/slabs-pages-chunks-and-memcached/" rel="nofollow">http://www.mikeperham.com/2009/06/22/slabs-pages-chunks-and-memcached/</a></p> <p>Basicly, there are small pieces of memory pages in memcache, inside which objects reside.</p> <p>And the default page size seems to be 1M, so the max object a page can contain is limited to 1M.</p> <p>Even though you can config it to increase the size, but I think this might have some kind of performance trade-off.</p>
1
2015-05-06T12:16:58Z
[ "python", "memcached" ]
Maximum size of object that can be saved in memcached with memcache.py
1,440,722
<p>I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<a href="http://www.sample.com/mybigfile.exe">http://www.sample.com/mybigfile.exe</a>); instead it must be accessed through code.</p> <p>Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good idea, let me know). Everything seems to work, fine (no errors), but when I try to retrieve the file from memcached I always get None, as if the file wasn't cached. </p> <p>Is there a size limit to what can be saved?</p> <p>Here's the code:</p> <pre><code>def download_demo(): """ Returns the demo file """ KEY = "xyz" TIME = 86400 #24 hours buff = memc.get(KEY) if not buff: file = open(FILENAME, 'r') buff = file.read() memc.set(KEY, buff, TIME) print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre>
20
2009-09-17T19:00:13Z
38,004,732
<p>If you are using python memcached client, please also make sure to increase the limit in client memcache.py file along with the memcached server. </p> <p>~/anaconda/lib/python2.7/site-packages/memcache.py</p> <pre><code>SERVER_MAX_KEY_LENGTH = 250 SERVER_MAX_VALUE_LENGTH = 1024 * 1024 * 15 </code></pre> <p>you can see in memcached console ( telnet localhost 11211 ) </p> <blockquote> <p>stats slabs STAT 48:chunk_size 3677344</p> </blockquote>
0
2016-06-24T02:26:44Z
[ "python", "memcached" ]
Finding the command for a specific PID in Linux from Python
1,440,941
<p>I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.</p> <p>Any help would be great. Thanks.</p>
5
2009-09-17T19:44:09Z
1,440,953
<p>Read up on the <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?ps"><code>ps</code></a> command and parse its output.</p> <pre><code>ps -p [PID] -o cmd </code></pre> <p>should do it</p>
6
2009-09-17T19:46:34Z
[ "python", "linux", "process" ]
Finding the command for a specific PID in Linux from Python
1,440,941
<p>I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.</p> <p>Any help would be great. Thanks.</p>
5
2009-09-17T19:44:09Z
1,440,965
<p>The proc filesystem exports this (and other) information. Look at the /proc/PID/cmd symlink.</p>
0
2009-09-17T19:49:09Z
[ "python", "linux", "process" ]
Finding the command for a specific PID in Linux from Python
1,440,941
<p>I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.</p> <p>Any help would be great. Thanks.</p>
5
2009-09-17T19:44:09Z
1,440,969
<h3>Look in <code>/proc/$PID/cmdline</code></h3>
7
2009-09-17T19:49:53Z
[ "python", "linux", "process" ]
Finding the command for a specific PID in Linux from Python
1,440,941
<p>I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.</p> <p>Any help would be great. Thanks.</p>
5
2009-09-17T19:44:09Z
1,441,057
<p>PLEASE, do not use <code>/proc</code> filesystem in production code. Instead, use well-defined POSIX interfaces, such as glibc calls and standard shell commands! Make the Linux world more standardized, it really needs to!</p> <p>What you need is well achieved by invoking a shell command </p> <pre><code>ps -p &lt;YOUR PID&gt; -o cmd h </code></pre> <p>No parsing is needed!</p> <p>Let alone that reading shell command output from python takes no more effort than reading from a file in <code>/proc</code>. And this makes your program more portable, either!</p>
8
2009-09-17T20:06:02Z
[ "python", "linux", "process" ]
Finding the command for a specific PID in Linux from Python
1,440,941
<p>I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.</p> <p>Any help would be great. Thanks.</p>
5
2009-09-17T19:44:09Z
1,443,544
<p>Look in <code>/proc/$PID/cmdline</code>, and then os.readlink() on <code>/proc/$PID/exe</code>.</p> <p><code>/proc/$PID/cmdline</code> is not necessarily going to be correct, as a program can change its argument vector or it may not contain a full path. Three examples of this from my current process list are:</p> <ul> <li><code>avahi-daemon: chroot helper</code></li> <li><code>qmgr -l -t fifo -u</code></li> <li><code>/usr/sbin/postgrey --pidfile=/var/run/postgrey.pid --daemonize --inet=127.0.0.1:60000 --delay=55</code></li> </ul> <p>That first one is obvious - it's not a valid path or program name. The second is just an executable with no path name. The third looks ok, but that whole command line is actually in <code>argv[0]</code>, with spaces separating the arguments. Normally you should have NUL separated arguments.</p> <p>All this goes to show that <code>/proc/$PID/cmdline</code> (or the ps(1) output) is not reliable.</p> <p>However, nor is <code>/proc/$PID/exe</code>. Usually it is a symlink to the executable that is the main text segment of the process. But sometimes it has " <code>(deleted)</code>" after it if the executable is no longer in the filesystem.</p> <p>Also, the program that is the text segment is not always what you want. For instance, <code>/proc/$PID/exe</code> from that <code>/usr/sbin/postgrey</code> example above is <code>/usr/bin/perl</code>. This will be the case for all interpretted scripts (#!).</p> <p>I settled on parsing <code>/proc/$PID/cmdline</code> - taking the first element of the vector, and then looking for spaces in that, and taking all before the first space. If that was an executable file - I stopped there. Otherwise I did a readlink(2) on <code>/proc/$PID/exe</code> and removed any " <code>(deleted)</code>" strings on the end. That first part will fail if the executable filename actually has spaces in it. There's not much you can do about that.</p> <p>BTW. The argument to use ps(1) instead of <code>/proc/$PID/cmdline</code> does not apply in this case, since you are going to fall back to <code>/proc/$PID/exe</code>. You will be dependent on the <code>/proc</code> filesystem, so you may as well read it with read(2) instead of pipe(2), fork(2), execve(2), readdir(3)..., write(2), read(2). While ps and <code>/proc/$PID/cmdline</code> may be the same from the point of view of lines of python code, there's a whole lot more going on behind the scenes with ps.</p>
5
2009-09-18T09:51:00Z
[ "python", "linux", "process" ]