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
What is the most "pythonic" way to iterate over a list in chunks?
434,287
<p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p> <pre><code>for i in xrange(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
241
2009-01-12T02:48:22Z
35,617,489
<p>It is easy to make <code>itertools.groupby</code> work for you to get an iterable of iterables, without creating any temporary lists:</p> <pre><code>groupby(iterable, (lambda x,y: (lambda z: x.next()/y))(count(),100)) </code></pre> <p>Don't get put off by the nested lambdas, outer lambda runs just once to put <code>count()</code> generator and the constant <code>100</code> into the scope of the inner lambda.</p> <p>I use this to send chunks of rows to mysql.</p> <pre><code>for k,v in groupby(bigdata, (lambda x,y: (lambda z: x.next()/y))(count(),100))): cursor.executemany(sql, v) </code></pre>
0
2016-02-25T03:10:02Z
[ "python", "list", "loops", "optimization", "chunks" ]
What is the most "pythonic" way to iterate over a list in chunks?
434,287
<p>I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:</p> <pre><code>for i in xrange(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] </code></pre> <p>It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?</p> <pre><code>while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] </code></pre> <p>Still doesn't quite "feel" right, though. :-/</p> <p>Related question: <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a></p>
241
2009-01-12T02:48:22Z
35,628,605
<pre><code>def chunker(iterable, n): """Yield iterable in chunk sizes. &gt;&gt;&gt; chunks = chunker('ABCDEF', n=4) &gt;&gt;&gt; chunks.next() ['A', 'B', 'C', 'D'] &gt;&gt;&gt; chunks.next() ['E', 'F'] """ it = iter(iterable) while True: chunk = [] for i in range(n): try: chunk.append(it.next()) except StopIteration: yield chunk raise StopIteration yield chunk if __name__ == '__main__': import doctest doctest.testmod() </code></pre>
1
2016-02-25T13:25:54Z
[ "python", "list", "loops", "optimization", "chunks" ]
Comparing dictionaries in Python
434,353
<p>Given two dictionaries, <code>d1</code> and <code>d2</code>, and an integer <code>l</code>, I want to find all keys <code>k</code> in <code>d1</code> such that either <code>d2[k]&lt;l</code> or <code>k not in l</code>. I want to output the keys and the corresponding values in <code>d2</code>, except if <code>d2</code> does not contain the key, I want to print 0. For instance, if <code>d1</code> is </p> <pre><code>a: 1 b: 1 c: 1 d: 1 </code></pre> <p>and <code>d2</code> is</p> <pre><code>a: 90 b: 89 x: 45 d: 90 </code></pre> <p>and <code>l</code> is 90, the output would be (possibly in a different order)</p> <pre><code>b 89 c 0 </code></pre> <p>What is the best way to do this in Python? I am just starting to learn the language, and so far this is what I have:</p> <pre><code>for k in d1.keys(): if k not in d2: print k, 0 else: if d2[k]&lt;l: print k, d2[k] </code></pre> <p>This works of course (unless I have a typo), but it seems to me that there would be a more pythonic way of doing it.</p>
5
2009-01-12T03:23:17Z
434,378
<p>You can simplify this by using a defaultdict. Calling __getitem__ on a defaultdict will return the "default" value.</p> <pre><code>from collections import defaultdict d = defaultdict(int) print d['this key does not exist'] # will print 0 </code></pre> <p>Another bit that you could change is not to call keys. The dictionary implements <strong>iter</strong>. It would be preferable to simply write:</p> <pre><code>for k in d1: </code></pre>
4
2009-01-12T03:43:45Z
[ "python", "dictionary" ]
Comparing dictionaries in Python
434,353
<p>Given two dictionaries, <code>d1</code> and <code>d2</code>, and an integer <code>l</code>, I want to find all keys <code>k</code> in <code>d1</code> such that either <code>d2[k]&lt;l</code> or <code>k not in l</code>. I want to output the keys and the corresponding values in <code>d2</code>, except if <code>d2</code> does not contain the key, I want to print 0. For instance, if <code>d1</code> is </p> <pre><code>a: 1 b: 1 c: 1 d: 1 </code></pre> <p>and <code>d2</code> is</p> <pre><code>a: 90 b: 89 x: 45 d: 90 </code></pre> <p>and <code>l</code> is 90, the output would be (possibly in a different order)</p> <pre><code>b 89 c 0 </code></pre> <p>What is the best way to do this in Python? I am just starting to learn the language, and so far this is what I have:</p> <pre><code>for k in d1.keys(): if k not in d2: print k, 0 else: if d2[k]&lt;l: print k, d2[k] </code></pre> <p>This works of course (unless I have a typo), but it seems to me that there would be a more pythonic way of doing it.</p>
5
2009-01-12T03:23:17Z
434,390
<p>Yours is actually fine -- you could simplify it to</p> <pre><code>for k in d1: if d2.get(k, 0) &lt; l: print k, d2.get(k, 0) </code></pre> <p>which is (to me) pythonic, and is pretty much a direct "translation" into code of your description.</p> <p>If you want to avoid the double lookup, you could do</p> <pre><code>for k in d1: val = d2.get(k, 0) if val &lt; l: print k, val </code></pre>
10
2009-01-12T03:50:58Z
[ "python", "dictionary" ]
Comparing dictionaries in Python
434,353
<p>Given two dictionaries, <code>d1</code> and <code>d2</code>, and an integer <code>l</code>, I want to find all keys <code>k</code> in <code>d1</code> such that either <code>d2[k]&lt;l</code> or <code>k not in l</code>. I want to output the keys and the corresponding values in <code>d2</code>, except if <code>d2</code> does not contain the key, I want to print 0. For instance, if <code>d1</code> is </p> <pre><code>a: 1 b: 1 c: 1 d: 1 </code></pre> <p>and <code>d2</code> is</p> <pre><code>a: 90 b: 89 x: 45 d: 90 </code></pre> <p>and <code>l</code> is 90, the output would be (possibly in a different order)</p> <pre><code>b 89 c 0 </code></pre> <p>What is the best way to do this in Python? I am just starting to learn the language, and so far this is what I have:</p> <pre><code>for k in d1.keys(): if k not in d2: print k, 0 else: if d2[k]&lt;l: print k, d2[k] </code></pre> <p>This works of course (unless I have a typo), but it seems to me that there would be a more pythonic way of doing it.</p>
5
2009-01-12T03:23:17Z
434,421
<p>Here is a compact version, but yours is perfectly OK:</p> <pre><code>from collections import defaultdict d1 = {'a': 1, 'b': 1, 'c': 1, 'd': 1} d2 = {'a': 90, 'b': 89, 'x': 45, 'd': 90} l = 90 # The default (==0) is a substitute for the condition "not in d2" # As daniel suggested, it would be better if d2 itself was a defaultdict d3 = defaultdict(int, d2) print [ (k, d3[k]) for k in d1 if d3[k] &lt; l ] </code></pre> <p>Output:</p> <pre><code>[('c', 0), ('b', 89)] </code></pre>
2
2009-01-12T04:15:41Z
[ "python", "dictionary" ]
Installing certain packages using virtualenv
434,407
<p>So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this?</p> <hr> <p>Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages'</p>
2
2009-01-12T04:05:35Z
434,445
<p>If you want django to be installed on EACH virtualenv, you might as well install it in the site-packages directory? Just a thought.</p>
2
2009-01-12T04:34:25Z
[ "python", "virtualenv", "buildout" ]
Installing certain packages using virtualenv
434,407
<p>So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this?</p> <hr> <p>Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages'</p>
2
2009-01-12T04:05:35Z
436,427
<p>The other option (one I've used) is to easy_install Django after you've created the virtual environment. This is easily scripted. The penalty you pay is waiting for Django installation in each of your virtual environments.</p> <p>I'm with Toby, though: Unless there's a compelling reason <strong>why</strong> you have to have a separate copy of Django in each virtual environment, you should just consider installing it in your main Python area, and allowing each virtual environment to use it from there.</p>
0
2009-01-12T18:18:48Z
[ "python", "virtualenv", "buildout" ]
Installing certain packages using virtualenv
434,407
<p>So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this?</p> <hr> <p>Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages'</p>
2
2009-01-12T04:05:35Z
440,843
<p>I want to check out this project:</p> <p><a href="http://www.stereoplex.com/two-voices/fez-djangoskel-django-projects-and-apps-as-eggs" rel="nofollow">http://www.stereoplex.com/two-voices/fez-djangoskel-django-projects-and-apps-as-eggs</a></p> <p>Might be my answer....</p>
0
2009-01-13T21:22:10Z
[ "python", "virtualenv", "buildout" ]
Installing certain packages using virtualenv
434,407
<p>So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this?</p> <hr> <p>Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages'</p>
2
2009-01-12T04:05:35Z
441,704
<p>I'd suggest using <code>virtualenv</code>'s <a href="http://pypi.python.org/pypi/virtualenv#creating-your-own-bootstrap-scripts" rel="nofollow">bootstrapping</a> support. This allows you to execute arbitrary Python after the virtualenv is created, such as installing new packages.</p>
1
2009-01-14T02:23:50Z
[ "python", "virtualenv", "buildout" ]
Installing certain packages using virtualenv
434,407
<p>So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this?</p> <hr> <p>Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages'</p>
2
2009-01-12T04:05:35Z
481,948
<p>I know where you're coming from with the no-sites-option. I want to use pip freeze to generate requirements lists and don't want a lot of extra cruft in site-packages. I also need to use multiple versions of django as I have legacy projects I haven't upgraded (some old svn checkouts (pre1.0), some 1.0, and some new svn checkouts). Installing Django in the global site-packages isn't really an option.</p> <p>Instead I have a django folder with releases and a couple of different svn versions and just symlink to the appropriate version in the local site-packages. For ease of use I link to the local site-packages at the same level as the environment and then link in the appropriate django directory and any other "system" style packages I need (usually just PIL). So:</p> <pre><code>$ virtualenv pyenv $ ln -s ./pyenv/lib/python2.5/site-packages ./installed $ ln -s /usr/lib/python2.5/site-packages/PIL ./installed $ ln -s /opt/django/django1.0svn/trunk/django ./installed </code></pre> <p>Now the following works:</p> <pre><code>$ source pyenv/bin/activate $ python &gt; import django &gt; import PIL </code></pre>
6
2009-01-27T00:35:43Z
[ "python", "virtualenv", "buildout" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
434,593
<p>My automatic response would be <a href="http://www.webfaction.com/">WebFaction</a>. </p> <p>I haven't personally hosted with them, but they are primarily Python-oriented (founded by the guy who wrote CherryPy, for example, and as far as I know they were the first to roll out <a href="http://blog.webfaction.com/python-3-0-is-here">Python 3.0 support</a>).</p>
21
2009-01-12T06:18:24Z
[ "python", "web-hosting", "wsgi" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
434,598
<p>I've been pretty happy with Dreamhost, and of course Google AppEngine.</p>
0
2009-01-12T06:23:54Z
[ "python", "web-hosting", "wsgi" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
434,701
<p>I am a big fan of <a href="http://www.slicehost.com/">Slicehost</a> -- you get root access to a virtual server that takes about 2 minutes to install from stock OS images. The 256m slice, which has been enough for me, is US$20/mo -- it is cheaper than keeping an old box plugged in, and easy to back up. Very easy to recommend.</p>
5
2009-01-12T07:23:17Z
[ "python", "web-hosting", "wsgi" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
435,197
<p>Google App engine and OpenHosting.com</p> <p>Have virtual server by OpenHosting, they are ultra fast with support and have very high uptime.</p>
0
2009-01-12T11:44:28Z
[ "python", "web-hosting", "wsgi" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
436,793
<p>I have been using <a href="http://www.webfaction.com/" rel="nofollow">WebFaction</a> for years and very happy with the service. They are not only python oriented. You should be able to run anything within the limitations of shared hosting (unless of course you have a dedicated server).</p> <p>They are probably not the cheapest hosting service though. I don't know the prices. But I can still remember very well my previous hosting provider was unreachable for a week (not their servers, I mean the people).</p>
1
2009-01-12T19:58:17Z
[ "python", "web-hosting", "wsgi" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
7,146,057
<p>Check out <a href="http://pythonplugged.com/" rel="nofollow">http://pythonplugged.com/</a> </p> <p>They are trying to collect information on Python hosting providers using variuos technologies (CGI, FCGI, mod_python, mod_wsgi, etc)</p>
0
2011-08-22T10:24:18Z
[ "python", "web-hosting", "wsgi" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
14,319,934
<p>Plug plug for <a href="http://www.pythonanywhere.com" rel="nofollow">PythonAnywhere</a>, our own modest offering in this space. </p> <p>We offer free hosting for basic web apps, with 1-click config for popular frameworks like Django, Flask, Web2py etc. MySql is included, and you also get full suite of browser-based development tools like an editor and a console...</p>
3
2013-01-14T14:04:19Z
[ "python", "web-hosting", "wsgi" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
17,217,896
<p>I advise you to have a look at <a href="http://www.python-cloud.com" rel="nofollow">http://www.python-cloud.com</a></p> <p>This PaaS platform can automatically scale up and down your application regarding your traffic. You can also finely customize if you want vertical, horizontal or both types of scalability. The consequence of this scaling is that you pay as you go : you only pay for your real consumption and not the potential one.</p> <p>Deployment via git.</p> <p>Non AWS, hosted in tier-4+ datacenters.</p> <p>Free trial ;)</p>
0
2013-06-20T15:36:44Z
[ "python", "web-hosting", "wsgi" ]
For Python support, what company would be best to get hosting from?
434,580
<p>I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?</p>
11
2009-01-12T06:07:39Z
22,368,517
<p>I use AWS micro server, 1 year free and after that you can get a 3 year reserved which works out to about $75/yr :) The micro server has only 20MB/sec throughput, ~600MB of ram, and a slower CPU. I run a few Mezzanine sites on mine and it seems fine.</p>
0
2014-03-13T03:32:24Z
[ "python", "web-hosting", "wsgi" ]
What is the fastest way to draw an image from discrete pixel values in Python?
434,583
<p>I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it. </p> <p>Do note that this is not image processing, since I'm not transforming an existing image nor doing any sort of whole-image transformations, and it's also not vector graphics as there is no pre-determined structure to the image I'm rendering- I'm probably going to be producing amorphous blobs of color one pixel at a time. </p> <p>I need to render images about 1kx1k pixels for now, but something scalable would be useful. Final target format is PNG or any other lossless format.</p> <p>I've been using PIL at the moment via ImageDraw's draw.point , and I was wondering, given the very specific and relatively basic features I require, is there any faster library available?</p>
20
2009-01-12T06:08:12Z
434,801
<p>I think you use PIL to generate an image file on the disk, and you later load it with an image reader software.</p> <p>You should get a small speed improvement by rendering directly the picture in memory (you will save the cost of writing the image on the disk and then re-loading it). Have a look at this thread <a href="http://stackoverflow.com/questions/326300/python-best-library-for-drawing">Python - Best library for drawing</a> for how to render that image with various python modules.</p> <p>I would personally try wxpython and the <strong>dc.DrawBitmap</strong> function. If you use such a module rather than an external image reader you will have many benefits:</p> <ul> <li>speed</li> <li>you will be able to create an interactive user interface with buttons for parameters.</li> <li>you will be able to easily program a Zoomin and Zoomout function</li> <li>you will be able to plot the image as you compute it, which can be quite useful if the computation takes a lot of time</li> </ul>
1
2009-01-12T08:35:27Z
[ "python", "image", "python-imaging-library" ]
What is the fastest way to draw an image from discrete pixel values in Python?
434,583
<p>I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it. </p> <p>Do note that this is not image processing, since I'm not transforming an existing image nor doing any sort of whole-image transformations, and it's also not vector graphics as there is no pre-determined structure to the image I'm rendering- I'm probably going to be producing amorphous blobs of color one pixel at a time. </p> <p>I need to render images about 1kx1k pixels for now, but something scalable would be useful. Final target format is PNG or any other lossless format.</p> <p>I've been using PIL at the moment via ImageDraw's draw.point , and I was wondering, given the very specific and relatively basic features I require, is there any faster library available?</p>
20
2009-01-12T06:08:12Z
435,215
<pre><code>import Image im= Image.new('RGB', (1024, 1024)) im.putdata([(255,0,0), (0,255,0), (0,0,255)]) im.save('test.png') </code></pre> <p>Puts a red, green and blue pixel in the top-left of the image.</p> <p><code>im.fromstring()</code> is faster still if you prefer to deal with byte values.</p>
9
2009-01-12T11:57:48Z
[ "python", "image", "python-imaging-library" ]
What is the fastest way to draw an image from discrete pixel values in Python?
434,583
<p>I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it. </p> <p>Do note that this is not image processing, since I'm not transforming an existing image nor doing any sort of whole-image transformations, and it's also not vector graphics as there is no pre-determined structure to the image I'm rendering- I'm probably going to be producing amorphous blobs of color one pixel at a time. </p> <p>I need to render images about 1kx1k pixels for now, but something scalable would be useful. Final target format is PNG or any other lossless format.</p> <p>I've been using PIL at the moment via ImageDraw's draw.point , and I was wondering, given the very specific and relatively basic features I require, is there any faster library available?</p>
20
2009-01-12T06:08:12Z
435,944
<p>If you have numpy and scipy available (and if you are manipulating large arrays in Python, I would recommend them), then the scipy.misc.pilutil.toimage function is very handy. A simple example:</p> <pre><code>import numpy as np import scipy.misc as smp # Create a 1024x1024x3 array of 8 bit unsigned integers data = np.zeros( (1024,1024,3), dtype=np.uint8 ) data[512,512] = [254,0,0] # Makes the middle pixel red data[512,513] = [0,0,255] # Makes the next pixel blue img = smp.toimage( data ) # Create a PIL image img.show() # View in default viewer </code></pre> <p>The nice thing is toimage copes with diferent data types very well, so a 2d array of floating point numbers gets sensibly converted to greyscale etc.</p> <p>You can download numpy and scipy from <a href="http://docs.scipy.org/doc/scipy/reference/misc.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/misc.html</a>.</p>
21
2009-01-12T16:20:57Z
[ "python", "image", "python-imaging-library" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
434,612
<p>In Mac OS, you can use the "open" command. There is a Windows API call that does something similar, but I don't remember it offhand.</p> <h3>Update</h3> <p>Okay, the "start" command will do it, so this should work.</p> <p>Mac OS/X:</p> <pre><code>os.system("open "+filename) </code></pre> <p>Windows:</p> <pre><code>os.system("start "+filename) </code></pre> <h3>Much later update by Edward: os.system works, but <em>it only works with filenames that don't have any spaces in folders and files in the filename (e.g. A:\abc\def\a.txt)</em>.</h3> <h3>Later Update</h3> <p>Okay, clearly this silly-ass controversy continues, so let's just look at doing this with subprocess.</p> <p><code>open</code> and <code>start</code> are command interpreter things for Mac OS/X and Windows respectively. Now, let's say we use subprocess. Canonically, you'd use:</p> <pre><code>try: retcode = subprocess.call("open " + filename, shell=True) if retcode &lt; 0: print &gt;&gt;sys.stderr, "Child was terminated by signal", -retcode else: print &gt;&gt;sys.stderr, "Child returned", retcode except OSError, e: print &gt;&gt;sys.stderr, "Execution failed:", e </code></pre> <p>Now, what are the advantages of this? In theory, this is more secure -- but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpet, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type <code>'filename ; rm -rf /'</code>" problem, and IF the file name can be corrupted, using <code>subprocess.call</code> gives us no protection.</p> <p>It doesn't actually give us any more error detection, we're still depending on the <code>retcode</code> in either case. We don't need to wait for the child process, since we're by problem statement starting a separate process.</p> <p>"But <code>subprocess</code> is preferred." However, <code>os.system()</code> is not deprecated, and it's the simplest tool for this particular job.</p> <p>Conclusion: using <code>os.system()</code> is the simplest, most straightforward way to do this, and is therefore a correct answer.</p>
48
2009-01-12T06:30:20Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
434,616
<p>on mac os you can call 'open'</p> <pre><code>import os os.popen("open myfile.txt") </code></pre> <p>this would open the file with TextEdit, or whatever app is set as default for this filetype</p>
0
2009-01-12T06:34:06Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
435,291
<p>I prefer:</p> <pre><code>os.startfile(path, 'open') </code></pre> <p>Note that this module supports filenames that have spaces in their folders and files e.g. </p> <pre><code>A:\abc\folder with spaces\file with-spaces.txt </code></pre> <p>(<a href="http://docs.python.org/library/os.html#os.startfile" rel="nofollow">python docs</a>) 'open' does not have to be added (it is the default). The docs specifically mention that this is like double-clicking on a file's icon in Windows Explorer.</p> <p>This solution is windows only.</p>
18
2009-01-12T12:33:39Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
435,631
<p>Just for completeness (it wasn't in the question), <a href="http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html">xdg-open</a> will do the same on Linux.</p>
26
2009-01-12T14:47:09Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
435,669
<p>Use the <code>subprocess</code> module available on Python 2.4+, not <code>os.system()</code>, so you don't have to deal with shell escaping.</p> <pre><code>import subprocess, os if sys.platform.startswith('darwin'): subprocess.call(('open', filepath)) elif os.name == 'nt': os.startfile(filepath) elif os.name == 'posix': subprocess.call(('xdg-open', filepath)) </code></pre> <p>The double parentheses are because <code>subprocess.call()</code> wants a sequence as its first argument, so we're using a tuple here. On Linux systems with Gnome there is also a <code>gnome-open</code> command that does the same thing, but <code>xdg-open</code> is the Free Desktop Foundation standard and works across Linux desktop environments.</p>
91
2009-01-12T15:00:22Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
435,748
<pre><code>import os import subprocess def click_on_file(filename): try: os.startfile(filename): except AttributeError: subprocess.call(['open', filename]) </code></pre>
20
2009-01-12T15:28:07Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
818,083
<p>If you want to specify the app to open the file with on Mac OS X, use this: <code>os.system("open -a [app name] [file name]")</code></p>
0
2009-05-03T21:46:36Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
1,585,848
<p>If you want to go the <code>subprocess.call()</code> way, it should look like this on Windows:</p> <pre><code>import subprocess subprocess.call(('cmd', '/C', 'start', '', FILE_NAME)) </code></pre> <p>You can't just use:</p> <pre><code>subprocess.call(('start', FILE_NAME)) </code></pre> <p>because <code>start</code> <a href="http://frank.neatstep.com/node/84" rel="nofollow">is not an executable</a> but a command of the <code>cmd.exe</code> program. This works:</p> <pre><code>subprocess.call(('cmd', '/C', 'start', FILE_NAME)) </code></pre> <p>but only if there are no spaces in the FILE_NAME.</p> <p>While <code>subprocess.call</code> method <strike>en</strike>quotes the parameters properly, the <code>start</code> command has a rather strange syntax, where:</p> <pre><code>start notes.txt </code></pre> <p>does something else than:</p> <pre><code>start "notes.txt" </code></pre> <p>The first quoted string should set the title of the window. To make it work with spaces, we have to do:</p> <pre><code>start "" "my notes.txt" </code></pre> <p>which is what the code on top does.</p>
3
2009-10-18T19:48:10Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
3,413,337
<p>Start does not support long path names and white spaces. You have to convert it to 8.3 compatible paths.</p> <pre><code>import subprocess import win32api filename = "C:\\Documents and Settings\\user\\Desktop\file.avi" filename_short = win32api.GetShortPathName(filename) subprocess.Popen('start ' + filename_short, shell=True ) </code></pre> <p>The file has to exist in order to work with the API call.</p>
4
2010-08-05T09:22:42Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
7,251,254
<p>I am pretty late to the lot, but here is a solution using the windows api. This always opens the associated application.</p> <pre><code>import ctypes shell32 = ctypes.windll.shell32 file = 'somedocument.doc' shell32.ShellExecuteA(0,"open",file,0,0,5) </code></pre> <p>A lot of magic constants. The first zero is the hwnd of the current program. Can be zero. The other two zeros are optional parameters (parameters and directory). 5 == SW_SHOW, it specifies how to execute the app. Read the <a href="http://msdn.microsoft.com/en-us/library/bb762153%28v=vs.85%29.aspx" rel="nofollow">ShellExecute API docs</a> for more info.</p>
1
2011-08-31T00:18:02Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
11,479,099
<p>If you have to use an heuristic method, you may consider <code>webbrowser</code>.<br> It's standard library and despite of its name it would also try to open files:</p> <blockquote> <p>Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable. (<a href="http://docs.python.org/library/webbrowser.html#webbrowser.open" rel="nofollow">Reference</a>)</p> </blockquote> <p>I tried this code and it worked fine in Windows 7 and Ubuntu Natty:</p> <pre><code>import webbrowser webbrowser.open("path_to_file") </code></pre> <p>This code also works fine in Windows XP Professional, using Internet Explorer 8.</p>
10
2012-07-13T22:19:01Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
24,895,085
<p>os.startfile(path, 'open') under windows is good because when spaces exist in the directory, os.system('start', path_name) can't open the app correct and when the i18n exist in the directory, os.system needs to change the unicode to the codec of the console in Windows.</p>
1
2014-07-22T18:32:40Z
[ "python", "windows", "osx" ]
Open document with default application in Python
434,597
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
66
2009-01-12T06:23:51Z
29,184,580
<p>On windows 8.1, below have worked while other given ways with <code>subprocess.call</code> fails with path has spaces in it.</p> <pre><code>subprocess.call('cmd /c start "" "any file path with spaces"') </code></pre> <p>By utilizing this and other's answers before, here's an inline code which works on multiple platforms.</p> <pre><code>import sys, os, subprocess subprocess.call(('cmd /c start "" "'+ filepath +'"') if os.name is 'nt' else ('open' if sys.platform.startswith('darwin') else 'xdg-open', filepath)) </code></pre>
0
2015-03-21T15:41:48Z
[ "python", "windows", "osx" ]
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
434,641
<p>When I extract files from a ZIP file created with the Python <a href="http://docs.python.org/library/zipfile.html"><code>zipfile</code></a> module, all the files are not writable, read only etc.</p> <p>The file is being created and extracted under Linux and Python 2.5.2.</p> <p>As best I can tell, I need to set the <code>ZipInfo.external_attr</code> property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me?</p>
27
2009-01-12T06:51:27Z
434,651
<p>Look at this: <a href="http://stackoverflow.com/questions/279945/set-permissions-on-a-compressed-file-in-python">http://stackoverflow.com/questions/279945/set-permissions-on-a-compressed-file-in-python</a></p> <p>I'm not entirely sure if that's what you want, but it seems to be.</p> <p>The key line appears to be:</p> <pre><code>zi.external_attr = 0777 &lt;&lt; 16L </code></pre> <p>It looks like it sets the permissions to <code>0777</code> there.</p>
12
2009-01-12T06:57:36Z
[ "python", "attributes", "zip", "file-permissions", "zipfile" ]
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
434,641
<p>When I extract files from a ZIP file created with the Python <a href="http://docs.python.org/library/zipfile.html"><code>zipfile</code></a> module, all the files are not writable, read only etc.</p> <p>The file is being created and extracted under Linux and Python 2.5.2.</p> <p>As best I can tell, I need to set the <code>ZipInfo.external_attr</code> property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me?</p>
27
2009-01-12T06:51:27Z
434,689
<p>This seems to work (thanks Evan, putting it here so the line is in context):</p> <pre><code>buffer = "path/filename.zip" # zip filename to write (or file-like object) name = "folder/data.txt" # name of file inside zip bytes = "blah blah blah" # contents of file inside zip zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) info = zipfile.ZipInfo(name) info.external_attr = 0777 &lt;&lt; 16L # give full access to included file zip.writestr(info, bytes) zip.close() </code></pre> <p>I'd still like to see something that documents this... An additional resource I found was a note on the Zip file format: <a href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT">http://www.pkware.com/documents/casestudies/APPNOTE.TXT</a></p>
28
2009-01-12T07:14:46Z
[ "python", "attributes", "zip", "file-permissions", "zipfile" ]
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
434,641
<p>When I extract files from a ZIP file created with the Python <a href="http://docs.python.org/library/zipfile.html"><code>zipfile</code></a> module, all the files are not writable, read only etc.</p> <p>The file is being created and extracted under Linux and Python 2.5.2.</p> <p>As best I can tell, I need to set the <code>ZipInfo.external_attr</code> property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me?</p>
27
2009-01-12T06:51:27Z
434,690
<p>When you do it like this, does it work alright?</p> <pre><code>zf = zipfile.ZipFile("something.zip") for name in zf.namelist(): f = open(name, 'wb') f.write(self.read(name)) f.close() </code></pre> <p>If not, I'd suggest throwing in an <code>os.chmod</code> in the for loop with 0777 permissions like this:</p> <pre><code>zf = zipfile.ZipFile("something.zip") for name in zf.namelist(): f = open(name, 'wb') f.write(self.read(name)) f.close() os.chmod(name, 0777) </code></pre>
0
2009-01-12T07:15:11Z
[ "python", "attributes", "zip", "file-permissions", "zipfile" ]
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
434,641
<p>When I extract files from a ZIP file created with the Python <a href="http://docs.python.org/library/zipfile.html"><code>zipfile</code></a> module, all the files are not writable, read only etc.</p> <p>The file is being created and extracted under Linux and Python 2.5.2.</p> <p>As best I can tell, I need to set the <code>ZipInfo.external_attr</code> property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me?</p>
27
2009-01-12T06:51:27Z
6,297,838
<p><a href="http://trac.edgewall.org/attachment/ticket/8919/ZipDownload.patch">This link</a> has more information than anything else I've been able to find on the net. Even the zip source doesn't have anything. Copying the relevant section for posterity. This patch isn't really about documenting this format, which just goes to show how pathetic (read non-existent) the current documentation is.</p> <pre><code># external_attr is 4 bytes in size. The high order two # bytes represent UNIX permission and file type bits, # while the low order two contain MS-DOS FAT file # attributes, most notably bit 4 marking directories. if node.isfile: zipinfo.compress_type = ZIP_DEFLATED zipinfo.external_attr = 0644 &lt;&lt; 16L # permissions -r-wr--r-- data = node.get_content().read() properties = node.get_properties() if 'svn:special' in properties and \ data.startswith('link '): data = data[5:] zipinfo.external_attr |= 0120000 &lt;&lt; 16L # symlink file type zipinfo.compress_type = ZIP_STORED if 'svn:executable' in properties: zipinfo.external_attr |= 0755 &lt;&lt; 16L # -rwxr-xr-x zipfile.writestr(zipinfo, data) elif node.isdir and path: if not zipinfo.filename.endswith('/'): zipinfo.filename += '/' zipinfo.compress_type = ZIP_STORED zipinfo.external_attr = 040755 &lt;&lt; 16L # permissions drwxr-xr-x zipinfo.external_attr |= 0x10 # MS-DOS directory flag zipfile.writestr(zipinfo, '') </code></pre> <p>Also, <a href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT">this link</a> has the following. Here the low order byte presumably means the rightmost (lowest) byte of the four bytes. So this one is for MS-DOS and can presumably be left as zero otherwise.</p> <blockquote> <p>external file attributes: (4 bytes)</p> <pre><code> The mapping of the external attributes is host-system dependent (see 'version made by'). For MS-DOS, the low order byte is the MS-DOS directory attribute byte. If input came from standard input, this field is set to zero. </code></pre> </blockquote> <p>Also, the source file unix/unix.c in the sources for InfoZIP's zip program, downloaded from <a href="http://packages.debian.org/source/stable/zip">Debian's archives</a> has the following in comments.</p> <pre><code> /* lower-middle external-attribute byte (unused until now): * high bit =&gt; (have GMT mod/acc times) &gt;&gt;&gt; NO LONGER USED! &lt;&lt;&lt; * second-high bit =&gt; have Unix UID/GID info * NOTE: The high bit was NEVER used in any official Info-ZIP release, * but its future use should be avoided (if possible), since it * was used as "GMT mod/acc times local extra field" flags in Zip beta * versions 2.0j up to 2.0v, for about 1.5 years. */ </code></pre> <p>So taking all this together, it looks like only the second highest byte is actually used, at least for Unix. </p> <p>EDIT: I asked about the Unix aspect of this on Unix.SX, in the question "<a href="http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute">The zip format's external file attribute</a>". Looks like I got a couple of things wrong. Specifically both of the top two bytes are used for Unix.</p>
14
2011-06-09T19:00:35Z
[ "python", "attributes", "zip", "file-permissions", "zipfile" ]
Cleaning up a database in django before every test method
434,700
<p>By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?</p> <p>Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that</p> <pre><code>class TestForManager(unittest.TestCase): def testAddingBlah(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlah(...) self.assertEquals(manager.getBlahs(), 1) def testAddingBlahInDifferentWay(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlahInDifferentWay(...) self.assertEquals(manager.getBlahs(), 1) </code></pre> <p>Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of <code>Blah</code> in the database.</p>
9
2009-01-12T07:22:59Z
435,087
<p>Why not do the following? This accomplishes what you need without a significant change to your code.</p> <pre><code>class TestOneForManager(unittest.TestCase): def testAddingBlah(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlah(...) self.assertEquals(manager.getBlahs(), 1) class TestTwoForManager(unittest.TestCase): def testAddingBlahInDifferentWay(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlahInDifferentWay(...) self.assertEquals(manager.getBlahs(), 1) </code></pre> <p><hr /></p> <p><strong>Edit</strong>. The "reset on TestCase" feature gives you complete control.</p> <ul> <li><p>Many test methods in a single TestCase are good when you have test cases that don't interfere with each other.</p></li> <li><p>Few test methods in a single TestCase are good when you have test cases that interfere with each other.</p></li> </ul> <p>You can choose which model applies to your tests by grouping your test methods in one or many TestCases. You have total and complete control.</p>
0
2009-01-12T10:54:59Z
[ "python", "django", "unit-testing", "django-models" ]
Cleaning up a database in django before every test method
434,700
<p>By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?</p> <p>Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that</p> <pre><code>class TestForManager(unittest.TestCase): def testAddingBlah(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlah(...) self.assertEquals(manager.getBlahs(), 1) def testAddingBlahInDifferentWay(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlahInDifferentWay(...) self.assertEquals(manager.getBlahs(), 1) </code></pre> <p>Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of <code>Blah</code> in the database.</p>
9
2009-01-12T07:22:59Z
436,795
<p>As always, solution is trivial: use <code>django.test.TestCase</code> not <code>unittest.TestCase</code>. And it works in all major versions of Django!</p>
22
2009-01-12T19:59:19Z
[ "python", "django", "unit-testing", "django-models" ]
Cleaning up a database in django before every test method
434,700
<p>By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?</p> <p>Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that</p> <pre><code>class TestForManager(unittest.TestCase): def testAddingBlah(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlah(...) self.assertEquals(manager.getBlahs(), 1) def testAddingBlahInDifferentWay(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlahInDifferentWay(...) self.assertEquals(manager.getBlahs(), 1) </code></pre> <p>Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of <code>Blah</code> in the database.</p>
9
2009-01-12T07:22:59Z
4,438,518
<p>You can use the <code>tearDown</code> method. It will be called after your test is run. You can delete all Blahs there.</p>
0
2010-12-14T11:11:26Z
[ "python", "django", "unit-testing", "django-models" ]
Ensuring contact form email isn't lost (python)
436,003
<p>I have a website with a contact form. User submits name, email and message and the site emails me the details.</p> <p>Very occasionally my server has a problem with it's email system and so the user gets an error and those contact details are lost. (Don't say: get a better server, any server can have email go down now and then and we do get a lot of submissions).</p> <p>I would like to implement a system that could store the user's details if the mail sending function returns with an error code. Then on every further submission, check for any stored submissions and try to send them off to me.</p> <p>But how to store the data?</p> <p>I'm using python so I thought about using <a href="http://docs.python.org/library/shelve.html" rel="nofollow">shelve</a> (single file semi-database). Or maybe someone could suggest a better data format? (I do think a full database solution would be overkill.)</p> <p>The problem I see with a single file approach is <em>race-conditions</em>: two or more failed emails at the same time would cause two edits to the data file resulting in data corruption.</p> <p>So what to do? Multi-file solution, file locking or something else?</p>
2
2009-01-12T16:33:03Z
436,008
<p>try <a href="http://www.sqlite.org/" rel="nofollow">sqlite</a>. It has default <a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">python bindings</a> in the standard library and should work for a useful level of load (or so I am told)</p>
4
2009-01-12T16:35:29Z
[ "python", "email", "race-condition", "data-formats" ]
Ensuring contact form email isn't lost (python)
436,003
<p>I have a website with a contact form. User submits name, email and message and the site emails me the details.</p> <p>Very occasionally my server has a problem with it's email system and so the user gets an error and those contact details are lost. (Don't say: get a better server, any server can have email go down now and then and we do get a lot of submissions).</p> <p>I would like to implement a system that could store the user's details if the mail sending function returns with an error code. Then on every further submission, check for any stored submissions and try to send them off to me.</p> <p>But how to store the data?</p> <p>I'm using python so I thought about using <a href="http://docs.python.org/library/shelve.html" rel="nofollow">shelve</a> (single file semi-database). Or maybe someone could suggest a better data format? (I do think a full database solution would be overkill.)</p> <p>The problem I see with a single file approach is <em>race-conditions</em>: two or more failed emails at the same time would cause two edits to the data file resulting in data corruption.</p> <p>So what to do? Multi-file solution, file locking or something else?</p>
2
2009-01-12T16:33:03Z
436,031
<p>When we implement email sending functionality in our environment we do it in a decoupled way. So for example a user would submit their data which would get stored in a database. We then have a separate service that runs, queries the database and sends out email. That way if there are ever any email server issues, the service will just try again later, data and user confidence is never lost.</p>
8
2009-01-12T16:40:21Z
[ "python", "email", "race-condition", "data-formats" ]
Ensuring contact form email isn't lost (python)
436,003
<p>I have a website with a contact form. User submits name, email and message and the site emails me the details.</p> <p>Very occasionally my server has a problem with it's email system and so the user gets an error and those contact details are lost. (Don't say: get a better server, any server can have email go down now and then and we do get a lot of submissions).</p> <p>I would like to implement a system that could store the user's details if the mail sending function returns with an error code. Then on every further submission, check for any stored submissions and try to send them off to me.</p> <p>But how to store the data?</p> <p>I'm using python so I thought about using <a href="http://docs.python.org/library/shelve.html" rel="nofollow">shelve</a> (single file semi-database). Or maybe someone could suggest a better data format? (I do think a full database solution would be overkill.)</p> <p>The problem I see with a single file approach is <em>race-conditions</em>: two or more failed emails at the same time would cause two edits to the data file resulting in data corruption.</p> <p>So what to do? Multi-file solution, file locking or something else?</p>
2
2009-01-12T16:33:03Z
436,106
<p>You could, as suggested, use sqlite for this. The main question is: How mans is "a lot of submissions"? I it is below of a few per second this would work. Otherwise the database file will be locked all the time and you have another problem. </p> <p>But you could it also keep it plain, stupid and simple: write files to disk. For every sumission a file is written in a temporary directory (if the mail server is down). Then you add a few lines to the mailserver startup script that reads the directory and sends out mails. No databases, no locking problems and if you use a directory for which a quota is set (or a ramdisk with fixed size) you shouldn't run into any problems.</p>
2
2009-01-12T16:57:17Z
[ "python", "email", "race-condition", "data-formats" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
436,214
<p>If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?</p> <p>If you need to dynamically import code the built-in function <a href="http://docs.python.org/library/functions.html#__import__" rel="nofollow">__ import__</a> and the module <a href="http://docs.python.org/library/imp.html" rel="nofollow">imp</a> are worth looking at.</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path = ['/path/to/script'] + sys.path &gt;&gt;&gt; __import__('test') &lt;module 'test' from '/path/to/script/test.pyc'&gt; &gt;&gt;&gt; __import__('test').run() 'Hello world!' </code></pre> <p>test.py:</p> <pre><code>def run(): return "Hello world!" </code></pre> <p>If you're using Python 3.1 or later, you should also take a look at <a href="http://docs.python.org/release/3.1/library/importlib.html" rel="nofollow">importlib</a>.</p>
11
2009-01-12T17:28:15Z
[ "python", "python-3.x" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
436,267
<p>You could write your own function:</p> <pre><code>def xfile(afile, globalz=None, localz=None): with open(afile, "r") as fh: exec(fh.read(), globalz, localz) </code></pre> <p>If you really needed to...</p>
16
2009-01-12T17:38:43Z
[ "python", "python-3.x" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
437,857
<p>You are just supposed to read the file and exec the code yourself. 2to3 current replaces</p> <pre><code>execfile("somefile.py", global_vars, local_vars) </code></pre> <p>as</p> <pre><code>with open("somefile.py") as f: code = compile(f.read(), "somefile.py", 'exec') exec(code, global_vars, local_vars) </code></pre> <p>(The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.)</p> <p>See:</p> <ul> <li><a href="http://docs.python.org/release/2.7.3/library/functions.html#execfile">http://docs.python.org/release/2.7.3/library/functions.html#execfile</a></li> <li><a href="http://docs.python.org/release/3.2.3/library/functions.html#compile">http://docs.python.org/release/3.2.3/library/functions.html#compile</a></li> <li><a href="http://docs.python.org/release/3.2.3/library/functions.html#exec">http://docs.python.org/release/3.2.3/library/functions.html#exec</a></li> </ul>
147
2009-01-13T03:20:59Z
[ "python", "python-3.x" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
2,849,077
<p>This one is better, since it takes the globals and locals from the caller:</p> <pre><code>import sys def execfile(filename, globals=None, locals=None): if globals is None: globals = sys._getframe(1).f_globals if locals is None: locals = sys._getframe(1).f_locals with open(filename, "r") as fh: exec(fh.read()+"\n", globals, locals) </code></pre>
11
2010-05-17T12:43:26Z
[ "python", "python-3.x" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
5,643,233
<p>Note that the above pattern will fail if you're using PEP-263 encoding declarations that aren't ascii or utf-8. You need to find the encoding of the data, and encode it correctly before handing it to exec().</p> <pre><code>class python3Execfile(object): def _get_file_encoding(self, filename): with open(filename, 'rb') as fp: try: return tokenize.detect_encoding(fp.readline)[0] except SyntaxError: return "utf-8" def my_execfile(filename): globals['__file__'] = filename with open(filename, 'r', encoding=self._get_file_encoding(filename)) as fp: contents = fp.read() if not contents.endswith("\n"): # http://bugs.python.org/issue10204 contents += "\n" exec(contents, globals, globals) </code></pre>
5
2011-04-13T00:43:54Z
[ "python", "python-3.x" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
16,577,427
<p>According to the documentation, instead of </p> <pre><code>execfile("./filename") </code></pre> <p>Use</p> <pre><code>exec(open("./filename").read()) </code></pre> <p>See:</p> <ul> <li><a href="http://docs.python.org/3.3/whatsnew/3.0.html?highlight=execfile#builtins">What’s New In Python 3.0</a></li> </ul>
113
2013-05-16T01:03:00Z
[ "python", "python-3.x" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
24,261,031
<p>As <a href="https://mail.python.org/pipermail/python-dev/2014-June/134992.html">suggested on the python-dev</a> mailinglist recently, the <a href="https://docs.python.org/3/library/runpy.html">runpy</a> module might be a viable alternative. Quoting from that message:</p> <blockquote> <p><a href="https://docs.python.org/3/library/runpy.html#runpy.run_path">https://docs.python.org/3/library/runpy.html#runpy.run_path</a></p> <pre><code>import runpy file_globals = runpy.run_path("file.py") </code></pre> </blockquote> <p>There are subtle differences to <code>execfile</code>:</p> <ul> <li><p><code>run_path</code> always creates a new namespace. It executes the code as a module, so there is no difference between globals and locals (which is why there is only a <code>init_globals</code> argument). The globals are returned.</p> <p><code>execfile</code> executed in the current namespace or the given namespace. The semantics of <code>locals</code> and <code>globals</code>, if given, were similar to locals and globals inside a class definition.</p></li> <li><p><code>run_path</code> can not only execute files, but also eggs and directories (refer to its documentation for details).</p></li> </ul>
15
2014-06-17T10:06:15Z
[ "python", "python-3.x" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
26,237,387
<p>Here's what I had (<code>file</code> is already assigned to the path to the file with the source code in both examples):</p> <pre><code>execfile(file) </code></pre> <p>Here's what I replaced it with:</p> <pre><code>exec(compile(open(file).read(), file, 'exec')) </code></pre> <p>My favorite part: the second version works just fine in both Python 2 and 3, meaning it's not necessary to add in version dependent logic.</p>
4
2014-10-07T13:39:03Z
[ "python", "python-3.x" ]
What is an alternative to execfile in Python 3.0?
436,198
<p>It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). </p> <p>Is there an obvious alternative I'm missing?</p>
154
2009-01-12T17:23:36Z
28,331,052
<p>locate the route of your folder installation (i have it in C:\python34) then execute on a regular cmd shell</p> <pre><code> set path=%path%;c:\python34 </code></pre> <p>now when you initiaze a shell, move to C:\python34\myscripts and use the classic command</p> <pre><code> python filename.py </code></pre>
0
2015-02-04T20:42:51Z
[ "python", "python-3.x" ]
Python: Is there a way to determine the encoding of text file?
436,220
<p>I know there is something buried in <a href="http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file">here</a>. But I was just wondering if there is an actual way built into Python to determine text file encoding?</p> <p>Thanks for your help :)</p> <p>Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?</p>
97
2009-01-12T17:30:27Z
436,232
<p>It is, in principle, impossible to determine the encoding of a text file, in the general case. So no, there is no standard Python library to do that for you.</p> <p>If you have more specific knowledge about the text file (e.g. that it is XML), there might be library functions.</p>
0
2009-01-12T17:32:27Z
[ "python", "encoding", "text-files" ]
Python: Is there a way to determine the encoding of text file?
436,220
<p>I know there is something buried in <a href="http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file">here</a>. But I was just wondering if there is an actual way built into Python to determine text file encoding?</p> <p>Thanks for your help :)</p> <p>Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?</p>
97
2009-01-12T17:30:27Z
436,259
<p>If you know the some content of the file you can try to decode it with several encoding and see which is missing. In general there is no way since a text file is a text file and those are stupid ;)</p>
0
2009-01-12T17:36:42Z
[ "python", "encoding", "text-files" ]
Python: Is there a way to determine the encoding of text file?
436,220
<p>I know there is something buried in <a href="http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file">here</a>. But I was just wondering if there is an actual way built into Python to determine text file encoding?</p> <p>Thanks for your help :)</p> <p>Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?</p>
97
2009-01-12T17:30:27Z
436,299
<p>Correctly detecting the encoding all times is <strong>impossible</strong>.</p> <p>(From chardet FAQ:)</p> <blockquote> <p>However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn't English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text's language.</p> </blockquote> <p>There is the <a href="http://pypi.python.org/pypi/chardet">chardet</a> library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla. </p> <p>You can also use <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">UnicodeDammit</a>. It will try the following methods:</p> <ul> <li>An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.</li> <li>An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-* encodings, EBCDIC, or ASCII.</li> <li>An encoding sniffed by the <a href="http://pypi.python.org/pypi/chardet">chardet</a> library, if you have it installed.</li> <li>UTF-8</li> <li>Windows-1252 </li> </ul>
100
2009-01-12T17:45:32Z
[ "python", "encoding", "text-files" ]
Python: Is there a way to determine the encoding of text file?
436,220
<p>I know there is something buried in <a href="http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file">here</a>. But I was just wondering if there is an actual way built into Python to determine text file encoding?</p> <p>Thanks for your help :)</p> <p>Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?</p>
97
2009-01-12T17:30:27Z
14,734,061
<p>Some encoding strategies, please uncomment to taste : </p> <pre><code>#!/bin/bash # tmpfile=$1 echo '-- info about file file ........' file -i $tmpfile enca -g $tmpfile echo 'recoding ........' #iconv -f iso-8859-2 -t utf-8 back_test.xml &gt; $tmpfile #enca -x utf-8 $tmpfile #enca -g $tmpfile recode CP1250..UTF-8 $tmpfile </code></pre> <p>You might like to check the encoding by opening and reading the file in a form of a loop... but you might need to check the filesize first :</p> <pre><code>encodings = ['utf-8', 'windows-1250', 'windows-1252' ...etc] for e in encodings: try: fh = codecs.open('file.txt', 'r', encoding=e) fh.readlines() fh.seek(0) except UnicodeDecodeError: print('got unicode error with %s , trying different encoding' % e) else: print('opening the file with encoding: %s ' % e) break </code></pre>
13
2013-02-06T16:32:05Z
[ "python", "encoding", "text-files" ]
Python: Is there a way to determine the encoding of text file?
436,220
<p>I know there is something buried in <a href="http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file">here</a>. But I was just wondering if there is an actual way built into Python to determine text file encoding?</p> <p>Thanks for your help :)</p> <p>Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?</p>
97
2009-01-12T17:30:27Z
16,203,777
<p>Another option for working out the encoding is to use <a href="http://linux.die.net/man/3/libmagic">libmagic</a> (which is the code behind the <a href="http://linux.die.net/man/1/file">file</a> command). There are a profusion of python bindings available.</p> <p>The python bindings that live in the file source tree are available as the <a href="http://packages.debian.org/search?keywords=python-magic&amp;searchon=names&amp;suite=all&amp;section=all">python-magic</a> (or <a href="http://packages.debian.org/search?keywords=python3-magic&amp;searchon=names&amp;suite=all&amp;section=all">python3-magic</a>) debian package. If can determine the encoding of a file by doing:</p> <pre><code>import magic blob = open('unknown-file').read() m = magic.open(magic.MAGIC_MIME_ENCODING) m.load() encoding = m.buffer(blob) # "utf-8" "us-ascii" etc </code></pre> <p>There is an identically named, but incompatible, <a href="https://pypi.python.org/pypi/python-magic">python-magic</a> pip package on pypi that also uses libmagic. It can also get the encoding, by doing:</p> <pre><code>import magic blob = open('unknown-file').read() m = magic.Magic(mime_encoding=True) encoding = m.from_buffer(blob) </code></pre>
22
2013-04-24T23:10:05Z
[ "python", "encoding", "text-files" ]
How do I split email address/password string in two in Python?
436,394
<p>Lets say we have this string: <code>[18] [email protected]:pwd:</code></p> <p><code>[email protected]</code> is the email and <code>pwd</code> is the password.</p> <p>Also, lets say we have this variable with a value</p> <pre><code>f = "[18] [email protected]:pwd:" </code></pre> <p>I would like to know if there is a way to make two other variables named <code>var1</code> and <code>var2</code>, where the <code>var1</code> variable will take the exact email info from variable <code>f</code> and <code>var2</code> the exact password info from <code>var2</code>.</p> <p>The result after running the app should be like:</p> <pre><code>var1 = "[email protected]" </code></pre> <p>and</p> <pre><code>var2 = "pwd" </code></pre>
2
2009-01-12T18:12:29Z
436,412
<pre><code>&gt;&gt;&gt; var1, var2, _ = "[18] [email protected]:pwd:"[5:].split(":") &gt;&gt;&gt; var1, var2 ('[email protected]', 'pwd') </code></pre> <p>Or if the "[18]" is not a fixed prefix:</p> <pre><code>&gt;&gt;&gt; var1, var2, _ = "[18] [email protected]:pwd:".split("] ")[1].split(":") &gt;&gt;&gt; var1, var2 ('[email protected]', 'pwd') </code></pre>
9
2009-01-12T18:15:58Z
[ "python", "parsing", "split" ]
How do I split email address/password string in two in Python?
436,394
<p>Lets say we have this string: <code>[18] [email protected]:pwd:</code></p> <p><code>[email protected]</code> is the email and <code>pwd</code> is the password.</p> <p>Also, lets say we have this variable with a value</p> <pre><code>f = "[18] [email protected]:pwd:" </code></pre> <p>I would like to know if there is a way to make two other variables named <code>var1</code> and <code>var2</code>, where the <code>var1</code> variable will take the exact email info from variable <code>f</code> and <code>var2</code> the exact password info from <code>var2</code>.</p> <p>The result after running the app should be like:</p> <pre><code>var1 = "[email protected]" </code></pre> <p>and</p> <pre><code>var2 = "pwd" </code></pre>
2
2009-01-12T18:12:29Z
436,415
<pre><code>import re var1, var2 = re.findall(r'\s(.*?):(.*):', f)[0] </code></pre> <p>If findall()[0] feels like two steps forward and one back:</p> <pre><code>var1, var2 = re.search(r'\s(.*?):(.*):', f).groups() </code></pre>
7
2009-01-12T18:16:08Z
[ "python", "parsing", "split" ]
How do I split email address/password string in two in Python?
436,394
<p>Lets say we have this string: <code>[18] [email protected]:pwd:</code></p> <p><code>[email protected]</code> is the email and <code>pwd</code> is the password.</p> <p>Also, lets say we have this variable with a value</p> <pre><code>f = "[18] [email protected]:pwd:" </code></pre> <p>I would like to know if there is a way to make two other variables named <code>var1</code> and <code>var2</code>, where the <code>var1</code> variable will take the exact email info from variable <code>f</code> and <code>var2</code> the exact password info from <code>var2</code>.</p> <p>The result after running the app should be like:</p> <pre><code>var1 = "[email protected]" </code></pre> <p>and</p> <pre><code>var2 = "pwd" </code></pre>
2
2009-01-12T18:12:29Z
436,450
<pre><code>var1, var2 = re.split(r'[ :]', f)[1:3] </code></pre>
5
2009-01-12T18:25:37Z
[ "python", "parsing", "split" ]
How do I split email address/password string in two in Python?
436,394
<p>Lets say we have this string: <code>[18] [email protected]:pwd:</code></p> <p><code>[email protected]</code> is the email and <code>pwd</code> is the password.</p> <p>Also, lets say we have this variable with a value</p> <pre><code>f = "[18] [email protected]:pwd:" </code></pre> <p>I would like to know if there is a way to make two other variables named <code>var1</code> and <code>var2</code>, where the <code>var1</code> variable will take the exact email info from variable <code>f</code> and <code>var2</code> the exact password info from <code>var2</code>.</p> <p>The result after running the app should be like:</p> <pre><code>var1 = "[email protected]" </code></pre> <p>and</p> <pre><code>var2 = "pwd" </code></pre>
2
2009-01-12T18:12:29Z
442,940
<p>To split on the first colon ":", you can do:</p> <pre><code># keep all after last space f1= f.rpartition(" ")[2] var1, _, var2= f1.partition(":") </code></pre>
1
2009-01-14T13:30:00Z
[ "python", "parsing", "split" ]
pyPdf for IndirectObject extraction
436,474
<p>Following this example, I can list all elements into a pdf file</p> <pre><code>import pyPdf pdf = pyPdf.PdfFileReader(open("pdffile.pdf")) list(pdf.pages) # Process all the objects. print pdf.resolvedObjects </code></pre> <p>now, I need to extract a non-standard object from the pdf file. </p> <p>My object is the one named MYOBJECT and it is a string.</p> <p>The piece printed by the python script that concernes me is:</p> <pre><code>{'/MYOBJECT': IndirectObject(584, 0)} </code></pre> <p>The pdf file is this:</p> <pre><code>558 0 obj &lt;&lt;/Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 R/Resources &lt;&lt;/ColorSpace &lt;&lt;/CS0 563 0 R&gt;&gt; /ExtGState &lt;&lt;/GS0 568 0 R&gt;&gt; /Font&lt;&lt;/TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R&gt;&gt; /ProcSet[/PDF/Text/ImageC] /Properties&lt;&lt;/MC0&lt;&lt;/MYOBJECT 584 0 R&gt;&gt;/MC1&lt;&lt;/SubKey 582 0 R&gt;&gt; &gt;&gt; /XObject&lt;&lt;/Im0 578 0 R&gt;&gt;&gt;&gt; /Rotate 0/StructParents 0/Type/Page&gt;&gt; endobj ... ... ... 584 0 obj &lt;&lt;/Length 8&gt;&gt;stream 1_22_4_1 ---&gt;&gt;&gt;&gt; this is the string I need to extract from the object endstream endobj </code></pre> <p>How can I follow the <code>584</code> value in order to refer to my string (under pyPdf of course)??</p>
6
2009-01-12T18:31:52Z
441,747
<p>each element in <code>pdf.pages</code> is a dictionary, so assuming it's on page 1, <code>pdf.pages[0]['/MYOBJECT']</code> should be the element you want. </p> <p>You can try to print that individually or poke at it with <code>help</code> and <code>dir</code> in a python prompt for more about how to get the string you want</p> <p>Edit:</p> <p>after receiving a copy of the pdf, i found the object at <code>pdf.resolvedObjects[0][558]['/Resources']['/Properties']['/MC0']['/MYOBJECT']</code> and the value can be retrieved via getData()</p> <p>the following function gives a more generic way to solve this by recursively looking for the key in question</p> <pre><code>import types import pyPdf pdf = pyPdf.PdfFileReader(open('file.pdf')) pages = list(pdf.pages) def findInDict(needle,haystack): for key in haystack.keys(): try: value = haystack[key] except: continue if key == needle: return value if type(value) == types.DictType or isinstance(value,pyPdf.generic.DictionaryObject): x = findInDict(needle,value) if x is not None: return x answer = findInDict('/MYOBJECT',pdf.resolvedObjects).getData() </code></pre>
8
2009-01-14T02:46:14Z
[ "python", "pdf", "stream", "pypdf" ]
pyPdf for IndirectObject extraction
436,474
<p>Following this example, I can list all elements into a pdf file</p> <pre><code>import pyPdf pdf = pyPdf.PdfFileReader(open("pdffile.pdf")) list(pdf.pages) # Process all the objects. print pdf.resolvedObjects </code></pre> <p>now, I need to extract a non-standard object from the pdf file. </p> <p>My object is the one named MYOBJECT and it is a string.</p> <p>The piece printed by the python script that concernes me is:</p> <pre><code>{'/MYOBJECT': IndirectObject(584, 0)} </code></pre> <p>The pdf file is this:</p> <pre><code>558 0 obj &lt;&lt;/Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 R/Resources &lt;&lt;/ColorSpace &lt;&lt;/CS0 563 0 R&gt;&gt; /ExtGState &lt;&lt;/GS0 568 0 R&gt;&gt; /Font&lt;&lt;/TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R&gt;&gt; /ProcSet[/PDF/Text/ImageC] /Properties&lt;&lt;/MC0&lt;&lt;/MYOBJECT 584 0 R&gt;&gt;/MC1&lt;&lt;/SubKey 582 0 R&gt;&gt; &gt;&gt; /XObject&lt;&lt;/Im0 578 0 R&gt;&gt;&gt;&gt; /Rotate 0/StructParents 0/Type/Page&gt;&gt; endobj ... ... ... 584 0 obj &lt;&lt;/Length 8&gt;&gt;stream 1_22_4_1 ---&gt;&gt;&gt;&gt; this is the string I need to extract from the object endstream endobj </code></pre> <p>How can I follow the <code>584</code> value in order to refer to my string (under pyPdf of course)??</p>
6
2009-01-12T18:31:52Z
442,401
<p>An IndirectObject refers to an actual object (it's like a link or alias so that the total size of the PDF can be reduced when the same content appears in multiple places). The getObject method will give you the actual object.</p> <p>If the object is a text object, then just doing a str() or unicode() on the object should get you the data inside of it.</p> <p>Alternatively, pyPdf stores the objects in the resolvedObjects attribute. For example, a PDF that contains this object:</p> <pre><code>13 0 obj &lt;&lt; /Type /Catalog /Pages 3 0 R &gt;&gt; endobj </code></pre> <p>Can be read with this:</p> <pre><code>&gt;&gt;&gt; import pyPdf &gt;&gt;&gt; pdf = pyPdf.PdfFileReader(open("pdffile.pdf")) &gt;&gt;&gt; pages = list(pdf.pages) &gt;&gt;&gt; pdf.resolvedObjects {0: {2: {'/Parent': IndirectObject(3, 0), '/Contents': IndirectObject(4, 0), '/Type': '/Page', '/Resources': IndirectObject(6, 0), '/MediaBox': [0, 0, 595.2756, 841.8898]}, 3: {'/Kids': [IndirectObject(2, 0)], '/Count': 1, '/Type': '/Pages', '/MediaBox': [0, 0, 595.2756, 841.8898]}, 4: {'/Filter': '/FlateDecode'}, 5: 147, 6: {'/ColorSpace': {'/Cs1': IndirectObject(7, 0)}, '/ExtGState': {'/Gs2': IndirectObject(9, 0), '/Gs1': IndirectObject(10, 0)}, '/ProcSet': ['/PDF', '/Text'], '/Font': {'/F1.0': IndirectObject(8, 0)}}, 13: {'/Type': '/Catalog', '/Pages': IndirectObject(3, 0)}}} &gt;&gt;&gt; pdf.resolvedObjects[0][13] {'/Type': '/Catalog', '/Pages': IndirectObject(3, 0)} </code></pre>
3
2009-01-14T09:32:55Z
[ "python", "pdf", "stream", "pypdf" ]
pyPdf for IndirectObject extraction
436,474
<p>Following this example, I can list all elements into a pdf file</p> <pre><code>import pyPdf pdf = pyPdf.PdfFileReader(open("pdffile.pdf")) list(pdf.pages) # Process all the objects. print pdf.resolvedObjects </code></pre> <p>now, I need to extract a non-standard object from the pdf file. </p> <p>My object is the one named MYOBJECT and it is a string.</p> <p>The piece printed by the python script that concernes me is:</p> <pre><code>{'/MYOBJECT': IndirectObject(584, 0)} </code></pre> <p>The pdf file is this:</p> <pre><code>558 0 obj &lt;&lt;/Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 R/Resources &lt;&lt;/ColorSpace &lt;&lt;/CS0 563 0 R&gt;&gt; /ExtGState &lt;&lt;/GS0 568 0 R&gt;&gt; /Font&lt;&lt;/TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R&gt;&gt; /ProcSet[/PDF/Text/ImageC] /Properties&lt;&lt;/MC0&lt;&lt;/MYOBJECT 584 0 R&gt;&gt;/MC1&lt;&lt;/SubKey 582 0 R&gt;&gt; &gt;&gt; /XObject&lt;&lt;/Im0 578 0 R&gt;&gt;&gt;&gt; /Rotate 0/StructParents 0/Type/Page&gt;&gt; endobj ... ... ... 584 0 obj &lt;&lt;/Length 8&gt;&gt;stream 1_22_4_1 ---&gt;&gt;&gt;&gt; this is the string I need to extract from the object endstream endobj </code></pre> <p>How can I follow the <code>584</code> value in order to refer to my string (under pyPdf of course)??</p>
6
2009-01-12T18:31:52Z
445,201
<p>Jehiah's method is good if looking everywhere for the object. My guess (looking at the PDF) is that it is always in the same place (the first page, in the 'MC0' property), and so a much simpler method of finding the string would be:</p> <pre><code>import pyPdf pdf = pyPdf.PdfFileReader(open("file.pdf")) pdf.getPage(0)['/Resources']['/Properties']['/MC0']['/MYOBJECT'].getData() </code></pre>
1
2009-01-15T00:25:07Z
[ "python", "pdf", "stream", "pypdf" ]
Python: import the containing package
436,497
<p>In a module residing inside a package, i have the need to use a function defined within the <code>__init__.py</code> of that package. how can i import the package within the module that resides within the package, so i can use that function?</p> <p>Importing <code>__init__</code> inside the module will not import the package, but instead a module named <code>__init__</code>, leading to two copies of things with different names...</p> <p>Is there a pythonic way to do this?</p>
50
2009-01-12T18:38:15Z
436,511
<p>This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the <code>__init__.py</code> file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the <code>__init__.py</code> file that will import that function (when the package is imported) as well.</p>
20
2009-01-12T18:40:53Z
[ "python", "module", "package", "python-import" ]
Python: import the containing package
436,497
<p>In a module residing inside a package, i have the need to use a function defined within the <code>__init__.py</code> of that package. how can i import the package within the module that resides within the package, so i can use that function?</p> <p>Importing <code>__init__</code> inside the module will not import the package, but instead a module named <code>__init__</code>, leading to two copies of things with different names...</p> <p>Is there a pythonic way to do this?</p>
50
2009-01-12T18:38:15Z
436,607
<p>If the package is named <code>testmod</code> and your init file is therefore <code>testmod/__init__.py</code> and your module within the package is <code>submod.py</code> then from within <code>submod.py</code> file, you should just be able to say <code>import testmod</code> and use whatever you want that's defined in testmod.</p>
5
2009-01-12T19:13:51Z
[ "python", "module", "package", "python-import" ]
Python: import the containing package
436,497
<p>In a module residing inside a package, i have the need to use a function defined within the <code>__init__.py</code> of that package. how can i import the package within the module that resides within the package, so i can use that function?</p> <p>Importing <code>__init__</code> inside the module will not import the package, but instead a module named <code>__init__</code>, leading to two copies of things with different names...</p> <p>Is there a pythonic way to do this?</p>
50
2009-01-12T18:38:15Z
436,662
<p>I'm not totally sure what the situation is, but this may solve your "different name" problem:</p> <pre><code>import __init__ as top top.some_function() </code></pre> <p>Or maybe?:</p> <pre><code>from __init__ import some_function some_function() </code></pre>
0
2009-01-12T19:26:02Z
[ "python", "module", "package", "python-import" ]
Python: import the containing package
436,497
<p>In a module residing inside a package, i have the need to use a function defined within the <code>__init__.py</code> of that package. how can i import the package within the module that resides within the package, so i can use that function?</p> <p>Importing <code>__init__</code> inside the module will not import the package, but instead a module named <code>__init__</code>, leading to two copies of things with different names...</p> <p>Is there a pythonic way to do this?</p>
50
2009-01-12T18:38:15Z
436,768
<p>Also, starting in Python 2.5, relative imports are possible. e.g.:</p> <pre><code>from . import foo </code></pre> <p>Quoting from <a href="http://docs.python.org/tutorial/modules.html#intra-package-references" rel="nofollow">http://docs.python.org/tutorial/modules.html#intra-package-references</a>:</p> <hr> <p>Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surrounding module for example, you might use:</p> <pre><code>from . import echo from .. import formats from ..filters import equalizer </code></pre>
39
2009-01-12T19:52:19Z
[ "python", "module", "package", "python-import" ]
Python: import the containing package
436,497
<p>In a module residing inside a package, i have the need to use a function defined within the <code>__init__.py</code> of that package. how can i import the package within the module that resides within the package, so i can use that function?</p> <p>Importing <code>__init__</code> inside the module will not import the package, but instead a module named <code>__init__</code>, leading to two copies of things with different names...</p> <p>Is there a pythonic way to do this?</p>
50
2009-01-12T18:38:15Z
708,076
<p>In Django, the file manage.py has <code>from django.core.management import execute_manager</code>, but <code>execute_manager</code> is not a module. It is a function within the <code>__init__.py</code> module of the <code>management</code> directory.</p>
1
2009-04-02T02:30:46Z
[ "python", "module", "package", "python-import" ]
Python Split String
436,599
<p>Lets Say we have <code>Zaptoit:685158:[email protected]</code> </p> <p>How do you split so it only be left <code>685158:[email protected]</code></p>
12
2009-01-12T19:10:57Z
436,613
<p>Another solution:</p> <pre><code>s = 'Zaptoit:685158:[email protected]' s.split(':', 1)[1] </code></pre>
5
2009-01-12T19:15:09Z
[ "python", "regex", "parsing", "split" ]
Python Split String
436,599
<p>Lets Say we have <code>Zaptoit:685158:[email protected]</code> </p> <p>How do you split so it only be left <code>685158:[email protected]</code></p>
12
2009-01-12T19:10:57Z
436,614
<pre><code>&gt;&gt;&gt; s = 'Zaptoit:685158:[email protected]' &gt;&gt;&gt; s.split( ':', 1 )[1] '685158:[email protected]' </code></pre>
13
2009-01-12T19:15:09Z
[ "python", "regex", "parsing", "split" ]
Python Split String
436,599
<p>Lets Say we have <code>Zaptoit:685158:[email protected]</code> </p> <p>How do you split so it only be left <code>685158:[email protected]</code></p>
12
2009-01-12T19:10:57Z
436,794
<pre><code>s = re.sub('^.*?:', '', s) </code></pre>
0
2009-01-12T19:58:45Z
[ "python", "regex", "parsing", "split" ]
Python Split String
436,599
<p>Lets Say we have <code>Zaptoit:685158:[email protected]</code> </p> <p>How do you split so it only be left <code>685158:[email protected]</code></p>
12
2009-01-12T19:10:57Z
436,799
<p>Another method, without using split: </p> <pre><code>s = 'Zaptoit:685158:[email protected]' s[s.find(':')+1:] </code></pre> <p>Ex:</p> <pre><code>&gt;&gt;&gt; s = 'Zaptoit:685158:[email protected]' &gt;&gt;&gt; s[s.find(':')+1:] '685158:[email protected]' </code></pre>
4
2009-01-12T19:59:47Z
[ "python", "regex", "parsing", "split" ]
Python Split String
436,599
<p>Lets Say we have <code>Zaptoit:685158:[email protected]</code> </p> <p>How do you split so it only be left <code>685158:[email protected]</code></p>
12
2009-01-12T19:10:57Z
8,793,066
<p>As of Python 2.5 there is an even more direct solution. It degrades nicely if the separator is not found:</p> <pre><code>&gt;&gt;&gt; s = 'Zaptoit:685158:[email protected]' &gt;&gt;&gt; s.partition(':') ('Zaptoit', ':', '685158:[email protected]') &gt;&gt;&gt; s.partition(':')[2] '685158:[email protected]' &gt;&gt;&gt; s.partition(';') ('Zaptoit:685158:[email protected]', '', '') </code></pre>
1
2012-01-09T18:07:31Z
[ "python", "regex", "parsing", "split" ]
Python Split String
436,599
<p>Lets Say we have <code>Zaptoit:685158:[email protected]</code> </p> <p>How do you split so it only be left <code>685158:[email protected]</code></p>
12
2009-01-12T19:10:57Z
8,803,444
<p>Use the method str.split() with the value of maxsplit argument as 1.</p> <pre><code>mailID = 'Zaptoit:685158:[email protected]' mailID.split(':', 1)[1] </code></pre> <p>Hope it helped.</p>
0
2012-01-10T12:41:59Z
[ "python", "regex", "parsing", "split" ]
What should "value_from_datadict" method of a custom form widget return?
436,944
<p>I'm trying to build my own custom django form widgets (putting them in widgets.py of my project directory). What should the value "value_from_datadict()" return? Is it returning a string or the actual expected value of the field?</p> <p>I'm building my own version of a split date/time widget using JQuery objects, what should each part of the widget return? Should the date widget return a datetime and the time widget return a datetime? What glue code merges the two values together?</p>
3
2009-01-12T20:40:11Z
437,354
<p>For <code>value_from_datadict()</code> you want to return the value you expect or None. The source in <a href="https://github.com/django/django/blob/master/django/forms/widgets.py" rel="nofollow">django/forms/widgets.py</a> provides some examples.</p> <p>But you should be able to build a DatePicker widget by just providing a <code>render</code> method:</p> <pre><code>DATE_FORMAT = '%m/%d/%y' class DatePickerWidget(widgets.Widget): def render(self, name, value, attrs=None): if value is None: vstr = '' elif hasattr(value, 'strftime'): vstr = datetime_safe.new_datetime(value).strftime(DATE_FORMAT) else: vstr = value id = "id_%s" % name args = [ "&lt;input type=\"text\" value=\"%s\" name=\"%s\" id=\"%s\" /&gt;" % \ (vstr, name, id), "&lt;script type=\"text/javascript\"&gt;$(\"#%s\").datepicker({dateFormat:'mm/dd/y'});&lt;/script&gt;" % id ] return mark_safe("\n".join(args)) </code></pre>
5
2009-01-12T22:56:34Z
[ "python", "django", "django-forms" ]
What should "value_from_datadict" method of a custom form widget return?
436,944
<p>I'm trying to build my own custom django form widgets (putting them in widgets.py of my project directory). What should the value "value_from_datadict()" return? Is it returning a string or the actual expected value of the field?</p> <p>I'm building my own version of a split date/time widget using JQuery objects, what should each part of the widget return? Should the date widget return a datetime and the time widget return a datetime? What glue code merges the two values together?</p>
3
2009-01-12T20:40:11Z
437,360
<p>The Django source says </p> <blockquote> <p>Given a dictionary of data and this widget's name, returns the value of this widget. Returns None if it's not provided.</p> </blockquote> <p>Reading the code, I see that Django's separate Date and Time widgets are both subclasses of Input, subclasses of Widget, which appears to work with simple Strings.</p>
0
2009-01-12T22:58:27Z
[ "python", "django", "django-forms" ]
How to implement a python REPL that nicely handles asynchronous output?
437,025
<p>I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using <code>raw_input('&gt; ')</code> to get the input. On Unix-based systems, I also <code>import readline</code> to make things behave a little better. All this is working fine.</p> <p>The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something.</p> <p>This seems like it must be a solved problem. What's the proper way to do this?</p> <p>Also note that some of my users are Windows-based.</p> <p>TIA</p> <p>Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated!</p>
12
2009-01-12T21:11:44Z
437,088
<p>Maybe something like this will do the trick:</p> <pre><code>#!/usr/bin/env python2.6 from __future__ import print_function import readline import threading PROMPT = '&gt; ' def interrupt(): print() # Don't want to end up on the same line the user is typing on. print('Interrupting cow -- moo!') print(PROMPT, readline.get_line_buffer(), sep='', end='') def cli(): while True: cli = str(raw_input(PROMPT)) if __name__ == '__main__': threading.Thread(target=cli).start() threading.Timer(2, interrupt).start() </code></pre> <p>I don't think that stdin is thread-safe, so you can end up losing characters to the interrupting thread (that the user will have to retype at the end of the <code>interrupt</code>). I exaggerated the amount of <code>interrupt</code> time with the <code>time.sleep</code> call. The <code>readline.get_line_buffer</code> call won't display the characters that get lost, so it all turns out alright.</p> <p>Note that stdout itself isn't thread safe, so if you've got multiple interrupting threads of execution, this can still end up looking gross.</p>
8
2009-01-12T21:33:20Z
[ "python", "readline", "read-eval-print-loop" ]
How to implement a python REPL that nicely handles asynchronous output?
437,025
<p>I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using <code>raw_input('&gt; ')</code> to get the input. On Unix-based systems, I also <code>import readline</code> to make things behave a little better. All this is working fine.</p> <p>The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something.</p> <p>This seems like it must be a solved problem. What's the proper way to do this?</p> <p>Also note that some of my users are Windows-based.</p> <p>TIA</p> <p>Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated!</p>
12
2009-01-12T21:11:44Z
437,377
<p>It's kind of a non-answer, but I would look at <a href="http://ipython.scipy.org/moin/" rel="nofollow">IPython</a>'s code to see how they're doing it.</p>
-1
2009-01-12T23:04:43Z
[ "python", "readline", "read-eval-print-loop" ]
How to implement a python REPL that nicely handles asynchronous output?
437,025
<p>I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using <code>raw_input('&gt; ')</code> to get the input. On Unix-based systems, I also <code>import readline</code> to make things behave a little better. All this is working fine.</p> <p>The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something.</p> <p>This seems like it must be a solved problem. What's the proper way to do this?</p> <p>Also note that some of my users are Windows-based.</p> <p>TIA</p> <p>Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated!</p>
12
2009-01-12T21:11:44Z
439,403
<p>I think you have 2 basic options:</p> <ol> <li>Synchronize your output (i.e. block until it comes back)</li> <li>Separate your input and your (asyncronous) output, perhaps in two separate columns.</li> </ol>
-1
2009-01-13T15:36:14Z
[ "python", "readline", "read-eval-print-loop" ]
How to implement a python REPL that nicely handles asynchronous output?
437,025
<p>I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using <code>raw_input('&gt; ')</code> to get the input. On Unix-based systems, I also <code>import readline</code> to make things behave a little better. All this is working fine.</p> <p>The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something.</p> <p>This seems like it must be a solved problem. What's the proper way to do this?</p> <p>Also note that some of my users are Windows-based.</p> <p>TIA</p> <p>Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated!</p>
12
2009-01-12T21:11:44Z
440,917
<p>Why are you writing your own REPL using <code>raw_input()</code>? Have you looked at the <code>cmd.Cmd</code> class? <strong>Edit:</strong> I just found the <a href="http://www.alittletooquiet.net/software/sclapp/" rel="nofollow">sclapp</a> library, which may also be useful.</p> <p>Note: the <code>cmd.Cmd</code> class (and sclapp) may or may not directly support your original goal; you may have to subclass it and modify it as needed to provide that feature.</p>
4
2009-01-13T21:44:41Z
[ "python", "readline", "read-eval-print-loop" ]
How to implement a python REPL that nicely handles asynchronous output?
437,025
<p>I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using <code>raw_input('&gt; ')</code> to get the input. On Unix-based systems, I also <code>import readline</code> to make things behave a little better. All this is working fine.</p> <p>The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something.</p> <p>This seems like it must be a solved problem. What's the proper way to do this?</p> <p>Also note that some of my users are Windows-based.</p> <p>TIA</p> <p>Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated!</p>
12
2009-01-12T21:11:44Z
4,394,267
<p>look into the code module, it lets you create objects for interpreting python code also (shameless plug) <a href="https://github.com/iridium172/PyTerm" rel="nofollow">https://github.com/iridium172/PyTerm</a> lets you create interactive command line programs that handle raw keyboard input (like ^C will raise a KeyboardInterrupt).</p>
0
2010-12-09T02:15:57Z
[ "python", "readline", "read-eval-print-loop" ]
How to implement a python REPL that nicely handles asynchronous output?
437,025
<p>I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using <code>raw_input('&gt; ')</code> to get the input. On Unix-based systems, I also <code>import readline</code> to make things behave a little better. All this is working fine.</p> <p>The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something.</p> <p>This seems like it must be a solved problem. What's the proper way to do this?</p> <p>Also note that some of my users are Windows-based.</p> <p>TIA</p> <p>Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated!</p>
12
2009-01-12T21:11:44Z
4,508,465
<p>run this:</p> <pre><code>python -m twisted.conch.stdio </code></pre> <p>You'll get a nice, colored, async REPL, <strong>without using threads</strong>. While you type in the prompt, the event loop is running.</p>
2
2010-12-22T10:57:43Z
[ "python", "readline", "read-eval-print-loop" ]
IronPython Webframework
437,160
<p>There seem to be many excellent web frameworks for Python. Has anyone used any of these (Pylons, Web2Py, Django) with IronPython?</p>
16
2009-01-12T21:57:38Z
437,368
<p>Django <a href="http://unbracketed.org/2008/mar/16/pycon-2008-django-now-plays-dark-side/">has been run on IronPython</a> before, but as a proof-of-concept. I know the IronPython team are interested in Django support as a metric for Python-compatibility.</p> <p>Somewhat related is the possibility to use <a href="http://haacked.com/archive/2008/09/23/refreshing-asp.net-dynamic-language-support.aspx">IronPython with ASP.NET and ASP.NET MVC</a>, which is probably more mature.</p>
6
2009-01-12T23:01:16Z
[ "python", "ironpython" ]
IronPython Webframework
437,160
<p>There seem to be many excellent web frameworks for Python. Has anyone used any of these (Pylons, Web2Py, Django) with IronPython?</p>
16
2009-01-12T21:57:38Z
478,994
<p>You may want to read <a href="http://groups.google.com/group/web2py/browse_thread/thread/857f9d7bc5c25822/278c5a8e209c83e5?lnk=gst&amp;q=ironpython#278c5a8e209c83e5">this</a></p> <p>Basically web2py code runs unmodified and out of the box but with IronPython but</p> <ul> <li>no CSV module (so no database IO)</li> <li>no third party database drivers (not even SQLite, so no databases at all)</li> <li>no built-in web server (unless you cripple it by removing signals and logging)</li> </ul> <p>This is because csv, signals, logging and sqlite are not present in IronPython. An you can see from the thread above there is work underway to find ways around.</p> <p>web2py also runs unmodified on Jython 2.5 beta, without any known limitation, except for a bug with regular expressions in Jython that makes it choke on some templates (re.compile(...).finditer goes in a loop). We are working to find a way around for this as well.</p>
6
2009-01-26T06:42:02Z
[ "python", "ironpython" ]
IronPython Webframework
437,160
<p>There seem to be many excellent web frameworks for Python. Has anyone used any of these (Pylons, Web2Py, Django) with IronPython?</p>
16
2009-01-12T21:57:38Z
1,923,258
<p>we2py released Feb 5, 2009 </p> <p><a href="http://www.web2py.com" rel="nofollow">http://www.web2py.com</a> </p> <ul> <li>Includes a Database Abstraction Layer that works with SQLite, MySQL,<br> PostgreSQL, FireBird, MSSQL, Oracle, AND the Google App Engine. </li> </ul>
-3
2009-12-17T17:19:52Z
[ "python", "ironpython" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
437,251
<p>I haven't tried it in django but python's <a href="http://docs.python.org/library/copy.html">deepcopy</a> might just work for you</p> <p><b>EDIT:</b></p> <p>You can define custom copy behavior for your models if you implement functions:</p> <pre><code>__copy__() and __deepcopy__() </code></pre>
9
2009-01-12T22:24:51Z
[ "python", "django", "django-models", "duplicates" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
437,427
<p>I think you'd be happier with a simpler data model, also.</p> <p>Is it really true that a Page is in some Chapter but a different book?</p> <pre><code>userMe = User( username="me" ) userYou= User( username="you" ) bookMyA = Book( userMe ) bookYourB = Book( userYou ) chapterA1 = Chapter( book= bookMyA, author=userYou ) # "me" owns the Book, "you" owns the chapter? chapterB2 = Chapter( book= bookYourB, author=userMe ) # "you" owns the book, "me" owns the chapter? page1 = Page( book= bookMyA, chapter= chapterB2, author=userMe ) # Book and Author aggree, chapter doesn't? </code></pre> <p>It seems like your model is too complex.</p> <p>I think you'd be happier with something simpler. I'm just guessing at this, since I don't your know entire problem.</p> <pre><code>class Book(models.Model) name = models.CharField(...) class Chapter(models.Model) name = models.CharField(...) book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') chapter = models.ForeignKey(Chapter) </code></pre> <p>Each page has distinct authorship. Each chapter, then, has a collection of authors, as does the book. Now you can duplicate Book, Chapter and Pages, assigning the cloned Pages to the new Author.</p> <p>Indeed, you might want to have a many-to-many relationship between Page and Chapter, allowing you to have multiple copies of just the Page, without cloning book and Chapter.</p>
1
2009-01-12T23:19:07Z
[ "python", "django", "django-models", "duplicates" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
441,453
<p>This no longer works in Django 1.3 as CollectedObjects was removed. See <a href="http://code.djangoproject.com/changeset/14507">changeset 14507</a></p> <p><a href="http://www.djangosnippets.org/snippets/1282/">I posted my solution on Django Snippets.</a> It's based heavily on the <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/query.py#L33"><code>django.db.models.query.CollectedObject</code></a> code used for deleting objects:</p> <pre><code>from django.db.models.query import CollectedObjects from django.db.models.fields.related import ForeignKey def duplicate(obj, value, field): """ Duplicate all related objects of `obj` setting `field` to `value`. If one of the duplicate objects has an FK to another duplicate object update that as well. Return the duplicate copy of `obj`. """ collected_objs = CollectedObjects() obj._collect_sub_objects(collected_objs) related_models = collected_objs.keys() root_obj = None # Traverse the related models in reverse deletion order. for model in reversed(related_models): # Find all FKs on `model` that point to a `related_model`. fks = [] for f in model._meta.fields: if isinstance(f, ForeignKey) and f.rel.to in related_models: fks.append(f) # Replace each `sub_obj` with a duplicate. sub_obj = collected_objs[model] for pk_val, obj in sub_obj.iteritems(): for fk in fks: fk_value = getattr(obj, "%s_id" % fk.name) # If this FK has been duplicated then point to the duplicate. if fk_value in collected_objs[fk.rel.to]: dupe_obj = collected_objs[fk.rel.to][fk_value] setattr(obj, fk.name, dupe_obj) # Duplicate the object and save it. obj.id = None setattr(obj, field, value) obj.save() if root_obj is None: root_obj = obj return root_obj </code></pre>
12
2009-01-14T00:28:16Z
[ "python", "django", "django-models", "duplicates" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
3,093,526
<p>If there's just a couple copies in the database you're building, I've found you can just use the back button in the admin interface, change the necessary fields and save the instance again. This has worked for me in cases where, for instance, I need to build a "gimlet" and a "vodka gimlet" cocktail where the only difference is replacing the name and an ingredient. Obviously, this requires a little foresight of the data and isn't as powerful as overriding django's copy/deepcopy - but it may do the trick for some.</p>
3
2010-06-22T13:28:48Z
[ "python", "django", "django-models", "duplicates" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
3,120,410
<p>Here's an easy way to copy your object.</p> <p>Basically:</p> <p>(1) set the id of your original object to None:</p> <p>book_to_copy.id = None</p> <p>(2) change the 'author' attribute and save the ojbect:</p> <p>book_to_copy.author = new_author</p> <p>book_to_copy.save()</p> <p>(3) INSERT performed instead of UPDATE</p> <p>(It doesn't address changing the author in the Page--I agree with the comments regarding re-structuring the models)</p>
9
2010-06-25T18:20:17Z
[ "python", "django", "django-models", "duplicates" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
6,064,096
<p>this is an edit of <a href="http://www.djangosnippets.org/snippets/1282/">http://www.djangosnippets.org/snippets/1282/</a></p> <p>It's now compatible with the Collector which replaced CollectedObjects in 1.3.</p> <p>I didn't really test this too heavily, but did test it with an object with about 20,000 sub-objects, but in only about three layers of foreign-key depth. Use at your own risk of course.</p> <p>For the ambitious guy who reads this post, you should consider subclassing Collector (or copying the entire class to remove this dependency on this unpublished section of the django API) to a class called something like "DuplicateCollector" and writing a .duplicate method that works similarly to the .delete method. that would solve this problem in a real way.</p> <pre><code>from django.db.models.deletion import Collector from django.db.models.fields.related import ForeignKey def duplicate(obj, value=None, field=None, duplicate_order=None): """ Duplicate all related objects of obj setting field to value. If one of the duplicate objects has an FK to another duplicate object update that as well. Return the duplicate copy of obj. duplicate_order is a list of models which specify how the duplicate objects are saved. For complex objects this can matter. Check to save if objects are being saved correctly and if not just pass in related objects in the order that they should be saved. """ collector = Collector({}) collector.collect([obj]) collector.sort() related_models = collector.data.keys() data_snapshot = {} for key in collector.data.keys(): data_snapshot.update({ key: dict(zip([item.pk for item in collector.data[key]], [item for item in collector.data[key]])) }) root_obj = None # Sometimes it's good enough just to save in reverse deletion order. if duplicate_order is None: duplicate_order = reversed(related_models) for model in duplicate_order: # Find all FKs on model that point to a related_model. fks = [] for f in model._meta.fields: if isinstance(f, ForeignKey) and f.rel.to in related_models: fks.append(f) # Replace each `sub_obj` with a duplicate. if model not in collector.data: continue sub_objects = collector.data[model] for obj in sub_objects: for fk in fks: fk_value = getattr(obj, "%s_id" % fk.name) # If this FK has been duplicated then point to the duplicate. fk_rel_to = data_snapshot[fk.rel.to] if fk_value in fk_rel_to: dupe_obj = fk_rel_to[fk_value] setattr(obj, fk.name, dupe_obj) # Duplicate the object and save it. obj.id = None if field is not None: setattr(obj, field, value) obj.save() if root_obj is None: root_obj = obj return root_obj </code></pre> <p>EDIT: Removed a debugging "print" statement.</p>
6
2011-05-19T19:51:02Z
[ "python", "django", "django-models", "duplicates" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
10,307,241
<p>Django does have a built-in way to duplicate an object via the admin - as answered here: <a href="http://stackoverflow.com/questions/180809/in-the-django-admin-interface-is-there-a-way-to-duplicate-an-item">In the Django admin interface, is there a way to duplicate an item?</a></p>
3
2012-04-24T23:06:54Z
[ "python", "django", "django-models", "duplicates" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
16,700,100
<p>In Django 1.5 this works for me:</p> <pre><code>thing.id = None thing.pk = None thing.save() </code></pre>
1
2013-05-22T19:28:37Z
[ "python", "django", "django-models", "duplicates" ]
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
<p>I've models for <code>Books</code>, <code>Chapters</code> and <code>Pages</code>. They are all written by a <code>User</code>:</p> <pre><code>from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) </code></pre> <p>What I'd like to do is duplicate an existing <code>Book</code> and update it's <code>User</code> to someone else. The wrinkle is I would also like to duplicate all related model instances to the <code>Book</code> - all it's <code>Chapters</code> and <code>Pages</code> as well!</p> <p>Things get really tricky when look at a <code>Page</code> - not only will the new <code>Pages</code> need to have their <code>author</code> field updated but they will also need to point to the new <code>Chapter</code> objects!</p> <p>Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?</p> <p>Cheers,</p> <p>John</p> <p><hr /></p> <p>Update:</p> <p>The classes given above are just an example to illustrate the problem I'm having!</p>
26
2009-01-12T21:58:55Z
34,959,368
<p>Using the CollectedObjects snippet above no longer works but can be done with the following modification:</p> <pre><code>from django.contrib.admin.util import NestedObjects from django.db import DEFAULT_DB_ALIAS </code></pre> <p>and </p> <pre><code>collector = NestedObjects(using=DEFAULT_DB_ALIAS) </code></pre> <p>instead of CollectorObjects</p>
2
2016-01-23T03:46:12Z
[ "python", "django", "django-models", "duplicates" ]
Safe escape function for terminal output
437,476
<p>I'm looking for the equivalent of a <a href="http://docs.python.org/library/urllib.html#urllib.quote_plus" rel="nofollow">urlencode</a> for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal.</p> <p>I'm working in Python, but anything I can readily translate works too. TIA!</p>
1
2009-01-12T23:33:46Z
437,497
<p>You could pipe it through strings</p> <pre><code>./command | strings </code></pre> <p>This will strip out the non string characters</p>
-1
2009-01-12T23:40:17Z
[ "python", "terminal", "escaping" ]
Safe escape function for terminal output
437,476
<p>I'm looking for the equivalent of a <a href="http://docs.python.org/library/urllib.html#urllib.quote_plus" rel="nofollow">urlencode</a> for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal.</p> <p>I'm working in Python, but anything I can readily translate works too. TIA!</p>
1
2009-01-12T23:33:46Z
437,514
<p>Unfortunately "terminal output" is a very poorly defined criterion for filtering (see <a href="http://stackoverflow.com/questions/418176/why-does-pythons-string-printable-contains-unprintable-characters">question 418176</a>). I would suggest simply whitelisting the characters that you want to allow (which would be most of string.printable), and replacing all others with whatever escaped format you like (\FF, %FF, etc), or even simply stripping them out.</p>
3
2009-01-12T23:49:53Z
[ "python", "terminal", "escaping" ]
Safe escape function for terminal output
437,476
<p>I'm looking for the equivalent of a <a href="http://docs.python.org/library/urllib.html#urllib.quote_plus" rel="nofollow">urlencode</a> for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal.</p> <p>I'm working in Python, but anything I can readily translate works too. TIA!</p>
1
2009-01-12T23:33:46Z
437,542
<pre> $ ./command | cat -v $ cat --help | grep nonprinting -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB </pre> <p>Here's the same in py3k based on <a href="http://www.google.com/codesearch/p?hl=en#2wSbThBwwIw/toolbox/cat.c&amp;q=file:%5Cbcat.c&amp;l=-1" rel="nofollow">android/cat.c</a>:</p> <pre><code>#!/usr/bin/env python3 """Emulate `cat -v` behaviour. use ^ and M- notation, except for LFD and TAB NOTE: python exits on ^Z in stdin on Windows NOTE: newlines handling skewed towards interactive terminal. Particularly, applying the conversion twice might *not* be a no-op """ import fileinput, sys def escape(bytes): for b in bytes: assert 0 &lt;= b &lt; 0x100 if b in (0x09, 0x0a): # '\t\n' yield b continue if b &gt; 0x7f: # not ascii yield 0x4d # 'M' yield 0x2d # '-' b &amp;= 0x7f if b &lt; 0x20: # control char yield 0x5e # '^' b |= 0x40 elif b == 0x7f: yield 0x5e # '^' yield 0x3f # '?' continue yield b if __name__ == '__main__': write_bytes = sys.stdout.buffer.write for bytes in fileinput.input(mode="rb"): write_bytes(escape(bytes)) </code></pre> <p>Example:</p> <pre> $ perl -e"print map chr,0..0xff" > bytes.bin $ cat -v bytes.bin > cat-v.out $ python30 cat-v.py bytes.bin > python.out $ diff -s cat-v.out python.out </pre> <p>It prints:</p> <pre> Files cat-v.out and python.out are identical </pre>
2
2009-01-13T00:09:29Z
[ "python", "terminal", "escaping" ]