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 |
|---|---|---|---|---|---|---|---|---|---|
Detect script start up from command prompt or "double click" on Windows
| 558,776
|
<p>Is is possible to detect if a Python script was started from the command prompt or by a user "double clicking" a .py file in the file explorer on Windows?</p>
| 4
|
2009-02-17T21:20:24Z
| 38,834,845
|
<p>I put this little function (pybyebye()) just before the return statement in some of my programs. I have tested it under Windows 10 on my desktop and laptop and it does what I want, i.e. it pauses awaiting user input only when the program has been started by double-clicking the program in File Explorer. This prevents the temporary command window from vanishing before the user says so. Under Linux, it does nothing. No harm anyway! Likewise on a Mac.</p>
<pre><code>## PYBYEBYE :
def pybyebye (eprompt="PROMPT",efps="FPS_BROWSER_"):
"nice exit in Windows according to program launch from: IDLE, command, clix."
## first examine environment (os & sys having been imported) :
ui = None
platform = sys.platform
## print("os =",platform)
if not platform.lower().startswith("win"):
return ui ## only relevant in windows
fromidle = False
launched = "Launched from"
if sys.executable.endswith("pythonw.exe"):
fromidle = True ## launched from within IDLE
envkeys = sorted(os.environ)
prompter = eprompt in envkeys
browser = False
for ek in envkeys:
## print(ek)
if ek.startswith(efps):
browser = True
break
## next decide on launch context :
if fromidle and not prompter: ## surely IDLE
## print(launched,"IDLE")
pass ## screen won't disappear
elif browser and not prompter: ## run with double click
## print(launched,"File Explorer")
print("Press Enter to finish ....") ; ui=input()
elif prompter and not fromidle: ## run from preexisting command window
## print(launched,"Command Window")
pass ## screen won't disappear
else: ## something funny going on, Mac or Linux ??
print("launch mode undetermined!")
return ui
</code></pre>
| 0
|
2016-08-08T17:03:50Z
|
[
"python",
"windows"
] |
Issue with PyAMF, Django, and Python's "property" feature
| 558,926
|
<p>So far, I've had great success using PyAMF to communicate between my Flex front-end and my Django back-end. However, I believe I've encountered a bug. The following example (emphasis on the word "example") demonstrates the (potential) bug:</p>
<p>My Flex app contains the following VO:</p>
<pre><code>package myproject.model.vo
{
[Bindable]
[RemoteClass(alias="myproject.models.Book")]
public class BookVO
{
public var id:int;
public var title:String;
public var numberOfOddPages:int;
}
}
</code></pre>
<p>My Django app contains the following model:</p>
<pre><code>class Book(models.Models):
title = models.CharField(max_length=20)
def _get_number_of_odd_pages(self):
#some code that calculates odd pages
return odd_page_total
numberOfOddPages = property(_get_number_of_odd_pages)
</code></pre>
<p>When I attempt to retrieve the book objects to display in a DataGrid, the books display in the grid as expected. However, "numberOfOddPages" is always set to 0. I have even attempted to explicitly set this attribute with a default value (i.e., "numberOfOddPages=100") to see if my "_get_number_of_odd_pages()" method had an error in it. Unfortunately, it yields the same result: the value in the VO remains at 0.</p>
<p>Does anyone have any insight into what I may be doing wrong?</p>
| 2
|
2009-02-17T22:05:10Z
| 560,919
|
<p>Not at all.</p>
<p>Do you think the error is from Django or from Flex? You could first of all trace the AMF Object in Flex. If the value there is allready 0 then have a good look what PyAMF does.</p>
| -1
|
2009-02-18T12:47:55Z
|
[
"python",
"django",
"flex",
"flex3",
"pyamf"
] |
Issue with PyAMF, Django, and Python's "property" feature
| 558,926
|
<p>So far, I've had great success using PyAMF to communicate between my Flex front-end and my Django back-end. However, I believe I've encountered a bug. The following example (emphasis on the word "example") demonstrates the (potential) bug:</p>
<p>My Flex app contains the following VO:</p>
<pre><code>package myproject.model.vo
{
[Bindable]
[RemoteClass(alias="myproject.models.Book")]
public class BookVO
{
public var id:int;
public var title:String;
public var numberOfOddPages:int;
}
}
</code></pre>
<p>My Django app contains the following model:</p>
<pre><code>class Book(models.Models):
title = models.CharField(max_length=20)
def _get_number_of_odd_pages(self):
#some code that calculates odd pages
return odd_page_total
numberOfOddPages = property(_get_number_of_odd_pages)
</code></pre>
<p>When I attempt to retrieve the book objects to display in a DataGrid, the books display in the grid as expected. However, "numberOfOddPages" is always set to 0. I have even attempted to explicitly set this attribute with a default value (i.e., "numberOfOddPages=100") to see if my "_get_number_of_odd_pages()" method had an error in it. Unfortunately, it yields the same result: the value in the VO remains at 0.</p>
<p>Does anyone have any insight into what I may be doing wrong?</p>
| 2
|
2009-02-17T22:05:10Z
| 561,072
|
<p>I just received the following response from PyAMF's lead developer. It's definitely a bug:</p>
<blockquote>
<p>This is a bug in the way the Django
adapter handles non models.fields.*
properties.</p>
<p>If I do:</p>
</blockquote>
<pre><code>import pyamf
class Book(object):
def _get_number_of_odd_pages(self):
return 52
numberOfOddPages = property(_get_number_of_odd_pages)
pyamf.register_class(Book, 'Book')
encoded = pyamf.encode(Book()).getvalue()
print pyamf.decode(encoded).next().numberOfOddPages
</code></pre>
<blockquote>
<p>Then i get the correct values of 52.</p>
<p>I have created <a href="http://pyamf.org/ticket/480" rel="nofollow">a ticket</a> for this
and will look into getting a patch a
little later.</p>
<p>Cheers,</p>
<p>Nick</p>
</blockquote>
<p><strong>UPDATE</strong>: Nick has fixed this bug and it will be released in PyAMF 0.4.1 (which should be released this weekend).</p>
| 1
|
2009-02-18T13:35:27Z
|
[
"python",
"django",
"flex",
"flex3",
"pyamf"
] |
Eclipse PyDev: setting breakpoints in site-packages source
| 558,999
|
<p>I am debugging a problem in Django with <strong>Pydev</strong>.<br />
I <strong>can set breakpoint</strong> in my django <strong>project code</strong> with out a problem.<br />
However I <strong>can't set breakpoints</strong> in the <strong>Django library source code</strong> (in site-packages). </p>
<p>The PyDev debugger user interface in this case <strong>simply does nothing when I click</strong> to set the breakpoint and does not break at that location when I run the debugger.</p>
<p>Am I missing some PyDev configuration? In other debuggers I have used, this behavior indicates a problem relating the debug information with the source code.
Any ideas on next steps would be a help.</p>
<p>I also have the <strong>site-packages</strong> configured in PyDev to be in my <strong>PYTHONPATH</strong></p>
<p>I am using Eclipse on Max OS X if that helps.</p>
<p>Thanks</p>
| 4
|
2009-02-17T22:25:46Z
| 559,411
|
<p>You might try instead the Python debugger pdb in this instance.</p>
<p>This is a helpful link describing it: <a href="http://www.ferg.org/papers/debugging_in_python.html" rel="nofollow">http://www.ferg.org/papers/debugging_in_python.html</a></p>
| 0
|
2009-02-18T00:54:32Z
|
[
"python",
"django",
"eclipse",
"pydev"
] |
Eclipse PyDev: setting breakpoints in site-packages source
| 558,999
|
<p>I am debugging a problem in Django with <strong>Pydev</strong>.<br />
I <strong>can set breakpoint</strong> in my django <strong>project code</strong> with out a problem.<br />
However I <strong>can't set breakpoints</strong> in the <strong>Django library source code</strong> (in site-packages). </p>
<p>The PyDev debugger user interface in this case <strong>simply does nothing when I click</strong> to set the breakpoint and does not break at that location when I run the debugger.</p>
<p>Am I missing some PyDev configuration? In other debuggers I have used, this behavior indicates a problem relating the debug information with the source code.
Any ideas on next steps would be a help.</p>
<p>I also have the <strong>site-packages</strong> configured in PyDev to be in my <strong>PYTHONPATH</strong></p>
<p>I am using Eclipse on Max OS X if that helps.</p>
<p>Thanks</p>
| 4
|
2009-02-17T22:25:46Z
| 559,588
|
<p>Hey, this is timely! Eric Moritz just announced the release of an interesting new way to debug views using pdb called <a href="http://eric.themoritzfamily.com/2009/02/17/announcing-django-viewtools/" rel="nofollow">django-viewtools</a>.</p>
| 1
|
2009-02-18T02:06:51Z
|
[
"python",
"django",
"eclipse",
"pydev"
] |
Eclipse PyDev: setting breakpoints in site-packages source
| 558,999
|
<p>I am debugging a problem in Django with <strong>Pydev</strong>.<br />
I <strong>can set breakpoint</strong> in my django <strong>project code</strong> with out a problem.<br />
However I <strong>can't set breakpoints</strong> in the <strong>Django library source code</strong> (in site-packages). </p>
<p>The PyDev debugger user interface in this case <strong>simply does nothing when I click</strong> to set the breakpoint and does not break at that location when I run the debugger.</p>
<p>Am I missing some PyDev configuration? In other debuggers I have used, this behavior indicates a problem relating the debug information with the source code.
Any ideas on next steps would be a help.</p>
<p>I also have the <strong>site-packages</strong> configured in PyDev to be in my <strong>PYTHONPATH</strong></p>
<p>I am using Eclipse on Max OS X if that helps.</p>
<p>Thanks</p>
| 4
|
2009-02-17T22:25:46Z
| 561,957
|
<p>Have you imported the Django source as a project? To do that you just create a new PyDev project and set it's location to the Django source folder.</p>
| 4
|
2009-02-18T17:03:21Z
|
[
"python",
"django",
"eclipse",
"pydev"
] |
Eclipse PyDev: setting breakpoints in site-packages source
| 558,999
|
<p>I am debugging a problem in Django with <strong>Pydev</strong>.<br />
I <strong>can set breakpoint</strong> in my django <strong>project code</strong> with out a problem.<br />
However I <strong>can't set breakpoints</strong> in the <strong>Django library source code</strong> (in site-packages). </p>
<p>The PyDev debugger user interface in this case <strong>simply does nothing when I click</strong> to set the breakpoint and does not break at that location when I run the debugger.</p>
<p>Am I missing some PyDev configuration? In other debuggers I have used, this behavior indicates a problem relating the debug information with the source code.
Any ideas on next steps would be a help.</p>
<p>I also have the <strong>site-packages</strong> configured in PyDev to be in my <strong>PYTHONPATH</strong></p>
<p>I am using Eclipse on Max OS X if that helps.</p>
<p>Thanks</p>
| 4
|
2009-02-17T22:25:46Z
| 2,516,750
|
<p>PyDev 1.5.5 seems to have an issue with Eclipse. Uninstall 1.5.5 and install the 1.5.4 version</p>
| 0
|
2010-03-25T15:17:27Z
|
[
"python",
"django",
"eclipse",
"pydev"
] |
Check whether a PDF-File is valid (Python)
| 559,096
|
<p><strong>I get a File via a HTTP-Upload and need to be sure its a pdf-file.</strong> Programing Language is Python, but this should not matter.</p>
<p>I thought of the following solutions:</p>
<ol>
<li><p>Check if the first bytes of the string are "%PDF". <em>This is not a good check but prevents the use from uploading other files accidentally.</em></p></li>
<li><p>Try the libmagic (the "file" command on the bash uses it). <em>This does exactly the same check as 1.</em></p></li>
<li><p>Take a lib and try to read the page-count out of the file. <em>If the lib is able to read a pagecount it should be a valid pdf. Problem: I dont know a lib for python which can do this</em></p></li>
</ol>
<p>So anybody got any solutions for a lib or another trick?</p>
<p>Thanks </p>
| 10
|
2009-02-17T22:53:27Z
| 559,116
|
<p>If you're on a Linux or OS X box, you could use <a href="http://en.wikipedia.org/wiki/Pdftotext" rel="nofollow">Pdftotext</a> (part of Xpdf, found <a href="http://www.foolabs.com/xpdf/download.html" rel="nofollow">here</a>). If you pass a non-PDF to pdftotext, it will certainly bark at you, and you can use commands.getstatusoutput to get the output and parse it for these warnings.</p>
<p>If you're looking for a platform-independent solution, you might be able to make use of <a href="http://pybrary.net/pyPdf/" rel="nofollow">pyPdf</a>.</p>
<p><strong>Edit:</strong> It's not elegant, but it looks like pyPdf's PdfFileReader will throw an IOError(22) if you attempt to load a non-PDF.</p>
| 2
|
2009-02-17T23:00:05Z
|
[
"python",
"file",
"pdf"
] |
Check whether a PDF-File is valid (Python)
| 559,096
|
<p><strong>I get a File via a HTTP-Upload and need to be sure its a pdf-file.</strong> Programing Language is Python, but this should not matter.</p>
<p>I thought of the following solutions:</p>
<ol>
<li><p>Check if the first bytes of the string are "%PDF". <em>This is not a good check but prevents the use from uploading other files accidentally.</em></p></li>
<li><p>Try the libmagic (the "file" command on the bash uses it). <em>This does exactly the same check as 1.</em></p></li>
<li><p>Take a lib and try to read the page-count out of the file. <em>If the lib is able to read a pagecount it should be a valid pdf. Problem: I dont know a lib for python which can do this</em></p></li>
</ol>
<p>So anybody got any solutions for a lib or another trick?</p>
<p>Thanks </p>
| 10
|
2009-02-17T22:53:27Z
| 559,176
|
<p>In a project if mine I need to check for the mime type of some uploaded file. I simply use the file command like this:</p>
<pre><code>from subprocess import Popen, PIPE
filetype = Popen("/usr/bin/file -b --mime -", shell=True, stdout=PIPE, stdin=PIPE).communicate(file.read(1024))[0].strip()
</code></pre>
<p>You of course might want to move the actual command into some configuration file as also command line options vary among operating systems (e.g. mac).</p>
<p>If you just need to know whether it's a PDF or not and do not need to process it anyway I think the file command is a faster solution than a lib. Doing it by hand is of course also possible but the file command gives you maybe more flexibility if you want to check for different types.</p>
| 7
|
2009-02-17T23:19:52Z
|
[
"python",
"file",
"pdf"
] |
Check whether a PDF-File is valid (Python)
| 559,096
|
<p><strong>I get a File via a HTTP-Upload and need to be sure its a pdf-file.</strong> Programing Language is Python, but this should not matter.</p>
<p>I thought of the following solutions:</p>
<ol>
<li><p>Check if the first bytes of the string are "%PDF". <em>This is not a good check but prevents the use from uploading other files accidentally.</em></p></li>
<li><p>Try the libmagic (the "file" command on the bash uses it). <em>This does exactly the same check as 1.</em></p></li>
<li><p>Take a lib and try to read the page-count out of the file. <em>If the lib is able to read a pagecount it should be a valid pdf. Problem: I dont know a lib for python which can do this</em></p></li>
</ol>
<p>So anybody got any solutions for a lib or another trick?</p>
<p>Thanks </p>
| 10
|
2009-02-17T22:53:27Z
| 559,442
|
<p>The two most commonly used PDF libraries for Python are:</p>
<ul>
<li><a href="http://pybrary.net/pyPdf/">pyPdf</a></li>
<li><a href="http://www.reportlab.org/downloads.html">ReportLab</a></li>
</ul>
<p>Both are pure python so should be easy to install as well be cross-platform.</p>
<p>With pyPdf it would probably be as simple as doing:</p>
<pre><code>from pyPdf import PdfFileReader
doc = PdfFileReader(file("upload.pdf", "rb"))
</code></pre>
<p>This should be enough, but <code>doc</code> will now have <code>documentInfo()</code> and <code>numPages()</code> methods if you want to do further checking.</p>
<p>As Carl answered, pdftotext is also a good solution, and would probably be faster on very large documents (especially ones with many cross-references). However it might be a little slower on small PDF's due to system overhead of forking a new process, etc.</p>
| 9
|
2009-02-18T01:10:35Z
|
[
"python",
"file",
"pdf"
] |
Check whether a PDF-File is valid (Python)
| 559,096
|
<p><strong>I get a File via a HTTP-Upload and need to be sure its a pdf-file.</strong> Programing Language is Python, but this should not matter.</p>
<p>I thought of the following solutions:</p>
<ol>
<li><p>Check if the first bytes of the string are "%PDF". <em>This is not a good check but prevents the use from uploading other files accidentally.</em></p></li>
<li><p>Try the libmagic (the "file" command on the bash uses it). <em>This does exactly the same check as 1.</em></p></li>
<li><p>Take a lib and try to read the page-count out of the file. <em>If the lib is able to read a pagecount it should be a valid pdf. Problem: I dont know a lib for python which can do this</em></p></li>
</ol>
<p>So anybody got any solutions for a lib or another trick?</p>
<p>Thanks </p>
| 10
|
2009-02-17T22:53:27Z
| 584,225
|
<p>By valid do you mean that it can be displayed by a PDF viewer, or that the text can be extracted? They are two very different things.</p>
<p>If you just want to check that it really is a PDF file that has been uploaded then the pyPDF solution, or something similar, will work. </p>
<p>If, however, you want to check that the text can be extracted then you have found a whole world of pain! Using pdftotext would be a simple solution that would work in a majority of cases but it is by no means 100% successful. We have found many examples of PDFs that pdftotext cannot extract from but Java libraries such as iText and PDFBox can. </p>
| 0
|
2009-02-25T00:10:24Z
|
[
"python",
"file",
"pdf"
] |
Check whether a PDF-File is valid (Python)
| 559,096
|
<p><strong>I get a File via a HTTP-Upload and need to be sure its a pdf-file.</strong> Programing Language is Python, but this should not matter.</p>
<p>I thought of the following solutions:</p>
<ol>
<li><p>Check if the first bytes of the string are "%PDF". <em>This is not a good check but prevents the use from uploading other files accidentally.</em></p></li>
<li><p>Try the libmagic (the "file" command on the bash uses it). <em>This does exactly the same check as 1.</em></p></li>
<li><p>Take a lib and try to read the page-count out of the file. <em>If the lib is able to read a pagecount it should be a valid pdf. Problem: I dont know a lib for python which can do this</em></p></li>
</ol>
<p>So anybody got any solutions for a lib or another trick?</p>
<p>Thanks </p>
| 10
|
2009-02-17T22:53:27Z
| 32,654,661
|
<p>Since apparently neither <code>PyPdf</code> nor <code>ReportLab</code> is available anymore, the current solution I found (as of 2015) is to use <a href="https://github.com/mstamy2/PyPDF2" rel="nofollow"><code>PyPDF2</code></a> and catch exceptions (and possibly analyze <a href="https://pythonhosted.org/PyPDF2/PdfFileReader.html#PyPDF2.PdfFileReader.getDocumentInfo" rel="nofollow"><code>getDocumentInfo()</code></a>)</p>
<pre><code>import PyPDF2
with open("testfile.txt", "w") as f:
f.write("hello world!")
try:
PyPDF2.PdfFileReader(open("testfile.txt", "rb"))
except PyPDF2.utils.PdfReadError:
print("invalid PDF file")
else:
pass
</code></pre>
| 1
|
2015-09-18T14:36:41Z
|
[
"python",
"file",
"pdf"
] |
How to display data using openlayers with OpenStreetMap in geodjango?
| 559,431
|
<p>I've got geodjango running using <a href="http://openlayers.org/">openlayers</a> and <a href="http://www.openstreetmap.org/">OpenStreetMaps</a> with the admin app.</p>
<p>Now I want to write some views to display the data. Basically, I just want to add a list of points (seen in the admin) to the map.</p>
<p>Geodjango appears to use a <em>special</em> <a href="http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/contrib/gis/templates/gis/admin/openlayers.js">openlayers.js</a> file to do it's magic in the admin. Is there a good way to interface with this?</p>
<p>How can I write a view/template to display the geodjango data on a open street map window, as is seen in the admin?</p>
<p>At the moment, I'm digging into the <a href="http://openlayers.org/">openlayers.js</a> file and api looking for an 'easy' solution. (I don't have js experience so this is taking some time.) </p>
<p>The current way I can see to do this is add the following as a template, and use django to add the code needed to display the points. (Based on the example <a href="http://openlayers.org/dev/examples/vector-features.html">here</a>)</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Draw Feature Example</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init(){
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(layer);
/*
* Layer style
*/
// we want opaque external graphics and non-opaque internal graphics
var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
layer_style.fillOpacity = 0.2;
layer_style.graphicOpacity = 1;
/*
* Blue style
*/
var style_blue = OpenLayers.Util.extend({}, layer_style);
style_blue.strokeColor = "blue";
style_blue.fillColor = "blue";
style_blue.graphicName = "star";
style_blue.pointRadius = 10;
style_blue.strokeWidth = 3;
style_blue.rotation = 45;
style_blue.strokeLinecap = "butt";
var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style: layer_style});
// create a point feature
var point = new OpenLayers.Geometry.Point(-111.04, 45.68);
var pointFeature = new OpenLayers.Feature.Vector(point,null,style_blue);
// Add additional points/features here via django
map.addLayer(vectorLayer);
map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5);
vectorLayer.addFeatures([pointFeature]);
}
</script>
</head>
<body onload="init()">
<div id="map" class="smallmap"></div>
</body>
</html>
</code></pre>
<p>Is this how it's done, or is there a better way?</p>
| 12
|
2009-02-18T01:03:40Z
| 569,890
|
<p>I think your solution is workable and probably the easiest approach. Just templatize the javascript and use Django to inject your data points as the template is rendered. </p>
<p>If you wanted to get fancier, you could have a Django view that served up the data points as JSON (application/json) and then use AJAX to call back and retrieve the data based on events that are happening in the browser. If you want your application to be highly interactive above and beyond what OpenLayers provides, this might be worth the added complexity, but of course it all depends on the needs of your application.</p>
| 2
|
2009-02-20T15:09:57Z
|
[
"python",
"mapping",
"openlayers",
"geodjango"
] |
How to display data using openlayers with OpenStreetMap in geodjango?
| 559,431
|
<p>I've got geodjango running using <a href="http://openlayers.org/">openlayers</a> and <a href="http://www.openstreetmap.org/">OpenStreetMaps</a> with the admin app.</p>
<p>Now I want to write some views to display the data. Basically, I just want to add a list of points (seen in the admin) to the map.</p>
<p>Geodjango appears to use a <em>special</em> <a href="http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/contrib/gis/templates/gis/admin/openlayers.js">openlayers.js</a> file to do it's magic in the admin. Is there a good way to interface with this?</p>
<p>How can I write a view/template to display the geodjango data on a open street map window, as is seen in the admin?</p>
<p>At the moment, I'm digging into the <a href="http://openlayers.org/">openlayers.js</a> file and api looking for an 'easy' solution. (I don't have js experience so this is taking some time.) </p>
<p>The current way I can see to do this is add the following as a template, and use django to add the code needed to display the points. (Based on the example <a href="http://openlayers.org/dev/examples/vector-features.html">here</a>)</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Draw Feature Example</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init(){
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(layer);
/*
* Layer style
*/
// we want opaque external graphics and non-opaque internal graphics
var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
layer_style.fillOpacity = 0.2;
layer_style.graphicOpacity = 1;
/*
* Blue style
*/
var style_blue = OpenLayers.Util.extend({}, layer_style);
style_blue.strokeColor = "blue";
style_blue.fillColor = "blue";
style_blue.graphicName = "star";
style_blue.pointRadius = 10;
style_blue.strokeWidth = 3;
style_blue.rotation = 45;
style_blue.strokeLinecap = "butt";
var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style: layer_style});
// create a point feature
var point = new OpenLayers.Geometry.Point(-111.04, 45.68);
var pointFeature = new OpenLayers.Feature.Vector(point,null,style_blue);
// Add additional points/features here via django
map.addLayer(vectorLayer);
map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5);
vectorLayer.addFeatures([pointFeature]);
}
</script>
</head>
<body onload="init()">
<div id="map" class="smallmap"></div>
</body>
</html>
</code></pre>
<p>Is this how it's done, or is there a better way?</p>
| 12
|
2009-02-18T01:03:40Z
| 1,976,231
|
<p>Another solution is to create a form that utilizes the GeoDjango Admin widget. </p>
<p>To do this, I:</p>
<p>Setup a GeneratePolygonAdminClass:</p>
<pre><code>class GeneratePolygonAdmin(admin.GeoModelAdmin):
list_filter=('polygon',)
list_display=('object', 'polygon')
</code></pre>
<p>Where the form is built:</p>
<pre><code>geoAdmin=GeneratePolygonAdmin(ModelWithPolygonField, admin.site)
PolygonFormField=GeneratePolygon._meta.get_field('Polygon')
PolygonWidget=geoAdmin.get_map_widget(PolygonFormField)
Dict['Polygon']=forms.CharField(widget=PolygonWidget()) #In this case, I am creating a Dict to use for a dynamic form
</code></pre>
<p>Populating the widget of the form:</p>
<pre><code>def SetupPolygonWidget(form, LayerName, MapFileName, DefaultPolygon=''):
form.setData({'Polygon':DefaultPolygon})
form.fields['Polygon'].widget.params['wms_layer']=LayerName
form.fields['Polygon'].widget.params['wms_url']='/cgi-bin/mapserv?MAP=' + MapFileName
form.fields['Polygon'].widget.params['default_lon']=-80.9
form.fields['Polygon'].widget.params['default_lat']=33.7
form.fields['Polygon'].widget.params['default_zoom']=11
form.fields['Polygon'].widget.params['wms_name']=YOURWMSLayerName
form.fields['Polygon'].widget.params['map_width']=800
form.fields['Polygon'].widget.params['map_height']=600
form.fields['Polygon'].widget.params['map_srid']=YOUR_SRID
form.fields['Polygon'].widget.params['modifiable']=True
form.fields['Polygon'].widget.params['map_options']={}
form.fields['Polygon'].widget.params['map_options']['buffer'] = 0
return form
</code></pre>
<p>Based on the code at:
<a href="http://code.djangoproject.com/browser/django/branches/gis/django/contrib/gis/admin/options.py?rev=7980" rel="nofollow">http://code.djangoproject.com/browser/django/branches/gis/django/contrib/gis/admin/options.py?rev=7980</a></p>
<p>It looks like you can use the extra_js option to include OpenStreetMap (I have not tested this).</p>
| 4
|
2009-12-29T18:51:11Z
|
[
"python",
"mapping",
"openlayers",
"geodjango"
] |
How to display data using openlayers with OpenStreetMap in geodjango?
| 559,431
|
<p>I've got geodjango running using <a href="http://openlayers.org/">openlayers</a> and <a href="http://www.openstreetmap.org/">OpenStreetMaps</a> with the admin app.</p>
<p>Now I want to write some views to display the data. Basically, I just want to add a list of points (seen in the admin) to the map.</p>
<p>Geodjango appears to use a <em>special</em> <a href="http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/contrib/gis/templates/gis/admin/openlayers.js">openlayers.js</a> file to do it's magic in the admin. Is there a good way to interface with this?</p>
<p>How can I write a view/template to display the geodjango data on a open street map window, as is seen in the admin?</p>
<p>At the moment, I'm digging into the <a href="http://openlayers.org/">openlayers.js</a> file and api looking for an 'easy' solution. (I don't have js experience so this is taking some time.) </p>
<p>The current way I can see to do this is add the following as a template, and use django to add the code needed to display the points. (Based on the example <a href="http://openlayers.org/dev/examples/vector-features.html">here</a>)</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Draw Feature Example</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init(){
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(layer);
/*
* Layer style
*/
// we want opaque external graphics and non-opaque internal graphics
var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
layer_style.fillOpacity = 0.2;
layer_style.graphicOpacity = 1;
/*
* Blue style
*/
var style_blue = OpenLayers.Util.extend({}, layer_style);
style_blue.strokeColor = "blue";
style_blue.fillColor = "blue";
style_blue.graphicName = "star";
style_blue.pointRadius = 10;
style_blue.strokeWidth = 3;
style_blue.rotation = 45;
style_blue.strokeLinecap = "butt";
var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style: layer_style});
// create a point feature
var point = new OpenLayers.Geometry.Point(-111.04, 45.68);
var pointFeature = new OpenLayers.Feature.Vector(point,null,style_blue);
// Add additional points/features here via django
map.addLayer(vectorLayer);
map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5);
vectorLayer.addFeatures([pointFeature]);
}
</script>
</head>
<body onload="init()">
<div id="map" class="smallmap"></div>
</body>
</html>
</code></pre>
<p>Is this how it's done, or is there a better way?</p>
| 12
|
2009-02-18T01:03:40Z
| 7,641,372
|
<p>You could consider using <a href="http://django-floppyforms.readthedocs.org/en/latest/geodjango.html" rel="nofollow">FloppyForms</a>. In the end, I usually end up customizing the solution to my own needs, but it's a nice way to get started.</p>
| 1
|
2011-10-03T22:26:06Z
|
[
"python",
"mapping",
"openlayers",
"geodjango"
] |
How to display data using openlayers with OpenStreetMap in geodjango?
| 559,431
|
<p>I've got geodjango running using <a href="http://openlayers.org/">openlayers</a> and <a href="http://www.openstreetmap.org/">OpenStreetMaps</a> with the admin app.</p>
<p>Now I want to write some views to display the data. Basically, I just want to add a list of points (seen in the admin) to the map.</p>
<p>Geodjango appears to use a <em>special</em> <a href="http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/contrib/gis/templates/gis/admin/openlayers.js">openlayers.js</a> file to do it's magic in the admin. Is there a good way to interface with this?</p>
<p>How can I write a view/template to display the geodjango data on a open street map window, as is seen in the admin?</p>
<p>At the moment, I'm digging into the <a href="http://openlayers.org/">openlayers.js</a> file and api looking for an 'easy' solution. (I don't have js experience so this is taking some time.) </p>
<p>The current way I can see to do this is add the following as a template, and use django to add the code needed to display the points. (Based on the example <a href="http://openlayers.org/dev/examples/vector-features.html">here</a>)</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Draw Feature Example</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init(){
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(layer);
/*
* Layer style
*/
// we want opaque external graphics and non-opaque internal graphics
var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
layer_style.fillOpacity = 0.2;
layer_style.graphicOpacity = 1;
/*
* Blue style
*/
var style_blue = OpenLayers.Util.extend({}, layer_style);
style_blue.strokeColor = "blue";
style_blue.fillColor = "blue";
style_blue.graphicName = "star";
style_blue.pointRadius = 10;
style_blue.strokeWidth = 3;
style_blue.rotation = 45;
style_blue.strokeLinecap = "butt";
var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style: layer_style});
// create a point feature
var point = new OpenLayers.Geometry.Point(-111.04, 45.68);
var pointFeature = new OpenLayers.Feature.Vector(point,null,style_blue);
// Add additional points/features here via django
map.addLayer(vectorLayer);
map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5);
vectorLayer.addFeatures([pointFeature]);
}
</script>
</head>
<body onload="init()">
<div id="map" class="smallmap"></div>
</body>
</html>
</code></pre>
<p>Is this how it's done, or is there a better way?</p>
| 12
|
2009-02-18T01:03:40Z
| 8,839,431
|
<p>Checkout this tutorial from the geodjango-basic-apps project:<br>
<a href="http://code.google.com/p/geodjango-basic-apps/wiki/FOSS4GWorkshop" rel="nofollow">http://code.google.com/p/geodjango-basic-apps/wiki/FOSS4GWorkshop</a></p>
<p>maybe you don't have to hack up your own javascript just yet</p>
| 0
|
2012-01-12T17:25:58Z
|
[
"python",
"mapping",
"openlayers",
"geodjango"
] |
How to display data using openlayers with OpenStreetMap in geodjango?
| 559,431
|
<p>I've got geodjango running using <a href="http://openlayers.org/">openlayers</a> and <a href="http://www.openstreetmap.org/">OpenStreetMaps</a> with the admin app.</p>
<p>Now I want to write some views to display the data. Basically, I just want to add a list of points (seen in the admin) to the map.</p>
<p>Geodjango appears to use a <em>special</em> <a href="http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/contrib/gis/templates/gis/admin/openlayers.js">openlayers.js</a> file to do it's magic in the admin. Is there a good way to interface with this?</p>
<p>How can I write a view/template to display the geodjango data on a open street map window, as is seen in the admin?</p>
<p>At the moment, I'm digging into the <a href="http://openlayers.org/">openlayers.js</a> file and api looking for an 'easy' solution. (I don't have js experience so this is taking some time.) </p>
<p>The current way I can see to do this is add the following as a template, and use django to add the code needed to display the points. (Based on the example <a href="http://openlayers.org/dev/examples/vector-features.html">here</a>)</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Draw Feature Example</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init(){
map = new OpenLayers.Map('map');
var layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(layer);
/*
* Layer style
*/
// we want opaque external graphics and non-opaque internal graphics
var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
layer_style.fillOpacity = 0.2;
layer_style.graphicOpacity = 1;
/*
* Blue style
*/
var style_blue = OpenLayers.Util.extend({}, layer_style);
style_blue.strokeColor = "blue";
style_blue.fillColor = "blue";
style_blue.graphicName = "star";
style_blue.pointRadius = 10;
style_blue.strokeWidth = 3;
style_blue.rotation = 45;
style_blue.strokeLinecap = "butt";
var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style: layer_style});
// create a point feature
var point = new OpenLayers.Geometry.Point(-111.04, 45.68);
var pointFeature = new OpenLayers.Feature.Vector(point,null,style_blue);
// Add additional points/features here via django
map.addLayer(vectorLayer);
map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5);
vectorLayer.addFeatures([pointFeature]);
}
</script>
</head>
<body onload="init()">
<div id="map" class="smallmap"></div>
</body>
</html>
</code></pre>
<p>Is this how it's done, or is there a better way?</p>
| 12
|
2009-02-18T01:03:40Z
| 13,852,322
|
<p>This is quite old, and I wouldn't go around creating a template hack as I originally was thinking. Now I would use <a href="http://leafletjs.com/examples/geojson.html" rel="nofollow">leaflet.js</a> with an ajax request to a django view that returns geojson to a leaflet geojson layer.</p>
<p>This makes the django side super easy. </p>
<p>Sample Django View:</p>
<pre><code># -*- coding: utf-8 -*-
'''
'''
import json
from django.http import HttpResponse, HttpResponseBadRequest
from django.contrib.gis.geos import Polygon
from models import ResultLayer, MyModel
def get_layer_polygons(request, layer_id):
"""
Return the polygons for the given bbox (bounding box)
"""
layer = ResultLayer.objects.get(id=layer_id)
bbox_raw = request.GET.get("bbox", None)
# Make sure the incoming bounding box is correctly formed!
bbox = None
if bbox_raw and bbox_raw.count(",") == 3:
bbox = [float(v) for v in bbox_raw.split(",")]
if not bbox:
msg = "Improperly formed or not given 'bbox' querystring option, should be in the format '?bbox=minlon,minlat,maxlon,maxlat'"
return HttpResponseBadRequest(msg)
bbox_poly = Polygon.from_bbox(bbox)
bbox_poly.srid = 900913 # google
bbox_poly.transform(layer.srid) # transform to the layer's srid for querying
bin_size = int(bin_size)
# build vector polygons from bin
results = MyModel.objects.filter(layer=layer, poly__intersects=bbox_poly).transform(900913, field_name="poly")
geojson_data = []
for r in results:
# loading json in order to dump json list later
gjson = r.poly.geojson
py_gjson = json.loads(gjson)
geojson_data.append(py_gjson)
return HttpResponse(json.dumps(geojson_data), mimetype='application/json')
</code></pre>
| 2
|
2012-12-13T03:11:07Z
|
[
"python",
"mapping",
"openlayers",
"geodjango"
] |
How do I validate the MX record for a domain in python?
| 559,436
|
<p>I have a large number of email addresses to validate. Initially I parse them with a regexp to throw out the completely crazy ones. I'm left with the ones that look sensible but still might contain errors. </p>
<p>I want to find which addresses have valid domains, so given me@abcxyz.com I want to know if it's even possible to send emails to abcxyz.com .</p>
<p>I want to test that to see if it corresponds to a valid A or MX record - is there an easy way to do it using only Python standard library? I'd rather not add an additional dependency to my project just to support this feature.</p>
| 13
|
2009-02-18T01:06:20Z
| 559,479
|
<p>There is no DNS interface in the standard library so you will either have to roll your own or use a third party library.</p>
<p>This is not a fast-changing concept though, so the external libraries are stable and well tested.</p>
<p>The one I've used successful for the same task as your question is <a href="http://pydns.sourceforge.net/">PyDNS</a>.</p>
<p>A very rough sketch of my code is something like this:</p>
<pre><code>import DNS, smtplib
DNS.DiscoverNameServers()
mx_hosts = DNS.mxlookup(hostname)
# Just doing the mxlookup might be enough for you,
# but do something like this to test for SMTP server
for mx in mx_hosts:
smtp = smtplib.SMTP()
#.. if this doesn't raise an exception it is a valid MX host...
try:
smtp.connect(mx[1])
except smtplib.SMTPConnectError:
continue # try the next MX server in list
</code></pre>
<p>Another library that might be better/faster than PyDNS is <a href="http://c0re.23.nu/c0de/dnsmodule/">dnsmodule</a> although it looks like it hasn't had any activity since 2002, compared to PyDNS last update in August 2008.</p>
<p><strong>Edit</strong>: I would also like to point out that email addresses can't be easily parsed with a regexp. You are better off using the parseaddr() function in the standard library email.utils module (see my <a href="http://stackoverflow.com/questions/550009/parsing-from-addresses-from-email-text/550036#550036">answer to this question</a> for example).</p>
| 16
|
2009-02-18T01:25:06Z
|
[
"python",
"email",
"dns"
] |
How do I validate the MX record for a domain in python?
| 559,436
|
<p>I have a large number of email addresses to validate. Initially I parse them with a regexp to throw out the completely crazy ones. I'm left with the ones that look sensible but still might contain errors. </p>
<p>I want to find which addresses have valid domains, so given me@abcxyz.com I want to know if it's even possible to send emails to abcxyz.com .</p>
<p>I want to test that to see if it corresponds to a valid A or MX record - is there an easy way to do it using only Python standard library? I'd rather not add an additional dependency to my project just to support this feature.</p>
| 13
|
2009-02-18T01:06:20Z
| 37,038,815
|
<p>The easy way to do this NOT in the standard library is to use the <a href="https://pypi.python.org/pypi/validate_email" rel="nofollow" title="validate_email package">validate_email package</a>: </p>
<pre><code>from validate_email import validate_email
is_valid = validate_email('example@example.com', check_mx=True)
</code></pre>
<p>For faster results to process a large number of email addresses (e.g. list <code>emails</code>, you could stash the domains and only do a check_mx if the domain isn't there. Something like:</p>
<pre><code>emails = ["email@example.com", "email@bad_domain", "email2@example.com", ...]
verified_domains = set()
for email in emails:
domain = email.split("@")[-1]
domain_verified = domain in verified_domains
is_valid = validate_email(email, check_mx=not domain_verified)
if is_valid:
verified_domains.add(domain)
</code></pre>
| 0
|
2016-05-04T21:59:14Z
|
[
"python",
"email",
"dns"
] |
Need a better way to execute console commands from python and log the results
| 559,578
|
<p>I have a python script which needs to execute several command line utilities. The stdout output is sometimes used for further processing. In all cases, I want to log the results and raise an exception if an error is detected. I use the following function to achieve this:</p>
<pre><code>def execute(cmd, logsink):
logsink.log("executing: %s\n" % cmd)
popen_obj = subprocess.Popen(\
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = popen_obj.communicate()
returncode = popen_obj.returncode
if (returncode <> 0):
logsink.log(" RETURN CODE: %s\n" % str(returncode))
if (len(stdout.strip()) > 0):
logsink.log(" STDOUT:\n%s\n" % stdout)
if (len(stderr.strip()) > 0):
logsink.log(" STDERR:\n%s\n" % stderr)
if (returncode <> 0):
raise Exception, "execute failed with error output:\n%s" % stderr
return stdout
</code></pre>
<p>"logsink" can be any python object with a log method. I typically use this to forward the logging data to a specific file, or echo it to the console, or both, or something else...</p>
<p>This works pretty good, except for three problems where I need more fine-grained control than the communicate() method provides:</p>
<ol>
<li>stdout and stderr output can be interleaved on the
console, but the above function logs
them separately. This can
complicate the interpretation of the
log. How do I log stdout and stderr
lines interleaved, in the same order
as they were output?</li>
<li>The above function will only log the
command output once the command has
completed. This complicates diagnosis of issues when commands get stuck in an infinite loop or take a very long time for some other reason. How do I get the log in real-time, while the command is still executing?</li>
<li>If the logs are large, it can get
hard to interpret which command
generated which output. Is there a
way to prefix each line with
something (e.g. the first word of
the cmd string followed by :).</li>
</ol>
| 4
|
2009-02-18T02:02:08Z
| 559,676
|
<p>You can redirect to a file if you just want the output in a file for later evaluation.</p>
<p>Your already defining the stdout/stderr of the processes your executuing by the stdout=/stderr= methods.</p>
<p>In your example code your just redirecting to the scripts current out/err assigments.</p>
<pre><code>subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
</code></pre>
<p>sys.stdout and sys.stderr are just file-like objects.
As the documentation documentation on <a href="http://docs.python.org/library/sys.html?highlight=stdout#sys.stdout" rel="nofollow">sys.stdout</a> mentions, "Any object is acceptable as long as it has a write() method that takes a string argument."</p>
<pre><code>f = open('cmd_fileoutput.txt', 'w')
subprocess.Popen(cmd, shell=True, stdout=f, stderr=f)
</code></pre>
<p>So you only need to given it a class with a write method in order to re-direct output.</p>
<p>If you want both console output and file output may be making a class to manage the output.</p>
<p>General redirection:</p>
<pre><code># Redirecting stdout and stderr to a file
f = open('log.txt', 'w')
sys.stdout = f
sys.stderr = f
</code></pre>
<p>Making a redirection class:</p>
<pre><code># redirecting to both
class OutputManager:
def __init__(self, filename, console):
self.f = open(filename, 'w')
self.con = console
def write(self, data):
self.con.write(data)
self.f.write(data)
new_stdout = OutputManager("log.txt", sys.stdout)
</code></pre>
<p>Interleaving is dependant on buffering, so you may or may not get the output you expect.
(You can probably turn off or reduce the buffering used, but I don't remember how at the moment)</p>
| 5
|
2009-02-18T02:58:26Z
|
[
"python",
"logging",
"command-line"
] |
Need a better way to execute console commands from python and log the results
| 559,578
|
<p>I have a python script which needs to execute several command line utilities. The stdout output is sometimes used for further processing. In all cases, I want to log the results and raise an exception if an error is detected. I use the following function to achieve this:</p>
<pre><code>def execute(cmd, logsink):
logsink.log("executing: %s\n" % cmd)
popen_obj = subprocess.Popen(\
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = popen_obj.communicate()
returncode = popen_obj.returncode
if (returncode <> 0):
logsink.log(" RETURN CODE: %s\n" % str(returncode))
if (len(stdout.strip()) > 0):
logsink.log(" STDOUT:\n%s\n" % stdout)
if (len(stderr.strip()) > 0):
logsink.log(" STDERR:\n%s\n" % stderr)
if (returncode <> 0):
raise Exception, "execute failed with error output:\n%s" % stderr
return stdout
</code></pre>
<p>"logsink" can be any python object with a log method. I typically use this to forward the logging data to a specific file, or echo it to the console, or both, or something else...</p>
<p>This works pretty good, except for three problems where I need more fine-grained control than the communicate() method provides:</p>
<ol>
<li>stdout and stderr output can be interleaved on the
console, but the above function logs
them separately. This can
complicate the interpretation of the
log. How do I log stdout and stderr
lines interleaved, in the same order
as they were output?</li>
<li>The above function will only log the
command output once the command has
completed. This complicates diagnosis of issues when commands get stuck in an infinite loop or take a very long time for some other reason. How do I get the log in real-time, while the command is still executing?</li>
<li>If the logs are large, it can get
hard to interpret which command
generated which output. Is there a
way to prefix each line with
something (e.g. the first word of
the cmd string followed by :).</li>
</ol>
| 4
|
2009-02-18T02:02:08Z
| 560,619
|
<p>You can look into pexpect (<a href="http://www.noah.org/wiki/Pexpect" rel="nofollow">http://www.noah.org/wiki/Pexpect</a>)</p>
<p>It solves 1) and 2) out of the box, prefixing the output might be a little trickier.</p>
| 2
|
2009-02-18T11:06:56Z
|
[
"python",
"logging",
"command-line"
] |
Need a better way to execute console commands from python and log the results
| 559,578
|
<p>I have a python script which needs to execute several command line utilities. The stdout output is sometimes used for further processing. In all cases, I want to log the results and raise an exception if an error is detected. I use the following function to achieve this:</p>
<pre><code>def execute(cmd, logsink):
logsink.log("executing: %s\n" % cmd)
popen_obj = subprocess.Popen(\
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = popen_obj.communicate()
returncode = popen_obj.returncode
if (returncode <> 0):
logsink.log(" RETURN CODE: %s\n" % str(returncode))
if (len(stdout.strip()) > 0):
logsink.log(" STDOUT:\n%s\n" % stdout)
if (len(stderr.strip()) > 0):
logsink.log(" STDERR:\n%s\n" % stderr)
if (returncode <> 0):
raise Exception, "execute failed with error output:\n%s" % stderr
return stdout
</code></pre>
<p>"logsink" can be any python object with a log method. I typically use this to forward the logging data to a specific file, or echo it to the console, or both, or something else...</p>
<p>This works pretty good, except for three problems where I need more fine-grained control than the communicate() method provides:</p>
<ol>
<li>stdout and stderr output can be interleaved on the
console, but the above function logs
them separately. This can
complicate the interpretation of the
log. How do I log stdout and stderr
lines interleaved, in the same order
as they were output?</li>
<li>The above function will only log the
command output once the command has
completed. This complicates diagnosis of issues when commands get stuck in an infinite loop or take a very long time for some other reason. How do I get the log in real-time, while the command is still executing?</li>
<li>If the logs are large, it can get
hard to interpret which command
generated which output. Is there a
way to prefix each line with
something (e.g. the first word of
the cmd string followed by :).</li>
</ol>
| 4
|
2009-02-18T02:02:08Z
| 2,448,906
|
<p>One other option:</p>
<pre><code>def run_test(test_cmd):
with tempfile.TemporaryFile() as cmd_out:
proc = subprocess.Popen(test_cmd, stdout=cmd_out, stderr=cmd_out)
proc.wait()
cmd_out.seek(0)
output = "".join(cmd_out.readlines())
return (proc.returncode, output)
</code></pre>
<p>This will interleave <code>stdout</code> and <code>stderr</code> as desired, in a real file that is conveniently open for you.</p>
| 1
|
2010-03-15T16:55:12Z
|
[
"python",
"logging",
"command-line"
] |
Need a better way to execute console commands from python and log the results
| 559,578
|
<p>I have a python script which needs to execute several command line utilities. The stdout output is sometimes used for further processing. In all cases, I want to log the results and raise an exception if an error is detected. I use the following function to achieve this:</p>
<pre><code>def execute(cmd, logsink):
logsink.log("executing: %s\n" % cmd)
popen_obj = subprocess.Popen(\
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = popen_obj.communicate()
returncode = popen_obj.returncode
if (returncode <> 0):
logsink.log(" RETURN CODE: %s\n" % str(returncode))
if (len(stdout.strip()) > 0):
logsink.log(" STDOUT:\n%s\n" % stdout)
if (len(stderr.strip()) > 0):
logsink.log(" STDERR:\n%s\n" % stderr)
if (returncode <> 0):
raise Exception, "execute failed with error output:\n%s" % stderr
return stdout
</code></pre>
<p>"logsink" can be any python object with a log method. I typically use this to forward the logging data to a specific file, or echo it to the console, or both, or something else...</p>
<p>This works pretty good, except for three problems where I need more fine-grained control than the communicate() method provides:</p>
<ol>
<li>stdout and stderr output can be interleaved on the
console, but the above function logs
them separately. This can
complicate the interpretation of the
log. How do I log stdout and stderr
lines interleaved, in the same order
as they were output?</li>
<li>The above function will only log the
command output once the command has
completed. This complicates diagnosis of issues when commands get stuck in an infinite loop or take a very long time for some other reason. How do I get the log in real-time, while the command is still executing?</li>
<li>If the logs are large, it can get
hard to interpret which command
generated which output. Is there a
way to prefix each line with
something (e.g. the first word of
the cmd string followed by :).</li>
</ol>
| 4
|
2009-02-18T02:02:08Z
| 3,097,473
|
<p>This is by no means a complete or exhaustive answer, but perhaps you should look into the Fabric module. </p>
<p><a href="http://docs.fabfile.org/0.9.1/" rel="nofollow">http://docs.fabfile.org/0.9.1/</a></p>
<p>Makes parallel execution of shell commands and error handling rather easy. </p>
| 1
|
2010-06-22T22:00:37Z
|
[
"python",
"logging",
"command-line"
] |
Shared folder sessions in Python
| 559,662
|
<p>I'm trying to get a list of currently-open sessions in Python via WMI.</p>
<p>What I'm after is the exact information displayed in the Computer Management thingy, when you go to <strong>System Tools</strong> -> <strong>Shared Folders</strong> -> <strong>Sessions</strong> (ie username, computer name, connected time, that sort of thing).</p>
<p>I know (or at least believe) it has something to do with *Win32_ConnectionShare*...</p>
<p>If it makes a difference, I'm using <a href="http://timgolden.me.uk/python/wmi.html" rel="nofollow">Tim Golden's wmi module</a>.</p>
<p>Of course, if there's another (non-WMI) way of getting this information then that's welcome too...</p>
| 1
|
2009-02-18T02:48:10Z
| 559,896
|
<p>Never mind -- I found it:</p>
<pre><code>>>> import wmi
>>> c = wmi.WMI()
>>> for x in c.Win32_ConnectionShare():
print "%s: %s" % (x.Dependent.Username, x.Dependent.ComputerName)
</code></pre>
| 1
|
2009-02-18T04:59:36Z
|
[
"python",
"winapi",
"wmi",
"shared-folders"
] |
Django - queries made repeat/inefficient
| 559,701
|
<p>Alright, I have a Django view, like this:</p>
<pre><code>@render_to('home/main.html')
def login(request):
# also tried Client.objects.select_related().all()
clients = Client.objects.all()
return {'clients':clients}
</code></pre>
<p>And I have a template, <code>main.html</code>, like this:</p>
<pre><code><ul>
{% for client in clients %}
<li>{{ client.full_name }}</li>
<ul>
{% for pet in client.pets.all %}
<li>{{ pet.full_name }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
</code></pre>
<p>I also print out all the queries in <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-debug" rel="nofollow"><code>sql_queries</code></a> at the bottom of my base template. When I run this view, the following queries are made:</p>
<pre><code>SELECT `home_client`.`id`, ... FROM `home_client`;
SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 1;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1;
SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 2;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 2;
</code></pre>
<p>My question is, why are all these queries being made? Shouldn't it just be 1 query to retrieve all the clients and a query per client to retrieve all the pets from each client? I have 2 clients in the <code>home_client</code> table, so it should be 3 queries total. Most troubling of all is that queries 3 and 4 are 100% identical. I don't want to "prematurely optimize" or anything but I do want to make sure Django isn't being wildly inefficient. Any help on this would be appreciated. Thanks.</p>
| 2
|
2009-02-18T03:12:29Z
| 559,708
|
<p>Django uses a cache. The RDBMS uses a cache. Don't prematurely optimize the queries. </p>
<p>You can play with bulk queries in your view function instead of one-at-a-time queries in your template. </p>
<pre><code>@render_to('home/main.html')
def login(request):
# Query all clients
clients = Client.objects.all()
# Assemble an in-memory table of pets
pets = collections.defaultdict(list)
for p in Pet.objects.all():
pets[pet.client].append(p)
# Create clients and pets tuples
clientsPetTuples = [ (c,pets[c]) for c in clients ]
return {'clientPets': clientsPetTuples}
</code></pre>
<p>However, you don't seem to have any evidence that your template is the slowest part of your application.</p>
<p>Further, this trades off giant memory use against SQL use. Until you have measurements that prove that your template queries are actually slow, you shouldn't be over thinking the SQL.</p>
<p>Don't worry about the SQL until you have evidence.</p>
| 7
|
2009-02-18T03:18:27Z
|
[
"python",
"django"
] |
Django - queries made repeat/inefficient
| 559,701
|
<p>Alright, I have a Django view, like this:</p>
<pre><code>@render_to('home/main.html')
def login(request):
# also tried Client.objects.select_related().all()
clients = Client.objects.all()
return {'clients':clients}
</code></pre>
<p>And I have a template, <code>main.html</code>, like this:</p>
<pre><code><ul>
{% for client in clients %}
<li>{{ client.full_name }}</li>
<ul>
{% for pet in client.pets.all %}
<li>{{ pet.full_name }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
</code></pre>
<p>I also print out all the queries in <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-debug" rel="nofollow"><code>sql_queries</code></a> at the bottom of my base template. When I run this view, the following queries are made:</p>
<pre><code>SELECT `home_client`.`id`, ... FROM `home_client`;
SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 1;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1;
SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 2;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 2;
</code></pre>
<p>My question is, why are all these queries being made? Shouldn't it just be 1 query to retrieve all the clients and a query per client to retrieve all the pets from each client? I have 2 clients in the <code>home_client</code> table, so it should be 3 queries total. Most troubling of all is that queries 3 and 4 are 100% identical. I don't want to "prematurely optimize" or anything but I do want to make sure Django isn't being wildly inefficient. Any help on this would be appreciated. Thanks.</p>
| 2
|
2009-02-18T03:12:29Z
| 559,712
|
<p>try using Client.objects.all().select_related()</p>
<p>This will automagically also cache related models in a single database query.</p>
| 4
|
2009-02-18T03:20:39Z
|
[
"python",
"django"
] |
Django - queries made repeat/inefficient
| 559,701
|
<p>Alright, I have a Django view, like this:</p>
<pre><code>@render_to('home/main.html')
def login(request):
# also tried Client.objects.select_related().all()
clients = Client.objects.all()
return {'clients':clients}
</code></pre>
<p>And I have a template, <code>main.html</code>, like this:</p>
<pre><code><ul>
{% for client in clients %}
<li>{{ client.full_name }}</li>
<ul>
{% for pet in client.pets.all %}
<li>{{ pet.full_name }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
</code></pre>
<p>I also print out all the queries in <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-debug" rel="nofollow"><code>sql_queries</code></a> at the bottom of my base template. When I run this view, the following queries are made:</p>
<pre><code>SELECT `home_client`.`id`, ... FROM `home_client`;
SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 1;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1;
SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 2;
SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 2;
</code></pre>
<p>My question is, why are all these queries being made? Shouldn't it just be 1 query to retrieve all the clients and a query per client to retrieve all the pets from each client? I have 2 clients in the <code>home_client</code> table, so it should be 3 queries total. Most troubling of all is that queries 3 and 4 are 100% identical. I don't want to "prematurely optimize" or anything but I do want to make sure Django isn't being wildly inefficient. Any help on this would be appreciated. Thanks.</p>
| 2
|
2009-02-18T03:12:29Z
| 560,552
|
<p>Does Client 1 have 2 Pets and Client 2 have 1 Pet?</p>
<p>If so, that would indicate to me that <code>Pet.full_name</code> or something else you're doing in the Pet display loop is trying to access its related Client's details. Django's ORM doesn't use an <a href="http://martinfowler.com/eaaCatalog/identityMap.html" rel="nofollow">identity map</a>, so accessing the Client foreign key from any of your Pet objects would require hitting the database again to retrieve that Client.</p>
<p>P.S. <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4" rel="nofollow"><code>select_related</code></a> won't have any effect on the data you're using in this scenario as it only follows foreign-key relationships, but the pet-to-client relationship is many-to-one.</p>
<p><strong>Update:</strong> if you want to avoid having to change the logic in <code>Pet.full_name</code> or having to perform said logic in the template instead for this case, you could alter the way you get a handle on each Client's Pets in order to prefill the ForeignKey cache with for each Pet with its Client:</p>
<pre><code>class Client(models.Model):
# ...
def get_pets(self):
for pet in self.pets.all():
setattr(pet, '_client_cache', self)
yield pet
</code></pre>
<p>...where the <code>'client'</code> part of <code>'_client_cache'</code> is whatever attribute name is used in the Pet class for the ForeignKey to the Pet's Client. This takes advantage of the way Django implements access to ForeignKey-related objects using its <code>SingleRelatedObjectDescriptor</code> class, which looks for this cache attribute before querying the database.</p>
<p>Resulting template usage:</p>
<pre><code>{% for pet in client.get_pets %}
...
{% endfor %}
</code></pre>
| 3
|
2009-02-18T10:40:17Z
|
[
"python",
"django"
] |
Conditional compilation in Python
| 560,040
|
<p>How to do conditional compilation in Python ?</p>
<p>Is it using DEF ?</p>
| 10
|
2009-02-18T06:26:54Z
| 560,044
|
<p>Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled "on the fly", you can think of it as being similar to a interpreted language like Basic or Perl.<sub>1</sub></p>
<p>You can do something equivalent to conditional compile by just using an if statement. For example:</p>
<pre><code>if FLAG:
def f():
print "Flag is set"
else:
def f():
print "Flag is not set"
</code></pre>
<p>You can do the same for the creation classes, setting of variables and pretty much everything.</p>
<p>The closest way to mimic IFDEF would be to use the hasattr function. E.g.:</p>
<pre><code>if hasattr(aModule, 'FLAG'):
# do stuff if FLAG is defined in the current module.
</code></pre>
<p>You could also use a try/except clause to catch name errors, but the idiomatic way would be to set a variable to None at the top of your script.</p>
<ol>
<li>Python code is byte compiled into an intermediate form like Java, however there generally isn't a separate compilation step. The "raw" source files that end in .py are executable.</li>
</ol>
| 21
|
2009-02-18T06:30:22Z
|
[
"python",
"conditional-compilation"
] |
Conditional compilation in Python
| 560,040
|
<p>How to do conditional compilation in Python ?</p>
<p>Is it using DEF ?</p>
| 10
|
2009-02-18T06:26:54Z
| 560,045
|
<p>Doesn't make much sense in a dynamic environment. If you are looking for conditional definition of functions, you can use <code>if</code>:</p>
<pre><code>if happy:
def makemehappy():
return "I'm good"
</code></pre>
| 3
|
2009-02-18T06:31:23Z
|
[
"python",
"conditional-compilation"
] |
Conditional compilation in Python
| 560,040
|
<p>How to do conditional compilation in Python ?</p>
<p>Is it using DEF ?</p>
| 10
|
2009-02-18T06:26:54Z
| 561,338
|
<p>There is actually a way to get conditional compilation, but it's very limited.</p>
<pre><code>if __debug__:
doSomething()
</code></pre>
<p>The <code>__debug__</code> flag is a special case. When calling python with the <code>-O</code> or <code>-OO</code> options, <code>__debug__</code> will be false, and the compiler will ignore that statement. This is used primarily with asserts, which is why assertions go away if you 'really compile' your scripts with optimization.</p>
<p>So if your goal is to add debugging code, but prevent it from slowing down or otherwise affecting a 'release' build, this does what you want. But you cannot assign a value to <code>__debug__</code>, so that's about all you can use it for.</p>
| 15
|
2009-02-18T14:47:12Z
|
[
"python",
"conditional-compilation"
] |
Conditional compilation in Python
| 560,040
|
<p>How to do conditional compilation in Python ?</p>
<p>Is it using DEF ?</p>
| 10
|
2009-02-18T06:26:54Z
| 563,187
|
<p>Python compiles a module automatically when you import it, so the only way to avoid compiling it is to not import it. You can write something like:</p>
<pre><code>if some_condition:
import some_module
</code></pre>
<p>But that would only work for complete modules. In C and C++ you typically use a preprocessor for conditional compilation. There is nothing stopping you from using a preprocessor on your Python code, so you could write something like:</p>
<pre><code>#ifdef SOME_CONDITION
def some_function():
pass
#endif
</code></pre>
<p>Run that through a C preprocessor and you'd have real conditional compilation and <code>some_function</code> will only be defined if <code>SOME_CONDITION</code> is defined.</p>
<p>BUT (and this is important): Conditional compilation is probably not what you want. Remember that when you import a module, Python simply executes the code in it. The def and class statements in the module are actually <em>executed</em> when you import the module. So the typical way of implementing what other languages would use conditional compilation for is just a normal if statement, like:</p>
<pre><code>if some_condition:
def some_function():
pass
</code></pre>
<p>This will only define <code>some_function</code> if <code>some_condition</code> is true.</p>
<p>It's stuff like this that makes dynamic languages so powerful while remaining conceptually simple.</p>
| 4
|
2009-02-18T22:43:46Z
|
[
"python",
"conditional-compilation"
] |
Conditional compilation in Python
| 560,040
|
<p>How to do conditional compilation in Python ?</p>
<p>Is it using DEF ?</p>
| 10
|
2009-02-18T06:26:54Z
| 5,320,530
|
<p>Use <a href="http://github.com/evanplaice/pypreprocessor/" rel="nofollow">pypreprocessor</a></p>
<p>Which can also be found on <a href="http://pypi.python.org/pypi/pypreprocessor" rel="nofollow">PYPI (Python Package Index)</a> and can be fetched using pip.</p>
<p>The basic example of usage is:</p>
<pre><code>from pypreprocessor import pypreprocessor
pypreprocessor.parse()
#define debug
#ifdef debug
print('The source is in debug mode')
#else
print('The source is not in debug mode')
#endif
</code></pre>
<p>You can also output the postprocessed code to a file by specifying...</p>
<pre><code>pypreprocessor.output = 'output_file_name.py'
</code></pre>
<p>anywhere between the pypreprocessor import and the call to parse().</p>
<p>The module is essentially the python implementation of C preprocessor conditional compilation.</p>
<p><em>SideNote: This is compatible with both python2x and python 3k</em></p>
<p><em>Disclaimer: I'm the author of pypreprocessor</em></p>
<p><strong>Update:</strong></p>
<p>I forgot to mention before. Unlike the <code>if</code>/<code>else</code> or <code>if _debug:</code> approaches described in other answers, this is a true preprocessor. The bytecode produced will not contain the code that is conditionally excluded.</p>
| 6
|
2011-03-16T02:53:03Z
|
[
"python",
"conditional-compilation"
] |
Conditional compilation in Python
| 560,040
|
<p>How to do conditional compilation in Python ?</p>
<p>Is it using DEF ?</p>
| 10
|
2009-02-18T06:26:54Z
| 6,420,277
|
<p>You could use the method discussed here: <a href="http://stackoverflow.com/questions/1592565/determine-if-variable-is-defined-in-python">Determine if variable is defined in Python</a> as a substitute for <code>#ifdef</code> </p>
| 0
|
2011-06-21T04:16:17Z
|
[
"python",
"conditional-compilation"
] |
How do you construct an array suitable for numpy sorting?
| 560,283
|
<p>I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods:</p>
<pre><code>import numpy
x=numpy.asarray([5,4,3])
y=numpy.asarray([33,44,55])
dtype=[('alpha',float), ('beta',float)]
values=numpy.array([(x),(y)])
values=numpy.rollaxis(values,1)
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
print "Try 1:\n", values
values=numpy.empty((len(x),2))
for n in range (len(x)):
values[n][0]=y[n]
values[n][1]=x[n]
print "Try 2:\n", values
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
###
values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])]
print "Try 3:\n", values
values = numpy.array(values, dtype=dtype)
a=numpy.array(values,dtype=dtype)
q=numpy.sort(a,order='alpha')
print "Result:\n",q
</code></pre>
<p>I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly?</p>
<p>*** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?</p>
| 1
|
2009-02-18T08:45:47Z
| 560,503
|
<p>I think you just need to specify the axis that you are sorting on when you have made your final ndarray. Alternatively argsort one of the original arrays and you'll have an index array that you can use to look up in both x and y, which might mean you don't need values at all.</p>
<p>(scipy.org seems to be unreachable right now or I would post you a link to some docs)</p>
<p>Given that your description doesn't quite match your code snippet it's hard to say with certainty, but I think you have over-complicated the creation of your numpy array.</p>
| 2
|
2009-02-18T10:18:49Z
|
[
"python",
"algorithm",
"arrays",
"numpy"
] |
How do you construct an array suitable for numpy sorting?
| 560,283
|
<p>I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods:</p>
<pre><code>import numpy
x=numpy.asarray([5,4,3])
y=numpy.asarray([33,44,55])
dtype=[('alpha',float), ('beta',float)]
values=numpy.array([(x),(y)])
values=numpy.rollaxis(values,1)
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
print "Try 1:\n", values
values=numpy.empty((len(x),2))
for n in range (len(x)):
values[n][0]=y[n]
values[n][1]=x[n]
print "Try 2:\n", values
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
###
values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])]
print "Try 3:\n", values
values = numpy.array(values, dtype=dtype)
a=numpy.array(values,dtype=dtype)
q=numpy.sort(a,order='alpha')
print "Result:\n",q
</code></pre>
<p>I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly?</p>
<p>*** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?</p>
| 1
|
2009-02-18T08:45:47Z
| 560,505
|
<p>I think what you want is the zip function. If you have </p>
<pre><code>x = [1,2,3]
y = [4,5,6]
</code></pre>
<p>then <code>zip(x,y) == [(1,4),(2,5),(3,6)]</code></p>
<p>So your array could be constructed using</p>
<pre><code>a = numpy.array(zip(x,y), dtype=dtype)
</code></pre>
| 6
|
2009-02-18T10:19:56Z
|
[
"python",
"algorithm",
"arrays",
"numpy"
] |
How do you construct an array suitable for numpy sorting?
| 560,283
|
<p>I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods:</p>
<pre><code>import numpy
x=numpy.asarray([5,4,3])
y=numpy.asarray([33,44,55])
dtype=[('alpha',float), ('beta',float)]
values=numpy.array([(x),(y)])
values=numpy.rollaxis(values,1)
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
print "Try 1:\n", values
values=numpy.empty((len(x),2))
for n in range (len(x)):
values[n][0]=y[n]
values[n][1]=x[n]
print "Try 2:\n", values
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
###
values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])]
print "Try 3:\n", values
values = numpy.array(values, dtype=dtype)
a=numpy.array(values,dtype=dtype)
q=numpy.sort(a,order='alpha')
print "Result:\n",q
</code></pre>
<p>I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly?</p>
<p>*** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?</p>
| 1
|
2009-02-18T08:45:47Z
| 560,521
|
<p>I couldn't get a working solution using Numpy's <code>sort</code> function, but here's something else that works:</p>
<pre><code>import numpy
x = [5,4,3]
y = [33,44,55]
r = numpy.asarray([(x[i],y[i]) for i in numpy.lexsort([x])])
</code></pre>
<p><code>lexsort</code> returns the permutation of the array indices which puts the rows in sorted order. If you wanted your results sorted on multiple keys, e.g. by <code>x</code> and then by <code>y</code>, use <code>numpy.lexsort([x,y])</code> instead.</p>
| 1
|
2009-02-18T10:27:04Z
|
[
"python",
"algorithm",
"arrays",
"numpy"
] |
How do you construct an array suitable for numpy sorting?
| 560,283
|
<p>I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods:</p>
<pre><code>import numpy
x=numpy.asarray([5,4,3])
y=numpy.asarray([33,44,55])
dtype=[('alpha',float), ('beta',float)]
values=numpy.array([(x),(y)])
values=numpy.rollaxis(values,1)
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
print "Try 1:\n", values
values=numpy.empty((len(x),2))
for n in range (len(x)):
values[n][0]=y[n]
values[n][1]=x[n]
print "Try 2:\n", values
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
###
values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])]
print "Try 3:\n", values
values = numpy.array(values, dtype=dtype)
a=numpy.array(values,dtype=dtype)
q=numpy.sort(a,order='alpha')
print "Result:\n",q
</code></pre>
<p>I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly?</p>
<p>*** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?</p>
| 1
|
2009-02-18T08:45:47Z
| 562,621
|
<p>for your bonus question -- zip actually unzips too:</p>
<pre><code>In [1]: a = range(10)
In [2]: b = range(10, 20)
In [3]: c = zip(a, b)
In [4]: c
Out[4]:
[(0, 10),
(1, 11),
(2, 12),
(3, 13),
(4, 14),
(5, 15),
(6, 16),
(7, 17),
(8, 18),
(9, 19)]
In [5]: d, e = zip(*c)
In [6]: d, e
Out[6]: ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19))
</code></pre>
| 3
|
2009-02-18T20:11:46Z
|
[
"python",
"algorithm",
"arrays",
"numpy"
] |
How do you construct an array suitable for numpy sorting?
| 560,283
|
<p>I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods:</p>
<pre><code>import numpy
x=numpy.asarray([5,4,3])
y=numpy.asarray([33,44,55])
dtype=[('alpha',float), ('beta',float)]
values=numpy.array([(x),(y)])
values=numpy.rollaxis(values,1)
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
print "Try 1:\n", values
values=numpy.empty((len(x),2))
for n in range (len(x)):
values[n][0]=y[n]
values[n][1]=x[n]
print "Try 2:\n", values
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
###
values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])]
print "Try 3:\n", values
values = numpy.array(values, dtype=dtype)
a=numpy.array(values,dtype=dtype)
q=numpy.sort(a,order='alpha')
print "Result:\n",q
</code></pre>
<p>I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly?</p>
<p>*** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?</p>
| 1
|
2009-02-18T08:45:47Z
| 1,084,546
|
<p>Simon suggested <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow">argsort</a> as an alternative approach; I'd recommend it as the way to go. No messy merging, zipping, or unzipping: just access by index.</p>
<pre><code>idx = numpy.argsort(x)
ans = [ (x[idx[i]],y[idx[i]]) for i in idx]
</code></pre>
| 3
|
2009-07-05T18:09:08Z
|
[
"python",
"algorithm",
"arrays",
"numpy"
] |
How do you construct an array suitable for numpy sorting?
| 560,283
|
<p>I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods:</p>
<pre><code>import numpy
x=numpy.asarray([5,4,3])
y=numpy.asarray([33,44,55])
dtype=[('alpha',float), ('beta',float)]
values=numpy.array([(x),(y)])
values=numpy.rollaxis(values,1)
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
print "Try 1:\n", values
values=numpy.empty((len(x),2))
for n in range (len(x)):
values[n][0]=y[n]
values[n][1]=x[n]
print "Try 2:\n", values
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
###
values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])]
print "Try 3:\n", values
values = numpy.array(values, dtype=dtype)
a=numpy.array(values,dtype=dtype)
q=numpy.sort(a,order='alpha')
print "Result:\n",q
</code></pre>
<p>I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly?</p>
<p>*** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?</p>
| 1
|
2009-02-18T08:45:47Z
| 2,612,647
|
<p><code>zip()</code> <em>might</em> be inefficient for large arrays. <a href="http://www.scipy.org/Numpy_Example_List#dstack" rel="nofollow"><code>numpy.dstack()</code></a> could be used instead of <code>zip</code>:</p>
<pre><code>ndx = numpy.argsort(x)
values = numpy.dstack((x[ndx], y[ndx]))
</code></pre>
| 3
|
2010-04-10T07:44:08Z
|
[
"python",
"algorithm",
"arrays",
"numpy"
] |
How do i extract my required data from HTML file?
| 560,936
|
<p>This is the HTML I have:</p>
<pre><code>p_tags = '''<p class="foo-body">
<font class="test-proof">Full name</font> Foobar<br />
<font class="test-proof">Born</font> July 7, 1923, foo, bar<br />
<font class="test-proof">Current age</font> 27 years 226 days<br />
<font class="test-proof">Major teams</font> <span style="white-space: nowrap">Japan,</span> <span style="white-space: nowrap">Jakarta,</span> <span style="white-space: nowrap">bazz,</span> <span style="white-space: nowrap">foo,</span> <span style="white-space: nowrap">foobazz</span><br />
<font class="test-proof">Also</font> bar<br />
<font class="test-proof">foo style</font> hand <br />
<font class="test-proof">bar style</font> ball<br />
<font class="test-proof">foo position</font> bak<br />
<br class="bar" />
</p>'''
</code></pre>
<p>This is my Python code, using Beautiful Soup:</p>
<pre><code>def get_info(p_tags):
"""Returns brief information."""
head_list = []
detail_list = []
# This works fine
for head in p_tags.findAll('font', 'test-proof'):
head_list.append(head.contents[0])
# Some problem with this?
for index in xrange(2, 30, 4):
detail_list.append(p_tags.contents[index])
return dict([(l, detail_list[head_list.index(l)]) for l in head_list])
</code></pre>
<p>I get the proper <code>head_list</code> from the HTML but the <code>detail_list</code> is not working.</p>
<pre>
head_list = [u'Full name',
u'Born',
u'Current age',
u'Major teams',
u'Also',
u'foo style',
u'bar style',
u'foo position']
</pre>
<p>I wanted something like this</p>
<pre>
{
'Full name': 'Foobar',
'Born': 'July 7, 1923, foo, bar',
'Current age': '78 years 226 days',
'Major teams': 'Japan, Jakarta, bazz, foo, foobazz',
'Also': 'bar',
'foo style': 'hand',
'bar style': 'ball',
'foo position': 'bak'
}
</pre>
<p>Any help would be appreciable. Thanks in advance.</p>
| 2
|
2009-02-18T12:51:28Z
| 560,973
|
<p>You want to find the strings preceded by > and followed by <, ignoring trailing or leading whitespace. You can do this quite easily with a loop looking at each character in the string, or regular expressions could help. Something like >[ \t]*[^<]+[ \t]*<.</p>
<p>You could also use <a href="http://www.amk.ca/python/howto/regex/regex.html#SECTION000610000000000000000" rel="nofollow">re.split</a> and a regex representing the tag contents, something like <[^>]*> as the splitter, you will get some empty entries in the array, but these are easily deleted.</p>
| 0
|
2009-02-18T13:03:57Z
|
[
"python",
"screen-scraping",
"beautifulsoup"
] |
How do i extract my required data from HTML file?
| 560,936
|
<p>This is the HTML I have:</p>
<pre><code>p_tags = '''<p class="foo-body">
<font class="test-proof">Full name</font> Foobar<br />
<font class="test-proof">Born</font> July 7, 1923, foo, bar<br />
<font class="test-proof">Current age</font> 27 years 226 days<br />
<font class="test-proof">Major teams</font> <span style="white-space: nowrap">Japan,</span> <span style="white-space: nowrap">Jakarta,</span> <span style="white-space: nowrap">bazz,</span> <span style="white-space: nowrap">foo,</span> <span style="white-space: nowrap">foobazz</span><br />
<font class="test-proof">Also</font> bar<br />
<font class="test-proof">foo style</font> hand <br />
<font class="test-proof">bar style</font> ball<br />
<font class="test-proof">foo position</font> bak<br />
<br class="bar" />
</p>'''
</code></pre>
<p>This is my Python code, using Beautiful Soup:</p>
<pre><code>def get_info(p_tags):
"""Returns brief information."""
head_list = []
detail_list = []
# This works fine
for head in p_tags.findAll('font', 'test-proof'):
head_list.append(head.contents[0])
# Some problem with this?
for index in xrange(2, 30, 4):
detail_list.append(p_tags.contents[index])
return dict([(l, detail_list[head_list.index(l)]) for l in head_list])
</code></pre>
<p>I get the proper <code>head_list</code> from the HTML but the <code>detail_list</code> is not working.</p>
<pre>
head_list = [u'Full name',
u'Born',
u'Current age',
u'Major teams',
u'Also',
u'foo style',
u'bar style',
u'foo position']
</pre>
<p>I wanted something like this</p>
<pre>
{
'Full name': 'Foobar',
'Born': 'July 7, 1923, foo, bar',
'Current age': '78 years 226 days',
'Major teams': 'Japan, Jakarta, bazz, foo, foobazz',
'Also': 'bar',
'foo style': 'hand',
'bar style': 'ball',
'foo position': 'bak'
}
</pre>
<p>Any help would be appreciable. Thanks in advance.</p>
| 2
|
2009-02-18T12:51:28Z
| 561,052
|
<p>The issue is that your HTML is not very well thought out -- you have a "mixed content model" where your labels and your data are interleaved. Your labels are wrapped in <code><font></code> Tags, but your data is in NavigableString nodes.</p>
<p>You need to iterate over the contents of <code>p_tag</code>. There will be two kinds of nodes: <code>Tag</code> nodes (which have your <code><font></code> tags) and <code>NavigableString</code> nodes which have the other bits of text.</p>
<pre><code>from beautifulsoup import *
label_value_pairs = []
for n in p_tag.contents:
if isinstance(n,Tag) and tag == "font"
label= n.string
elif isinstance(n, NavigableString):
value= n.string
label_value_pairs.append( label, value )
else:
# Generally tag == "br"
pass
print dict( label_value_pairs )
</code></pre>
<p>Something approximately like that.</p>
| 4
|
2009-02-18T13:30:15Z
|
[
"python",
"screen-scraping",
"beautifulsoup"
] |
How do i extract my required data from HTML file?
| 560,936
|
<p>This is the HTML I have:</p>
<pre><code>p_tags = '''<p class="foo-body">
<font class="test-proof">Full name</font> Foobar<br />
<font class="test-proof">Born</font> July 7, 1923, foo, bar<br />
<font class="test-proof">Current age</font> 27 years 226 days<br />
<font class="test-proof">Major teams</font> <span style="white-space: nowrap">Japan,</span> <span style="white-space: nowrap">Jakarta,</span> <span style="white-space: nowrap">bazz,</span> <span style="white-space: nowrap">foo,</span> <span style="white-space: nowrap">foobazz</span><br />
<font class="test-proof">Also</font> bar<br />
<font class="test-proof">foo style</font> hand <br />
<font class="test-proof">bar style</font> ball<br />
<font class="test-proof">foo position</font> bak<br />
<br class="bar" />
</p>'''
</code></pre>
<p>This is my Python code, using Beautiful Soup:</p>
<pre><code>def get_info(p_tags):
"""Returns brief information."""
head_list = []
detail_list = []
# This works fine
for head in p_tags.findAll('font', 'test-proof'):
head_list.append(head.contents[0])
# Some problem with this?
for index in xrange(2, 30, 4):
detail_list.append(p_tags.contents[index])
return dict([(l, detail_list[head_list.index(l)]) for l in head_list])
</code></pre>
<p>I get the proper <code>head_list</code> from the HTML but the <code>detail_list</code> is not working.</p>
<pre>
head_list = [u'Full name',
u'Born',
u'Current age',
u'Major teams',
u'Also',
u'foo style',
u'bar style',
u'foo position']
</pre>
<p>I wanted something like this</p>
<pre>
{
'Full name': 'Foobar',
'Born': 'July 7, 1923, foo, bar',
'Current age': '78 years 226 days',
'Major teams': 'Japan, Jakarta, bazz, foo, foobazz',
'Also': 'bar',
'foo style': 'hand',
'bar style': 'ball',
'foo position': 'bak'
}
</pre>
<p>Any help would be appreciable. Thanks in advance.</p>
| 2
|
2009-02-18T12:51:28Z
| 561,085
|
<p>Sorry for the unnecessarily complex code, I badly need a big dose of caffeine ;)</p>
<pre><code>import re
str = """<p class="foo-body">
<font class="test-proof">Full name</font> Foobar<br />
<font class="test-proof">Born</font> July 7, 1923, foo, bar<br />
<font class="test-proof">Current age</font> 27 years 226 days<br />
<font class="test-proof">Major teams</font> <span style="white-space: nowrap">Japan,</span> <span style="white-space: nowrap">Jakarta,</span> <span style="white-space: nowrap">bazz,</span> <span style="white-space: nowrap">foo,</span> <span style="white-space: nowrap">foobazz</span><br />
<font class="test-proof">Also</font> bar<br />
<font class="test-proof">foo style</font> hand <br />
<font class="test-proof">bar style</font> ball<br />
<font class="test-proof">foo position</font> bak<br />
<br class="bar" />
</p>"""
R_EXTRACT_DATA = re.compile("<font\s[^>]*>[\s]*(.*?)[\s]*</font>[\s]*(.*?)[\s]*<br />", re.IGNORECASE)
R_STRIP_TAGS = re.compile("<span\s[^>]*>|</span>", re.IGNORECASE)
def strip_tags(str):
"""Strip un-necessary <span> tags
"""
return R_STRIP_TAGS.sub("", str)
def get_info(str):
"""Extract useful info from the given string
"""
data = R_EXTRACT_DATA.findall(str)
data_dict = {}
for x in [(x[0], strip_tags(x[1])) for x in data]:
data_dict[x[0]] = x[1]
return data_dict
print get_info(str)
</code></pre>
| 2
|
2009-02-18T13:41:10Z
|
[
"python",
"screen-scraping",
"beautifulsoup"
] |
How do i extract my required data from HTML file?
| 560,936
|
<p>This is the HTML I have:</p>
<pre><code>p_tags = '''<p class="foo-body">
<font class="test-proof">Full name</font> Foobar<br />
<font class="test-proof">Born</font> July 7, 1923, foo, bar<br />
<font class="test-proof">Current age</font> 27 years 226 days<br />
<font class="test-proof">Major teams</font> <span style="white-space: nowrap">Japan,</span> <span style="white-space: nowrap">Jakarta,</span> <span style="white-space: nowrap">bazz,</span> <span style="white-space: nowrap">foo,</span> <span style="white-space: nowrap">foobazz</span><br />
<font class="test-proof">Also</font> bar<br />
<font class="test-proof">foo style</font> hand <br />
<font class="test-proof">bar style</font> ball<br />
<font class="test-proof">foo position</font> bak<br />
<br class="bar" />
</p>'''
</code></pre>
<p>This is my Python code, using Beautiful Soup:</p>
<pre><code>def get_info(p_tags):
"""Returns brief information."""
head_list = []
detail_list = []
# This works fine
for head in p_tags.findAll('font', 'test-proof'):
head_list.append(head.contents[0])
# Some problem with this?
for index in xrange(2, 30, 4):
detail_list.append(p_tags.contents[index])
return dict([(l, detail_list[head_list.index(l)]) for l in head_list])
</code></pre>
<p>I get the proper <code>head_list</code> from the HTML but the <code>detail_list</code> is not working.</p>
<pre>
head_list = [u'Full name',
u'Born',
u'Current age',
u'Major teams',
u'Also',
u'foo style',
u'bar style',
u'foo position']
</pre>
<p>I wanted something like this</p>
<pre>
{
'Full name': 'Foobar',
'Born': 'July 7, 1923, foo, bar',
'Current age': '78 years 226 days',
'Major teams': 'Japan, Jakarta, bazz, foo, foobazz',
'Also': 'bar',
'foo style': 'hand',
'bar style': 'ball',
'foo position': 'bak'
}
</pre>
<p>Any help would be appreciable. Thanks in advance.</p>
| 2
|
2009-02-18T12:51:28Z
| 561,106
|
<p>I started answering this before I realised you were using 'beautiful soup' but here's a parser that I think works with your example string written using the HTMLParser library</p>
<pre><code>from HTMLParser import HTMLParser
results = {}
class myParse(HTMLParser):
def __init__(self):
self.state = ""
HTMLParser.__init__(self)
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "font" and attrs.has_key("class") and attrs['class'] == "test-proof":
self.state = "getKey"
def handle_endtag(self, tag):
if self.state == "getKey" and tag == "font":
self.state = "getValue"
def handle_data(self, data):
data = data.strip()
if not data:
return
if self.state == "getKey":
self.resultsKey = data
elif self.state == "getValue":
if results.has_key(self.resultsKey):
results[self.resultsKey] += " " + data
else:
results[self.resultsKey] = data
if __name__ == "__main__":
p_tags = """<p class="foo-body"> <font class="test-proof">Full name</font> Foobar<br /> <font class="test-proof">Born</font> July 7, 1923, foo, bar<br /> <font class="test-proof">Current age</font> 27 years 226 days<br /> <font class="test-proof">Major teams</font> <span style="white-space: nowrap">Japan,</span> <span style="white-space: nowrap">Jakarta,</span> <span style="white-space: nowrap">bazz,</span> <span style="white-space: nowrap">foo,</span> <span style="white-space: nowrap">foobazz</span><br /> <font class="test-proof">Also</font> bar<br /> <font class="test-proof">foo style</font> hand <br /> <font class="test-proof">bar style</font> ball<br /> <font class="test-proof">foo position</font> bak<br /> <br class="bar" /></p>"""
parser = myParse()
parser.feed(p_tags)
print results
</code></pre>
<p>Gives the result:</p>
<pre><code>{'foo position': 'bak',
'Major teams': 'Japan, Jakarta, bazz, foo, foobazz',
'Also': 'bar',
'Current age': '27 years 226 days',
'Born': 'July 7, 1923, foo, bar' ,
'foo style': 'hand',
'bar style': 'ball',
'Full name': 'Foobar'}
</code></pre>
| 4
|
2009-02-18T13:50:26Z
|
[
"python",
"screen-scraping",
"beautifulsoup"
] |
Implementing chat in an application?
| 561,301
|
<p>I'm making a game and I am using Python for the server side. </p>
<p>It would be fairly trivial to implement chat myself using Python - that's not my question.<br>
<strong>My question is</strong><br>
I was just wondering if there were any pre-made chat servers or some kind of service that I would be able to implement inside of my game instead of rolling my own chat server?<br>
Maybe like a different process I could run next to my game server process?</p>
| 3
|
2009-02-18T14:38:01Z
| 561,313
|
<p>I recommend using XMPP/Jabber. There are a lot of libraries for clients and servers in different languages. It's free/open source.</p>
<p><a href="http://en.wikipedia.org/wiki/XMPP" rel="nofollow">http://en.wikipedia.org/wiki/XMPP</a></p>
| 10
|
2009-02-18T14:40:42Z
|
[
"python",
"chat"
] |
Implementing chat in an application?
| 561,301
|
<p>I'm making a game and I am using Python for the server side. </p>
<p>It would be fairly trivial to implement chat myself using Python - that's not my question.<br>
<strong>My question is</strong><br>
I was just wondering if there were any pre-made chat servers or some kind of service that I would be able to implement inside of my game instead of rolling my own chat server?<br>
Maybe like a different process I could run next to my game server process?</p>
| 3
|
2009-02-18T14:38:01Z
| 561,331
|
<p>Maybe you could use IRC as a chat service, I know of <a href="http://python-irclib.sourceforge.net/" rel="nofollow">irclib</a> for python, its more of a client but in theory you could use it to proxy an other IRC server from the game server.</p>
<p>Its a little hackish, just thought I'd mention it</p>
| 1
|
2009-02-18T14:45:15Z
|
[
"python",
"chat"
] |
Implementing chat in an application?
| 561,301
|
<p>I'm making a game and I am using Python for the server side. </p>
<p>It would be fairly trivial to implement chat myself using Python - that's not my question.<br>
<strong>My question is</strong><br>
I was just wondering if there were any pre-made chat servers or some kind of service that I would be able to implement inside of my game instead of rolling my own chat server?<br>
Maybe like a different process I could run next to my game server process?</p>
| 3
|
2009-02-18T14:38:01Z
| 564,419
|
<p>Honestly, I think it'd be best for you to roll your own and get it tightly integrated with your program. I know there's no sense in reinventing the wheel, but there are several advantages to doing so in your case: integration, learning, security, and simplicity.</p>
| 1
|
2009-02-19T08:42:01Z
|
[
"python",
"chat"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,493
|
<p>I'd go the 'encode integer as binary string, then base64 encode that' method you suggest, and I'd do it using struct:</p>
<pre><code>>>> import struct, base64
>>> base64.b64encode(struct.pack('l', 47))
'LwAAAA=='
>>> struct.unpack('l', base64.b64decode(_))
(47,)
</code></pre>
<p>Edit again:
To strip out the extra 0s on numbers that are too small to need full 32-bit precision, try this:</p>
<pre><code>def pad(str, l=4):
while len(str) < l:
str = '\x00' + str
return str
>>> base64.b64encode(struct.pack('!l', 47).replace('\x00', ''))
'Lw=='
>>> struct.unpack('!l', pad(base64.b64decode('Lw==')))
(47,)
</code></pre>
| 1
|
2009-02-18T15:27:18Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,534
|
<p>Base64 takes 4 bytes/characters to encode 3 bytes and can only encode multiples of 3 bytes (and adds padding otherwise).</p>
<p>So representing 4 bytes (your average int) in Base64 would take 8 bytes. Encoding the same 4 bytes in hex would also take 8 bytes. So you wouldn't gain anything for a single int.</p>
| 4
|
2009-02-18T15:33:18Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,547
|
<p>If you are looking for a way to <em>shorten</em> the integer representation using base64, I think you need to look elsewhere. When you encode something with base64 it doesn't get shorter, in fact it gets longer. </p>
<p>E.g. 11234 encoded with base64 would yield MTEyMzQ=</p>
<p>When using base64 you have overlooked the fact that you are not converting just the digits (0-9) to a 64 character encoding. You are converting 3 bytes into 4 bytes so you are guaranteed your base64 encoded string would be 33.33% longer.</p>
| 2
|
2009-02-18T15:35:18Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,630
|
<p>You don't want base64 encoding, you want to represent a base 10 numeral in numeral base X.</p>
<p>If you want your base 10 numeral represented in the 26 letters available you could use: <a href="http://en.wikipedia.org/wiki/Hexavigesimal">http://en.wikipedia.org/wiki/Hexavigesimal</a>.
(You can extend that example for a much larger base by using all the legal url characters)</p>
<p>You should atleast be able to get base 38 (26 letters, 10 numbers, +, _)</p>
| 7
|
2009-02-18T15:48:31Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,631
|
<p>The easy bit is converting the byte string to web-safe base64:</p>
<pre><code>import base64
output = base64.urlsafe_b64encode(s)
</code></pre>
<p>The tricky bit is the first step - convert the integer to a byte string.</p>
<p>If your integers are small you're better off hex encoding them - see <a href="http://stackoverflow.com/questions/561486/how-do-you-base64-encode-an-integer-in-python/561534#561534">saua</a></p>
<p>Otherwise (hacky recursive version):</p>
<pre><code>def convertIntToByteString(i):
if i == 0:
return ""
else:
return convertIntToByteString(i >> 8) + chr(i & 255)
</code></pre>
| 8
|
2009-02-18T15:48:31Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,704
|
<p>This answer is similar in spirit to Douglas Leeder's, with the following changes:</p>
<ul>
<li>It doesn't use actual Base64, so there's no padding characters</li>
<li><p>Instead of converting the number first to a byte-string (base 256), it converts it directly to base 64, which has the advantage of letting you represent negative numbers using a sign character.</p>
<pre><code>import string
ALPHABET = string.ascii_uppercase + string.ascii_lowercase + \
string.digits + '-_'
ALPHABET_REVERSE = dict((c, i) for (i, c) in enumerate(ALPHABET))
BASE = len(ALPHABET)
SIGN_CHARACTER = '$'
def num_encode(n):
if n < 0:
return SIGN_CHARACTER + num_encode(-n)
s = []
while True:
n, r = divmod(n, BASE)
s.append(ALPHABET[r])
if n == 0: break
return ''.join(reversed(s))
def num_decode(s):
if s[0] == SIGN_CHARACTER:
return -num_decode(s[1:])
n = 0
for c in s:
n = n * BASE + ALPHABET_REVERSE[c]
return n
</code></pre></li>
</ul>
<hr>
<pre><code> >>> num_encode(0)
'A'
>>> num_encode(64)
'BA'
>>> num_encode(-(64**5-1))
'$_____'
</code></pre>
<hr>
<p>A few side notes:</p>
<ul>
<li>You could (<em>marginally</em>) increase the human-readibility of the base-64 numbers by putting string.digits first in the alphabet (and making the sign character '-'); I chose the order that I did based on Python's urlsafe_b64encode.</li>
<li>If you're encoding a lot of negative numbers, you could increase the efficiency by using a sign bit or one's/two's complement instead of a sign character.</li>
<li>You should be able to easily adapt this code to different bases by changing the alphabet, either to restrict it to only alphanumeric characters or to add additional "URL-safe" characters.</li>
<li>I would recommend <em>against</em> using a representation other than base 10 in URIs in most casesâit adds complexity and makes debugging harder without significant savings compared to the overhead of HTTPâunless you're going for something TinyURL-esque.</li>
</ul>
| 54
|
2009-02-18T16:00:18Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,799
|
<p>a little hacky, but it works:</p>
<pre><code>def b64num(num_to_encode):
h = hex(num_to_encode)[2:] # hex(n) returns 0xhh, strip off the 0x
h = len(h) & 1 and '0'+h or h # if odd number of digits, prepend '0' which hex codec requires
return h.decode('hex').encode('base64')
</code></pre>
<p>you could replace the call to .encode('base64') with something in the base64 module, such as urlsafe_b64encode()</p>
| 3
|
2009-02-18T16:19:56Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,809
|
<p>To encode <code>n</code>:</p>
<pre><code>data = ''
while n > 0:
data = chr(n & 255) + data
n = n >> 8
encoded = base64.urlsafe_b64encode(data).rstrip('=')
</code></pre>
<p>To decode <code>s</code>:</p>
<pre><code>data = base64.urlsafe_b64decode(s + '===')
decoded = 0
while len(data) > 0:
decoded = (decoded << 8) | ord(data[0])
data = data[1:]
</code></pre>
<p>In the same spirit as other for some âoptimalâ encoding, you can use <strong>73</strong> characters according to RFC 1738 (actually 74 if you count â+â as usable):</p>
<pre><code>alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_`\"!$'()*,-."
encoded = ''
while n > 0:
n, r = divmod(n, len(alphabet))
encoded = alphabet[r] + encoded
</code></pre>
<p>and the decoding:</p>
<pre><code>decoded = 0
while len(s) > 0:
decoded = decoded * len(alphabet) + alphabet.find(s[0])
s = s[1:]
</code></pre>
| 9
|
2009-02-18T16:22:44Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 561,875
|
<p>You probably do not want real base64 encoding for this - it will add padding etc, potentially even resulting in larger strings than hex would for small numbers. If there's no need to interoperate with anything else, just use your own encoding. Eg. here's a function that will encode to any base (note the digits are actually stored least-significant first to avoid extra reverse() calls:</p>
<pre><code>def make_encoder(baseString):
size = len(baseString)
d = dict((ch, i) for (i, ch) in enumerate(baseString)) # Map from char -> value
if len(d) != size:
raise Exception("Duplicate characters in encoding string")
def encode(x):
if x==0: return baseString[0] # Only needed if don't want '' for 0
l=[]
while x>0:
l.append(baseString[x % size])
x //= size
return ''.join(l)
def decode(s):
return sum(d[ch] * size**i for (i,ch) in enumerate(s))
return encode, decode
# Base 64 version:
encode,decode = make_encoder("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
assert decode(encode(435346456456)) == 435346456456
</code></pre>
<p>This has the advantage that you can use whatever base you want, just by adding appropriate
characters to the encoder's base string.</p>
<p>Note that the gains for larger bases are not going to be that big however. base 64 will only reduce the size to 2/3rds of base 16 (6 bits/char instead of 4). Each doubling only adds one more bit per character. Unless you've a real need to compact things, just using hex will probably be the simplest and fastest option.</p>
| 13
|
2009-02-18T16:40:37Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 6,602,286
|
<p>I maintain a little library named zbase62: <a href="http://pypi.python.org/pypi/zbase62" rel="nofollow">http://pypi.python.org/pypi/zbase62</a></p>
<p>With it you can convert from a Python 2 str object to a base-62 encoded string and vice versa:</p>
<pre><code>Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> d = os.urandom(32)
>>> d
'C$\x8f\xf9\x92NV\x97\x13H\xc7F\x0c\x0f\x8d9}\xf5.u\xeeOr\xc2V\x92f\x1b=:\xc3\xbc'
>>> from zbase62 import zbase62
>>> encoded = zbase62.b2a(d)
>>> encoded
'Fv8kTvGhIrJvqQ2oTojUGlaVIxFE1b6BCLpH8JfYNRs'
>>> zbase62.a2b(encoded)
'C$\x8f\xf9\x92NV\x97\x13H\xc7F\x0c\x0f\x8d9}\xf5.u\xeeOr\xc2V\x92f\x1b=:\xc3\xbc'
</code></pre>
<p>However, you still need to convert from integer to str. This comes built-in to Python 3:</p>
<pre><code>Python 3.2 (r32:88445, Mar 25 2011, 19:56:22)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> d = os.urandom(32)
>>> d
b'\xe4\x0b\x94|\xb6o\x08\xe9oR\x1f\xaa\xa8\xe8qS3\x86\x82\t\x15\xf2"\x1dL%?\xda\xcc3\xe3\xba'
>>> int.from_bytes(d, 'big')
103147789615402524662804907510279354159900773934860106838120923694590497907642
>>> x= _
>>> x.to_bytes(32, 'big')
b'\xe4\x0b\x94|\xb6o\x08\xe9oR\x1f\xaa\xa8\xe8qS3\x86\x82\t\x15\xf2"\x1dL%?\xda\xcc3\xe3\xba'
</code></pre>
<p>To convert from int to bytes and vice versa in Python 2, there is not a convenient, standard way as far as I know. I guess maybe I should copy some implementation, such as this one: <a href="https://github.com/warner/foolscap/blob/46e3a041167950fa93e48f65dcf106a576ed110e/foolscap/banana.py#L41" rel="nofollow">https://github.com/warner/foolscap/blob/46e3a041167950fa93e48f65dcf106a576ed110e/foolscap/banana.py#L41</a> into zbase62 for your convenience.</p>
| 3
|
2011-07-06T20:08:32Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 7,011,482
|
<p>I needed a signed integer, so I ended up going with:</p>
<pre><code>import struct, base64
def b64encode_integer(i):
return base64.urlsafe_b64encode(struct.pack('i', i)).rstrip('=\n')
</code></pre>
<p>Example:</p>
<pre><code>>>> b64encode_integer(1)
'AQAAAA'
>>> b64encode_integer(-1)
'_____w'
>>> b64encode_integer(256)
'AAEAAA'
</code></pre>
| 2
|
2011-08-10T13:23:09Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 18,001,426
|
<p>All the answers given regarding Base64 are very reasonable solutions. But they're technically incorrect. To convert an integer to the <em>shortest URL safe string</em> possible, what you want is base 66 (there are <a href="http://tools.ietf.org/html/rfc3986#section-2.3">66 URL safe characters</a>).</p>
<p>That code looks like this:</p>
<pre><code>from io import StringIO
import urllib
BASE66_ALPHABET = u"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~"
BASE = len(BASE66_ALPHABET)
def hexahexacontadecimal_encode_int(n):
if n == 0:
return BASE66_ALPHABET[0].encode('ascii')
r = StringIO()
while n:
n, t = divmod(n, BASE)
r.write(BASE66_ALPHABET[t])
return r.getvalue().encode('ascii')[::-1]
</code></pre>
<p>Here's a full implementation with source and ready to go pip installable package: </p>
<p><a href="https://github.com/aljungberg/hexahexacontadecimal">https://github.com/aljungberg/hexahexacontadecimal</a></p>
| 18
|
2013-08-01T18:08:21Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 30,480,048
|
<p>I'm working on making a pip package for this.</p>
<p>I recommend you use my bases.py <a href="https://github.com/kamijoutouma/bases.py" rel="nofollow">https://github.com/kamijoutouma/bases.py</a> which was inspired by bases.js</p>
<pre><code>from bases import Bases
bases = Bases()
bases.toBase16(200) // => 'c8'
bases.toBase(200, 16) // => 'c8'
bases.toBase62(99999) // => 'q0T'
bases.toBase(200, 62) // => 'q0T'
bases.toAlphabet(300, 'aAbBcC') // => 'Abba'
bases.fromBase16('c8') // => 200
bases.fromBase('c8', 16) // => 200
bases.fromBase62('q0T') // => 99999
bases.fromBase('q0T', 62) // => 99999
bases.fromAlphabet('Abba', 'aAbBcC') // => 300
</code></pre>
<p>refer to <a href="https://github.com/kamijoutouma/bases.py#known-basesalphabets" rel="nofollow">https://github.com/kamijoutouma/bases.py#known-basesalphabets</a>
for what bases are usable</p>
<p>For your case </p>
<p>I recommend you use either base 32, 58 or 64</p>
<p>Base-64 warning: besides there being several different standards, padding isn't currently added and line lengths aren't tracked. Not recommended for use with APIs that expect formal base-64 strings!</p>
<p>Same goes for base 66 which is currently not supported by both bases.js and bases.py but it might in the <a href="https://github.com/aseemk/bases.js/issues/7" rel="nofollow">future</a></p>
| 2
|
2015-05-27T10:37:39Z
|
[
"python",
"url",
"base64"
] |
How to convert an integer to the shortest url-safe string in Python?
| 561,486
|
<p>I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the cleanest way to convert an integer to base64 (and back again) using Python.</p>
<p>The base64 module has methods for dealing with bytestrings - so maybe one solution would be to convert an integer to its binary representation as a Python string... but I'm not sure how to do that either.</p>
| 60
|
2009-02-18T15:25:25Z
| 31,845,739
|
<p><strong>Pure python, no dependancies, no encoding of byte strings or other nonesense, just turning a base 10 int into base 64 int with the correct RFC 4648 characters:</strong></p>
<pre><code>def tetrasexagesimal(number):
out=""
while number>=0:
if number == 0: out = 'A' + out; break
digit = number % 64
out = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[digit] + out
number /= 64
if number == 0: break
return out
tetrasexagesimal(1)
</code></pre>
<p>Note that 64 is 'BA' which might confuse you at first. Surely its 'AA'? No. It's BA. Where B is like 1 and A is like 0, and thus BA is base64's equivalent of for 10. 00 in base 10 is still 0. :) Hope that saves you some hair pulling, because im definitely running low.</p>
| 1
|
2015-08-06T02:14:30Z
|
[
"python",
"url",
"base64"
] |
Import python functions into a .NET language?
| 561,626
|
<p>I am a C# .NET programmer and am learning Python. I have downloaded IronPython, and know that it can call into .NET libraries. </p>
<p>I'm wondering whether there is a way to do the reverse, that is to call into some existing "classic" Python libraries in my C# code, maybe using .NET Interop.</p>
<p>I'd like to be able to access functions in libraries such as pygame.</p>
| 5
|
2009-02-18T15:47:53Z
| 562,490
|
<p>Ironpython 2.0 is CPython 2.5 compatible, so pure Python that uses <=2.5 APIs should work fine under Ironpython. I believe Ironpython code can then be compiled into a DLL.</p>
<p>For C-extensions like Pygame, you might want to take a look at <a href="http://code.google.com/p/ironclad/">Ironclad</a>. It's a project to allow for C-extensions to be used within Ironpython. This may also give you the native code bridge you're looking for.</p>
| 5
|
2009-02-18T19:32:18Z
|
[
"c#",
"python",
"ironpython"
] |
Import python functions into a .NET language?
| 561,626
|
<p>I am a C# .NET programmer and am learning Python. I have downloaded IronPython, and know that it can call into .NET libraries. </p>
<p>I'm wondering whether there is a way to do the reverse, that is to call into some existing "classic" Python libraries in my C# code, maybe using .NET Interop.</p>
<p>I'd like to be able to access functions in libraries such as pygame.</p>
| 5
|
2009-02-18T15:47:53Z
| 564,023
|
<p>You can use <a href="http://pythonnet.sourceforge.net/" rel="nofollow">Python for .Net</a>, which allows you to 'use CLR services and continue to use existing Python code and C-based extensions while maintaining native execution speeds for Python code.' </p>
<p>Further, 'A key goal for this project has been that Python for .NET should "<strong>work just the way you'd expect in Python</strong>", except for cases that are .NET specific (in which case the goal is to work "just the way you'd expect in C#"). In addition, with the IronPython project gaining traction, it is my goal that code written for IronPython run without modification under Python for .NET.'</p>
<p>Hope this helps</p>
| 3
|
2009-02-19T05:12:58Z
|
[
"c#",
"python",
"ironpython"
] |
python MySQL module class file name
| 561,791
|
<p>I am confused how directory name, file name and class name all work together.</p>
<p>This is what I have at the moment</p>
<pre class="lang-none prettyprint-override"><code> app.py
database/
client.py
staff.py
order.py
</code></pre>
<p>Inside <code>client.py</code> I have a single class called <code>client</code>, which acts as the database model (MVC). The same with my other files: <code>staff.py</code> has a class called <code>staff</code>, <code>order.py</code> has <code>order</code>.</p>
<p>Then in <code>app.py</code> I do:</p>
<pre class="lang-py prettyprint-override"><code> from database import client as model
c = model.client()
</code></pre>
<p>And then I get confused. In an ideal world <strong>this is what I want to do</strong>:</p>
<ol>
<li><p>Keep my database model classes in separate files in their own directory.</p></li>
<li><p>Use them like this:</p></li>
</ol>
<pre class="lang-py prettyprint-override"><code> c = model.client()
o = model.order()
s = model.staff()
</code></pre>
<p>The only way I can see to do this is to put all my classes in a single file called <code>model.py</code> and save this at the root.</p>
<p>I'm sure I am missing something very basic here.</p>
| 2
|
2009-02-18T16:16:36Z
| 561,860
|
<p>Python has two basic ways of importing content. Modules and Packages.</p>
<p><hr /></p>
<p>A module is simply a python file on the include path: <strong>order.py</strong></p>
<p>If order.py defines a class named <strong>foo</strong>, then access to that class could be had by:</p>
<pre><code>import order
o = order.foo()
</code></pre>
<p>In order to use the syntax from the orignial question, you would need to ensure that your <strong>model.py</strong> file has the following attributes: [client, staff, order]</p>
<p>However, that typically means placing them in a single file. Which is what you are trying to avoid.</p>
<p><hr /></p>
<p>A package is a directory with an <strong>__init</strong>.py** inside of it. The <strong>init</strong>.py initializes the package (ie. it is run on first import), and you can have either modules or sub-packages within that directory.</p>
<pre><code>model
__init__.py
client.py
staff.py
order.py
</code></pre>
<p>That way, to access any of the sub modules, you would simply say:</p>
<pre><code>import model.client
</code></pre>
<p>However, that is simply importing the module. It is not importing any of the attributes of the module. So in order to access a class inside the module, you would need to specify it:</p>
<pre><code>import model.client
o = model.client.clientclass()
</code></pre>
<p>This is a bit tedious, but very well organized.</p>
<p><hr /></p>
<p><strong>Best of both (where performance isn't a big deal):</strong></p>
<p>If you type the following code in <strong>__init</strong>.py**:</p>
<pre><code>from .client import clientclass as client
from .staff import staffclass as staff
from .order import orderclass as order
</code></pre>
<p>Then you have auto-loaded all of your classes, and they can be accessed as:</p>
<pre><code>import model
c = model.client()
s = model.staff()
o = model.order()
</code></pre>
<p><hr /></p>
<p>In the end, it may be more simple to stick with the non-magical way to do it: </p>
<pre><code>import model.client
o = model.client.clientclass()
</code></pre>
<p>--Gahooa</p>
| 4
|
2009-02-18T16:37:41Z
|
[
"python",
"file",
"class",
"directory",
"module"
] |
Detect file handle leaks in python?
| 561,988
|
<p>My program appears to be leaking file handles. How can I find out where?</p>
<p>My program uses file handles in a few different placesâoutput from child processes, call <code>ctypes</code> API (ImageMagick) opens files, and they are copied.</p>
<p>It crashes in <code>shutil.copyfile</code>, but I'm pretty sure this is not the place it is leaking.</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 874, in main
magpy.run_all()
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 656, in run_all
[operation.operate() for operation in operations]
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 417, in operate
output_file = self.place_image(output_file)
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 336, in place_image
shutil.copyfile(str(input_file), str(self.full_filename))
File "C:\Python25\Lib\shutil.py", line 47, in copyfile
fdst = open(dst, 'wb')
IOError: [Errno 24] Too many open files: 'C:\\Documents and Settings\\stuart.axon\\Desktop\\calzone\\output\\wwtbam4\\Nokia_NCD\\nl\\icon_42x42_V000.png'
Press any key to continue . . .
</code></pre>
| 7
|
2009-02-18T17:09:13Z
| 562,005
|
<p>Look at output from <code>ls -l /proc/$pid/fd/</code> (substituting the PID of your process, of course) to see which files are open [or, on win32, use <A HREF="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow">Process Explorer</A> to list open files]; then figure out where in your code you're opening them, and make that <code>close()</code> is being called. (Yes, the garbage collector will eventually close things, but it's not always fast enough to avoid running out of fds).</p>
<p>Checking for any circular references which might be preventing garbage collection is also a good practice. (The cycle collector will eventually dispose of these -- but it may not run frequently enough to avoid file descriptor exhaustion; I've been bitten by this personally).</p>
| 3
|
2009-02-18T17:12:26Z
|
[
"python",
"file",
"handle"
] |
Detect file handle leaks in python?
| 561,988
|
<p>My program appears to be leaking file handles. How can I find out where?</p>
<p>My program uses file handles in a few different placesâoutput from child processes, call <code>ctypes</code> API (ImageMagick) opens files, and they are copied.</p>
<p>It crashes in <code>shutil.copyfile</code>, but I'm pretty sure this is not the place it is leaking.</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 874, in main
magpy.run_all()
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 656, in run_all
[operation.operate() for operation in operations]
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 417, in operate
output_file = self.place_image(output_file)
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 336, in place_image
shutil.copyfile(str(input_file), str(self.full_filename))
File "C:\Python25\Lib\shutil.py", line 47, in copyfile
fdst = open(dst, 'wb')
IOError: [Errno 24] Too many open files: 'C:\\Documents and Settings\\stuart.axon\\Desktop\\calzone\\output\\wwtbam4\\Nokia_NCD\\nl\\icon_42x42_V000.png'
Press any key to continue . . .
</code></pre>
| 7
|
2009-02-18T17:09:13Z
| 562,072
|
<p>Use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow">Process Explorer</a>, select your process, View->Lower Pane View->Handles - then look for what seems out of place - usually lots of the same or similar files open points to the problem.</p>
| 3
|
2009-02-18T17:28:47Z
|
[
"python",
"file",
"handle"
] |
Detect file handle leaks in python?
| 561,988
|
<p>My program appears to be leaking file handles. How can I find out where?</p>
<p>My program uses file handles in a few different placesâoutput from child processes, call <code>ctypes</code> API (ImageMagick) opens files, and they are copied.</p>
<p>It crashes in <code>shutil.copyfile</code>, but I'm pretty sure this is not the place it is leaking.</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 874, in main
magpy.run_all()
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 656, in run_all
[operation.operate() for operation in operations]
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 417, in operate
output_file = self.place_image(output_file)
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 336, in place_image
shutil.copyfile(str(input_file), str(self.full_filename))
File "C:\Python25\Lib\shutil.py", line 47, in copyfile
fdst = open(dst, 'wb')
IOError: [Errno 24] Too many open files: 'C:\\Documents and Settings\\stuart.axon\\Desktop\\calzone\\output\\wwtbam4\\Nokia_NCD\\nl\\icon_42x42_V000.png'
Press any key to continue . . .
</code></pre>
| 7
|
2009-02-18T17:09:13Z
| 4,485,624
|
<p><code>lsof -p <process_id></code> works well on several UNIX-like systems including FreeBSD.</p>
| 3
|
2010-12-19T23:01:21Z
|
[
"python",
"file",
"handle"
] |
Detect file handle leaks in python?
| 561,988
|
<p>My program appears to be leaking file handles. How can I find out where?</p>
<p>My program uses file handles in a few different placesâoutput from child processes, call <code>ctypes</code> API (ImageMagick) opens files, and they are copied.</p>
<p>It crashes in <code>shutil.copyfile</code>, but I'm pretty sure this is not the place it is leaking.</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 874, in main
magpy.run_all()
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 656, in run_all
[operation.operate() for operation in operations]
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 417, in operate
output_file = self.place_image(output_file)
File "C:\Python25\Lib\site-packages\magpy\magpy.py", line 336, in place_image
shutil.copyfile(str(input_file), str(self.full_filename))
File "C:\Python25\Lib\shutil.py", line 47, in copyfile
fdst = open(dst, 'wb')
IOError: [Errno 24] Too many open files: 'C:\\Documents and Settings\\stuart.axon\\Desktop\\calzone\\output\\wwtbam4\\Nokia_NCD\\nl\\icon_42x42_V000.png'
Press any key to continue . . .
</code></pre>
| 7
|
2009-02-18T17:09:13Z
| 23,762,447
|
<p>I had similar problems, running out of file descriptors during subprocess.Popen() calls. I used the following script to debug on what is happening:</p>
<pre><code>import os
import stat
_fd_types = (
('REG', stat.S_ISREG),
('FIFO', stat.S_ISFIFO),
('DIR', stat.S_ISDIR),
('CHR', stat.S_ISCHR),
('BLK', stat.S_ISBLK),
('LNK', stat.S_ISLNK),
('SOCK', stat.S_ISSOCK)
)
def fd_table_status():
result = []
for fd in range(100):
try:
s = os.fstat(fd)
except:
continue
for fd_type, func in _fd_types:
if func(s.st_mode):
break
else:
fd_type = str(s.st_mode)
result.append((fd, fd_type))
return result
def fd_table_status_logify(fd_table_result):
return ('Open file handles: ' +
', '.join(['{0}: {1}'.format(*i) for i in fd_table_result]))
def fd_table_status_str():
return fd_table_status_logify(fd_table_status())
if __name__=='__main__':
print fd_table_status_str()
</code></pre>
<p>You can import this module and call <code>fd_table_status_str()</code> to log the file descriptor table status at different points in your code.</p>
<p>Also, make sure that subprocess.Popen instances are destroyed. Keeping references of Popen instances in Windows prevent the GC from running. And if the instances are kept, the associated pipes are not closed. More info <a href="http://mihalop.blogspot.gr/2014/05/python-subprocess-and-file-descriptors.html" rel="nofollow">here</a>.</p>
| 3
|
2014-05-20T14:22:46Z
|
[
"python",
"file",
"handle"
] |
wxPython - Redrawing Error when replacing wxFrame's Panel
| 561,991
|
<p>I'm creating a small wxPython utility for the first time, and I'm stuck on a problem. </p>
<p>I would like to add components to an already created frame. To do this, I am destroying the frame's old panel, and creating a new panel with all new components. </p>
<p>1: Is there a better way of dynamically adding content to a panel?</p>
<p>2: Why, in the following example, do I get a a strange redraw error in which in the panel is drawn only in the top left hand corner, and when resized, the panel is drawn correctly?
(WinXP, Python 2.5, latest wxPython)</p>
<p>Thank you for the help!</p>
<pre><code> import wx
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'TimeTablr')
#Variables
self.iCalFiles = ['Empty', 'Empty', 'Empty']
self.panel = wx.Panel(self, -1)
self.layoutElements()
def layoutElements(self):
self.panel.Destroy()
self.panel = wx.Panel(self, -1)
#Buttons
self.getFilesButton = wx.Button(self.panel, 1, 'Get Files')
self.calculateButton = wx.Button(self.panel, 2, 'Calculate')
self.quitButton = wx.Button(self.panel, 3, 'Quit Application')
#Binds
self.Bind(wx.EVT_BUTTON, self.Quit, id=3)
self.Bind(wx.EVT_BUTTON, self.getFiles, id=1)
#Layout Managers
vbox = wx.BoxSizer(wx.VERTICAL)
#Panel Contents
self.ctrlsToDescribe = []
self.fileNames = []
for iCalFile in self.iCalFiles:
self.ctrlsToDescribe.append(wx.TextCtrl(self.panel, -1))
self.fileNames.append(wx.StaticText(self.panel, -1, iCalFile))
#Add Components to Layout Managers
for i in range(0, len(self.ctrlsToDescribe)):
hboxtemp = wx.BoxSizer(wx.HORIZONTAL)
hboxtemp.AddStretchSpacer()
hboxtemp.Add(self.fileNames[i], 1, wx.EXPAND)
hboxtemp.AddStretchSpacer()
hboxtemp.Add(self.ctrlsToDescribe[i], 2, wx.EXPAND)
hboxtemp.AddStretchSpacer()
vbox.Add(hboxtemp)
finalHBox = wx.BoxSizer(wx.HORIZONTAL)
finalHBox.Add(self.getFilesButton)
finalHBox.Add(self.calculateButton)
finalHBox.Add(self.quitButton)
vbox.Add(finalHBox)
self.panel.SetSizer(vbox)
self.Show()
def Quit(self, event):
self.Destroy()
def getFiles(self, event):
self.iCalFiles = ['Example1','Example1','Example1','Example1','Example1','Example1']
self.layoutElements()
self.Update()
app = wx.App()
MainFrame()
app.MainLoop()
del app
</code></pre>
| 0
|
2009-02-18T17:09:37Z
| 562,057
|
<p>1) I beleive the Sizer will let you insert elements into the existing ordering of them. That would probably be a bit faster.</p>
<p>2) I don't see the behavior you're describing on OSX, but at a guess, try calling self.Layout() before self.Show() in layoutElements?</p>
| 1
|
2009-02-18T17:25:31Z
|
[
"python",
"wxpython",
"wxwidgets"
] |
wxPython - Redrawing Error when replacing wxFrame's Panel
| 561,991
|
<p>I'm creating a small wxPython utility for the first time, and I'm stuck on a problem. </p>
<p>I would like to add components to an already created frame. To do this, I am destroying the frame's old panel, and creating a new panel with all new components. </p>
<p>1: Is there a better way of dynamically adding content to a panel?</p>
<p>2: Why, in the following example, do I get a a strange redraw error in which in the panel is drawn only in the top left hand corner, and when resized, the panel is drawn correctly?
(WinXP, Python 2.5, latest wxPython)</p>
<p>Thank you for the help!</p>
<pre><code> import wx
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'TimeTablr')
#Variables
self.iCalFiles = ['Empty', 'Empty', 'Empty']
self.panel = wx.Panel(self, -1)
self.layoutElements()
def layoutElements(self):
self.panel.Destroy()
self.panel = wx.Panel(self, -1)
#Buttons
self.getFilesButton = wx.Button(self.panel, 1, 'Get Files')
self.calculateButton = wx.Button(self.panel, 2, 'Calculate')
self.quitButton = wx.Button(self.panel, 3, 'Quit Application')
#Binds
self.Bind(wx.EVT_BUTTON, self.Quit, id=3)
self.Bind(wx.EVT_BUTTON, self.getFiles, id=1)
#Layout Managers
vbox = wx.BoxSizer(wx.VERTICAL)
#Panel Contents
self.ctrlsToDescribe = []
self.fileNames = []
for iCalFile in self.iCalFiles:
self.ctrlsToDescribe.append(wx.TextCtrl(self.panel, -1))
self.fileNames.append(wx.StaticText(self.panel, -1, iCalFile))
#Add Components to Layout Managers
for i in range(0, len(self.ctrlsToDescribe)):
hboxtemp = wx.BoxSizer(wx.HORIZONTAL)
hboxtemp.AddStretchSpacer()
hboxtemp.Add(self.fileNames[i], 1, wx.EXPAND)
hboxtemp.AddStretchSpacer()
hboxtemp.Add(self.ctrlsToDescribe[i], 2, wx.EXPAND)
hboxtemp.AddStretchSpacer()
vbox.Add(hboxtemp)
finalHBox = wx.BoxSizer(wx.HORIZONTAL)
finalHBox.Add(self.getFilesButton)
finalHBox.Add(self.calculateButton)
finalHBox.Add(self.quitButton)
vbox.Add(finalHBox)
self.panel.SetSizer(vbox)
self.Show()
def Quit(self, event):
self.Destroy()
def getFiles(self, event):
self.iCalFiles = ['Example1','Example1','Example1','Example1','Example1','Example1']
self.layoutElements()
self.Update()
app = wx.App()
MainFrame()
app.MainLoop()
del app
</code></pre>
| 0
|
2009-02-18T17:09:37Z
| 828,593
|
<p>I had a similar problem where the panel would be squished into the upper-right corner. I solved it by calling <code>panel.Fit()</code>.</p>
<p>In your example, you should call <code>self.panel.Fit()</code> after <code>self.panel.SetSizer(vbox)</code></p>
| 0
|
2009-05-06T08:29:12Z
|
[
"python",
"wxpython",
"wxwidgets"
] |
python upload - where are tmp/FILES?
| 562,278
|
<p>I'm running python 2.4 from cgi and I'm trying to upload to a cloud service using a python api. In php, the $_FILE array contains a "tmp" element which is where the file lives until you place it where you want it. What's the equivalent in python? </p>
<p>if I do this </p>
<pre><code>fileitem = form['file']
</code></pre>
<p><code>fileitem.filename</code> is the name of the file </p>
<p>if i print fileitem, the array simply contains the file name and what looks to be the file itself. </p>
<p>I am trying to stream things and it requires the tmp location when using the php api. </p>
| 0
|
2009-02-18T18:27:21Z
| 562,322
|
<p>Here's a code snippet taken from my site:</p>
<pre><code>h = open("user_uploaded_file", "wb")
while 1:
data = form["file"].file.read(4096)
if not data:
break
h.write(data)
h.close()
</code></pre>
<p>Hope this helps.</p>
| 1
|
2009-02-18T18:36:34Z
|
[
"python",
"upload",
"cgi",
"mosso"
] |
python upload - where are tmp/FILES?
| 562,278
|
<p>I'm running python 2.4 from cgi and I'm trying to upload to a cloud service using a python api. In php, the $_FILE array contains a "tmp" element which is where the file lives until you place it where you want it. What's the equivalent in python? </p>
<p>if I do this </p>
<pre><code>fileitem = form['file']
</code></pre>
<p><code>fileitem.filename</code> is the name of the file </p>
<p>if i print fileitem, the array simply contains the file name and what looks to be the file itself. </p>
<p>I am trying to stream things and it requires the tmp location when using the php api. </p>
| 0
|
2009-02-18T18:27:21Z
| 562,535
|
<p>The file is a real file, but the <code>cgi.FieldStorage</code> unlinked it as soon as it was created so that it would exist only as long as you keep it open, and no longer has a real path on the file system.</p>
<p>You can, however, change this...</p>
<p>You can extend the <code>cgi.FieldStorage</code> and replace the <code>make_file</code> method to place the file wherever you want:</p>
<pre><code>import os
import cgi
class MyFieldStorage(cgi.FieldStorage):
def make_file(self, binary=None):
return open(os.path.join('/tmp', self.filename), 'wb')
</code></pre>
<p>You must also keep in mind that the <code>FieldStorage</code> object only creates a real file if it recieves more than 1000B (otherwise it is a <code>cStringIO.StringIO</code>)</p>
<p><strong>EDIT</strong>: The <code>cgi</code> module actually makes the file with the <code>tempfile</code> module, so check that out if you want lots of gooey details.</p>
| 2
|
2009-02-18T19:46:11Z
|
[
"python",
"upload",
"cgi",
"mosso"
] |
I want to load all of the unit-tests in a tree, can it be done?
| 562,349
|
<p>I have a heirarchical folder full of Python unit-tests. They are all importable ".py" files which define TestCase objects. This folder contains thousands of files in many nested subdirectories and was written by somebody else. I do not have permission to change it, I just have to run it.</p>
<p>I want to generate a single TestSuite object which contains all of the TestCases in the folder. Is there an easy and elegant way to do this? </p>
<p>Thanks</p>
| 0
|
2009-02-18T18:44:56Z
| 562,403
|
<p>The <strong>nose</strong> application may be useful for you, either directly, or to show how to implement this.</p>
<p><a href="http://code.google.com/p/python-nose/" rel="nofollow">http://code.google.com/p/python-nose/</a> seems to be the home page.</p>
<p>Basically, what you want to do is walk the source tree (<code>os.walk</code>), use <code>imp.load_module</code>
to load the module, use <code>unittest.defaultTestLoader</code> to load the tests from the module into a <code>TestSuite</code>, and then use that in whatever way you need to use it.</p>
<p>Or at least that's approximately what I do in my custom <code>TestRunner</code> implementation
(<code>bzr get <a href="http://code.liw.fi/coverage-test-runner/bzr/trunk" rel="nofollow">http://code.liw.fi/coverage-test-runner/bzr/trunk</a></code>).</p>
| 4
|
2009-02-18T19:06:15Z
|
[
"python",
"unit-testing"
] |
I want to load all of the unit-tests in a tree, can it be done?
| 562,349
|
<p>I have a heirarchical folder full of Python unit-tests. They are all importable ".py" files which define TestCase objects. This folder contains thousands of files in many nested subdirectories and was written by somebody else. I do not have permission to change it, I just have to run it.</p>
<p>I want to generate a single TestSuite object which contains all of the TestCases in the folder. Is there an easy and elegant way to do this? </p>
<p>Thanks</p>
| 0
|
2009-02-18T18:44:56Z
| 562,489
|
<p>Look at the unittest.TestLoader (<a href="https://docs.python.org/library/unittest.html#loading-and-running-tests" rel="nofollow">https://docs.python.org/library/unittest.html#loading-and-running-tests</a>)</p>
<p>And the os.walk (<a href="https://docs.python.org/library/os.html#files-and-directories" rel="nofollow">https://docs.python.org/library/os.html#files-and-directories</a>)</p>
<p>You should be able to traverse your package tree using the TestLoader to build a suite which you can then run.</p>
<p>Something along the lines of this.</p>
<pre><code>runner = unittest.TextTestRunner()
superSuite = unittest.TestSuite()
for path, dirs, files in os.walk( 'path/to/tree' ):
# if a CVS dir or whatever: continue
for f in files:
# if not a python file: continue
suite= unittest.defaultTestLoader.loadTestsFromModule( os.path.join(path,f)
superSuite .addTests(suite ) # OR runner.run( suite)
runner.run( superSuite )
</code></pre>
<p>You can either walk through the tree simply running each test (<code>runner.run(suite)</code>) <strong>or</strong> you can accumulate a <code>superSuite</code> of all individual suites and run the whole mass as a single test (<code>runner.run( superSuite )</code>).</p>
<p>You don't need to do both, but I included both sets of suggestions in the above (untested) code.</p>
| 2
|
2009-02-18T19:32:06Z
|
[
"python",
"unit-testing"
] |
I want to load all of the unit-tests in a tree, can it be done?
| 562,349
|
<p>I have a heirarchical folder full of Python unit-tests. They are all importable ".py" files which define TestCase objects. This folder contains thousands of files in many nested subdirectories and was written by somebody else. I do not have permission to change it, I just have to run it.</p>
<p>I want to generate a single TestSuite object which contains all of the TestCases in the folder. Is there an easy and elegant way to do this? </p>
<p>Thanks</p>
| 0
|
2009-02-18T18:44:56Z
| 562,529
|
<p>The test directory of the <a href="http://svn.python.org/view/python/trunk/Lib/test/" rel="nofollow">Python Library source</a> shows the way.
The <a href="http://svn.python.org/view/python/trunk/Lib/test/README?view=markup" rel="nofollow">README</a> file describes how to write Python Regression Tests for library modules.</p>
<p>The <a href="http://svn.python.org/view/python/trunk/Lib/test/regrtest.py?view=markup" rel="nofollow">regrtest.py module</a> starts with:</p>
<pre><code>"""Regression test.
This will find all modules whose name is "test_*" in the test
directory, and run them.
</code></pre>
| 1
|
2009-02-18T19:43:18Z
|
[
"python",
"unit-testing"
] |
Python Imaging Library save function syntax
| 562,519
|
<p>Simple one I think but essentially I need to know what the syntax is for the save function on the PIL. The help is really vague and I can't find anything online. Any help'd be great, thanks :).</p>
| 11
|
2009-02-18T19:38:57Z
| 562,530
|
<p>From the <a href="http://effbot.org/imagingbook/image.htm#tag-Image.Image.save">PIL Handbook</a>:</p>
<pre><code>im.save(outfile, options...)
im.save(outfile, format, options...)
</code></pre>
<p>Simplest case:</p>
<pre><code>im.save('my_image.png')
</code></pre>
<p>or whatever. In this case, the type of the image will be determined from the extension. Is there a particular problem you're having? Or specific saving option that you'd like to use but aren't sure how to do so?</p>
<p>You may be able to find additional information in the documentation on each filetype. <a href="http://effbot.org/imagingbook/pil-index.htm#appendixes">The PIL Handbox Appendixes</a> list the different file types that are supported. In some cases, options are given for <code>save</code>. For example, on the <a href="http://effbot.org/imagingbook/format-jpeg.htm">JPEG file format page</a>, we're told that save supports</p>
<ul>
<li><code>quality</code></li>
<li><code>optimize</code>, and </li>
<li><code>progressive</code></li>
</ul>
<p>with notes about each option.</p>
| 15
|
2009-02-18T19:43:19Z
|
[
"python",
"python-imaging-library"
] |
Python Imaging Library save function syntax
| 562,519
|
<p>Simple one I think but essentially I need to know what the syntax is for the save function on the PIL. The help is really vague and I can't find anything online. Any help'd be great, thanks :).</p>
| 11
|
2009-02-18T19:38:57Z
| 562,533
|
<p><code>Image.save(filename[, format[, options]])</code>. You can usually just use <code>Image.save(filename)</code> since it automatically figures out the file type for you from the extension.</p>
| 1
|
2009-02-18T19:45:19Z
|
[
"python",
"python-imaging-library"
] |
What's Python good practice for importing and offering optional features?
| 563,022
|
<p>I'm writing a piece of software over on github. It's basically a tray icon with some extra features. I want to provide a working piece of code without actually having to make the user install what are essentially dependencies for optional features and I don't actually want to import things I'm not going to use so I thought code like this would be "good solution":</p>
<pre><code>---- IN LOADING FUNCTION ----
features = []
for path in sys.path:
if os.path.exists(os.path.join(path, 'pynotify')):
features.append('pynotify')
if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
features.append('gnome-keyring')
#user dialog to ask for stuff
#notifications available, do you want them enabled?
dlg = ConfigDialog(features)
if not dlg.get_notifications():
features.remove('pynotify')
service_start(features ...)
---- SOMEWHERE ELSE ------
def service_start(features, other_config):
if 'pynotify' in features:
import pynotify
#use pynotify...
</code></pre>
<p>There are some issues however. If a user formats his machine and installs the newest version of his OS and redeploys this application, features suddenly disappear without warning. The solution is to present this on the configuration window:</p>
<pre><code>if 'pynotify' in features:
#gtk checkbox
else:
#gtk label reading "Get pynotify and enjoy notification pop ups!"
</code></pre>
<p>But if this is say, a mac, how do I know I'm not sending the user on a wild goose chase looking for a dependency they can never fill?</p>
<p>The second problem is the:</p>
<pre><code>if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
</code></pre>
<p>issue. Can I be sure that the file is always called gnomekeyring.so across all the linux distros?</p>
<p>How do other people test these features? The problem with the basic</p>
<pre><code>try:
import pynotify
except:
pynotify = disabled
</code></pre>
<p>is that the code is global, these might be littered around and even if the user doesn't want pynotify....it's loaded anyway.</p>
<p>So what do people think is the best way to solve this problem?</p>
| 12
|
2009-02-18T21:58:01Z
| 563,060
|
<p>The <code>try:</code> method does not need to be global â it can be used in any scope and so modules can be "lazy-loaded" at runtime. For example:</p>
<pre><code>def foo():
try:
import external_module
except ImportError:
pass
if external_module:
external_module.some_whizzy_feature()
else:
print "You could be using a whizzy feature right now, if you had external_module."
</code></pre>
<p>When your script is run, no attempt will be made to load <code>external_module</code>. The first time <code>foo()</code> is called, <code>external_module</code> is (if available) loaded and inserted into the function's local scope. Subsequent calls to <code>foo()</code> reinsert <code>external_module</code> into its scope without needing to reload the module.</p>
<p>In general, it's best to let Python handle import logic â it's been doing it for a while. :-)</p>
| 25
|
2009-02-18T22:05:59Z
|
[
"python",
"python-import"
] |
What's Python good practice for importing and offering optional features?
| 563,022
|
<p>I'm writing a piece of software over on github. It's basically a tray icon with some extra features. I want to provide a working piece of code without actually having to make the user install what are essentially dependencies for optional features and I don't actually want to import things I'm not going to use so I thought code like this would be "good solution":</p>
<pre><code>---- IN LOADING FUNCTION ----
features = []
for path in sys.path:
if os.path.exists(os.path.join(path, 'pynotify')):
features.append('pynotify')
if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
features.append('gnome-keyring')
#user dialog to ask for stuff
#notifications available, do you want them enabled?
dlg = ConfigDialog(features)
if not dlg.get_notifications():
features.remove('pynotify')
service_start(features ...)
---- SOMEWHERE ELSE ------
def service_start(features, other_config):
if 'pynotify' in features:
import pynotify
#use pynotify...
</code></pre>
<p>There are some issues however. If a user formats his machine and installs the newest version of his OS and redeploys this application, features suddenly disappear without warning. The solution is to present this on the configuration window:</p>
<pre><code>if 'pynotify' in features:
#gtk checkbox
else:
#gtk label reading "Get pynotify and enjoy notification pop ups!"
</code></pre>
<p>But if this is say, a mac, how do I know I'm not sending the user on a wild goose chase looking for a dependency they can never fill?</p>
<p>The second problem is the:</p>
<pre><code>if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
</code></pre>
<p>issue. Can I be sure that the file is always called gnomekeyring.so across all the linux distros?</p>
<p>How do other people test these features? The problem with the basic</p>
<pre><code>try:
import pynotify
except:
pynotify = disabled
</code></pre>
<p>is that the code is global, these might be littered around and even if the user doesn't want pynotify....it's loaded anyway.</p>
<p>So what do people think is the best way to solve this problem?</p>
| 12
|
2009-02-18T21:58:01Z
| 563,075
|
<p>You might want to have a look at the <a href="http://docs.python.org/library/imp.html">imp module</a>, which basically does what you do manually above. So you can first look for a module with find_module() and then load it via load_module() or by simply importing it (after checking the config).</p>
<p>And btw, if using except: I always would add the specific exception to it (here ImportError) to not accidently catch unrelated errors.</p>
| 7
|
2009-02-18T22:09:38Z
|
[
"python",
"python-import"
] |
What's Python good practice for importing and offering optional features?
| 563,022
|
<p>I'm writing a piece of software over on github. It's basically a tray icon with some extra features. I want to provide a working piece of code without actually having to make the user install what are essentially dependencies for optional features and I don't actually want to import things I'm not going to use so I thought code like this would be "good solution":</p>
<pre><code>---- IN LOADING FUNCTION ----
features = []
for path in sys.path:
if os.path.exists(os.path.join(path, 'pynotify')):
features.append('pynotify')
if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
features.append('gnome-keyring')
#user dialog to ask for stuff
#notifications available, do you want them enabled?
dlg = ConfigDialog(features)
if not dlg.get_notifications():
features.remove('pynotify')
service_start(features ...)
---- SOMEWHERE ELSE ------
def service_start(features, other_config):
if 'pynotify' in features:
import pynotify
#use pynotify...
</code></pre>
<p>There are some issues however. If a user formats his machine and installs the newest version of his OS and redeploys this application, features suddenly disappear without warning. The solution is to present this on the configuration window:</p>
<pre><code>if 'pynotify' in features:
#gtk checkbox
else:
#gtk label reading "Get pynotify and enjoy notification pop ups!"
</code></pre>
<p>But if this is say, a mac, how do I know I'm not sending the user on a wild goose chase looking for a dependency they can never fill?</p>
<p>The second problem is the:</p>
<pre><code>if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
</code></pre>
<p>issue. Can I be sure that the file is always called gnomekeyring.so across all the linux distros?</p>
<p>How do other people test these features? The problem with the basic</p>
<pre><code>try:
import pynotify
except:
pynotify = disabled
</code></pre>
<p>is that the code is global, these might be littered around and even if the user doesn't want pynotify....it's loaded anyway.</p>
<p>So what do people think is the best way to solve this problem?</p>
| 12
|
2009-02-18T21:58:01Z
| 565,179
|
<p>One way to handle the problem of different dependencies for different features is to implement the optional features as plugins. That way the user has control over which features are activated in the app but isn't responsible for tracking down the dependencies herself. That task then gets handled at the time of each plugin's installation.</p>
| 0
|
2009-02-19T12:49:09Z
|
[
"python",
"python-import"
] |
What's Python good practice for importing and offering optional features?
| 563,022
|
<p>I'm writing a piece of software over on github. It's basically a tray icon with some extra features. I want to provide a working piece of code without actually having to make the user install what are essentially dependencies for optional features and I don't actually want to import things I'm not going to use so I thought code like this would be "good solution":</p>
<pre><code>---- IN LOADING FUNCTION ----
features = []
for path in sys.path:
if os.path.exists(os.path.join(path, 'pynotify')):
features.append('pynotify')
if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
features.append('gnome-keyring')
#user dialog to ask for stuff
#notifications available, do you want them enabled?
dlg = ConfigDialog(features)
if not dlg.get_notifications():
features.remove('pynotify')
service_start(features ...)
---- SOMEWHERE ELSE ------
def service_start(features, other_config):
if 'pynotify' in features:
import pynotify
#use pynotify...
</code></pre>
<p>There are some issues however. If a user formats his machine and installs the newest version of his OS and redeploys this application, features suddenly disappear without warning. The solution is to present this on the configuration window:</p>
<pre><code>if 'pynotify' in features:
#gtk checkbox
else:
#gtk label reading "Get pynotify and enjoy notification pop ups!"
</code></pre>
<p>But if this is say, a mac, how do I know I'm not sending the user on a wild goose chase looking for a dependency they can never fill?</p>
<p>The second problem is the:</p>
<pre><code>if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
</code></pre>
<p>issue. Can I be sure that the file is always called gnomekeyring.so across all the linux distros?</p>
<p>How do other people test these features? The problem with the basic</p>
<pre><code>try:
import pynotify
except:
pynotify = disabled
</code></pre>
<p>is that the code is global, these might be littered around and even if the user doesn't want pynotify....it's loaded anyway.</p>
<p>So what do people think is the best way to solve this problem?</p>
| 12
|
2009-02-18T21:58:01Z
| 38,891,837
|
<p>If <code>optional_module</code> is used in multiple occasions, it might become awkward to add an <code>if optional_module_available ...</code> each time. Alternatively, you might replace the module object with a dummy which raises an informative error on any attribute access. And use <code>optional_module</code> as if it was available:</p>
<pre><code>class NotInstalled(object):
def __init__(self, name):
self.__name = name
def __getattr__(item):
raise ImportError('The {0} package is required to use this '
'optional feature'.format(self.__name))
try:
import optional_module
except ImportError:
optional_module = NotInstalled(name='optional_module')
def func1():
optional_module.submodule.method() # raises ImportError
def func2():
optional_module.another_method() # raises ImportError
</code></pre>
| 0
|
2016-08-11T09:02:18Z
|
[
"python",
"python-import"
] |
Getting return values from a MySQL stored procedure in Python, using MySQLdb
| 563,182
|
<p>I've got a stored procedure in a MySQL database that simply updates a date column and returns the previous date. If I call this stored procedure from the MySQL client, it works fine, but when I try to call the stored procedure from Python using MySQLdb I can't seem to get it to give me the return value.</p>
<p>Here's the code to the stored procedure:</p>
<pre><code>CREATE PROCEDURE test_stuff.get_lastpoll()
BEGIN
DECLARE POLLTIME TIMESTAMP DEFAULT NULL;
START TRANSACTION;
SELECT poll_date_time
FROM test_stuff.poll_table
LIMIT 1
INTO POLLTIME
FOR UPDATE;
IF POLLTIME IS NULL THEN
INSERT INTO
test_stuff.poll_table
(poll_date_time)
VALUES
( UTC_TIMESTAMP() );
COMMIT;
SELECT NULL as POLL_DATE_TIME;
ELSE
UPDATE test_stuff.poll_table SET poll_date_time = UTC_TIMESTAMP();
COMMIT;
SELECT DATE_FORMAT(POLLTIME, '%Y-%m-%d %H:%i:%s') as POLL_DATE_TIME;
END IF;
END
</code></pre>
<p>The code I'm using to try to call the stored procedure is similar to this:</p>
<pre><code>#!/usr/bin/python
import sys
import MySQLdb
try:
mysql = MySQLdb.connect(user=User,passwd=Passwd,db="test_stuff")
mysql_cursor = mysql.cursor()
results=mysql_cursor.callproc( "get_lastpoll", () )
print results
mysql_cursor.close()
mysql.close()
except MySQLdb.Error, e:
print "MySQL Error %d: %s" % ( e.args[0], e.args[1] )
sys.exit(1)
</code></pre>
<p>I know that you can do IN and OUT parameters, but from what I can determine from the MySQLdb documentation, this isn't possible with MySQLdb. Does anyone have any clue how I could get the results of the stored procedure?</p>
<p>If I run it from a SQL tool, here's the output:</p>
<pre><code>POLL_DATE_TIME
-------------------
2009-02-18 22:27:07
</code></pre>
<p>If I run the Python script, it returns back an empty set, like this:</p>
<pre><code>()
</code></pre>
| 6
|
2009-02-18T22:42:25Z
| 563,258
|
<p>You still have to fetch the results.</p>
<pre><code>results = cursor.fetchone()
</code></pre>
<p>or</p>
<pre><code>results = cursor.fetchall()
</code></pre>
<p>etc..</p>
| 5
|
2009-02-18T23:05:57Z
|
[
"python",
"mysql"
] |
Getting return values from a MySQL stored procedure in Python, using MySQLdb
| 563,182
|
<p>I've got a stored procedure in a MySQL database that simply updates a date column and returns the previous date. If I call this stored procedure from the MySQL client, it works fine, but when I try to call the stored procedure from Python using MySQLdb I can't seem to get it to give me the return value.</p>
<p>Here's the code to the stored procedure:</p>
<pre><code>CREATE PROCEDURE test_stuff.get_lastpoll()
BEGIN
DECLARE POLLTIME TIMESTAMP DEFAULT NULL;
START TRANSACTION;
SELECT poll_date_time
FROM test_stuff.poll_table
LIMIT 1
INTO POLLTIME
FOR UPDATE;
IF POLLTIME IS NULL THEN
INSERT INTO
test_stuff.poll_table
(poll_date_time)
VALUES
( UTC_TIMESTAMP() );
COMMIT;
SELECT NULL as POLL_DATE_TIME;
ELSE
UPDATE test_stuff.poll_table SET poll_date_time = UTC_TIMESTAMP();
COMMIT;
SELECT DATE_FORMAT(POLLTIME, '%Y-%m-%d %H:%i:%s') as POLL_DATE_TIME;
END IF;
END
</code></pre>
<p>The code I'm using to try to call the stored procedure is similar to this:</p>
<pre><code>#!/usr/bin/python
import sys
import MySQLdb
try:
mysql = MySQLdb.connect(user=User,passwd=Passwd,db="test_stuff")
mysql_cursor = mysql.cursor()
results=mysql_cursor.callproc( "get_lastpoll", () )
print results
mysql_cursor.close()
mysql.close()
except MySQLdb.Error, e:
print "MySQL Error %d: %s" % ( e.args[0], e.args[1] )
sys.exit(1)
</code></pre>
<p>I know that you can do IN and OUT parameters, but from what I can determine from the MySQLdb documentation, this isn't possible with MySQLdb. Does anyone have any clue how I could get the results of the stored procedure?</p>
<p>If I run it from a SQL tool, here's the output:</p>
<pre><code>POLL_DATE_TIME
-------------------
2009-02-18 22:27:07
</code></pre>
<p>If I run the Python script, it returns back an empty set, like this:</p>
<pre><code>()
</code></pre>
| 6
|
2009-02-18T22:42:25Z
| 566,260
|
<p>What I had to do is modify the Python code to use execute() instead of callproc(), and then use the fetchone() to get the results. I'm answering it myself since mluebke's answer wasn't entirely complete (even though it was helpful!).</p>
<pre><code>mysql_cursor.execute( "call get_lastpoll();" )
results=mysql_cursor.fetchone()
print results[0]
</code></pre>
<p>This gives me the correct output:</p>
<pre><code>2009-02-19 17:10:42
</code></pre>
| 9
|
2009-02-19T17:11:44Z
|
[
"python",
"mysql"
] |
Getting return values from a MySQL stored procedure in Python, using MySQLdb
| 563,182
|
<p>I've got a stored procedure in a MySQL database that simply updates a date column and returns the previous date. If I call this stored procedure from the MySQL client, it works fine, but when I try to call the stored procedure from Python using MySQLdb I can't seem to get it to give me the return value.</p>
<p>Here's the code to the stored procedure:</p>
<pre><code>CREATE PROCEDURE test_stuff.get_lastpoll()
BEGIN
DECLARE POLLTIME TIMESTAMP DEFAULT NULL;
START TRANSACTION;
SELECT poll_date_time
FROM test_stuff.poll_table
LIMIT 1
INTO POLLTIME
FOR UPDATE;
IF POLLTIME IS NULL THEN
INSERT INTO
test_stuff.poll_table
(poll_date_time)
VALUES
( UTC_TIMESTAMP() );
COMMIT;
SELECT NULL as POLL_DATE_TIME;
ELSE
UPDATE test_stuff.poll_table SET poll_date_time = UTC_TIMESTAMP();
COMMIT;
SELECT DATE_FORMAT(POLLTIME, '%Y-%m-%d %H:%i:%s') as POLL_DATE_TIME;
END IF;
END
</code></pre>
<p>The code I'm using to try to call the stored procedure is similar to this:</p>
<pre><code>#!/usr/bin/python
import sys
import MySQLdb
try:
mysql = MySQLdb.connect(user=User,passwd=Passwd,db="test_stuff")
mysql_cursor = mysql.cursor()
results=mysql_cursor.callproc( "get_lastpoll", () )
print results
mysql_cursor.close()
mysql.close()
except MySQLdb.Error, e:
print "MySQL Error %d: %s" % ( e.args[0], e.args[1] )
sys.exit(1)
</code></pre>
<p>I know that you can do IN and OUT parameters, but from what I can determine from the MySQLdb documentation, this isn't possible with MySQLdb. Does anyone have any clue how I could get the results of the stored procedure?</p>
<p>If I run it from a SQL tool, here's the output:</p>
<pre><code>POLL_DATE_TIME
-------------------
2009-02-18 22:27:07
</code></pre>
<p>If I run the Python script, it returns back an empty set, like this:</p>
<pre><code>()
</code></pre>
| 6
|
2009-02-18T22:42:25Z
| 1,019,866
|
<p><code>callproc</code> also works fine, you don't need to use <code>execute</code>:</p>
<pre><code>mysql_cursor.callproc( "get_lastpoll", () )
result = mysql_cursor.fetchone()
</code></pre>
| 5
|
2009-06-19T20:19:55Z
|
[
"python",
"mysql"
] |
Getting return values from a MySQL stored procedure in Python, using MySQLdb
| 563,182
|
<p>I've got a stored procedure in a MySQL database that simply updates a date column and returns the previous date. If I call this stored procedure from the MySQL client, it works fine, but when I try to call the stored procedure from Python using MySQLdb I can't seem to get it to give me the return value.</p>
<p>Here's the code to the stored procedure:</p>
<pre><code>CREATE PROCEDURE test_stuff.get_lastpoll()
BEGIN
DECLARE POLLTIME TIMESTAMP DEFAULT NULL;
START TRANSACTION;
SELECT poll_date_time
FROM test_stuff.poll_table
LIMIT 1
INTO POLLTIME
FOR UPDATE;
IF POLLTIME IS NULL THEN
INSERT INTO
test_stuff.poll_table
(poll_date_time)
VALUES
( UTC_TIMESTAMP() );
COMMIT;
SELECT NULL as POLL_DATE_TIME;
ELSE
UPDATE test_stuff.poll_table SET poll_date_time = UTC_TIMESTAMP();
COMMIT;
SELECT DATE_FORMAT(POLLTIME, '%Y-%m-%d %H:%i:%s') as POLL_DATE_TIME;
END IF;
END
</code></pre>
<p>The code I'm using to try to call the stored procedure is similar to this:</p>
<pre><code>#!/usr/bin/python
import sys
import MySQLdb
try:
mysql = MySQLdb.connect(user=User,passwd=Passwd,db="test_stuff")
mysql_cursor = mysql.cursor()
results=mysql_cursor.callproc( "get_lastpoll", () )
print results
mysql_cursor.close()
mysql.close()
except MySQLdb.Error, e:
print "MySQL Error %d: %s" % ( e.args[0], e.args[1] )
sys.exit(1)
</code></pre>
<p>I know that you can do IN and OUT parameters, but from what I can determine from the MySQLdb documentation, this isn't possible with MySQLdb. Does anyone have any clue how I could get the results of the stored procedure?</p>
<p>If I run it from a SQL tool, here's the output:</p>
<pre><code>POLL_DATE_TIME
-------------------
2009-02-18 22:27:07
</code></pre>
<p>If I run the Python script, it returns back an empty set, like this:</p>
<pre><code>()
</code></pre>
| 6
|
2009-02-18T22:42:25Z
| 19,341,993
|
<p>From the API documentation for the <code>MySQLdb</code> library. You will need to call <code>cursor_obj.nextset()</code> before you will see the result set returned by the stored procedure. This is because the call to the stored procedure creates a result set. The result sets returned by the stored procedure follow.</p>
<p><a href="http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.cursors.BaseCursor-class.html#callproc" rel="nofollow">More info</a></p>
| 0
|
2013-10-13T04:53:55Z
|
[
"python",
"mysql"
] |
What's the fastest way to test the validity of a large number of well-formed URLs
| 563,384
|
<p>My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs</p>
<p>I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).</p>
<p>Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.</p>
<p>Can it be done? </p>
| 2
|
2009-02-18T23:46:48Z
| 563,398
|
<p>Just send HTTP HEAD requests as shown in the accepted answer to <a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">this question</a>.</p>
| 3
|
2009-02-18T23:54:51Z
|
[
"python",
"http"
] |
What's the fastest way to test the validity of a large number of well-formed URLs
| 563,384
|
<p>My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs</p>
<p>I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).</p>
<p>Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.</p>
<p>Can it be done? </p>
| 2
|
2009-02-18T23:46:48Z
| 563,402
|
<p>I'm assuming you want to do it in Python based on your tags. In that case, I'd use httplib. Optionally, somehow group the URLs by host so you can make multiple requests in one connection for those URLs that have the same host. Use the HEAD request.</p>
<pre><code>conn = httplib.HTTPConnection("example.com")
conn.request("HEAD", "/index.html")
resp = conn.getresponse()
print resp.status
</code></pre>
| 6
|
2009-02-18T23:56:34Z
|
[
"python",
"http"
] |
What's the fastest way to test the validity of a large number of well-formed URLs
| 563,384
|
<p>My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs</p>
<p>I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).</p>
<p>Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.</p>
<p>Can it be done? </p>
| 2
|
2009-02-18T23:46:48Z
| 563,412
|
<p>To really make this fast you might also use <a href="http://pypi.python.org/pypi/eventlet" rel="nofollow">eventlet</a> which uses non-blocking IO to speed things up.</p>
<p>You can use a head request like this:</p>
<pre><code>from eventlet import httpc
try:
res = httpc.head(url)
except httpc.NotFound:
# handle 404
</code></pre>
<p>You can then put this into some simple script like <a href="http://wiki.secondlife.com/wiki/Eventlet/Examples" rel="nofollow">that example script here</a>. With that you should get pretty much concurrency by using a coroutines pool.</p>
| 7
|
2009-02-18T23:59:04Z
|
[
"python",
"http"
] |
What's the fastest way to test the validity of a large number of well-formed URLs
| 563,384
|
<p>My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs</p>
<p>I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).</p>
<p>Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.</p>
<p>Can it be done? </p>
| 2
|
2009-02-18T23:46:48Z
| 563,415
|
<p>Instead of sending an HTTP GET request for each URL you can try sending an HTTP HEAD request. They are described in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4" rel="nofollow">this document</a>.</p>
| 1
|
2009-02-18T23:59:55Z
|
[
"python",
"http"
] |
What's the fastest way to test the validity of a large number of well-formed URLs
| 563,384
|
<p>My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs</p>
<p>I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).</p>
<p>Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.</p>
<p>Can it be done? </p>
| 2
|
2009-02-18T23:46:48Z
| 563,416
|
<p>Using <a href="http://docs.python.org/library/httplib.html" rel="nofollow">httplib</a> and <a href="http://docs.python.org/library/urlparse.html" rel="nofollow">urlparse</a>:</p>
<pre><code>def checkURL(url):
import httplib
import urlparse
protocol, host, path, query, fragment = urlparse.urlsplit(url)
if protocol == "http":
conntype = httplib.HTTPConnection
elif protocol == "https":
conntype = httplib.HTTPSConnection
else:
raise ValueError("unsupported protocol: " + protocol)
conn = conntype(host)
conn.request("HEAD", path)
resp = conn.getresponse()
conn.close()
if resp.status < 400:
return true
return false
</code></pre>
| 4
|
2009-02-19T00:00:00Z
|
[
"python",
"http"
] |
What's the fastest way to test the validity of a large number of well-formed URLs
| 563,384
|
<p>My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs</p>
<p>I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).</p>
<p>Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.</p>
<p>Can it be done? </p>
| 2
|
2009-02-18T23:46:48Z
| 563,591
|
<p>This is a trivial case for <a href="http://twistedmatrix.com/" rel="nofollow">twisted</a>. There are a couple of concurrency tools you can use to slow it down, otherwise, it'll pretty much do it all at once.</p>
<p>Twisted is definitely my favorite thing about python. :)</p>
| 0
|
2009-02-19T01:30:44Z
|
[
"python",
"http"
] |
What's the fastest way to test the validity of a large number of well-formed URLs
| 563,384
|
<p>My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs</p>
<p>I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).</p>
<p>Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.</p>
<p>Can it be done? </p>
| 2
|
2009-02-18T23:46:48Z
| 583,223
|
<p>This might help you to start. The file sitelist.txt contains a list of URIs. You might have to install httplib2, highly recommended. I put a sleep between each request so if you have many URIs on the same site, your client will not be blacklisted for abusing resources.</p>
<pre><code> import httplib2
import time
h = httplib2.Http(".cache")
f = open("sitelist.txt", "r")
urllist = f.readlines()
f.close()
for url in urllist:
# wait 10 seconds before the next request - be nice with the site
time.sleep(10)
resp= {}
urlrequest = url.strip()
try:
resp, content = h.request(urlrequest, "HEAD")
if resp['status'] == "200":
print url, "200 - Good"
else:
print url, resp['status'], " you might want to double check"
except:
pass
</code></pre>
| 0
|
2009-02-24T19:34:30Z
|
[
"python",
"http"
] |
What's the fastest way to test the validity of a large number of well-formed URLs
| 563,384
|
<p>My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs</p>
<p>I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).</p>
<p>Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.</p>
<p>Can it be done? </p>
| 2
|
2009-02-18T23:46:48Z
| 590,517
|
<p>A Python program which does a similar work (for a list of URL stored at <a href="http://del.icio.us/" rel="nofollow">del.icio.us</a>) is <a href="http://www.bortzmeyer.org/disastrous.html" rel="nofollow">disastrous</a>. </p>
<p>And, yes, it uses HEAD and not GET but do note some (not HTTP standard) servers send different results for HEAD and for GET: the Python environment Zope is a typical culprit.(Also, in some case, network problems, for instance tunnels + broken firewalls which block ICMP, prevent big packets to get through so HEAD works and not GET.)</p>
| 0
|
2009-02-26T13:21:16Z
|
[
"python",
"http"
] |
How to stop Tkinter Frame from shrinking to fit its contents?
| 563,827
|
<p>This is the code that's giving me trouble. </p>
<pre><code>f = Frame(root, width=1000, bg="blue")
f.pack(fill=X, expand=True)
l = Label(f, text="hi", width=10, bg="red", fg="white")
l.pack()
</code></pre>
<p>If I comment out the lines with the Label, the Frame displays with the right width. However, adding the Label seems to shrink the Frame down to the Label's size. Is there a way to prevent that from happening? </p>
| 27
|
2009-02-19T03:21:07Z
| 566,840
|
<p>By default, tk frames <em>shrink or grow to fit their contents</em>, which is what you want 99% of the time. The term that describes this feature is "geometry propagation". There is a <a href="http://effbot.org/tkinterbook/pack.htm#Tkinter.Pack.pack_propagate-method">command</a> to turn geometry propagation on or off.</p>
<p>Since you are using pack, the syntax would be:</p>
<pre><code>f.pack_propagate(0)
</code></pre>
<p>or maybe <code>root.pack_propagate(0)</code>, depending on which widget(s) you actually want to affect.</p>
<p>That being said, the vast majority of the time you should let tkinter compute the size. When you turn geometry propagation off your GUI won't respond well to changes in resolution, changes in fonts, etc. tkinter's geometry managers (<code>pack</code>, <code>place</code> and <code>grid</code>) are remarkably powerful. Learn to take advantage of that power. </p>
| 37
|
2009-02-19T19:42:43Z
|
[
"python",
"label",
"tkinter",
"frame"
] |
How can I check the memory usage of objects in iPython?
| 563,840
|
<p>I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:</p>
<pre><code>In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB
</code></pre>
<p>Something like <code>%memusage <object></code> and return the memory used by the object.</p>
<p><strong>Duplicate</strong></p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/33978/find-out-how-much-memory-is-being-used-by-an-object-in-python">Find out how much memory is being used by an object in Python</a></p>
</blockquote>
| 15
|
2009-02-19T03:27:34Z
| 563,921
|
<p>UPDATE: Here is <a href="http://code.activestate.com/recipes/544288/">another</a>, maybe more thorough recipe for estimating the size of a python object. </p>
<p>Here is a <a href="http://mail.python.org/pipermail/python-list/2008-January/472683.html">thread</a> addressing a similar question </p>
<p>The solution proposed is to write your own... using some estimates of the known size of primitives, python's object overhead, and the sizes of built in container types. </p>
<p>Since the code is not that long, here is a direct copy of it: </p>
<pre><code>def sizeof(obj):
"""APPROXIMATE memory taken by some Python objects in
the current 32-bit CPython implementation.
Excludes the space used by items in containers; does not
take into account overhead of memory allocation from the
operating system, or over-allocation by lists and dicts.
"""
T = type(obj)
if T is int:
kind = "fixed"
container = False
size = 4
elif T is list or T is tuple:
kind = "variable"
container = True
size = 4*len(obj)
elif T is dict:
kind = "variable"
container = True
size = 144
if len(obj) > 8:
size += 12*(len(obj)-8)
elif T is str:
kind = "variable"
container = False
size = len(obj) + 1
else:
raise TypeError("don't know about this kind of object")
if kind == "fixed":
overhead = 8
else: # "variable"
overhead = 12
if container:
garbage_collector = 8
else:
garbage_collector = 0
malloc = 8 # in most cases
size = size + overhead + garbage_collector + malloc
# Round to nearest multiple of 8 bytes
x = size % 8
if x != 0:
size += 8-x
size = (size + 8)
return size
</code></pre>
| 13
|
2009-02-19T04:07:23Z
|
[
"python",
"memory",
"ipython"
] |
How can I check the memory usage of objects in iPython?
| 563,840
|
<p>I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:</p>
<pre><code>In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB
</code></pre>
<p>Something like <code>%memusage <object></code> and return the memory used by the object.</p>
<p><strong>Duplicate</strong></p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/33978/find-out-how-much-memory-is-being-used-by-an-object-in-python">Find out how much memory is being used by an object in Python</a></p>
</blockquote>
| 15
|
2009-02-19T03:27:34Z
| 565,382
|
<p>Unfortunately this is not possible, but there are a number of ways of approximating the answer:</p>
<ol>
<li><p>for very simple objects (e.g. ints, strings, floats, doubles) which are represented more or less as simple C-language types you can simply calculate the number of bytes as with <a href="http://stackoverflow.com/a/563921/1922357">John Mulder's solution</a>.</p></li>
<li><p>For more complex objects a good approximation is to serialize the object to a string using cPickle.dumps. The length of the string is a good approximation of the amount of memory required to store an object. </p></li>
</ol>
<p>There is one big snag with solution 2, which is that objects usually contain references to other objects. For example a dict contains string-keys and other objects as values. Those other objects might be shared. Since pickle always tries to do a complete serialization of the object it will always over-estimate the amount of memory required to store an object.</p>
| 22
|
2009-02-19T13:50:09Z
|
[
"python",
"memory",
"ipython"
] |
How can I check the memory usage of objects in iPython?
| 563,840
|
<p>I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:</p>
<pre><code>In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB
</code></pre>
<p>Something like <code>%memusage <object></code> and return the memory used by the object.</p>
<p><strong>Duplicate</strong></p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/33978/find-out-how-much-memory-is-being-used-by-an-object-in-python">Find out how much memory is being used by an object in Python</a></p>
</blockquote>
| 15
|
2009-02-19T03:27:34Z
| 15,591,157
|
<p>If you are using a <a href="http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html">numpy array</a>, then you can use the attribute <code>ndarray.nbytes</code> to evaluate its size in memory:</p>
<pre><code>from pylab import *
d = array([2,3,4,5])
d.nbytes
#Output: 32
</code></pre>
| 11
|
2013-03-23T19:30:46Z
|
[
"python",
"memory",
"ipython"
] |
Anybody tried mosso CloudFiles with Google AppEngine?
| 564,460
|
<p>I'm wondering if anybody tried to integrate mosso CloudFiles with an application running on Google AppEngine (mosso does not provide testing sandbox so I cann't check for myself without registering)? Looking at the code it seems that this will not work due to httplib and urllib limitations in AppEngine environment, but maybe somebody has patched cloudfiles?</p>
| 1
|
2009-02-19T09:01:04Z
| 564,966
|
<p>It appears to implement a simple RESTful API, so there's no reason you couldn't use it from App Engine. Previously, you'd have had to write your own library to do so, using App Engine's urlfetch API, but with the release of SDK 1.1.9, you can now use urllib and httplib instead.</p>
| 1
|
2009-02-19T11:56:20Z
|
[
"python",
"google-app-engine",
"storage",
"cloud",
"mosso"
] |
Python - ConfigParser throwing comments
| 564,662
|
<p>Based on ConfigParser module how can I filter out and throw every comments from an ini file?</p>
<pre><code>import ConfigParser
config = ConfigParser.ConfigParser()
config.read("sample.cfg")
for section in config.sections():
print section
for option in config.options(section):
print option, "=", config.get(section, option)
</code></pre>
<p>eg. in the ini file below the above basic script prints out the further comments lines as well like:</p>
<pre><code>something = 128 ; comment line1
; further comments
; one more line comment
</code></pre>
<p>What I need is having only the section names and pure key-value pairs inside them without any comments. Does ConfigParser handles this somehow or should I use regexp...or? Cheers</p>
| 1
|
2009-02-19T10:27:21Z
| 564,690
|
<p>according to <a href="http://docs.python.org/library/configparser.html" rel="nofollow">docs</a> lines starting with <code>;</code> or <code>#</code> will be ignored. it doesn't seem like your format satisfies that requirement. can you by any chance change format of your input file?</p>
<p><strong>edit</strong>: since you cannot modify your input files, I'd suggest pre-parsing them with something along the lines:</p>
<pre><code>tmp_fname = 'config.tmp'
with open(config_file) as old_file:
with open(tmp_fname, 'w') as tmp_file:
tmp_file.writelines(i.replace(';', '\n;') for i in old_lines.readlines())
# then use tmp_fname with ConfigParser
</code></pre>
<p>obviously if semi-colon is present in options you'll have to be more creative.</p>
| 5
|
2009-02-19T10:36:28Z
|
[
"python",
"configparser"
] |
Python - ConfigParser throwing comments
| 564,662
|
<p>Based on ConfigParser module how can I filter out and throw every comments from an ini file?</p>
<pre><code>import ConfigParser
config = ConfigParser.ConfigParser()
config.read("sample.cfg")
for section in config.sections():
print section
for option in config.options(section):
print option, "=", config.get(section, option)
</code></pre>
<p>eg. in the ini file below the above basic script prints out the further comments lines as well like:</p>
<pre><code>something = 128 ; comment line1
; further comments
; one more line comment
</code></pre>
<p>What I need is having only the section names and pure key-value pairs inside them without any comments. Does ConfigParser handles this somehow or should I use regexp...or? Cheers</p>
| 1
|
2009-02-19T10:27:21Z
| 564,897
|
<p>It seems your comments are not on lines that <em>start</em> with the comment leader. It should work if the comment leader is the first character on the line.</p>
| 2
|
2009-02-19T11:40:31Z
|
[
"python",
"configparser"
] |
Python - ConfigParser throwing comments
| 564,662
|
<p>Based on ConfigParser module how can I filter out and throw every comments from an ini file?</p>
<pre><code>import ConfigParser
config = ConfigParser.ConfigParser()
config.read("sample.cfg")
for section in config.sections():
print section
for option in config.options(section):
print option, "=", config.get(section, option)
</code></pre>
<p>eg. in the ini file below the above basic script prints out the further comments lines as well like:</p>
<pre><code>something = 128 ; comment line1
; further comments
; one more line comment
</code></pre>
<p>What I need is having only the section names and pure key-value pairs inside them without any comments. Does ConfigParser handles this somehow or should I use regexp...or? Cheers</p>
| 1
|
2009-02-19T10:27:21Z
| 565,332
|
<p>Best way is to write a commentless <code>file</code> subclass:</p>
<pre><code>class CommentlessFile(file):
def readline(self):
line = super(CommentlessFile, self).readline()
if line:
line = line.split(';', 1)[0].strip()
return line + '\n'
else:
return ''
</code></pre>
<p>You could use it then with configparser (your code):</p>
<pre><code>import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(CommentlessFile("sample.cfg"))
for section in config.sections():
print section
for option in config.options(section):
print option, "=", config.get(section, option)
</code></pre>
| 3
|
2009-02-19T13:38:19Z
|
[
"python",
"configparser"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.