title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
Tool/library for calculating intervals like "last thursday of the month"
| 614,518
|
<p>I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month".</p>
<p>i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that.</p>
<p>Any suggestions?</p>
| 2
|
2009-03-05T12:11:07Z
| 614,551
|
<p>Well, don't know if such library exists, but <code>date</code> from GNU coreutils has something like that:</p>
<pre><code>$ date -d "last monday"
Mon Mar 2 00:00:00 RST 2009
</code></pre>
| 1
|
2009-03-05T12:21:06Z
|
[
"python",
"datetime",
"date"
] |
Tool/library for calculating intervals like "last thursday of the month"
| 614,518
|
<p>I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month".</p>
<p>i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that.</p>
<p>Any suggestions?</p>
| 2
|
2009-03-05T12:11:07Z
| 614,552
|
<p>I think you can get pretty far using just Python's standard <a href="http://docs.python.org/library/calendar.html#module-calendar" rel="nofollow">calendar</a> module, maybe by adding some "human-friendly" methods on top of those methods. The module gives you iterators for dates, while taking weeks into consideration, and so on.</p>
<p>First I guess you must answer the question "what are some human-friendly ways to talk about dates?", which I guess is more than half the difficulty of this problem.</p>
| 3
|
2009-03-05T12:21:15Z
|
[
"python",
"datetime",
"date"
] |
Tool/library for calculating intervals like "last thursday of the month"
| 614,518
|
<p>I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month".</p>
<p>i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that.</p>
<p>Any suggestions?</p>
| 2
|
2009-03-05T12:11:07Z
| 614,595
|
<p>Use <strong>mxDateTime</strong>. <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/" rel="nofollow">http://www.egenix.com/products/python/mxBase/mxDateTime/</a></p>
| 1
|
2009-03-05T12:32:41Z
|
[
"python",
"datetime",
"date"
] |
Tool/library for calculating intervals like "last thursday of the month"
| 614,518
|
<p>I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month".</p>
<p>i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that.</p>
<p>Any suggestions?</p>
| 2
|
2009-03-05T12:11:07Z
| 614,623
|
<p>If this is for a web app take a look at <a href="http://www.datejs.com/" rel="nofollow">Datejs</a>, it may be easier to use that in your form then just pass it's date object's value to Python.</p>
<p>If you end up writing one yourself the source may be helpful too.</p>
| -1
|
2009-03-05T12:46:27Z
|
[
"python",
"datetime",
"date"
] |
Tool/library for calculating intervals like "last thursday of the month"
| 614,518
|
<p>I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month".</p>
<p>i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that.</p>
<p>Any suggestions?</p>
| 2
|
2009-03-05T12:11:07Z
| 614,662
|
<p>Neither mxDateTime nor Datejs nor that webservice support "last thursday of the month". The OP wants to know all of the last thursdays of the month for, say, a full year.</p>
<p>mxDateTime supports the operations, but the question must be posed in Python code, not as a string.</p>
<p>The best I could figure is <a href="http://code.google.com/p/parsedatetime/" rel="nofollow">parsedatetime</a>, but that doesn't support "last thursday of the month". It does support:</p>
<pre><code>>>> c.parseDateText("last thursday of april 2001")
(2001, 4, 20, 13, 55, 58, 3, 64, 0)
>>> c.parseDateText("last thursday of may 2001")
(2001, 5, 20, 13, 56, 3, 3, 64, 0)
>>> c.parseDateText("last thursday of may 2010")
(2010, 5, 20, 13, 56, 7, 3, 64, 0)
>>>
</code></pre>
<p>(Note that neither DateJS nor that web service support this syntax.)</p>
<p><strong>EDIT</strong>: Umm, okay, but while the year and the month are right, the day isn't. The last thursday of april 2001 was the 27th. I think you're going to have to roll your own solution here.</p>
<p>It does not support:</p>
<pre><code>>>> c.parseDateText("last thursday of 2010")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "parsedatetime/parsedatetime.py", line 411, in parseDateText
mth = self.ptc.MonthOffsets[mth]
KeyError
>>>
</code></pre>
<p>So one possibility is text substitution: normalize the string to lowercase, single spaces, etc. then do a string substitution of "the month" for each of the months you're interested in. You'll likely have to tweak any solution you find. For example, in some <a href="http://web.archive.org/web/20050309211440/manatee.mojam.com/~skip/python/dates.py" rel="nofollow">old code of Skip Montanaro</a> which he wrote for an online music calendering system:</p>
<pre><code> # someone keeps submitting dates with september spelled wrong...
'septmber':9,
</code></pre>
<p>Or you write your own parser on top of mxDateTime, using all of the above links as references.</p>
| 7
|
2009-03-05T13:03:01Z
|
[
"python",
"datetime",
"date"
] |
Tool/library for calculating intervals like "last thursday of the month"
| 614,518
|
<p>I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month".</p>
<p>i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that.</p>
<p>Any suggestions?</p>
| 2
|
2009-03-05T12:11:07Z
| 614,667
|
<p>The algorithms aren't hard. They're provided in the following book, which is worth every penny.</p>
<p><a href="http://emr.cs.iit.edu/home/reingold/calendar-book/third-edition/" rel="nofollow">http://emr.cs.iit.edu/home/reingold/calendar-book/third-edition/</a></p>
<p>The general approach is to find first days of a required month. You can then subtract one day to find the last day of a required month. Then you compute an offset for day of week you want relative to the day of the week you found.</p>
<p>Assume you have a <code>datetime.dat</code>e, <code>d</code>. You can work out the end of the month by computing the start of the next month minus one day.</p>
<pre><code>monIx= d.year*12 + (d.month-1) + 1
endOfMonth= datetime.date( monIx//12, monIx%12+1, 1 ) - datetime.timedelta( days=1 )
</code></pre>
<p>At this point, you're looking for an offset to the required day of the week. In this case, the desired day of the week is Thursday, which is <code>3</code>.</p>
<pre><code>dayOffset = ((3 - endOfMonth.weekday()) -7 ) % -7
lastDay = endOfMonth + datetime.timedelta( days=dayOffset )
</code></pre>
<p>The general approach of getting the day-of-week offset requires a little bit of thinking, but there are only a few combinations of cases to experiment with.</p>
| 3
|
2009-03-05T13:03:52Z
|
[
"python",
"datetime",
"date"
] |
Tool/library for calculating intervals like "last thursday of the month"
| 614,518
|
<p>I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month".</p>
<p>i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that.</p>
<p>Any suggestions?</p>
| 2
|
2009-03-05T12:11:07Z
| 615,731
|
<p>I'm not entirely sure, but you might look at the Python <a href="http://labix.org/python-dateutil" rel="nofollow">DateUtil</a> module.</p>
| 2
|
2009-03-05T17:20:41Z
|
[
"python",
"datetime",
"date"
] |
Big images with cairo
| 614,949
|
<p>I have to render a very big image (>50.000² pixel) with cairo. To do this without running out of memory I render parts of the image (<1.000² pixel) one after another and merge them together later.</p>
<ol>
<li>Create 1000x1000 Surface</li>
<li>Translate to position of the current part</li>
<li>Draw image (calling the drawing instructions using pycairo)</li>
<li>Render/Save image to file (cairo_surface_write_to_png)</li>
<li>Repeat with next part</li>
</ol>
<p>Because cairos clipping algorithms are faster than my own, step three draws the whole image, even if only a part of it is visible. Most of the CPU is used in Step 3 (by python). Most of the memory is used in Step 4 (by cairo).</p>
<p>Is there a way to speed things up? Something like this?</p>
<ol>
<li>Create 1000x1000 Surface</li>
<li>Draw image</li>
<li>Move everything to position of the current part</li>
<li>Render/Save image to file</li>
<li>Repeat 3 with next part</li>
</ol>
<p>or</p>
<ol>
<li>Create 50000x50000 Surface</li>
<li>Draw image</li>
<li>Render/Save only the current part of the image to file</li>
<li>Repeat 3 with next part</li>
</ol>
| 5
|
2009-03-05T14:19:46Z
| 615,003
|
<p>First of all, using C or Vala instead of Python will probably speed things up.</p>
<p>As for memory usage, I would try writing to my own stream, rather than a file (see <a href="http://cairographics.org/manual/cairo-png-functions.html#cairo-surface-write-to-png-stream" rel="nofollow">write_to_png_stream</a>). This <em>could</em> allow you to (I didn't try this) control memory usage, assuming Cairo doesn't call your function only once after everything's done.</p>
| 2
|
2009-03-05T14:30:03Z
|
[
"python",
"cairo"
] |
How to detect errors from compileall.compile_dir?
| 615,632
|
<p>How do I detect an error when compiling a directory of python files using compile_dir?</p>
<p>Currently I get something on stderr, but no way to detect it in my app.
py_compile.compile() takes a 'doraise' argument, but nothing here.</p>
<p>Or is there a better way to do this from a python script?</p>
<p>Edit:</p>
<p>I fixed it with os.walk and calling py_compile.compile for each file. But the question remains.</p>
| 0
|
2009-03-05T16:48:51Z
| 615,682
|
<p>works fine for me. Could it be that you're not setting <code>doraise</code> to <code>True</code> somehow?</p>
| 0
|
2009-03-05T17:02:45Z
|
[
"python"
] |
How to detect errors from compileall.compile_dir?
| 615,632
|
<p>How do I detect an error when compiling a directory of python files using compile_dir?</p>
<p>Currently I get something on stderr, but no way to detect it in my app.
py_compile.compile() takes a 'doraise' argument, but nothing here.</p>
<p>Or is there a better way to do this from a python script?</p>
<p>Edit:</p>
<p>I fixed it with os.walk and calling py_compile.compile for each file. But the question remains.</p>
| 0
|
2009-03-05T16:48:51Z
| 616,423
|
<p>I don't see a better way. The code is designed to support the command-line program, and the API doesn't seem fully meant to be used as a library.</p>
<p>If you really had to use the compileall then you could fake it out with this hack, which notices that "quiet" is tested for boolean-ness while in the caught exception handler. I can override that with <strong>nonzero</strong>, check the exception state to see if it came from py_compile (quiet is tested in other contexts) and do something with that information:</p>
<pre><code>import sys
import py_compile
import compileall
class ReportProblem:
def __nonzero__(self):
type, value, traceback = sys.exc_info()
if type is not None and issubclass(type, py_compile.PyCompileError):
print "Problem with", repr(value)
raise type, value, traceback
return 1
report_problem = ReportProblem()
compileall.compile_dir(".", quiet=report_problem)
</code></pre>
<p>Förresten, det finns GothPy på första måndagen varje månad, om du skulle ta sällskap med andra Python-användare i Gbg.</p>
| 2
|
2009-03-05T20:10:23Z
|
[
"python"
] |
Django labels and translations - Model Design
| 616,187
|
<p>Lets say I have the following Django model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
</code></pre>
<p>Each label has an ID number, the label text, and an abbreviation. Now, I want to have these labels translatable into other languages. What is the best way to do this?</p>
<p>As I see it, I have a few options:</p>
<p>1: Add the translations as fields on the model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label_english = models.CharField(max_length=255)
abbreviation_english = models.CharField(max_length=255)
label_spanish = models.CharField(max_length=255)
abbreviation_spanish = models.CharField(max_length=255)
</code></pre>
<p>This is obviously not ideal - adding languages requires editing the model, the correct field name depends on the language.</p>
<p>2: Add the language as a foreign key:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
</code></pre>
<p>This is much better, now I can ask for all labels with a certain language, and throw them into a dict:</p>
<pre><code>labels = StandardLabel.objects.filter(language=1)
labels = dict((x.pk, x) for x in labels)
</code></pre>
<p>But the problem here is that the labels dict is meant to be a lookup table, like so:</p>
<pre><code>x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3)
thelabel = labels[x.labelIdNumber].label
</code></pre>
<p>Which doesn't work if there is a row per label, possibly with multiple languages for a single label. To solve that one, I need another field:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
group_id = models.IntegerField(db_index=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
class Meta:
unique_together=(("group_id", "language"),)
#and I need to group them differently:
labels = StandardLabel.objects.filter(language=1)
labels = dict((x.group_id, x) for x in labels)
</code></pre>
<p>3: Throw label text out into a new model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
text = models.ManyToManyField('LabelText')
class LabelText(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
labels = StandardLabel.objects.filter(text__language=1)
labels = dict((x.pk, x) for x in labels)
</code></pre>
<p>But then this doesn't work, and causes a database hit every time I reference the label's text:</p>
<pre><code>x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3)
thelabel = labels[x.labelIdNumber].text.get(language=1)
</code></pre>
<p>I've implemented option 2, but I find it very ugly - i don't like the group_id field, and I can't think of anything better to name it. In addition, StandardLabel as i'm using it is an abstract model, which I subclass to get different label sets for different fields.</p>
<p>I suppose that if option 3 /didn't/ hit the database, it's what I'd choose. I believe the real problem is that the filter <code>text__language=1</code> doesn't cache the <code>LabelText</code> instances, and so the DB is hit when I <code>text.get(language=1)</code></p>
<p>What are your thoughts on this? Can anyone recommend a cleaner solution?</p>
<p><strong>Edit</strong>: Just to make it clear, these are not form labels, so the Django Internationalization system doesn't help.</p>
| 2
|
2009-03-05T19:09:49Z
| 616,317
|
<p>I would keep things as simple as possible. The lookup will be faster and the code cleaner with something like this:</p>
<pre><code>class StandardLabel(models.Model):
abbreviation = models.CharField(max_length=255)
label = models.CharField(max_length=255)
language = models.CharField(max_length=2)
# or, alternately, specify language as a foreign key:
#language = models.ForeignKey(Language)
class Meta:
unique_together = ('language', 'abbreviation')
</code></pre>
<p>Then query based on abbreviation and language:</p>
<pre><code>l = StandardLabel.objects.get(language='en', abbreviation='suite')
</code></pre>
| 2
|
2009-03-05T19:38:25Z
|
[
"python",
"django",
"django-models",
"localization"
] |
Django labels and translations - Model Design
| 616,187
|
<p>Lets say I have the following Django model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
</code></pre>
<p>Each label has an ID number, the label text, and an abbreviation. Now, I want to have these labels translatable into other languages. What is the best way to do this?</p>
<p>As I see it, I have a few options:</p>
<p>1: Add the translations as fields on the model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label_english = models.CharField(max_length=255)
abbreviation_english = models.CharField(max_length=255)
label_spanish = models.CharField(max_length=255)
abbreviation_spanish = models.CharField(max_length=255)
</code></pre>
<p>This is obviously not ideal - adding languages requires editing the model, the correct field name depends on the language.</p>
<p>2: Add the language as a foreign key:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
</code></pre>
<p>This is much better, now I can ask for all labels with a certain language, and throw them into a dict:</p>
<pre><code>labels = StandardLabel.objects.filter(language=1)
labels = dict((x.pk, x) for x in labels)
</code></pre>
<p>But the problem here is that the labels dict is meant to be a lookup table, like so:</p>
<pre><code>x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3)
thelabel = labels[x.labelIdNumber].label
</code></pre>
<p>Which doesn't work if there is a row per label, possibly with multiple languages for a single label. To solve that one, I need another field:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
group_id = models.IntegerField(db_index=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
class Meta:
unique_together=(("group_id", "language"),)
#and I need to group them differently:
labels = StandardLabel.objects.filter(language=1)
labels = dict((x.group_id, x) for x in labels)
</code></pre>
<p>3: Throw label text out into a new model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
text = models.ManyToManyField('LabelText')
class LabelText(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
labels = StandardLabel.objects.filter(text__language=1)
labels = dict((x.pk, x) for x in labels)
</code></pre>
<p>But then this doesn't work, and causes a database hit every time I reference the label's text:</p>
<pre><code>x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3)
thelabel = labels[x.labelIdNumber].text.get(language=1)
</code></pre>
<p>I've implemented option 2, but I find it very ugly - i don't like the group_id field, and I can't think of anything better to name it. In addition, StandardLabel as i'm using it is an abstract model, which I subclass to get different label sets for different fields.</p>
<p>I suppose that if option 3 /didn't/ hit the database, it's what I'd choose. I believe the real problem is that the filter <code>text__language=1</code> doesn't cache the <code>LabelText</code> instances, and so the DB is hit when I <code>text.get(language=1)</code></p>
<p>What are your thoughts on this? Can anyone recommend a cleaner solution?</p>
<p><strong>Edit</strong>: Just to make it clear, these are not form labels, so the Django Internationalization system doesn't help.</p>
| 2
|
2009-03-05T19:09:49Z
| 616,361
|
<p>Another option you might consider, depending on your application design of course, is to make use of Django's internationalization features. The approach they use is quite common to the approach found in desktop software. </p>
<p>I see the question was edited to add a reference to Django internationalization, so you do know about it, but the intl features in Django apply to much more than just Forms; it touchs quite a lot, and needs only a few tweaks to your app design.</p>
<p>Their docs are here: <a href="http://docs.djangoproject.com/en/dev/topics/i18n/#topics-i18n" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/i18n/#topics-i18n</a></p>
<p>The idea is that you define your model as if there was only one language. In other words, make no reference to language at all, and put only, say, English in the model.</p>
<p>So:</p>
<pre><code>class StandardLabel(models.Model):
abbreviation = models.CharField(max_length=255)
label = models.CharField(max_length=255)
</code></pre>
<p>I know this looks like you've totally thrown out the language issue, but you've actually just relocated it. Instead of the language being in your data model, you've pushed it to the view.</p>
<p>The django internationalization features allow you to generate text translation files, and provides a number of features for pulling text out of the system into files. This is actually quite useful because it allows you to send plain files to your translator, which makes their job easier. Adding a new language is as easy as getting the file translated into a new language.</p>
<p>The translation files define the label from the database, and a translation for that language. There are functions for handling the language translation dynamically at run time for models, admin views, javascript, and templates.</p>
<p>For example, in a template, you might do something like:</p>
<pre><code><b>Hello {% trans "Here's the string in english" %}</b>
</code></pre>
<p>Or in view code, you could do:</p>
<pre><code># See docs on setting language, or getting Django to auto-set language
s = StandardLabel.objects.get(id=1)
lang_specific_label = ugettext(s.label)
</code></pre>
<p>Of course, if your app is all about entering new languages <code>on the fly</code>, then this approach may not work for you. Still, have a look at the Internationalization project as you may either be able to use it "as is", or be inspired to a django-appropriate solution that does work for your domain.</p>
| 3
|
2009-03-05T19:51:20Z
|
[
"python",
"django",
"django-models",
"localization"
] |
Django labels and translations - Model Design
| 616,187
|
<p>Lets say I have the following Django model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
</code></pre>
<p>Each label has an ID number, the label text, and an abbreviation. Now, I want to have these labels translatable into other languages. What is the best way to do this?</p>
<p>As I see it, I have a few options:</p>
<p>1: Add the translations as fields on the model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label_english = models.CharField(max_length=255)
abbreviation_english = models.CharField(max_length=255)
label_spanish = models.CharField(max_length=255)
abbreviation_spanish = models.CharField(max_length=255)
</code></pre>
<p>This is obviously not ideal - adding languages requires editing the model, the correct field name depends on the language.</p>
<p>2: Add the language as a foreign key:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
</code></pre>
<p>This is much better, now I can ask for all labels with a certain language, and throw them into a dict:</p>
<pre><code>labels = StandardLabel.objects.filter(language=1)
labels = dict((x.pk, x) for x in labels)
</code></pre>
<p>But the problem here is that the labels dict is meant to be a lookup table, like so:</p>
<pre><code>x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3)
thelabel = labels[x.labelIdNumber].label
</code></pre>
<p>Which doesn't work if there is a row per label, possibly with multiple languages for a single label. To solve that one, I need another field:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
group_id = models.IntegerField(db_index=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
class Meta:
unique_together=(("group_id", "language"),)
#and I need to group them differently:
labels = StandardLabel.objects.filter(language=1)
labels = dict((x.group_id, x) for x in labels)
</code></pre>
<p>3: Throw label text out into a new model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
text = models.ManyToManyField('LabelText')
class LabelText(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
labels = StandardLabel.objects.filter(text__language=1)
labels = dict((x.pk, x) for x in labels)
</code></pre>
<p>But then this doesn't work, and causes a database hit every time I reference the label's text:</p>
<pre><code>x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3)
thelabel = labels[x.labelIdNumber].text.get(language=1)
</code></pre>
<p>I've implemented option 2, but I find it very ugly - i don't like the group_id field, and I can't think of anything better to name it. In addition, StandardLabel as i'm using it is an abstract model, which I subclass to get different label sets for different fields.</p>
<p>I suppose that if option 3 /didn't/ hit the database, it's what I'd choose. I believe the real problem is that the filter <code>text__language=1</code> doesn't cache the <code>LabelText</code> instances, and so the DB is hit when I <code>text.get(language=1)</code></p>
<p>What are your thoughts on this? Can anyone recommend a cleaner solution?</p>
<p><strong>Edit</strong>: Just to make it clear, these are not form labels, so the Django Internationalization system doesn't help.</p>
| 2
|
2009-03-05T19:09:49Z
| 616,702
|
<p>Although I would go with <a href="http://stackoverflow.com/questions/616187/django-labels-and-translations-model-design/616317#616317">Daniel's solution</a>, here is an alternative from what I've understood from your comments:</p>
<p>You can use an <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#xmlfield" rel="nofollow">XMLField</a> or JSONField to store your language/translation pairs. This would allow your objects referencing your labels to use a single <code>id</code> for all translations. And then you can have a custom manager method to call a specific translation:</p>
<pre><code>Label.objects.get_by_language('ru', **kwargs)
</code></pre>
<p>Or a slightly cleaner and slightly more complicated solution that plays well with <code>admin</code> would be to denormalize the XMLField to another model with many-to-one relationship to the <code>Label</code> model. Same API, but instead of parsing XML it could query related models.</p>
<p>For both suggestions there's a single object where users of a label will point to.</p>
<p>I wouldn't worry about the queries too much, Django caches queries and your DBMS would probably have superior caching there as well.</p>
| 0
|
2009-03-05T21:30:00Z
|
[
"python",
"django",
"django-models",
"localization"
] |
Django labels and translations - Model Design
| 616,187
|
<p>Lets say I have the following Django model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
</code></pre>
<p>Each label has an ID number, the label text, and an abbreviation. Now, I want to have these labels translatable into other languages. What is the best way to do this?</p>
<p>As I see it, I have a few options:</p>
<p>1: Add the translations as fields on the model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label_english = models.CharField(max_length=255)
abbreviation_english = models.CharField(max_length=255)
label_spanish = models.CharField(max_length=255)
abbreviation_spanish = models.CharField(max_length=255)
</code></pre>
<p>This is obviously not ideal - adding languages requires editing the model, the correct field name depends on the language.</p>
<p>2: Add the language as a foreign key:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
</code></pre>
<p>This is much better, now I can ask for all labels with a certain language, and throw them into a dict:</p>
<pre><code>labels = StandardLabel.objects.filter(language=1)
labels = dict((x.pk, x) for x in labels)
</code></pre>
<p>But the problem here is that the labels dict is meant to be a lookup table, like so:</p>
<pre><code>x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3)
thelabel = labels[x.labelIdNumber].label
</code></pre>
<p>Which doesn't work if there is a row per label, possibly with multiple languages for a single label. To solve that one, I need another field:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
group_id = models.IntegerField(db_index=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
class Meta:
unique_together=(("group_id", "language"),)
#and I need to group them differently:
labels = StandardLabel.objects.filter(language=1)
labels = dict((x.group_id, x) for x in labels)
</code></pre>
<p>3: Throw label text out into a new model:</p>
<pre><code>class StandardLabel(models.Model):
id = models.AutoField(primary_key=True)
text = models.ManyToManyField('LabelText')
class LabelText(models.Model):
id = models.AutoField(primary_key=True)
label = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255)
language = models.ForeignKey('languages.Language')
labels = StandardLabel.objects.filter(text__language=1)
labels = dict((x.pk, x) for x in labels)
</code></pre>
<p>But then this doesn't work, and causes a database hit every time I reference the label's text:</p>
<pre><code>x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3)
thelabel = labels[x.labelIdNumber].text.get(language=1)
</code></pre>
<p>I've implemented option 2, but I find it very ugly - i don't like the group_id field, and I can't think of anything better to name it. In addition, StandardLabel as i'm using it is an abstract model, which I subclass to get different label sets for different fields.</p>
<p>I suppose that if option 3 /didn't/ hit the database, it's what I'd choose. I believe the real problem is that the filter <code>text__language=1</code> doesn't cache the <code>LabelText</code> instances, and so the DB is hit when I <code>text.get(language=1)</code></p>
<p>What are your thoughts on this? Can anyone recommend a cleaner solution?</p>
<p><strong>Edit</strong>: Just to make it clear, these are not form labels, so the Django Internationalization system doesn't help.</p>
| 2
|
2009-03-05T19:09:49Z
| 620,095
|
<p>I'd much prefer to add a field per language than a new model instance per language. It does require schema alteration when you add a new language, but that isn't hard, and how often do you expect to add languages? In the meantime, it'll give you better database performance (no added joins or indexes) and you don't have to muck up your query logic with translation stuff; keep it all in the templates where it belongs.</p>
<p>Even better, use a reusable app like <a href="http://code.google.com/p/django-transmeta/" rel="nofollow">django-transmeta</a> or <a href="http://code.google.com/p/django-modeltranslation/" rel="nofollow">django-modeltranslation</a> that makes this stupid simple and almost completely transparent.</p>
| 1
|
2009-03-06T19:26:19Z
|
[
"python",
"django",
"django-models",
"localization"
] |
Is it possible to remove recursion from this function?
| 616,416
|
<p>I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY_Go function.</p>
<pre><code>def XinY_Go(x,y,index,slots):
if (y - index) == 1:
slots[index] = x
print slots
slots[index] = 0
return
for i in range(x+1):
slots[index] = x-i
XinY_Go(x-(x-i), y, index + 1, slots)
def XinY(x,y):
return XinY_Go(x,y,0,[0] * y)
</code></pre>
<p>The function is calculating the number of ways to put X marbles in Y slots. Here is some sample output:</p>
<pre>
>>> xy.XinY(1,2)
[1, 0]
[0, 1]
>>> xy.XinY(2,3)
[2, 0, 0]
[1, 1, 0]
[1, 0, 1]
[0, 2, 0]
[0, 1, 1]
[0, 0, 2]
</pre>
| 3
|
2009-03-05T20:09:17Z
| 616,432
|
<p>Everything we think of as recursion can also be thought of as a stack-based problem, where the recursive function just uses the program's call stack rather than creating a separate stack. That means any recursive function can be re-written using a stack instead. </p>
<p>I don't know python well enough to give you an implementation, but that should point you in the right direction. But in a nutshell, push the initial arguments for the function onto the stack and add a loop that runs as long as the size of the stack is greater than zero. Pop once per loop iteration, push every time the function currently calls itself. </p>
| 21
|
2009-03-05T20:12:19Z
|
[
"python",
"recursion"
] |
Is it possible to remove recursion from this function?
| 616,416
|
<p>I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY_Go function.</p>
<pre><code>def XinY_Go(x,y,index,slots):
if (y - index) == 1:
slots[index] = x
print slots
slots[index] = 0
return
for i in range(x+1):
slots[index] = x-i
XinY_Go(x-(x-i), y, index + 1, slots)
def XinY(x,y):
return XinY_Go(x,y,0,[0] * y)
</code></pre>
<p>The function is calculating the number of ways to put X marbles in Y slots. Here is some sample output:</p>
<pre>
>>> xy.XinY(1,2)
[1, 0]
[0, 1]
>>> xy.XinY(2,3)
[2, 0, 0]
[1, 1, 0]
[1, 0, 1]
[0, 2, 0]
[0, 1, 1]
[0, 0, 2]
</pre>
| 3
|
2009-03-05T20:09:17Z
| 616,455
|
<p>Look at this code for creating all permutations, I guess I'd be relatively simple to implement something similar for your problem.</p>
<p><a href="http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python">How to generate all permutations of a list in python?</a></p>
| 2
|
2009-03-05T20:20:19Z
|
[
"python",
"recursion"
] |
Is it possible to remove recursion from this function?
| 616,416
|
<p>I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY_Go function.</p>
<pre><code>def XinY_Go(x,y,index,slots):
if (y - index) == 1:
slots[index] = x
print slots
slots[index] = 0
return
for i in range(x+1):
slots[index] = x-i
XinY_Go(x-(x-i), y, index + 1, slots)
def XinY(x,y):
return XinY_Go(x,y,0,[0] * y)
</code></pre>
<p>The function is calculating the number of ways to put X marbles in Y slots. Here is some sample output:</p>
<pre>
>>> xy.XinY(1,2)
[1, 0]
[0, 1]
>>> xy.XinY(2,3)
[2, 0, 0]
[1, 1, 0]
[1, 0, 1]
[0, 2, 0]
[0, 1, 1]
[0, 0, 2]
</pre>
| 3
|
2009-03-05T20:09:17Z
| 616,666
|
<p>A naive implementation of <a href="http://stackoverflow.com/questions/616416/is-it-possible-to-remove-recursion-from-this-function/616432#616432">@Joel Coehoorn's suggestion</a> follows:</p>
<pre><code>def XinY_Stack(x, y):
stack = [(x, 0, [0]*y)]
while stack:
x, index, slots = stack.pop()
if (y - index) == 1:
slots[index] = x
print slots
slots[index] = 0
else:
for i in range(x + 1):
slots[index] = x-i
stack.append((i, index + 1, slots[:]))
</code></pre>
<p>Example:</p>
<pre><code>>>> XinY_Stack(2, 3)
[0, 0, 2]
[0, 1, 1]
[0, 2, 0]
[1, 0, 1]
[1, 1, 0]
[2, 0, 0]
</code></pre>
<h3>Based on <a href="http://docs.python.org/library/itertools.html#itertools.product"><code>itertools.product</code></a></h3>
<pre><code>def XinY_Product(nmarbles, nslots):
return (slots
for slots in product(xrange(nmarbles + 1), repeat=nslots)
if sum(slots) == nmarbles)
</code></pre>
<h3>Based on nested loops</h3>
<pre><code>def XinY_Iter(nmarbles, nslots):
assert 0 < nslots < 22 # 22 -> too many statically nested blocks
if nslots == 1: return iter([nmarbles])
# generate code for iter solution
TAB = " "
loopvars = []
stmt = ["def f(n):\n"]
for i in range(nslots - 1):
var = "m%d" % i
stmt += [TAB * (i + 1), "for %s in xrange(n - (%s)):\n"
% (var, '+'.join(loopvars) or 0)]
loopvars.append(var)
stmt += [TAB * (i + 2), "yield ", ','.join(loopvars),
', n - 1 - (', '+'.join(loopvars), ')\n']
print ''.join(stmt)
# exec the code within empty namespace
ns = {}
exec(''.join(stmt), ns, ns)
return ns['f'](nmarbles + 1)
</code></pre>
<p>Example:</p>
<pre><code>>>> list(XinY_Product(2, 3))
[(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)]
>>> list(XinY_Iter(2, 3))
def f(n):
for m0 in xrange(n - (0)):
for m1 in xrange(n - (m0)):
yield m0,m1, n - 1 - (m0+m1)
[(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)]
</code></pre>
| 14
|
2009-03-05T21:19:22Z
|
[
"python",
"recursion"
] |
Python in tcsh
| 616,440
|
<p>I don't have much experience with tcsh, but I'm interested in learning. I've been having issues getting Python to see PYTHONPATH. I can echo $PYTHONPATH, and it is correct, but when I start up Python, my paths do not show up in sys.path. Any ideas?</p>
<p>EDIT:</p>
<pre><code>[dmcdonal@tg-steele ~]$ echo $PYTHONPATH
/home/ba01/u116/dmcdonal/PyCogent-v1.1
>>> from sys import path
>>> from os import environ
>>> path
['', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/setuptools-0.6c8-py2.5.egg', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/FiPy-2.0-py2.5.egg', '/apps/steele/Python-2.5.2', '/apps/steele/Python-2.5.2/lib/python25.zip', '/apps/steele/Python-2.5.2/lib/python2.5', '/apps/steele/Python-2.5.2/lib/python2.5/plat-linux2', '/apps/steele/Python-2.5.2/lib/python2.5/lib-tk', '/apps/steele/Python-2.5.2/lib/python2.5/lib-dynload', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/Numeric']
>>> environ['PYTHONPATH']
'/apps/steele/Python-2.5.2'
</code></pre>
| 5
|
2009-03-05T20:16:30Z
| 616,476
|
<p>Make sure that you're not starting python with the <code>-E</code> option (which is: ignore environment variables). If you start python via a shell script or some other app, just double check it doesn't add anything.</p>
<p>Since the list of sys.path is long, it can be hard to miss your paths. PYTHONPATH stuff normally gets added to about the middle of the list, after all the library paths. Any chance your paths are there, just buried in the middle?</p>
| 1
|
2009-03-05T20:26:27Z
|
[
"python",
"tcsh"
] |
Python in tcsh
| 616,440
|
<p>I don't have much experience with tcsh, but I'm interested in learning. I've been having issues getting Python to see PYTHONPATH. I can echo $PYTHONPATH, and it is correct, but when I start up Python, my paths do not show up in sys.path. Any ideas?</p>
<p>EDIT:</p>
<pre><code>[dmcdonal@tg-steele ~]$ echo $PYTHONPATH
/home/ba01/u116/dmcdonal/PyCogent-v1.1
>>> from sys import path
>>> from os import environ
>>> path
['', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/setuptools-0.6c8-py2.5.egg', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/FiPy-2.0-py2.5.egg', '/apps/steele/Python-2.5.2', '/apps/steele/Python-2.5.2/lib/python25.zip', '/apps/steele/Python-2.5.2/lib/python2.5', '/apps/steele/Python-2.5.2/lib/python2.5/plat-linux2', '/apps/steele/Python-2.5.2/lib/python2.5/lib-tk', '/apps/steele/Python-2.5.2/lib/python2.5/lib-dynload', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/Numeric']
>>> environ['PYTHONPATH']
'/apps/steele/Python-2.5.2'
</code></pre>
| 5
|
2009-03-05T20:16:30Z
| 616,530
|
<p>Check:</p>
<ol>
<li>PYTHONPATH is in os.environ,</li>
<li>and set to the correct value of a colon separated list of paths.</li>
</ol>
<p>If it is, and you can confirm that your paths are not in sys.path, you have found a bug.</p>
<p>If it is not in os.environ, your environment is not passing through to Python (probably another bug).</p>
<p>Of course, show us the actual code/exports, and someone will tell you pretty quickly.</p>
| 0
|
2009-03-05T20:43:58Z
|
[
"python",
"tcsh"
] |
Python in tcsh
| 616,440
|
<p>I don't have much experience with tcsh, but I'm interested in learning. I've been having issues getting Python to see PYTHONPATH. I can echo $PYTHONPATH, and it is correct, but when I start up Python, my paths do not show up in sys.path. Any ideas?</p>
<p>EDIT:</p>
<pre><code>[dmcdonal@tg-steele ~]$ echo $PYTHONPATH
/home/ba01/u116/dmcdonal/PyCogent-v1.1
>>> from sys import path
>>> from os import environ
>>> path
['', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/setuptools-0.6c8-py2.5.egg', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/FiPy-2.0-py2.5.egg', '/apps/steele/Python-2.5.2', '/apps/steele/Python-2.5.2/lib/python25.zip', '/apps/steele/Python-2.5.2/lib/python2.5', '/apps/steele/Python-2.5.2/lib/python2.5/plat-linux2', '/apps/steele/Python-2.5.2/lib/python2.5/lib-tk', '/apps/steele/Python-2.5.2/lib/python2.5/lib-dynload', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/Numeric']
>>> environ['PYTHONPATH']
'/apps/steele/Python-2.5.2'
</code></pre>
| 5
|
2009-03-05T20:16:30Z
| 616,558
|
<p>How are you setting PYTHONPATH? You might be confusing tcsh's set vs. setenv. Use "set" to set what tcsh calls <em>shell variables</em> and use "setenv" to set <em>environment variables</em>. So, you need to use setenv in order for Python to see it. For example:</p>
<pre><code>$ set FOO='bar'
$ echo $FOO
bar
$ python -c 'import os; print os.getenv("FOO")'
None
$ setenv BAR 'wiz'
$ echo $BAR
wiz
$ python -c 'import os; print os.getenv("BAR")'
wiz
</code></pre>
<p>There is some more information available in <a href="http://wings.buffalo.edu/computing/Documentation/unix/tcsh.html">the variables section of the tcsh documentation</a>.</p>
| 9
|
2009-03-05T20:54:26Z
|
[
"python",
"tcsh"
] |
Python in tcsh
| 616,440
|
<p>I don't have much experience with tcsh, but I'm interested in learning. I've been having issues getting Python to see PYTHONPATH. I can echo $PYTHONPATH, and it is correct, but when I start up Python, my paths do not show up in sys.path. Any ideas?</p>
<p>EDIT:</p>
<pre><code>[dmcdonal@tg-steele ~]$ echo $PYTHONPATH
/home/ba01/u116/dmcdonal/PyCogent-v1.1
>>> from sys import path
>>> from os import environ
>>> path
['', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/setuptools-0.6c8-py2.5.egg', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/FiPy-2.0-py2.5.egg', '/apps/steele/Python-2.5.2', '/apps/steele/Python-2.5.2/lib/python25.zip', '/apps/steele/Python-2.5.2/lib/python2.5', '/apps/steele/Python-2.5.2/lib/python2.5/plat-linux2', '/apps/steele/Python-2.5.2/lib/python2.5/lib-tk', '/apps/steele/Python-2.5.2/lib/python2.5/lib-dynload', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/Numeric']
>>> environ['PYTHONPATH']
'/apps/steele/Python-2.5.2'
</code></pre>
| 5
|
2009-03-05T20:16:30Z
| 4,744,590
|
<p>I also have the same issue even I set environment <code>PYTHONPATH</code> correctly in <code>.cshrc</code> when I used Python <code>2.5.1</code>, when I switch the to Python <code>2.6.2</code>, It works fine. Looks like it is a python bug.</p>
| 0
|
2011-01-20T07:45:11Z
|
[
"python",
"tcsh"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 616,672
|
<p><strong>The <code>print</code> statement will call the <code>write()</code> method of any object you assign to sys.stdout.</strong> </p>
<p>I would spin up a small class to write to two places at once...</p>
<pre><code>import sys
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open("log.dat", "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
sys.stdout = Logger()
</code></pre>
<p><strong>Now the <code>print</code> statement will both echo to the screen and append to your log file:</strong></p>
<pre><code># prints "1 2" to <stdout> AND log.dat
print "%d %d" % (1,2)
</code></pre>
<p>This is obviously quick-and-dirty. Some notes:</p>
<ul>
<li>You probably ought to parametize the log filename.</li>
<li>You should probably revert sys.stdout to <code><stdout></code> if you
won't be logging for the duration of the program.</li>
<li>You may want the ability to write to multiple log files at once, or handle different log levels, etc.</li>
</ul>
<p>These are all straightforward enough that I'm comfortable leaving them as exercises for the reader. The key insight here is that <code>print</code> just calls a "file-like object" that's assigned to <code>sys.stdout</code>.</p>
| 57
|
2009-03-05T21:21:21Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 616,686
|
<p>I had this same issue before and found this snippet very useful:</p>
<pre><code>class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
</code></pre>
<p>from: <a href="http://mail.python.org/pipermail/python-list/2007-May/438106.html">http://mail.python.org/pipermail/python-list/2007-May/438106.html</a></p>
| 102
|
2009-03-05T21:24:48Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 616,709
|
<p>What you really want is <code>logging</code> module from standard library. Create a logger and attach two handlers, one would be writing to a file and the other to stdout or stderr.</p>
<p>See <a href="http://docs.python.org/library/logging.html#logging-to-multiple-destinations">Logging to multiple destinations</a> for details</p>
| 52
|
2009-03-05T21:31:47Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 648,322
|
<p>(Ah, just re-read your question and see that this doesn't quite apply.)</p>
<p>Here is a sample program that makes uses the <a href="http://docs.python.org/library/logging.html">python logging module</a>. This logging module has been in all versions since 2.3. In this sample the logging is configurable by command line options. </p>
<p>In quite mode it will only log to a file, in normal mode it will log to both a file and the console.</p>
<pre><code>import os
import sys
import logging
from optparse import OptionParser
def initialize_logging(options):
""" Log information based upon users options"""
logger = logging.getLogger('project')
formatter = logging.Formatter('%(asctime)s %(levelname)s\t%(message)s')
level = logging.__dict__.get(options.loglevel.upper(),logging.DEBUG)
logger.setLevel(level)
# Output logging information to screen
if not options.quiet:
hdlr = logging.StreamHandler(sys.stderr)
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
# Output logging information to file
logfile = os.path.join(options.logdir, "project.log")
if options.clean and os.path.isfile(logfile):
os.remove(logfile)
hdlr2 = logging.FileHandler(logfile)
hdlr2.setFormatter(formatter)
logger.addHandler(hdlr2)
return logger
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
# Setup command line options
parser = OptionParser("usage: %prog [options]")
parser.add_option("-l", "--logdir", dest="logdir", default=".", help="log DIRECTORY (default ./)")
parser.add_option("-v", "--loglevel", dest="loglevel", default="debug", help="logging level (debug, info, error)")
parser.add_option("-q", "--quiet", action="store_true", dest="quiet", help="do not log to console")
parser.add_option("-c", "--clean", dest="clean", action="store_true", default=False, help="remove old log file")
# Process command line options
(options, args) = parser.parse_args(argv)
# Setup logger format and output locations
logger = initialize_logging(options)
# Examples
logger.error("This is an error message.")
logger.info("This is an info message.")
logger.debug("This is a debug message.")
if __name__ == "__main__":
sys.exit(main())
</code></pre>
| 8
|
2009-03-15T18:49:54Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 651,718
|
<p>Since you're comfortable spawning external processes from your code, you could use <code>tee</code> itself. I don't know of any Unix system calls that do exactly what <code>tee</code> does.</p>
<pre><code>import subprocess, os, sys
# Unbuffer output
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
tee = subprocess.Popen(["tee", "log.txt"], stdin=subprocess.PIPE)
os.dup2(tee.stdin.fileno(), sys.stdout.fileno())
os.dup2(tee.stdin.fileno(), sys.stderr.fileno())
print "\nstdout"
print >>sys.stderr, "stderr"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>You could also emulate <code>tee</code> using the <a href="http://docs.python.org/dev/library/multiprocessing.html">multiprocessing</a> package (or use <a href="http://pypi.python.org/pypi/processing">processing</a> if you're using Python 2.5 or earlier).</p>
| 30
|
2009-03-16T19:00:09Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 2,216,517
|
<p>As described elsewhere, perhaps the best solution is to use the logging module directly:</p>
<pre><code>import logging
logging.basicConfig(level=logging.DEBUG, filename='mylog.log')
logging.info('this should to write to the log file')
</code></pre>
<p>However, there are some (rare) occasions where you <em>really want</em> to redirect stdout. I had this situation when I was extending django's runserver command which uses print: I didn't want to hack the django source but needed the print statements to go to a file.</p>
<p>This is a way of redirecting stdout and stderr away from the shell using the logging module:</p>
<pre><code>import logging, sys
class LogFile(object):
"""File-like object to log text using the `logging` module."""
def __init__(self, name=None):
self.logger = logging.getLogger(name)
def write(self, msg, level=logging.INFO):
self.logger.log(level, msg)
def flush(self):
for handler in self.logger.handlers:
handler.flush()
logging.basicConfig(level=logging.DEBUG, filename='mylog.log')
# Redirect stdout and stderr
sys.stdout = LogFile('stdout')
sys.stderr = LogFile('stderr')
print 'this should to write to the log file'
</code></pre>
<p>You should only use this LogFile implementation if you really cannot use the logging module directly.</p>
| 6
|
2010-02-07T09:20:32Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 2,841,525
|
<p>another solution using logging module:</p>
<pre><code>import logging
import sys
log = logging.getLogger('stdxxx')
class StreamLogger(object):
def __init__(self, stream, prefix=''):
self.stream = stream
self.prefix = prefix
self.data = ''
def write(self, data):
self.stream.write(data)
self.stream.flush()
self.data += data
tmp = str(self.data)
if '\x0a' in tmp or '\x0d' in tmp:
tmp = tmp.rstrip('\x0a\x0d')
log.info('%s%s' % (self.prefix, tmp))
self.data = ''
logging.basicConfig(level=logging.INFO,
filename='text.log',
filemode='a')
sys.stdout = StreamLogger(sys.stdout, '[stdout] ')
print 'test for stdout'
</code></pre>
| 2
|
2010-05-15T19:46:49Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 3,423,392
|
<p>I wrote a <code>tee()</code> implementation in Python that should work for most cases, and it works on Windows also.</p>
<p><a href="https://github.com/pycontribs/tendo" rel="nofollow">https://github.com/pycontribs/tendo</a></p>
<p>Also, you can use it in combination with <code>logging</code> module from Python if you want.</p>
| 9
|
2010-08-06T11:39:55Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 3,936,968
|
<p>I'm writing a script to run cmd-line scripts. ( Because in some cases, there just is no viable substitute for a Linux command -- such as the case of rsync. )</p>
<p>What I really wanted was to use the default python logging mechanism in every case where it was possible to do so, but to still capture any error when something went wrong that was unanticipated.</p>
<p>This code seems to do the trick. It may not be particularly elegant or efficient ( although it doesn't use string+=string, so at least it doesn't have that particular potential bottle-
neck ). I'm posting it in case it gives someone else any useful ideas.</p>
<pre><code>import logging
import os, sys
import datetime
# Get name of module, use as application name
try:
ME=os.path.split(__file__)[-1].split('.')[0]
except:
ME='pyExec_'
LOG_IDENTIFIER="uuu___( o O )___uuu "
LOG_IDR_LENGTH=len(LOG_IDENTIFIER)
class PyExec(object):
# Use this to capture all possible error / output to log
class SuperTee(object):
# Original reference: http://mail.python.org/pipermail/python-list/2007-May/442737.html
def __init__(self, name, mode):
self.fl = open(name, mode)
self.fl.write('\n')
self.stdout = sys.stdout
self.stdout.write('\n')
self.stderr = sys.stderr
sys.stdout = self
sys.stderr = self
def __del__(self):
self.fl.write('\n')
self.fl.flush()
sys.stderr = self.stderr
sys.stdout = self.stdout
self.fl.close()
def write(self, data):
# If the data to write includes the log identifier prefix, then it is already formatted
if data[0:LOG_IDR_LENGTH]==LOG_IDENTIFIER:
self.fl.write("%s\n" % data[LOG_IDR_LENGTH:])
self.stdout.write(data[LOG_IDR_LENGTH:])
# Otherwise, we can give it a timestamp
else:
timestamp=str(datetime.datetime.now())
if 'Traceback' == data[0:9]:
data='%s: %s' % (timestamp, data)
self.fl.write(data)
else:
self.fl.write(data)
self.stdout.write(data)
def __init__(self, aName, aCmd, logFileName='', outFileName=''):
# Using name for 'logger' (context?), which is separate from the module or the function
baseFormatter=logging.Formatter("%(asctime)s \t %(levelname)s \t %(name)s:%(module)s:%(lineno)d \t %(message)s")
errorFormatter=logging.Formatter(LOG_IDENTIFIER + "%(asctime)s \t %(levelname)s \t %(name)s:%(module)s:%(lineno)d \t %(message)s")
if logFileName:
# open passed filename as append
fl=logging.FileHandler("%s.log" % aName)
else:
# otherwise, use log filename as a one-time use file
fl=logging.FileHandler("%s.log" % aName, 'w')
fl.setLevel(logging.DEBUG)
fl.setFormatter(baseFormatter)
# This will capture stdout and CRITICAL and beyond errors
if outFileName:
teeFile=PyExec.SuperTee("%s_out.log" % aName)
else:
teeFile=PyExec.SuperTee("%s_out.log" % aName, 'w')
fl_out=logging.StreamHandler( teeFile )
fl_out.setLevel(logging.CRITICAL)
fl_out.setFormatter(errorFormatter)
# Set up logging
self.log=logging.getLogger('pyExec_main')
log=self.log
log.addHandler(fl)
log.addHandler(fl_out)
print "Test print statement."
log.setLevel(logging.DEBUG)
log.info("Starting %s", ME)
log.critical("Critical.")
# Caught exception
try:
raise Exception('Exception test.')
except Exception,e:
log.exception(str(e))
# Uncaught exception
a=2/0
PyExec('test_pyExec',None)
</code></pre>
<p>Obviously, if you're not as subject to whimsy as I am, replace LOG_IDENTIFIER with another string that you're not like to ever see someone write to a log.</p>
| 0
|
2010-10-14T19:51:00Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 7,206,730
|
<p>None of the answers above really seems to answer the problem posed. I know this is an old thread, but I think this problem is a lot simpler than everyone is making it:</p>
<pre><code>class tee_err(object):
def __init__(self):
self.errout = sys.stderr
sys.stderr = self
self.log = 'logfile.log'
log = open(self.log,'w')
log.close()
def write(self, line):
log = open(self.log,'a')
log.write(line)
log.close()
self.errout.write(line)
</code></pre>
<p>Now this will repeat everything to the normal sys.stderr handler and your file. Create another class <code>tee_out</code> for <code>sys.stdout</code>.</p>
| 1
|
2011-08-26T15:04:46Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 16,551,730
|
<p>Here is another solution, which is more general than the others -- it supports splitting output (written to <code>sys.stdout</code>) to any number of file-like objects. There's no requirement that <code>__stdout__</code> itself is included.</p>
<pre><code>import sys
class multifile(object):
def __init__(self, files):
self._files = files
def __getattr__(self, attr, *args):
return self._wrap(attr, *args)
def _wrap(self, attr, *args):
def g(*a, **kw):
for f in self._files:
res = getattr(f, attr, *args)(*a, **kw)
return res
return g
# for a tee-like behavior, use like this:
sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])
# all these forms work:
print 'abc'
print >>sys.stdout, 'line2'
sys.stdout.write('line3\n')
</code></pre>
<p>NOTE: This is a proof-of-concept. The implementation here is not complete, as it only wraps <em>methods</em> of the file-like objects (e.g. <code>write</code>), leaving out members/properties/setattr, etc. However, it is probably good enough for most people as it currently stands.</p>
<p>What I like about it, other than its generality, is that it is clean in the sense it doesn't make any direct calls to <code>write</code>, <code>flush</code>, <code>os.dup2</code>, etc.</p>
| 6
|
2013-05-14T19:52:43Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 17,942,748
|
<p>To complete John T answer: <a href="http://stackoverflow.com/a/616686/395687">http://stackoverflow.com/a/616686/395687</a></p>
<p>I added an <strong>enter</strong> and <strong>exit</strong> method to use it as a context manager with the 'with' keyword, which gives this code</p>
<pre><code>class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def __enter__(self):
pass
def __exit__(self, _type, _value, _traceback):
pass
</code></pre>
<p>It can then be used as</p>
<pre><code>with Tee('outfile.log', 'w'):
print 'I am written to both stdout and outfile.log'
</code></pre>
| 4
|
2013-07-30T09:07:29Z
|
[
"python",
"tee"
] |
How do I duplicate sys.stdout to a log file in python?
| 616,645
|
<p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<p><hr /></p>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicate</em> instead of redirect.</p>
<p>At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p>
| 105
|
2009-03-05T21:12:13Z
| 24,583,265
|
<p>I know this question has been answered repeatedly, but for this I've taken the main answer from <a href="http://stackoverflow.com/a/616686">John T's</a> answer and modified it so it contains the suggested flush and followed its linked revised version. I've also added the enter and exit as mentioned in <a href="http://stackoverflow.com/a/17942748">cladmi's</a> answer for use with the with statement. In addition, the <a href="http://docs.python.org/2/library/stdtypes.html#file.flush" rel="nofollow">documentation</a> mentions to flush files using <code>os.fsync()</code> so I've added that as well. I don't know if you <em>really</em> need that but its there.</p>
<pre><code>import sys, os
class Logger(object):
"Lumberjack class - duplicates sys.stdout to a log file and it's okay"
#source: http://stackoverflow.com/q/616645
def __init__(self, filename="Red.Wood", mode="a", buff=0):
self.stdout = sys.stdout
self.file = open(filename, mode, buff)
sys.stdout = self
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
self.close()
def write(self, message):
self.stdout.write(message)
self.file.write(message)
def flush(self):
self.stdout.flush()
self.file.flush()
os.fsync(self.file.fileno())
def close(self):
if self.stdout != None:
sys.stdout = self.stdout
self.stdout = None
if self.file != None:
self.file.close()
self.file = None
</code></pre>
<p>You can then use it</p>
<pre><code>with Logger('My_best_girlie_by_my.side'):
print("we'd sing sing sing")
</code></pre>
<p>or </p>
<pre><code>Log=Logger('Sleeps_all.night')
print('works all day')
Log.close()
</code></pre>
| 2
|
2014-07-05T05:24:52Z
|
[
"python",
"tee"
] |
Iterative version of Python's deepcopy
| 617,097
|
<p>Is there an existing implementation of an iterative version of deepcopy for Python 2.5.2? The deepcopy method available from the copy module is recursive and fails on large trees. I am not in a position where we can safely increase the stack limit at runtime.</p>
<p>EDIT</p>
<p>I did track this down:</p>
<p><a href="http://code.activestate.com/recipes/302535/" rel="nofollow">http://code.activestate.com/recipes/302535/</a></p>
<p>I haven't tested it, but it looks like it has potential.</p>
| 4
|
2009-03-05T23:07:10Z
| 617,113
|
<p>I'm not sure this would make sense. Isn't the whole point of <code>deepcopy</code> that each object will ask its children to copy themselves?</p>
<p>Presumably you know exactly what kind of object you're copying and what its children look like as well, so if I were you, I'd just write my own function to copy it. Shouldn't be too hard.</p>
| 1
|
2009-03-05T23:11:45Z
|
[
"python",
"recursion",
"iteration"
] |
Iterative version of Python's deepcopy
| 617,097
|
<p>Is there an existing implementation of an iterative version of deepcopy for Python 2.5.2? The deepcopy method available from the copy module is recursive and fails on large trees. I am not in a position where we can safely increase the stack limit at runtime.</p>
<p>EDIT</p>
<p>I did track this down:</p>
<p><a href="http://code.activestate.com/recipes/302535/" rel="nofollow">http://code.activestate.com/recipes/302535/</a></p>
<p>I haven't tested it, but it looks like it has potential.</p>
| 4
|
2009-03-05T23:07:10Z
| 617,394
|
<p>Maybe it would work as such with <a href="http://en.wikipedia.org/wiki/Stackless%5FPython" rel="nofollow">Stackless Python</a></p>
| 0
|
2009-03-06T01:08:35Z
|
[
"python",
"recursion",
"iteration"
] |
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
| 617,202
|
<p>I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?</p>
| 11
|
2009-03-05T23:46:26Z
| 617,215
|
<p><a href="http://www.askdavetaylor.com/detect%5Fapple%5Fiphone%5Fuser%5Fweb%5Fsite%5Fserver.html" rel="nofollow">This article</a> outlines a few ways of detecting an iPhone through by checking the HTTP_USER_AGENT agent variable. Depending on where you want to do the check at (HTML level, Javascript, CSS, etc.), I'm sure you can extrapolate this into your Python app. Sorry, I'm not a python guy. 8^D</p>
| 2
|
2009-03-05T23:53:04Z
|
[
"iphone",
"python",
"google-app-engine",
"web-applications"
] |
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
| 617,202
|
<p>I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?</p>
| 11
|
2009-03-05T23:46:26Z
| 617,216
|
<p>Check the user agent. It will be</p>
<blockquote>
<p>Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 </p>
</blockquote>
<p>I'm not sure how to do this with appengine, but the equivalent PHP code can be found here: <a href="http://www.mattcutts.com/blog/iphone-user-agent/" rel="nofollow">http://www.mattcutts.com/blog/iphone-user-agent/</a></p>
| 0
|
2009-03-05T23:53:29Z
|
[
"iphone",
"python",
"google-app-engine",
"web-applications"
] |
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
| 617,202
|
<p>I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?</p>
| 11
|
2009-03-05T23:46:26Z
| 618,041
|
<p>Here's how to do implement it as middleware in Django, assuming that's what you're using on appengine. </p>
<pre><code>class DetectiPhone(object):
def process_request(self, request):
if 'HTTP_USER_AGENT' in request.META and request.META['HTTP_USER_AGENT'].find('(iPhone') >= 0:
request.META['iPhone'] = True
</code></pre>
<p>Basically look for 'iPhone' in the HTTP_USER_AGENT. Note that iPod Touch has a slightly different signature than the iPhone, hence the broad 'iPhone' search instead of a more restrictive search.</p>
| 1
|
2009-03-06T08:17:57Z
|
[
"iphone",
"python",
"google-app-engine",
"web-applications"
] |
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
| 617,202
|
<p>I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?</p>
| 11
|
2009-03-05T23:46:26Z
| 618,051
|
<p>if you're using the standard webapp framework the user agent will be in the request instance. This should be good enough:</p>
<pre><code> if "iPhone" in request.headers["User-Agent"]:
# do iPhone logic
</code></pre>
| 1
|
2009-03-06T08:25:39Z
|
[
"iphone",
"python",
"google-app-engine",
"web-applications"
] |
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
| 617,202
|
<p>I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?</p>
| 11
|
2009-03-05T23:46:26Z
| 618,062
|
<p>The <a href="http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/chapter%5F3%5Fsection%5F3.html" rel="nofollow">Using the Safari on iPhone User Agent String</a> article on the apple website indicate the different user agents for iPhone and iPod touch.</p>
<pre><code>Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3
Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_0 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/XXXXX Safari/525.20
</code></pre>
| 2
|
2009-03-06T08:31:02Z
|
[
"iphone",
"python",
"google-app-engine",
"web-applications"
] |
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
| 617,202
|
<p>I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?</p>
| 11
|
2009-03-05T23:46:26Z
| 721,243
|
<pre><code>import os
class MainPage(webapp.RequestHandler):
@login_required
def get(self):
userAgent = os.environ['HTTP_USER_AGENT']
if userAgent.find('iPhone') > 0:
self.response.out.write('iPhone support is coming soon...')
else:
self.response.out.write('Hey... you are not from iPhone...')
</code></pre>
| 0
|
2009-04-06T12:39:39Z
|
[
"iphone",
"python",
"google-app-engine",
"web-applications"
] |
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
| 617,202
|
<p>I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?</p>
| 11
|
2009-03-05T23:46:26Z
| 738,766
|
<p>This is the syntax I was looking for, works with iphone and ipod touch:</p>
<pre><code>uastring = self.request.headers.get('user_agent')
if "Mobile" in uastring and "Safari" in uastring:
# do iphone / ipod stuff
</code></pre>
| 7
|
2009-04-10T20:27:02Z
|
[
"iphone",
"python",
"google-app-engine",
"web-applications"
] |
Python Popen, closing streams and multiple processes
| 617,308
|
<p>I have some data that I would like to gzip, uuencode and then print to standard out. What I basically have is:</p>
<pre><code>compressor = Popen("gzip", stdin = subprocess.PIPE, stdout = subprocess.PIPE)
encoder = Popen(["uuencode", "dummy"], stdin = compressor.stdout)
</code></pre>
<p>The way I feed data to the compressor is through compressor.stdin.write(stuff).</p>
<p>What I really need to do is to send an EOF to the compressor, and I have no idea how to do it.</p>
<p>At some point, I tried compressor.stdin.close() but that doesn't work -- it works well when the compressor writes to a file directly, but in the case above, the process doesn't terminate and stalls on compressor.wait().</p>
<p>Suggestions? In this case, gzip is an example and I really need to do something with piping the output of one process to another.</p>
<p>Note: The data I need to compress won't fit in memory, so communicate isn't really a good option here. Also, if I just run </p>
<pre><code>compressor.communicate("Testing")
</code></pre>
<p>after the 2 lines above, it still hangs with the error</p>
<pre>
File "/usr/lib/python2.4/subprocess.py", line 1041, in communicate
rlist, wlist, xlist = select.select(read_set, write_set, [])
</pre>
| 2
|
2009-03-06T00:30:08Z
| 617,316
|
<p>if you just want to compress and don't need the file wrappers consider using the zlib module</p>
<pre><code>import zlib
compressed = zlib.compress("text")
</code></pre>
<p>any reason why the shell=True and unix pipes suggestions won't work?</p>
<pre><code>from subprocess import *
pipes = Popen("gzip | uuencode dummy", stdin=PIPE, stdout=PIPE, shell=True)
for i in range(1, 100):
pipes.stdin.write("some data")
pipes.stdin.close()
print pipes.stdout.read()
</code></pre>
<p>seems to work</p>
| 1
|
2009-03-06T00:34:00Z
|
[
"python",
"stream",
"popen",
"eof"
] |
Python Popen, closing streams and multiple processes
| 617,308
|
<p>I have some data that I would like to gzip, uuencode and then print to standard out. What I basically have is:</p>
<pre><code>compressor = Popen("gzip", stdin = subprocess.PIPE, stdout = subprocess.PIPE)
encoder = Popen(["uuencode", "dummy"], stdin = compressor.stdout)
</code></pre>
<p>The way I feed data to the compressor is through compressor.stdin.write(stuff).</p>
<p>What I really need to do is to send an EOF to the compressor, and I have no idea how to do it.</p>
<p>At some point, I tried compressor.stdin.close() but that doesn't work -- it works well when the compressor writes to a file directly, but in the case above, the process doesn't terminate and stalls on compressor.wait().</p>
<p>Suggestions? In this case, gzip is an example and I really need to do something with piping the output of one process to another.</p>
<p>Note: The data I need to compress won't fit in memory, so communicate isn't really a good option here. Also, if I just run </p>
<pre><code>compressor.communicate("Testing")
</code></pre>
<p>after the 2 lines above, it still hangs with the error</p>
<pre>
File "/usr/lib/python2.4/subprocess.py", line 1041, in communicate
rlist, wlist, xlist = select.select(read_set, write_set, [])
</pre>
| 2
|
2009-03-06T00:30:08Z
| 617,346
|
<p>This is not the sort of thing you should be doing directly in python, there are eccentricities regarding the how thing work that make it a much better idea to do this with a shell. If you can just use subprocess.Popen("foo | bar", shell=True), then all the better.</p>
<p>What might be happening is that gzip has not been able to output all of its input yet, and the process will no exit until its stdout writes have been finished.</p>
<p>You can look at what system call a process is blocking on if you use strace. Use <code>ps auxwf</code> to discover which process is the gzip process, then use <code>strace -p $pidnum</code> to see what system call it is performing. Note that stdin is FD 0 and stdout is FD 1, you will probably see it reading or writing on those file descriptors.</p>
| 3
|
2009-03-06T00:49:17Z
|
[
"python",
"stream",
"popen",
"eof"
] |
Python Popen, closing streams and multiple processes
| 617,308
|
<p>I have some data that I would like to gzip, uuencode and then print to standard out. What I basically have is:</p>
<pre><code>compressor = Popen("gzip", stdin = subprocess.PIPE, stdout = subprocess.PIPE)
encoder = Popen(["uuencode", "dummy"], stdin = compressor.stdout)
</code></pre>
<p>The way I feed data to the compressor is through compressor.stdin.write(stuff).</p>
<p>What I really need to do is to send an EOF to the compressor, and I have no idea how to do it.</p>
<p>At some point, I tried compressor.stdin.close() but that doesn't work -- it works well when the compressor writes to a file directly, but in the case above, the process doesn't terminate and stalls on compressor.wait().</p>
<p>Suggestions? In this case, gzip is an example and I really need to do something with piping the output of one process to another.</p>
<p>Note: The data I need to compress won't fit in memory, so communicate isn't really a good option here. Also, if I just run </p>
<pre><code>compressor.communicate("Testing")
</code></pre>
<p>after the 2 lines above, it still hangs with the error</p>
<pre>
File "/usr/lib/python2.4/subprocess.py", line 1041, in communicate
rlist, wlist, xlist = select.select(read_set, write_set, [])
</pre>
| 2
|
2009-03-06T00:30:08Z
| 617,451
|
<p>I suspect the issue is with the order in which you open the pipes. UUEncode is funny is that it will whine when you launch it if there's no incoming pipe in just the right way (try launching the darn thing on it's own in a Popen call to see the explosion with just PIPE as the stdin and stdout)</p>
<p>Try this:</p>
<pre><code>encoder = Popen(["uuencode", "dummy"], stdin=PIPE, stdout=PIPE)
compressor = Popen("gzip", stdin=PIPE, stdout=encoder.stdin)
compressor.communicate("UUencode me please")
encoded_text = encoder.communicate()[0]
print encoded_text
begin 644 dummy
F'XL(`%]^L$D``PL-3<U+SD])5<A-52C(24TL3@4`;2O+"!(`````
`
end
</code></pre>
<p>You are right, btw... there is no way to send a generic EOF down a pipe. After all, each program really defines its own EOF. The way to do it is to close the pipe, as you were trying to do.</p>
<p>EDIT: I should be clearer about uuencode. As a shell program, it's default behaviour is to expect console input. If you run it without a "live" incoming pipe, it will block waiting for console input. By opening the encoder second, before you had sent material down the compressor pipe, the encoder was blocking waiting for you to start typing. Jerub was right in that there was something blocking.</p>
| 4
|
2009-03-06T01:37:43Z
|
[
"python",
"stream",
"popen",
"eof"
] |
Poplib not working correctly?
| 617,892
|
<p>I want to get all the messages from my gmail inbox, but I am facing 2 problems.</p>
<ol>
<li>It does not get all the emails, (as per the count in stat function)</li>
<li>The order of emails it get is random.</li>
</ol>
<p>I am unsure if its the problem with poplib or gmail pop server.</p>
<p>What am I missing here?</p>
| 0
|
2009-03-06T06:55:18Z
| 618,688
|
<p>Why don't you try to use <a href="http://libgmail.sourceforge.net/" rel="nofollow">libgmail</a>?</p>
| 0
|
2009-03-06T12:28:55Z
|
[
"python",
"python-2.5",
"poplib"
] |
Poplib not working correctly?
| 617,892
|
<p>I want to get all the messages from my gmail inbox, but I am facing 2 problems.</p>
<ol>
<li>It does not get all the emails, (as per the count in stat function)</li>
<li>The order of emails it get is random.</li>
</ol>
<p>I am unsure if its the problem with poplib or gmail pop server.</p>
<p>What am I missing here?</p>
| 0
|
2009-03-06T06:55:18Z
| 628,089
|
<p>What does your code look like? Using poplib, you're able to decide on the order and number of the messages downloaded. The code from the <a href="http://docs.python.org/library/poplib.html#id2" rel="nofollow">poplib documentation</a> should work:</p>
<pre><code>import getpass, poplib
M = poplib.POP3('localhost')
M.user(getpass.getuser())
M.pass_(getpass.getpass())
numMessages = len(M.list()[1])
for i in range(numMessages):
for j in M.retr(i+1)[1]:
print j
</code></pre>
| 1
|
2009-03-09T21:19:39Z
|
[
"python",
"python-2.5",
"poplib"
] |
Poplib not working correctly?
| 617,892
|
<p>I want to get all the messages from my gmail inbox, but I am facing 2 problems.</p>
<ol>
<li>It does not get all the emails, (as per the count in stat function)</li>
<li>The order of emails it get is random.</li>
</ol>
<p>I am unsure if its the problem with poplib or gmail pop server.</p>
<p>What am I missing here?</p>
| 0
|
2009-03-06T06:55:18Z
| 628,130
|
<p>You can also try <code>imaplib</code> module since GMail also provides access to email via IMAP protocol.</p>
| 1
|
2009-03-09T21:39:14Z
|
[
"python",
"python-2.5",
"poplib"
] |
Poplib not working correctly?
| 617,892
|
<p>I want to get all the messages from my gmail inbox, but I am facing 2 problems.</p>
<ol>
<li>It does not get all the emails, (as per the count in stat function)</li>
<li>The order of emails it get is random.</li>
</ol>
<p>I am unsure if its the problem with poplib or gmail pop server.</p>
<p>What am I missing here?</p>
| 0
|
2009-03-06T06:55:18Z
| 6,231,079
|
<p>It's the problem of gmail: <a href="https://mail.google.com/support/bin/answer.py?answer=13291" rel="nofollow">https://mail.google.com/support/bin/answer.py?answer=13291</a></p>
<p>Try to use recent:username@gmail.com as your email address. At least you'll have all your last month mail in correct order.</p>
| 0
|
2011-06-03T18:20:53Z
|
[
"python",
"python-2.5",
"poplib"
] |
How do I make this python command line an alias in bash?
| 617,952
|
<p>I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work?</p>
<pre><code>alias myip='python -c "from urllib import urlopen; print urlopen("http://whatismyip.appjet.net").read()[:-1]"'
</code></pre>
| 1
|
2009-03-06T07:27:36Z
| 617,966
|
<p>Quote the inside double-quotes:</p>
<pre><code>alias myip='python -c "from urllib import urlopen; print urlopen(\"http://whatismyip.appjet.net\").read()[:-1]"'
</code></pre>
| 6
|
2009-03-06T07:34:21Z
|
[
"python",
"bash",
"alias"
] |
How do I make this python command line an alias in bash?
| 617,952
|
<p>I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work?</p>
<pre><code>alias myip='python -c "from urllib import urlopen; print urlopen("http://whatismyip.appjet.net").read()[:-1]"'
</code></pre>
| 1
|
2009-03-06T07:27:36Z
| 617,968
|
<pre><code>alias myip="python -c 'from urllib import urlopen; print urlopen(\"http://whatismyip.appjet.net\").read()[:-1]'"
</code></pre>
<p>You need to use single quotes inside the alias to stop bash trying to interpret parts of your code inside them. The escapes on the double quotes get stripped out while processing what the alias itself is.</p>
| 7
|
2009-03-06T07:34:49Z
|
[
"python",
"bash",
"alias"
] |
How do I make this python command line an alias in bash?
| 617,952
|
<p>I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work?</p>
<pre><code>alias myip='python -c "from urllib import urlopen; print urlopen("http://whatismyip.appjet.net").read()[:-1]"'
</code></pre>
| 1
|
2009-03-06T07:27:36Z
| 618,043
|
<p>could also be done with curl:</p>
<pre><code>alias myip='curl "http://whatismyip.appjet.net"'
</code></pre>
<p>or using wget:</p>
<pre><code>alias myip='wget -O - "http://whatismyip.appjet.net" 2>/dev/null'
</code></pre>
| 5
|
2009-03-06T08:19:46Z
|
[
"python",
"bash",
"alias"
] |
How to find whether a number belongs to a particular range in Python?
| 618,093
|
<p>Suppose I want to check if <code>x</code> belongs to range 0 to 0.5. How can I do it?</p>
| 30
|
2009-03-06T08:49:08Z
| 618,099
|
<pre><code>print 'yes' if 0 < x < 0.5 else 'no'
</code></pre>
<p><a href="http://docs.python.org/library/functions.html#range"><code>range()</code></a> is for generating arrays of consecutive integers</p>
| 23
|
2009-03-06T08:51:47Z
|
[
"python",
"range"
] |
How to find whether a number belongs to a particular range in Python?
| 618,093
|
<p>Suppose I want to check if <code>x</code> belongs to range 0 to 0.5. How can I do it?</p>
| 30
|
2009-03-06T08:49:08Z
| 618,100
|
<p>No, you can't do that. <code>range()</code> expects integer arguments. If you want to know if <code>x</code> is inside this range try some form of this:</p>
<pre><code>print 0.0 <= x <= 0.5
</code></pre>
<p>Be careful with your upper limit. If you use <code>range()</code> it is excluded (<code>range(0, 5)</code> does not include 5!)</p>
| 59
|
2009-03-06T08:53:15Z
|
[
"python",
"range"
] |
How to find whether a number belongs to a particular range in Python?
| 618,093
|
<p>Suppose I want to check if <code>x</code> belongs to range 0 to 0.5. How can I do it?</p>
| 30
|
2009-03-06T08:49:08Z
| 618,106
|
<pre><code>>>> s = 1.1
>>> 0<= s <=0.2
False
>>> 0<= s <=1.2
True
</code></pre>
| 3
|
2009-03-06T08:54:56Z
|
[
"python",
"range"
] |
How to find whether a number belongs to a particular range in Python?
| 618,093
|
<p>Suppose I want to check if <code>x</code> belongs to range 0 to 0.5. How can I do it?</p>
| 30
|
2009-03-06T08:49:08Z
| 618,147
|
<p>To check whether some number n is in the inclusive range denoted by the two number a and b you do either </p>
<pre><code>if a <= n <= b:
print "yes"
else:
print "no"
</code></pre>
<p>use the replace <code>>=</code> and <code><=</code> with <code>></code> and <code><</code> to check whether <code>n</code> is in the exclusive range denoted by <code>a</code> and <code>b</code> (i.e. <code>a</code> and <code>b</code> are not themselves members of the range).</p>
<p>Alternatively, you can also check for:</p>
<pre><code>if (b - n) >= a :
print "yes"
...
</code></pre>
<p>Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the <a href="http://docs.python.org/library/functions.html?#range" rel="nofollow">documentation</a>. This is not what you want I guess.</p>
| 2
|
2009-03-06T09:12:17Z
|
[
"python",
"range"
] |
How to find whether a number belongs to a particular range in Python?
| 618,093
|
<p>Suppose I want to check if <code>x</code> belongs to range 0 to 0.5. How can I do it?</p>
| 30
|
2009-03-06T08:49:08Z
| 618,560
|
<p>Old faithful:</p>
<pre><code>if n >= a and n <= b:
</code></pre>
<p>And it doesn't look like Perl (joke)</p>
| 3
|
2009-03-06T11:40:55Z
|
[
"python",
"range"
] |
How to find whether a number belongs to a particular range in Python?
| 618,093
|
<p>Suppose I want to check if <code>x</code> belongs to range 0 to 0.5. How can I do it?</p>
| 30
|
2009-03-06T08:49:08Z
| 1,278,055
|
<p>I would use the numpy library, which would allow you to do this for a list of numbers as well:</p>
<pre><code>from numpy import array
a = array([1, 2, 3, 4, 5, 6,])
a[a < 2]
</code></pre>
| 3
|
2009-08-14T14:06:52Z
|
[
"python",
"range"
] |
How to find whether a number belongs to a particular range in Python?
| 618,093
|
<p>Suppose I want to check if <code>x</code> belongs to range 0 to 0.5. How can I do it?</p>
| 30
|
2009-03-06T08:49:08Z
| 28,989,561
|
<pre class="lang-python prettyprint-override"><code>if num in range(min, max):
"""do stuff..."""
else:
"""do other stuff..."""
</code></pre>
| 0
|
2015-03-11T14:39:42Z
|
[
"python",
"range"
] |
Prevent wxPython from showing 'Unhandled exception' dialog
| 618,429
|
<p>I have complex GUI application written in Python and wxPython.</p>
<p>I want it to be certified for Windows Vista, so it has to crash in a way that causes Windows Error Reporting dialog (The one that asks "<em>Do you want to send report to Microsoft?</em>") to appear. This is relevant to test case no 32 from "<em>Certified for Windows Vista Test Cases</em>" document.</p>
<p>Unfortunately when I crash my app with <code>ThreadHijacker</code> tool wxPython shows message like:</p>
<pre>Unhandled exception
---------------------------
An unhandled exception occurred. Press "Abort" to terminate the program,
"Retry" to exit the program normally and "Ignore" to try to continue.
---------------------------
Abort Retry Ignore</pre>
<p>How can I prevent wxPython from showing this message? I have custom <code>sys.excepthook</code>, but it seems that this dialog is shown before my except hook can interfere.</p>
<p><strong>EDIT:</strong> </p>
<p>wxWidgets <a href="http://docs.wxwidgets.org/trunk/classwx%5Fapp%5Fconsole.html#ca806b41cf74fd6166e4fb2e2708e9bf" rel="nofollow">docs</a> says that <em>wxAppConsole::OnExceptionInMainLoop</em> is called and under MSW it displays some fancy dialog that allows user to choose between the different options. It seems however, that wxPython doesn't allow overloading that function... Does anyone know how to change default behaviour of <em>wxAppConsole::OnExceptionInMainLoop</em> in wxPython?<br />
I prefer solutions that are on Python level over those that go into C/C++</p>
<p><strong>EDIT2:</strong></p>
<p>All in all, I asked at wxPython mailing list, and Robin Dunn answered that he'll look into making <em>wxAppConsole::OnExceptionInMainLoop</em> overridable in next releases of wxPython. Since I couldn't wait, I had to compile my own version of wxPython which does not include that function. It turned out that the presence of <em>wxAppConsole::OnExceptionInMainLoop</em> function can be enabled/disabled by proper setting of compilation flags.</p>
| 1
|
2009-03-06T10:51:27Z
| 618,469
|
<p>Try <a href="http://wiki.python.org/moin/CrashingPython" rel="nofollow">http://wiki.python.org/moin/CrashingPython</a></p>
| 0
|
2009-03-06T11:11:12Z
|
[
"python",
"windows",
"wxpython",
"error-reporting"
] |
Prevent wxPython from showing 'Unhandled exception' dialog
| 618,429
|
<p>I have complex GUI application written in Python and wxPython.</p>
<p>I want it to be certified for Windows Vista, so it has to crash in a way that causes Windows Error Reporting dialog (The one that asks "<em>Do you want to send report to Microsoft?</em>") to appear. This is relevant to test case no 32 from "<em>Certified for Windows Vista Test Cases</em>" document.</p>
<p>Unfortunately when I crash my app with <code>ThreadHijacker</code> tool wxPython shows message like:</p>
<pre>Unhandled exception
---------------------------
An unhandled exception occurred. Press "Abort" to terminate the program,
"Retry" to exit the program normally and "Ignore" to try to continue.
---------------------------
Abort Retry Ignore</pre>
<p>How can I prevent wxPython from showing this message? I have custom <code>sys.excepthook</code>, but it seems that this dialog is shown before my except hook can interfere.</p>
<p><strong>EDIT:</strong> </p>
<p>wxWidgets <a href="http://docs.wxwidgets.org/trunk/classwx%5Fapp%5Fconsole.html#ca806b41cf74fd6166e4fb2e2708e9bf" rel="nofollow">docs</a> says that <em>wxAppConsole::OnExceptionInMainLoop</em> is called and under MSW it displays some fancy dialog that allows user to choose between the different options. It seems however, that wxPython doesn't allow overloading that function... Does anyone know how to change default behaviour of <em>wxAppConsole::OnExceptionInMainLoop</em> in wxPython?<br />
I prefer solutions that are on Python level over those that go into C/C++</p>
<p><strong>EDIT2:</strong></p>
<p>All in all, I asked at wxPython mailing list, and Robin Dunn answered that he'll look into making <em>wxAppConsole::OnExceptionInMainLoop</em> overridable in next releases of wxPython. Since I couldn't wait, I had to compile my own version of wxPython which does not include that function. It turned out that the presence of <em>wxAppConsole::OnExceptionInMainLoop</em> function can be enabled/disabled by proper setting of compilation flags.</p>
| 1
|
2009-03-06T10:51:27Z
| 618,500
|
<p>If I remember correctly, this is a catch(...) at top level (wxApp) in wxWidgets. You can either use a vectored Exception Handler or _set_se_translator() to get a first shot at the Structured Exception, and exit to WER, i.e. ReportFault() from there.</p>
| 1
|
2009-03-06T11:19:15Z
|
[
"python",
"windows",
"wxpython",
"error-reporting"
] |
Prevent wxPython from showing 'Unhandled exception' dialog
| 618,429
|
<p>I have complex GUI application written in Python and wxPython.</p>
<p>I want it to be certified for Windows Vista, so it has to crash in a way that causes Windows Error Reporting dialog (The one that asks "<em>Do you want to send report to Microsoft?</em>") to appear. This is relevant to test case no 32 from "<em>Certified for Windows Vista Test Cases</em>" document.</p>
<p>Unfortunately when I crash my app with <code>ThreadHijacker</code> tool wxPython shows message like:</p>
<pre>Unhandled exception
---------------------------
An unhandled exception occurred. Press "Abort" to terminate the program,
"Retry" to exit the program normally and "Ignore" to try to continue.
---------------------------
Abort Retry Ignore</pre>
<p>How can I prevent wxPython from showing this message? I have custom <code>sys.excepthook</code>, but it seems that this dialog is shown before my except hook can interfere.</p>
<p><strong>EDIT:</strong> </p>
<p>wxWidgets <a href="http://docs.wxwidgets.org/trunk/classwx%5Fapp%5Fconsole.html#ca806b41cf74fd6166e4fb2e2708e9bf" rel="nofollow">docs</a> says that <em>wxAppConsole::OnExceptionInMainLoop</em> is called and under MSW it displays some fancy dialog that allows user to choose between the different options. It seems however, that wxPython doesn't allow overloading that function... Does anyone know how to change default behaviour of <em>wxAppConsole::OnExceptionInMainLoop</em> in wxPython?<br />
I prefer solutions that are on Python level over those that go into C/C++</p>
<p><strong>EDIT2:</strong></p>
<p>All in all, I asked at wxPython mailing list, and Robin Dunn answered that he'll look into making <em>wxAppConsole::OnExceptionInMainLoop</em> overridable in next releases of wxPython. Since I couldn't wait, I had to compile my own version of wxPython which does not include that function. It turned out that the presence of <em>wxAppConsole::OnExceptionInMainLoop</em> function can be enabled/disabled by proper setting of compilation flags.</p>
| 1
|
2009-03-06T10:51:27Z
| 624,644
|
<p>Is it possible for you to just handle everything? You would have to, I guess, put a try:except: block around every method bound to a widget. You could write a decorator:</p>
<pre><code>def catch_exception(f):
def safe(*args, **kw):
try:
f(*args, **kw)
except Exception, e:
handle_exception(e)
return safe
def handle_exception(e):
# do Vista stuff
sys.exit()
</code></pre>
<p>Then decorate any function that could be called by the mainloop (since I presume that's where wxPython does its own catching).</p>
| 1
|
2009-03-09T00:48:15Z
|
[
"python",
"windows",
"wxpython",
"error-reporting"
] |
Prevent wxPython from showing 'Unhandled exception' dialog
| 618,429
|
<p>I have complex GUI application written in Python and wxPython.</p>
<p>I want it to be certified for Windows Vista, so it has to crash in a way that causes Windows Error Reporting dialog (The one that asks "<em>Do you want to send report to Microsoft?</em>") to appear. This is relevant to test case no 32 from "<em>Certified for Windows Vista Test Cases</em>" document.</p>
<p>Unfortunately when I crash my app with <code>ThreadHijacker</code> tool wxPython shows message like:</p>
<pre>Unhandled exception
---------------------------
An unhandled exception occurred. Press "Abort" to terminate the program,
"Retry" to exit the program normally and "Ignore" to try to continue.
---------------------------
Abort Retry Ignore</pre>
<p>How can I prevent wxPython from showing this message? I have custom <code>sys.excepthook</code>, but it seems that this dialog is shown before my except hook can interfere.</p>
<p><strong>EDIT:</strong> </p>
<p>wxWidgets <a href="http://docs.wxwidgets.org/trunk/classwx%5Fapp%5Fconsole.html#ca806b41cf74fd6166e4fb2e2708e9bf" rel="nofollow">docs</a> says that <em>wxAppConsole::OnExceptionInMainLoop</em> is called and under MSW it displays some fancy dialog that allows user to choose between the different options. It seems however, that wxPython doesn't allow overloading that function... Does anyone know how to change default behaviour of <em>wxAppConsole::OnExceptionInMainLoop</em> in wxPython?<br />
I prefer solutions that are on Python level over those that go into C/C++</p>
<p><strong>EDIT2:</strong></p>
<p>All in all, I asked at wxPython mailing list, and Robin Dunn answered that he'll look into making <em>wxAppConsole::OnExceptionInMainLoop</em> overridable in next releases of wxPython. Since I couldn't wait, I had to compile my own version of wxPython which does not include that function. It turned out that the presence of <em>wxAppConsole::OnExceptionInMainLoop</em> function can be enabled/disabled by proper setting of compilation flags.</p>
| 1
|
2009-03-06T10:51:27Z
| 2,537,311
|
<p>It all ended up with compiling my own wxWidgets and wxPython, with just one compilation flag changed: <strong>wxUSE_EXCEPTIONS</strong> should be set to 0.</p>
<p>Robin Dunn wrote that he will try to patch wxPython, so this behaviour could be modified without recompiling of the whole library.</p>
| 2
|
2010-03-29T10:53:30Z
|
[
"python",
"windows",
"wxpython",
"error-reporting"
] |
Python regex split a string by one of two delimiters
| 618,551
|
<p>I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space.</p>
<p>And I thought it would be pretty straight-forward :</p>
<pre><code>sep = re.compile('(\s*,*)+')
print sep.split("""a@b.com, c@d.com
e@f.com,,g@h.com""")
</code></pre>
<p>But it isn't. I can't find a regex that won't leave some empty slots like this :</p>
<pre><code>['a@b.com', '', 'c@d.com', '', 'e@f.com', '', 'g@h.com']
</code></pre>
<p>I've tried various combinations, but none seem to work. Is this, in fact, possible, with regex?</p>
| 7
|
2009-03-06T11:36:13Z
| 618,562
|
<p>Doh!</p>
<p>It's just this.</p>
<pre><code>sep = re.compile('[\s,]+')
</code></pre>
| 13
|
2009-03-06T11:42:11Z
|
[
"python",
"regex"
] |
Python regex split a string by one of two delimiters
| 618,551
|
<p>I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space.</p>
<p>And I thought it would be pretty straight-forward :</p>
<pre><code>sep = re.compile('(\s*,*)+')
print sep.split("""a@b.com, c@d.com
e@f.com,,g@h.com""")
</code></pre>
<p>But it isn't. I can't find a regex that won't leave some empty slots like this :</p>
<pre><code>['a@b.com', '', 'c@d.com', '', 'e@f.com', '', 'g@h.com']
</code></pre>
<p>I've tried various combinations, but none seem to work. Is this, in fact, possible, with regex?</p>
| 7
|
2009-03-06T11:36:13Z
| 618,564
|
<p>I like the following...</p>
<pre><code>>>> sep= re.compile( r',*\s*' )
>>> sep.split("""a@b.com, c@d.com
e@f.com,,g@h.com""")
['a@b.com', 'c@d.com', 'e@f.com', 'g@h.com']
</code></pre>
<p>Which also seems to work on your test data.</p>
| 2
|
2009-03-06T11:44:11Z
|
[
"python",
"regex"
] |
Python regex split a string by one of two delimiters
| 618,551
|
<p>I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space.</p>
<p>And I thought it would be pretty straight-forward :</p>
<pre><code>sep = re.compile('(\s*,*)+')
print sep.split("""a@b.com, c@d.com
e@f.com,,g@h.com""")
</code></pre>
<p>But it isn't. I can't find a regex that won't leave some empty slots like this :</p>
<pre><code>['a@b.com', '', 'c@d.com', '', 'e@f.com', '', 'g@h.com']
</code></pre>
<p>I've tried various combinations, but none seem to work. Is this, in fact, possible, with regex?</p>
| 7
|
2009-03-06T11:36:13Z
| 618,669
|
<p>without re</p>
<pre><code>line = 'e@d , f@g, 7@g'
addresses = line.split(',')
addresses = [ address.strip() for address in addresses ]
</code></pre>
| 3
|
2009-03-06T12:23:44Z
|
[
"python",
"regex"
] |
Django: using <select multiple> and POST
| 618,557
|
<p>I'm using something like this in my template</p>
<pre><code><select multiple="multiple" name="services" id="services" size="5">
{% for service in services %}
<option value="{{service.id}}">{{service}}</option>
{% endfor %}
</select>
</code></pre>
<p>When I view the POST data in Firebug or the Django debug, I see it only sends one value. Am I doing something wrong or misunderstanding a concept?</p>
| 34
|
2009-03-06T11:39:14Z
| 618,626
|
<pre><code>request.POST.getlist('services')
</code></pre>
| 86
|
2009-03-06T12:06:52Z
|
[
"python",
"django",
"http"
] |
Django: using <select multiple> and POST
| 618,557
|
<p>I'm using something like this in my template</p>
<pre><code><select multiple="multiple" name="services" id="services" size="5">
{% for service in services %}
<option value="{{service.id}}">{{service}}</option>
{% endfor %}
</select>
</code></pre>
<p>When I view the POST data in Firebug or the Django debug, I see it only sends one value. Am I doing something wrong or misunderstanding a concept?</p>
| 34
|
2009-03-06T11:39:14Z
| 6,587,210
|
<p>Just FYI, I had to use:</p>
<p>list = <strong>request.POST.getlist('items[ ]')</strong></p>
<p>because omitting the [] caused a blank list to be returned instead of the correct values. I'm using jQuery to fetch the values of a multiple select element, and jQuery appears to be adding the [] </p>
| 6
|
2011-07-05T18:31:45Z
|
[
"python",
"django",
"http"
] |
Django: using <select multiple> and POST
| 618,557
|
<p>I'm using something like this in my template</p>
<pre><code><select multiple="multiple" name="services" id="services" size="5">
{% for service in services %}
<option value="{{service.id}}">{{service}}</option>
{% endfor %}
</select>
</code></pre>
<p>When I view the POST data in Firebug or the Django debug, I see it only sends one value. Am I doing something wrong or misunderstanding a concept?</p>
| 34
|
2009-03-06T11:39:14Z
| 13,742,103
|
<p>Watch out! getlist method from QueryDict returns an empty list if the key doesn't exist. It does not throw an exception. <a href="http://bit.ly/MdgrUH" rel="nofollow">http://bit.ly/MdgrUH</a></p>
| 1
|
2012-12-06T10:56:04Z
|
[
"python",
"django",
"http"
] |
Optimizing Jinja2 Environment creation
| 618,827
|
<p>My application is running on Google App Engine and most of requests constantly gets yellow flag due to high CPU usage. Using profiler I tracked the issue down to the routine of creating <code>jinja2.Environment</code> instance.</p>
<p>I'm creating the instance at module level:</p>
<pre><code>from jinja2 import Environment, FileSystemLoader
jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_DIRS))
</code></pre>
<p>Due to the Google AppEngine operation mode (CGI), this code can be run upon each and every request (their module import cache seems to cache modules for seconds rather than for minutes).</p>
<p>I was thinking about storing the environment instance in memcache, but it seems to be not picklable. <code>FileSystemLoader</code> instance seems to be picklable and can be cached, but I did not observe any substantial improvement in CPU usage with this approach.</p>
<p>Anybody can suggest a way to decrease the overhead of creating <code>jinja2.Environment</code> instance?</p>
<p><strong>Edit</strong>: below is (relevant) part of profiler output.</p>
<pre><code>222172 function calls (215262 primitive calls) in 8.695 CPU seconds
ncalls tottime percall cumtime percall filename:lineno(function)
33 1.073 0.033 1.083 0.033 {google3.apphosting.runtime._apphosting_runtime___python__apiproxy.Wait}
438/111 0.944 0.002 2.009 0.018 /base/python_dist/lib/python2.5/sre_parse.py:385(_parse)
4218 0.655 0.000 1.002 0.000 /base/python_dist/lib/python2.5/pickle.py:1166(load_long_binput)
1 0.611 0.611 0.679 0.679 /base/data/home/apps/with-the-flow/1.331879498764931274/jinja2/environment.py:10()
</code></pre>
<p>One call, but as far I can see (and this is consistent across all my GAE-based apps), the most expensive in the whole request processing cycle.</p>
| 8
|
2009-03-06T13:19:58Z
| 624,222
|
<p>OK, people, this is what I got today on #pocoo:</p>
<p>[20:59] zgoda: hello, i'd like to know if i could optimize my jinja2 environment creation process, the problem -> <a href="http://stackoverflow.com/questions/618827/optimizing-jinja2-environment-creation">http://stackoverflow.com/questions/618827/optimizing-jinja2-environment-creation</a></p>
<p>[21:00] zgoda: i have profiler output from "cold" app -> <a href="http://paste.pocoo.org/show/107009/" rel="nofollow">http://paste.pocoo.org/show/107009/</a></p>
<p>[21:01] zgoda: and for "hot" -> <a href="http://paste.pocoo.org/show/107014/" rel="nofollow">http://paste.pocoo.org/show/107014/</a></p>
<p>[21:02] zgoda: i'm wondering if i could somewhat lower the CPU cost of creating environment for "cold" requests</p>
<p>[21:05] mitsuhiko: zgoda: put the env creation into a module that you import</p>
<p>[21:05] mitsuhiko: like</p>
<p>[21:05] mitsuhiko: from yourapplication.utils import env</p>
<p>[21:05] zgoda: it's already there</p>
<p>[21:06] mitsuhiko: hmm</p>
<p>[21:06] mitsuhiko: i think the problem is that the template are re-compiled each access</p>
<p>[21:06] mitsuhiko: unfortunately gae is incredible limited, i don't know if there is much i can do currently</p>
<p>[21:07] zgoda: i tried with jinja bytecache but it does not work on prod (its on on dev server)</p>
<p>[21:08] mitsuhiko: i know</p>
<p>[21:08] mitsuhiko: appengine does not have marshal</p>
<p>[21:12] zgoda: mitsuhiko: thank you</p>
<p>[21:13] zgoda: i was hoping i'm doing something wrong and this can be optimized...</p>
<p>[21:13] mitsuhiko: zgoda: next release will come with improved appengine support, but i'm not sure yet how to implement improved caching for ae</p>
<p>It looks Armin is aware of problems with bytecode caching on AppEngine and has some plans to improve Jinja2 to allow caching on GAE. I hope things will get better over time.</p>
| 4
|
2009-03-08T20:20:49Z
|
[
"python",
"google-app-engine",
"jinja2"
] |
Optimizing Jinja2 Environment creation
| 618,827
|
<p>My application is running on Google App Engine and most of requests constantly gets yellow flag due to high CPU usage. Using profiler I tracked the issue down to the routine of creating <code>jinja2.Environment</code> instance.</p>
<p>I'm creating the instance at module level:</p>
<pre><code>from jinja2 import Environment, FileSystemLoader
jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_DIRS))
</code></pre>
<p>Due to the Google AppEngine operation mode (CGI), this code can be run upon each and every request (their module import cache seems to cache modules for seconds rather than for minutes).</p>
<p>I was thinking about storing the environment instance in memcache, but it seems to be not picklable. <code>FileSystemLoader</code> instance seems to be picklable and can be cached, but I did not observe any substantial improvement in CPU usage with this approach.</p>
<p>Anybody can suggest a way to decrease the overhead of creating <code>jinja2.Environment</code> instance?</p>
<p><strong>Edit</strong>: below is (relevant) part of profiler output.</p>
<pre><code>222172 function calls (215262 primitive calls) in 8.695 CPU seconds
ncalls tottime percall cumtime percall filename:lineno(function)
33 1.073 0.033 1.083 0.033 {google3.apphosting.runtime._apphosting_runtime___python__apiproxy.Wait}
438/111 0.944 0.002 2.009 0.018 /base/python_dist/lib/python2.5/sre_parse.py:385(_parse)
4218 0.655 0.000 1.002 0.000 /base/python_dist/lib/python2.5/pickle.py:1166(load_long_binput)
1 0.611 0.611 0.679 0.679 /base/data/home/apps/with-the-flow/1.331879498764931274/jinja2/environment.py:10()
</code></pre>
<p>One call, but as far I can see (and this is consistent across all my GAE-based apps), the most expensive in the whole request processing cycle.</p>
| 8
|
2009-03-06T13:19:58Z
| 806,902
|
<p>According to this <a href="http://appengine-cookbook.appspot.com/recipe/better-performance-with-jinja2/?id=ahJhcHBlbmdpbmUtY29va2Jvb2tyqwELEgtSZWNpcGVJbmRleCJGYWhKaGNIQmxibWRwYm1VdFkyOXZhMkp2YjJ0eUhnc1NDRU5oZEdWbmIzSjVJaEJYWldKaGNIQWdSbkpoYldWM2IzSnJEQQwLEgZSZWNpcGUiSGFoSmhjSEJsYm1kcGJtVXRZMjl2YTJKdmIydHlIZ3NTQ0VOaGRHVm5iM0o1SWhCWFpXSmhjSEFnUm5KaGJXVjNiM0pyREExMAw" rel="nofollow">google recipe</a> you can use memcache to cache bytecodes. You can also cache the template file content itself. All in the same recipe</p>
| 2
|
2009-04-30T13:29:51Z
|
[
"python",
"google-app-engine",
"jinja2"
] |
Optimizing Jinja2 Environment creation
| 618,827
|
<p>My application is running on Google App Engine and most of requests constantly gets yellow flag due to high CPU usage. Using profiler I tracked the issue down to the routine of creating <code>jinja2.Environment</code> instance.</p>
<p>I'm creating the instance at module level:</p>
<pre><code>from jinja2 import Environment, FileSystemLoader
jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_DIRS))
</code></pre>
<p>Due to the Google AppEngine operation mode (CGI), this code can be run upon each and every request (their module import cache seems to cache modules for seconds rather than for minutes).</p>
<p>I was thinking about storing the environment instance in memcache, but it seems to be not picklable. <code>FileSystemLoader</code> instance seems to be picklable and can be cached, but I did not observe any substantial improvement in CPU usage with this approach.</p>
<p>Anybody can suggest a way to decrease the overhead of creating <code>jinja2.Environment</code> instance?</p>
<p><strong>Edit</strong>: below is (relevant) part of profiler output.</p>
<pre><code>222172 function calls (215262 primitive calls) in 8.695 CPU seconds
ncalls tottime percall cumtime percall filename:lineno(function)
33 1.073 0.033 1.083 0.033 {google3.apphosting.runtime._apphosting_runtime___python__apiproxy.Wait}
438/111 0.944 0.002 2.009 0.018 /base/python_dist/lib/python2.5/sre_parse.py:385(_parse)
4218 0.655 0.000 1.002 0.000 /base/python_dist/lib/python2.5/pickle.py:1166(load_long_binput)
1 0.611 0.611 0.679 0.679 /base/data/home/apps/with-the-flow/1.331879498764931274/jinja2/environment.py:10()
</code></pre>
<p>One call, but as far I can see (and this is consistent across all my GAE-based apps), the most expensive in the whole request processing cycle.</p>
| 8
|
2009-03-06T13:19:58Z
| 1,020,013
|
<p>Armin suggested to pre-compile Jinja2 templates to python code, and use the compiled templates in production. So I've made a compiler/loader for that, and it now renders some complex templates 13 times faster, throwing away <strong>all</strong> the parsing overhead. The related discussion with link to the repository is <a href="http://groups.google.com/group/google-appengine-python/browse%5Fthread/thread/04d4bf3dd615ed1e/2907cdeff922710c">here</a>.</p>
| 8
|
2009-06-19T21:02:24Z
|
[
"python",
"google-app-engine",
"jinja2"
] |
dateutil.rrule.rrule.between() gives only dates after now
| 618,910
|
<p>From the IPython console:</p>
<pre><code>In [16]: b
Out[16]: datetime.datetime(2008, 3, 1, 0, 0)
In [17]: e
Out[17]: datetime.datetime(2010, 5, 2, 0, 0)
In [18]: rrule(MONTHLY).between(b, e, inc=True)
Out[18]:
[datetime.datetime(2009, 3, 6, 14, 42, 1),
datetime.datetime(2009, 4, 6, 14, 42, 1),
datetime.datetime(2009, 5, 6, 14, 42, 1),
datetime.datetime(2009, 6, 6, 14, 42, 1),
datetime.datetime(2009, 7, 6, 14, 42, 1),
datetime.datetime(2009, 8, 6, 14, 42, 1),
datetime.datetime(2009, 9, 6, 14, 42, 1),
datetime.datetime(2009, 10, 6, 14, 42, 1),
datetime.datetime(2009, 11, 6, 14, 42, 1),
datetime.datetime(2009, 12, 6, 14, 42, 1),
datetime.datetime(2010, 1, 6, 14, 42, 1),
datetime.datetime(2010, 2, 6, 14, 42, 1),
datetime.datetime(2010, 3, 6, 14, 42, 1),
datetime.datetime(2010, 4, 6, 14, 42, 1)]
</code></pre>
<p>How do I make <code>between()</code> return dates starting from the begining (<code>b</code>) date?</p>
| 4
|
2009-03-06T13:48:08Z
| 618,939
|
<p>You need to pass <code>b</code> into rrule, like this:</p>
<pre><code>rrule(MONTHLY, dtstart = b).between(b, e, inc=True)
</code></pre>
<p>From these docs (<a href="http://labix.org/python-dateutil">http://labix.org/python-dateutil</a>), it looks like calling rrule without specifying dtstart will use datetime.datetime.now() as the start point for the sequence that you're later applying <code>between</code> to. That's why your values begin at 2009-03-06.</p>
| 10
|
2009-03-06T13:58:08Z
|
[
"python",
"python-dateutil",
"rrule"
] |
Python build/release system
| 618,958
|
<p>I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended.</p>
<p>I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basically need it to do what ANT does - do SVN updates, move/copy files, archive etc using an XML file.</p>
<p>Thanks,
g</p>
| 4
|
2009-03-06T14:04:56Z
| 619,012
|
<p>what about maven? (<a href="http://maven.apache.org/" rel="nofollow">http://maven.apache.org/</a>) With the right plugins it can do much more then ant, it can even use ant for building if you configure it so.</p>
<p>It's very flexible and supports the full product life cycle. I really recommend you take a look at it.</p>
| 0
|
2009-03-06T14:21:34Z
|
[
"python",
"ant",
"build-automation"
] |
Python build/release system
| 618,958
|
<p>I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended.</p>
<p>I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basically need it to do what ANT does - do SVN updates, move/copy files, archive etc using an XML file.</p>
<p>Thanks,
g</p>
| 4
|
2009-03-06T14:04:56Z
| 619,035
|
<p>Probably the best answer is to use Ant as-is... that is, use the Java version. My second suggestion would be to use <a href="http://www.scons.org/" rel="nofollow">scons</a>. It won't take much time using scons before you're asking, "Who ever thought of using XML to script a build?"</p>
| 5
|
2009-03-06T14:31:09Z
|
[
"python",
"ant",
"build-automation"
] |
Python build/release system
| 618,958
|
<p>I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended.</p>
<p>I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basically need it to do what ANT does - do SVN updates, move/copy files, archive etc using an XML file.</p>
<p>Thanks,
g</p>
| 4
|
2009-03-06T14:04:56Z
| 619,060
|
<p>Its not completely comparable but I tend to use <a href="http://www.nongnu.org/fab/" rel="nofollow">fabric</a>. Its more geared towards deployment with support for ssh to production host and runing things as root there etc.</p>
| 2
|
2009-03-06T14:36:23Z
|
[
"python",
"ant",
"build-automation"
] |
Python build/release system
| 618,958
|
<p>I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended.</p>
<p>I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basically need it to do what ANT does - do SVN updates, move/copy files, archive etc using an XML file.</p>
<p>Thanks,
g</p>
| 4
|
2009-03-06T14:04:56Z
| 619,209
|
<p>Some people use <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">Paver</a> for build/deployment of Python packages. While I know it works, it does not appeal to me that much.</p>
| 2
|
2009-03-06T15:20:33Z
|
[
"python",
"ant",
"build-automation"
] |
Python metaclasses
| 618,960
|
<p>I've been hacking classes in Python like this:</p>
<pre><code>def hack(f,aClass) :
class MyClass(aClass) :
def f(self) :
f()
return MyClass
A = hack(afunc,A)
</code></pre>
<p>Which looks pretty clean to me. It takes a class, A, creates a new class derived from it that has an extra method, calling f, and then reassigns the new class to A.</p>
<p>How does this differ from metaclass hacking in Python? What are the advantages of using a <strong>metaclass</strong> over this?</p>
| 6
|
2009-03-06T14:06:27Z
| 619,025
|
<p>The definition of a class in Python is an instance of type (or an instance of a subclass of type). In other words, the class definition itself is an object. With metaclasses, you have the ability to control the type instance that becomes the class definition.</p>
<p>When a metaclass is invoked, you have the ability to completely re-write the class definition. You have access to all the proposed attributes of the class, its ancestors, etc. More than just injecting a method or removing a method, you can radically alter the inheritance tree, the type, and pretty much any other aspect. You can also chain metaclasses together for a very dynamic and totally convoluted experience.</p>
<p>I suppose the real benefit, though is that the class's type remains the class's type. In your example, typing:</p>
<pre><code>a_inst = A()
type(a_inst)
</code></pre>
<p>will show that it is an instance of <code>MyClass</code>. Yes, <code>isinstance(a_inst, aClass)</code> would return <code>True</code>, but you've introduced a subclass, rather than a dynamically re-defined class. The distinction there is probably the key.</p>
<p>As rjh points out, the anonymous inner class also has performance and extensibility implications. A metaclass is processed only once, and the moment that the class is defined, and never again. Users of your API can also extend your metaclass because it is not enclosed within a function, so you gain a certain degree of extensibility.</p>
<p>This slightly old article actually has a good explanation that compares exactly the "function decoration" approach you used in the example with metaclasses, and shows the history of the Python metaclass evolution in that context: <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">http://www.ibm.com/developerworks/linux/library/l-pymeta.html</a></p>
| 5
|
2009-03-06T14:27:36Z
|
[
"python",
"metaclass"
] |
Python metaclasses
| 618,960
|
<p>I've been hacking classes in Python like this:</p>
<pre><code>def hack(f,aClass) :
class MyClass(aClass) :
def f(self) :
f()
return MyClass
A = hack(afunc,A)
</code></pre>
<p>Which looks pretty clean to me. It takes a class, A, creates a new class derived from it that has an extra method, calling f, and then reassigns the new class to A.</p>
<p>How does this differ from metaclass hacking in Python? What are the advantages of using a <strong>metaclass</strong> over this?</p>
| 6
|
2009-03-06T14:06:27Z
| 815,963
|
<p>A metaclass is the class of a class. IMO, the bloke here covered it quite serviceably, including some use-cases. See Stack Overflow question <em><a href="http://stackoverflow.com/questions/395982/metaclass-new-cls-and-super-can-someone-explain-the-mechanism-exactly/396109#396109">"MetaClass", "<strong>new</strong>", "cls" and "super" - what is the mechanism exactly?</a></em>.</p>
| 1
|
2009-05-03T00:09:30Z
|
[
"python",
"metaclass"
] |
Python metaclasses
| 618,960
|
<p>I've been hacking classes in Python like this:</p>
<pre><code>def hack(f,aClass) :
class MyClass(aClass) :
def f(self) :
f()
return MyClass
A = hack(afunc,A)
</code></pre>
<p>Which looks pretty clean to me. It takes a class, A, creates a new class derived from it that has an extra method, calling f, and then reassigns the new class to A.</p>
<p>How does this differ from metaclass hacking in Python? What are the advantages of using a <strong>metaclass</strong> over this?</p>
| 6
|
2009-03-06T14:06:27Z
| 914,283
|
<p>You can use the <code>type</code> callable as well.</p>
<pre><code>def hack(f, aClass):
newfunc = lambda self: f()
return type('MyClass', (aClass,), {'f': newfunc})
</code></pre>
<p>I find using <code>type</code> the easiest way to get into the metaclass world.</p>
| 1
|
2009-05-27T06:40:19Z
|
[
"python",
"metaclass"
] |
Set the size of wx.GridBagSizer dynamically
| 619,163
|
<p>I'm creating an app where I drag button widgets into a panel. I would like to have a visible grid in the panel where i drop the widgets so the widgets will be aligned to the grid.</p>
<p>I guess it isn't hard making a grid where the squares are 15x15 pixels using a GridBagSizer(since the widgets will span between multiple cells), but how can the number of squares be made dynamically according to the size of the panel?</p>
<p>Do I have to calculate how many squares i need to fill the panel on init and on each resize?</p>
<p>Using python and wxpython btw.</p>
<p>Oerjan Pettersen</p>
| 1
|
2009-03-06T15:05:34Z
| 619,375
|
<p>Don't use a sizer at all for this. Just position the buttons yourself, with whatever co-ordinate rounding you like. (using <a href="http://docs.wxwidgets.org/2.8/wx%5Fwxwindow.html#wxwindowsetsize" rel="nofollow">wxWindow::SetSize()</a>).</p>
<p>(The point of a <a href="http://docs.wxwidgets.org/2.8/wx%5Fwxsizer.html" rel="nofollow">sizer</a> is that the buttons will get moved and/or resized when the window is resized. As you don't want that behaviour, then you shouldn't use a sizer.)</p>
| 1
|
2009-03-06T16:07:55Z
|
[
"python",
"wxpython",
"wxwidgets"
] |
Tools to ease executing raw SQL with Django ORM
| 619,384
|
<p>I often need to execute custom sql queries in django, and manually converting query results into objects every time is kinda painful. I wonder how fellow Slackers deal with this. Maybe someone had written some kind of a library to help dealing with custom SQL in Django?</p>
| 2
|
2009-03-06T16:11:46Z
| 619,691
|
<p>Not exactly sure what you're looking for, but you can always add a method onto a model to execute custom SQL per <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql" rel="nofollow" title="the docs">the docs</a>:</p>
<pre><code>def my_custom_sql(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
</code></pre>
<p>For something more generic, create an <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#id6" rel="nofollow">abstract base model</a> that defines a function like that with an "sql" parameter.</p>
| 4
|
2009-03-06T17:26:39Z
|
[
"python",
"django",
"orm"
] |
Tools to ease executing raw SQL with Django ORM
| 619,384
|
<p>I often need to execute custom sql queries in django, and manually converting query results into objects every time is kinda painful. I wonder how fellow Slackers deal with this. Maybe someone had written some kind of a library to help dealing with custom SQL in Django?</p>
| 2
|
2009-03-06T16:11:46Z
| 620,117
|
<p>Since the issue is "manually converting query results into objects," the simplest solution is often to see if your custom SQL can fit into an ORM .extra() call rather than being a pure-SQL query. Often it can, and then you let the ORM do all the work of building up objects as usual.</p>
| 3
|
2009-03-06T19:33:52Z
|
[
"python",
"django",
"orm"
] |
Tools to ease executing raw SQL with Django ORM
| 619,384
|
<p>I often need to execute custom sql queries in django, and manually converting query results into objects every time is kinda painful. I wonder how fellow Slackers deal with this. Maybe someone had written some kind of a library to help dealing with custom SQL in Django?</p>
| 2
|
2009-03-06T16:11:46Z
| 2,673,733
|
<p>The newest development version (future 1.2) has .raw() method to help you with that:</p>
<pre><code>Person.objects.raw('SELECT * FROM myapp_person')
</code></pre>
<p>More information can be found under <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/sql/</a>.</p>
| 4
|
2010-04-20T08:46:11Z
|
[
"python",
"django",
"orm"
] |
What does PyPy have to offer over CPython, Jython, and IronPython?
| 619,437
|
<p>From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of a technical exercise on what can be done?</p>
| 28
|
2009-03-06T16:25:49Z
| 619,463
|
<p>The most important feature is of course the JIT compiler. In CPython files are compiled to bytecode (<code>.pyc</code>) or optimized bytecode (<code>.pyo</code>) and then interpreted. With PyPy they will be compiled to native code. PyPy also includes <a href="http://www.stackless.com/" rel="nofollow">Stackless Python</a> patches, including it's impressive <a href="http://codespeak.net/pypy/dist/pypy/doc/stackless.html" rel="nofollow">features</a> (tasklet serialization, light threads etc.)</p>
| 4
|
2009-03-06T16:29:52Z
|
[
"python",
"interpreter",
"pypy"
] |
What does PyPy have to offer over CPython, Jython, and IronPython?
| 619,437
|
<p>From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of a technical exercise on what can be done?</p>
| 28
|
2009-03-06T16:25:49Z
| 619,466
|
<p>In case that Python gets a real <a href="http://en.wikipedia.org/wiki/Just-in-time%5Fcompilation" rel="nofollow">JIT</a> I think it's going to be as fast as any other implementation.</p>
<p>The advantage is that it's much easier to implement new features. One can see this today by observing the library. Often modules are written in Python first and then translated into C.</p>
| 0
|
2009-03-06T16:30:06Z
|
[
"python",
"interpreter",
"pypy"
] |
What does PyPy have to offer over CPython, Jython, and IronPython?
| 619,437
|
<p>From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of a technical exercise on what can be done?</p>
| 28
|
2009-03-06T16:25:49Z
| 619,480
|
<blockquote>
<p><em>cross-platform compatibility</em></p>
</blockquote>
<p>Yes</p>
| 0
|
2009-03-06T16:33:03Z
|
[
"python",
"interpreter",
"pypy"
] |
What does PyPy have to offer over CPython, Jython, and IronPython?
| 619,437
|
<p>From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of a technical exercise on what can be done?</p>
| 28
|
2009-03-06T16:25:49Z
| 619,544
|
<p>PyPy is really two projects:</p>
<ul>
<li>An interpreter compiler toolchain allowing you to write interpreters in RPython (a static subset of Python) and have cross-platform interpreters compiled standalone, for the JVM, for .NET (etc)</li>
<li>An implementation of Python in RPython</li>
</ul>
<p>These two projects allow for <em>many</em> things.</p>
<ul>
<li>Maintaining Python in Python is much easier than maintaining it in C</li>
<li>From a single codebase you can generate Python interpreters that run on the JVM, .NET and standalone - rather than having multiple slightly incompatible implementations</li>
<li>Part of the compiler toolchain includes an experimental JIT generator (now in its fifth incarnation and starting to work really well) - the <em>goal</em> is for a JITed PyPy to run <em>much</em> faster than CPython</li>
<li>It is much easier to experiment with fundamental language features - like removing the GIL, better garbage collection, integrating stackless and so on</li>
</ul>
<p>So there are really a lot of reasons for PyPy to be exciting, and it is finally starting to live up to all its promises.</p>
| 38
|
2009-03-06T16:46:37Z
|
[
"python",
"interpreter",
"pypy"
] |
What does PyPy have to offer over CPython, Jython, and IronPython?
| 619,437
|
<p>From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of a technical exercise on what can be done?</p>
| 28
|
2009-03-06T16:25:49Z
| 723,987
|
<p>This is a <a href="http://blip.tv/file/1957282">link</a> to presentation one of the PyPy authors gave at PyCon 2009. It is very informative.</p>
| 5
|
2009-04-07T02:39:24Z
|
[
"python",
"interpreter",
"pypy"
] |
Will python provide enough performance for a proxy?
| 619,575
|
<p>I want to start writing a http proxy that will modify responses according to some rules/filters I will configure. However, before I start coding it, I want to make sure I'm making the right choice in going with Python. Later, this tool would have to be able to process a lot of requests, so, I would like to know I can count on it later on to be able to perform when "push comes to shove".</p>
| 2
|
2009-03-06T16:52:36Z
| 619,587
|
<p>As long as the bulk of the processing uses Python's built-in modules it should be fine as far as performance. The biggest strength of Python is its clear syntax and ease of testing/maintainability. If you find that one section of your code is slowing down the process, you can rewrite that section and use it as a C module, while keeping the bulk of your control code in Python. </p>
<p>However if you're looking to make the most optimized Python Code you may want to check out <a href="http://stackoverflow.com/questions/172720/speeding-up-python">this SO post</a>.</p>
| 4
|
2009-03-06T16:55:56Z
|
[
"python",
"performance",
"proxy"
] |
Will python provide enough performance for a proxy?
| 619,575
|
<p>I want to start writing a http proxy that will modify responses according to some rules/filters I will configure. However, before I start coding it, I want to make sure I'm making the right choice in going with Python. Later, this tool would have to be able to process a lot of requests, so, I would like to know I can count on it later on to be able to perform when "push comes to shove".</p>
| 2
|
2009-03-06T16:52:36Z
| 619,605
|
<p>This will depend on the library you use more than the language itself. The <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted</a> framework is known to scale well. </p>
<p>Here's a <a href="http://wiki.python.org/moin/Twisted-Examples" rel="nofollow">proxy server example in python/twisted</a> to get you started.</p>
<p>Bottomline: choose your third party tools wisely and I'm sure you'll be fine.</p>
| 2
|
2009-03-06T17:00:36Z
|
[
"python",
"performance",
"proxy"
] |
Will python provide enough performance for a proxy?
| 619,575
|
<p>I want to start writing a http proxy that will modify responses according to some rules/filters I will configure. However, before I start coding it, I want to make sure I'm making the right choice in going with Python. Later, this tool would have to be able to process a lot of requests, so, I would like to know I can count on it later on to be able to perform when "push comes to shove".</p>
| 2
|
2009-03-06T16:52:36Z
| 619,606
|
<p>Yes, I think you will find Python to be perfectly adequate for your needs. There's a huge number of web frameworks, WSGI libraries, etc. to choose from, or learn from when building your own.</p>
<p>There's an interesting <a href="http://python-history.blogspot.com/2009/01/microsoft-ships-python-code-in-1996.html" rel="nofollow">post</a> on the <a href="http://python-history.blogspot.com/" rel="nofollow">Python History blog</a> about how Python was supporting high performance websites in 1996.</p>
| 2
|
2009-03-06T17:02:41Z
|
[
"python",
"performance",
"proxy"
] |
Will python provide enough performance for a proxy?
| 619,575
|
<p>I want to start writing a http proxy that will modify responses according to some rules/filters I will configure. However, before I start coding it, I want to make sure I'm making the right choice in going with Python. Later, this tool would have to be able to process a lot of requests, so, I would like to know I can count on it later on to be able to perform when "push comes to shove".</p>
| 2
|
2009-03-06T16:52:36Z
| 619,640
|
<p>Python performs pretty well for most tasks, but you'll need to change the way you program if you're used to other languages. See <a href="http://dirtsimple.org/2004/12/python-is-not-java.html" rel="nofollow">Python is not Java</a> for more info.</p>
<p>If plain old CPython doesn't give the performance you need, you have other options as well.<br />
As has been mentioned, you can extend it in C (using a tool like <a href="http://www.swig.org/" rel="nofollow">swig</a> or <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a>). I also hear good things about <a href="http://codespeak.net/pypy/dist/pypy/doc/" rel="nofollow">PyPy</a> as well, but bear in mind that it uses a restricted subset of Python. Lastly, a lot of people use <a href="http://psyco.sourceforge.net/" rel="nofollow">psyco</a> to speed up performance.</p>
| 2
|
2009-03-06T17:11:58Z
|
[
"python",
"performance",
"proxy"
] |
What is the best way to represent a schedule in a database, via Python/Django?
| 619,592
|
<p>I am writing a backup system in Python, with a Django front-end. I have decided to implement the scheduling in a slightly strange way - the client will poll the server (every 10 minutes or so), for a list of backups that need doing. The server will only respond when the time to backup is reached. This is to keep the system platform independent - so that I don't rely on cronjobs or suchlike. Therefore the Django front-end (which exposes an XML-RPC API) has to store the schedule in a database, and interpret that schedule to decide if a client should start backing up or not.</p>
<p>At present, the schedule is stored using 3 fields: days, hours and minutes. These are comma-separated lists of integers, representing the days of the week (0-6), hours of the day (0-23) and minutes of the hour (0-59). To decide whether a client should start backing up or not is a horribly inefficient operation - Python must loop over all the days since a time 7-days in the past, then the hours, then the minutes. I have done some optimization to make sure it doesn't loop too much - but still!</p>
<p>This works relatively well, although the implementation is pretty ugly. The problem I have is how to display and interpret this information via the HTML form on the front-end. Currently I just have huge lists of multi-select fields, which obviously doesn't work well.</p>
<p>Can anyone suggest a different method for implementing the schedule that would be more efficient, and also easier to represent in an HTML form?</p>
| 0
|
2009-03-06T16:56:50Z
| 619,734
|
<p>Take a look at <a href="http://code.google.com/p/django-chronograph/" rel="nofollow">django-chronograph</a>. It has a pretty nice interface for scheduling jobs at all sorts of intervals. You might be able to borrow some ideas from that. It relies on <a href="http://labix.org/python-dateutil" rel="nofollow">python-dateutil</a>, which you might also find useful for specifying repeating events.</p>
| 3
|
2009-03-06T17:39:35Z
|
[
"python",
"django",
"django-models",
"backup",
"django-forms"
] |
What is the best way to represent a schedule in a database, via Python/Django?
| 619,592
|
<p>I am writing a backup system in Python, with a Django front-end. I have decided to implement the scheduling in a slightly strange way - the client will poll the server (every 10 minutes or so), for a list of backups that need doing. The server will only respond when the time to backup is reached. This is to keep the system platform independent - so that I don't rely on cronjobs or suchlike. Therefore the Django front-end (which exposes an XML-RPC API) has to store the schedule in a database, and interpret that schedule to decide if a client should start backing up or not.</p>
<p>At present, the schedule is stored using 3 fields: days, hours and minutes. These are comma-separated lists of integers, representing the days of the week (0-6), hours of the day (0-23) and minutes of the hour (0-59). To decide whether a client should start backing up or not is a horribly inefficient operation - Python must loop over all the days since a time 7-days in the past, then the hours, then the minutes. I have done some optimization to make sure it doesn't loop too much - but still!</p>
<p>This works relatively well, although the implementation is pretty ugly. The problem I have is how to display and interpret this information via the HTML form on the front-end. Currently I just have huge lists of multi-select fields, which obviously doesn't work well.</p>
<p>Can anyone suggest a different method for implementing the schedule that would be more efficient, and also easier to represent in an HTML form?</p>
| 0
|
2009-03-06T16:56:50Z
| 37,279,723
|
<p>Your question is a bit ambiguousâdo you mean: <em>"Back up every Sunday, Monday and Friday at time X."</em>? </p>
<p>If so, use a <a href="https://en.wikipedia.org/wiki/Mask_(computing)" rel="nofollow">Bitmask</a> to store the recurring schedule as an integer:</p>
<p>Let's say that you want a backup as mentioned aboveâon Sundays, Mondays and Fridays. Encode the days of the week as an integer (represented in Binary):</p>
<pre><code>S M T W T F S
1 1 0 0 0 1 0 = 98
</code></pre>
<p>To find out if today (eg. Friday) is a backup day, simply do a bitwise <code>and</code>:</p>
<pre><code>>>> 0b1100010 & 0b0000010 != 0
True
</code></pre>
<p>To get the current day as an integer, you need to offset it by one since <code>weekday()</code> assumes week starts on Monday:</p>
<pre><code>current_day = (timezone.now().weekday() + 1) % 7
</code></pre>
<p>In summary, the schema for your <code>Schedule</code> object would look something like:</p>
<pre><code>class Schedule(models.Model):
days_recurrence = models.PositiveSmallIntegerField(db_index=True)
time = models.TimeField()
</code></pre>
<p>With this schema, you would need a new <code>Schedule</code> object for each time of the day you would like to back-up. This is a fast lookup since the bitwise operation costs around 2 cycles and since you're indexing the field <code>days_recurrence</code>, you have a worst-case day-lookup of <code>O(logn)</code> which should cut down your complexity considerably. If you want to squeeze more performance out of this, you can also use a bitmask for an <em>hour</em> then store the minute.</p>
| 0
|
2016-05-17T14:59:39Z
|
[
"python",
"django",
"django-models",
"backup",
"django-forms"
] |
Using pixel fonts in PIL
| 619,618
|
<p>I am creating images using PIL that contain numerous exactly placed text strings. My first attempt was to convert pixel fonts into the pil-compatible format as described <a href="http://llbb.wordpress.com/2006/11/24/making-pil-font-for-python-image-library/" rel="nofollow">here</a>. For example, I download the Silksreen font and convert it:</p>
<pre><code>otf2bdf -p 8pt -o fonts/slkscr.bdf fonts/slkscr.ttf
pilfont.py fonts/slkscr.bdf
</code></pre>
<p>I can then use the font in PIL like so:</p>
<pre><code>import Image, ImageDraw, os, sys, ImageFont
im = Image.new("RGB", (40,10))
draw = ImageDraw.Draw(im)
fn = ImageFont.load('fonts/slkscr.pil')
draw.text((0,0), "Hello", font=fn)
del draw
# write to stdout
im.save(sys.stdout, "PNG")
</code></pre>
<p>However, the resulting image (<img src="http://i.stack.imgur.com/L4koP.png" alt="alt text">) does not reflect what the font <a href="http://kottke.org/plus/type/silkscreen/" rel="nofollow">should look like</a>.</p>
<p>What procedure should I be using to convert and use pixel fonts so that they render as intended?</p>
<p>Thanks in advance.</p>
| 6
|
2009-03-06T17:05:11Z
| 619,919
|
<p>Eureka!</p>
<p>Just needed to specify a resolution of 72 dpi (default is 100) for otf2bdf:</p>
<pre><code>otf2bdf -p 8 -r 72 -o fonts/slkscr.bdf fonts/slkscr.ttf
</code></pre>
<p>Now, <img src="http://i.stack.imgur.com/QReUU.png" alt="alt text"> looks great!</p>
| 3
|
2009-03-06T18:31:15Z
|
[
"python",
"imaging"
] |
Do Django custom authentication backends need to take a password?
| 619,620
|
<p>Here's how my university handles authentication: we redirect the user to a website, they enter in their username and password, then they get redirected back to us with the username and a login key passed in the query string. When we get the user back, we call a stored procedure in the university's database that takes the username, login key, and ip address and tells us if this is valid.</p>
<p>I've got a Django custom authentication backend set up to handle our end of all of this. Does it make any difference one way or another whether I make it able to accept a password argument (since we're not actually taking their password)? Right now, I have it set up so that it takes the login key as the password argument. Would it be good, bad, or neither for me to change this to take this as say, login_key instead of as password?</p>
| 2
|
2009-03-06T17:05:24Z
| 619,700
|
<p>The <a href="http://docs.djangoproject.com/en/dev/topics/auth/">Django docs</a> say this:</p>
<blockquote>
<p>Either way, authenticate should check
the credentials it gets, and it should
return a User object that matches
those credentials, if the credentials
are valid. If they're not valid, it
should return None.</p>
</blockquote>
<p>The 'Either way' refers to whether the authenticate() method takes a username/password combination, or just a token. Your scenario falls between those two, so I'd think that the 'best' answer would be to write your authenticate() to take a username and a login key, and return the right User or None as appropriate.</p>
| 6
|
2009-03-06T17:29:05Z
|
[
"python",
"django",
"authentication",
"django-authentication",
"custom-backend"
] |
Supplying password to wrapped-up MySQL
| 619,804
|
<p>Greetings.</p>
<p>I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architectures.] The subprocess technique works, provided that I supply the password in the command that starts the process; however, that means that other users on the machine could see the password.</p>
<p>The original code I wrote can be seen <a href="http://armagons-isles.blogspot.com/2009/03/python-subprocess-wrapper-for-mysql.html" rel="nofollow">here</a>.</p>
<p>This variant below is very similar, although I will omit the test routine to keep it shorter:</p>
<pre><code>#!/usr/bin/env python
from subprocess import Popen, PIPE
# Set the command you need to connect to your database
mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql -u root -p"
mysql_password = "root"
def RunSqlCommand(sql_statement, database=None):
"""Pass in the SQL statement that you would like executed.
Optionally, specify a database to operate on. Returns the result."""
command_list = mysql_cmd_line.split()
if database:
command_list.append(database)
# Run mysql in a subprocess
process = Popen(command_list, stdin=PIPE, stdout=PIPE,
stderr=PIPE, close_fds=True)
#print "Asking for output"
#needs_pw = process.stdout.readline()
#print "Got: " + needs_pw
# pass it in the password
process.stdin.write(mysql_password + "\n")
# pass it our commands, and get the results
#(stdout, stderr) = process.communicate( mysql_password + "\n" + sql_statement)
(stdout, stderr) = process.communicate( sql_statement )
return stdout
</code></pre>
<p>I am suspicious that the MySQL password prompt is not actually on stdout (or stderr), although I don't know how that could be or if it means I could trap it.</p>
<p>I did try reading output first, before supplying a password, but it didn't work. I also tried passing the password</p>
<p>Again, if I supply the password on the command line (and thus have no code between the "Popen" and "communicate" functions) my wrapped function works.</p>
<p><hr /></p>
<p><em>Two new thoughts, months laster:</em></p>
<ol>
<li><p>Using <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> would let me supply a password. It simulates a tty and gets all output, even that which bypasses stdout and stderr.</p></li>
<li><p>There is a project called <a href="https://launchpad.net/myconnpy" rel="nofollow">MySQL Connector/Python</a>, in early alpha, that will allow provide a pure python library for accessing MySQL, without requiring you to compile any C-code.</p></li>
</ol>
| 2
|
2009-03-06T17:58:49Z
| 619,871
|
<p>This may be a windows / SQL Server feature, but could you use a Trusted Connection (i.e. use your OS login/password to access the DB)? There may be an OS X equivalent for MySQL.</p>
<p>Or you may just need to set up your DB to use the OS login and password so that you don't need to keep it in your code.</p>
<p>Anyway, just an idea.</p>
| 2
|
2009-03-06T18:15:44Z
|
[
"python",
"mysql",
"subprocess"
] |
Supplying password to wrapped-up MySQL
| 619,804
|
<p>Greetings.</p>
<p>I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architectures.] The subprocess technique works, provided that I supply the password in the command that starts the process; however, that means that other users on the machine could see the password.</p>
<p>The original code I wrote can be seen <a href="http://armagons-isles.blogspot.com/2009/03/python-subprocess-wrapper-for-mysql.html" rel="nofollow">here</a>.</p>
<p>This variant below is very similar, although I will omit the test routine to keep it shorter:</p>
<pre><code>#!/usr/bin/env python
from subprocess import Popen, PIPE
# Set the command you need to connect to your database
mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql -u root -p"
mysql_password = "root"
def RunSqlCommand(sql_statement, database=None):
"""Pass in the SQL statement that you would like executed.
Optionally, specify a database to operate on. Returns the result."""
command_list = mysql_cmd_line.split()
if database:
command_list.append(database)
# Run mysql in a subprocess
process = Popen(command_list, stdin=PIPE, stdout=PIPE,
stderr=PIPE, close_fds=True)
#print "Asking for output"
#needs_pw = process.stdout.readline()
#print "Got: " + needs_pw
# pass it in the password
process.stdin.write(mysql_password + "\n")
# pass it our commands, and get the results
#(stdout, stderr) = process.communicate( mysql_password + "\n" + sql_statement)
(stdout, stderr) = process.communicate( sql_statement )
return stdout
</code></pre>
<p>I am suspicious that the MySQL password prompt is not actually on stdout (or stderr), although I don't know how that could be or if it means I could trap it.</p>
<p>I did try reading output first, before supplying a password, but it didn't work. I also tried passing the password</p>
<p>Again, if I supply the password on the command line (and thus have no code between the "Popen" and "communicate" functions) my wrapped function works.</p>
<p><hr /></p>
<p><em>Two new thoughts, months laster:</em></p>
<ol>
<li><p>Using <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> would let me supply a password. It simulates a tty and gets all output, even that which bypasses stdout and stderr.</p></li>
<li><p>There is a project called <a href="https://launchpad.net/myconnpy" rel="nofollow">MySQL Connector/Python</a>, in early alpha, that will allow provide a pure python library for accessing MySQL, without requiring you to compile any C-code.</p></li>
</ol>
| 2
|
2009-03-06T17:58:49Z
| 619,899
|
<p>You could simply build a my.cnf file and point to that on the mysql command. Obviously you'll want to protect that file with permissions/acls. But it shouldn't be really an more/less secure then having the password in your python script, or the config for your python script.</p>
<p>So you would do something like </p>
<pre><code>mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql --defaults-file=credentials.cnf"
</code></pre>
<p>and your config would look about like this</p>
<pre><code>[client]
host = localhost
user = root
password = password
socket = /var/run/mysqld/mysqld.sock
</code></pre>
| 6
|
2009-03-06T18:22:20Z
|
[
"python",
"mysql",
"subprocess"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.