title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Finding the command for a specific PID in Linux from Python
1,440,941
<p>I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.</p> <p>Any help would be great. Thanks.</p>
5
2009-09-17T19:44:09Z
11,960,592
<p>An interesting Python package is <a href="http://code.google.com/p/psutil" rel="nofollow">psutil</a>.</p> <p>For example, to get the command for a specific PID:</p> <pre><code>import psutil pid = 1234 # The pid whose info you're looking for p = psutil.Process(pid) print p.cmdline </code></pre> <p>The last line will print something like <code>['/usr/bin/python', 'main.py'] </code>.</p> <p>A more robust way to get this information, being careful if the pid represents a process no longer running:</p> <pre><code>import psutil pid = 1234 # The pid whose info you're looking for if pid in psutil.get_pid_list(): p = psutil.Process(pid) print p.cmdline </code></pre>
3
2012-08-14T20:55:30Z
[ "python", "linux", "process" ]
Finding the command for a specific PID in Linux from Python
1,440,941
<p>I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.</p> <p>Any help would be great. Thanks.</p>
5
2009-09-17T19:44:09Z
31,840,230
<p>This worked for me:</p> <pre><code>def filter_non_printable(str): ret="" for c in str: if ord(c) &gt; 31 or ord(c) == 9: ret += c else: ret += " " return ret # # Get /proc/&lt;cpu&gt;/cmdline information # def pid_name(pid): try: with open(os.path.join('/proc/', pid, 'cmdline'), 'r') as pidfile: return filter_non_printable(pidfile.readline()) except Exception: pass return </code></pre>
0
2015-08-05T18:34:16Z
[ "python", "linux", "process" ]
Python Inspect - Lookup the data type for a property in a GAE db.model Class
1,440,958
<pre><code>class Employee(db.Model): firstname = db.StringProperty() lastname = db.StringProperty() address1 = db.StringProperty() timezone = db.FloatProperty() #might be -3.5 (can contain fractions) class TestClassAttributes(webapp.RequestHandler): """ Enumerate attributes of a db.Model class """ def get(self): for item in Employee.properties(): self.response.out.write("&lt;br/&gt;" + item) #for subitem in item.__dict__: # self.response.out.write("&lt;br/&gt;&amp;nbsp;&amp;nbsp;--" + subitem) </code></pre> <p>The above will give me a list of the property names for the variable "item". My idea of <code>item.__dict__</code> didn't work because <code>item</code> was a <code>str</code>. How can I then display the data field type for each property, such as <code>db.FloatProperty()</code> for the property called <code>timezone</code>? </p> <p>GAE = Google App Engine - but I'm sure the same answer would work for any class. </p> <p>Thanks, Neal Walters </p>
1
2009-09-17T19:48:21Z
1,441,354
<p>Iterate using "for name, property in Employee.properties().items()". The property argument is the Property instance, which you can compare using instanceof.</p>
2
2009-09-17T21:05:35Z
[ "python", "google-app-engine", "reflection", "inspection" ]
Python Inspect - Lookup the data type for a property in a GAE db.model Class
1,440,958
<pre><code>class Employee(db.Model): firstname = db.StringProperty() lastname = db.StringProperty() address1 = db.StringProperty() timezone = db.FloatProperty() #might be -3.5 (can contain fractions) class TestClassAttributes(webapp.RequestHandler): """ Enumerate attributes of a db.Model class """ def get(self): for item in Employee.properties(): self.response.out.write("&lt;br/&gt;" + item) #for subitem in item.__dict__: # self.response.out.write("&lt;br/&gt;&amp;nbsp;&amp;nbsp;--" + subitem) </code></pre> <p>The above will give me a list of the property names for the variable "item". My idea of <code>item.__dict__</code> didn't work because <code>item</code> was a <code>str</code>. How can I then display the data field type for each property, such as <code>db.FloatProperty()</code> for the property called <code>timezone</code>? </p> <p>GAE = Google App Engine - but I'm sure the same answer would work for any class. </p> <p>Thanks, Neal Walters </p>
1
2009-09-17T19:48:21Z
1,441,598
<p>For problems like these, the interactive Python shell is really handy. If you had used it to poke around at your Employee object, you might have discovered the answer to your question through trial and error.</p> <p>Something like:</p> <pre><code>&gt;&gt;&gt; from groups.models import Group &gt;&gt;&gt; Group.properties() {'avatar': &lt;google.appengine.ext.db.StringProperty object at 0x19f73b0&gt;, 'created_at': &lt;google.appengine.ext.db.DateTimeProperty object at 0x19f7330&gt;, 'description': &lt;google.appengine.ext.db.TextProperty object at 0x19f7210&gt;, 'group_type': &lt;google.appengine.ext.db.StringProperty object at 0x19f73d0&gt;} </code></pre> <p>From that you know that the <code>properties()</code> method of a <code>db.Model</code> object returns a <code>dict</code> mapping the model's property names to the actual property objects they represent.</p>
1
2009-09-17T22:14:48Z
[ "python", "google-app-engine", "reflection", "inspection" ]
Python Inspect - Lookup the data type for a property in a GAE db.model Class
1,440,958
<pre><code>class Employee(db.Model): firstname = db.StringProperty() lastname = db.StringProperty() address1 = db.StringProperty() timezone = db.FloatProperty() #might be -3.5 (can contain fractions) class TestClassAttributes(webapp.RequestHandler): """ Enumerate attributes of a db.Model class """ def get(self): for item in Employee.properties(): self.response.out.write("&lt;br/&gt;" + item) #for subitem in item.__dict__: # self.response.out.write("&lt;br/&gt;&amp;nbsp;&amp;nbsp;--" + subitem) </code></pre> <p>The above will give me a list of the property names for the variable "item". My idea of <code>item.__dict__</code> didn't work because <code>item</code> was a <code>str</code>. How can I then display the data field type for each property, such as <code>db.FloatProperty()</code> for the property called <code>timezone</code>? </p> <p>GAE = Google App Engine - but I'm sure the same answer would work for any class. </p> <p>Thanks, Neal Walters </p>
1
2009-09-17T19:48:21Z
4,241,950
<p>I add the same problem, and the first 2 answers did not help me 100%. I was not able to get the type information, from the meta data of the class or the instance property, which is bizarre. So I had to use a dictionary.</p> <p>The method GetType() will return the type of the property as a string.</p> <p>Here is my answer:</p> <pre><code>class RFolder(db.Model): def GetPropertyTypeInstance(self, pname): for name, property in self.properties().items(): if name==pname: return property return None def GetType(self, pname): t = self.GetPropertyTypeInstance(pname) return RFolder.__DB_PROPERTY_INFO[type(t)] __DB_PROPERTY_INFO = { db.StringProperty :"String", db.ByteStringProperty :"ByteString", db.BooleanProperty :"Boolean", db.IntegerProperty :"Integer", db.FloatProperty :"Float", db.DateTimeProperty :"DateTime", db.DateProperty :"Date", db.TimeProperty :"Time", db.ListProperty :"List", db.StringListProperty :"StringList", db.ReferenceProperty :"Reference", db.SelfReferenceProperty :"SelfReference", db.UserProperty :"User", db.BlobProperty :"Blob", db.TextProperty :"Text", db.CategoryProperty :"Category", db.LinkProperty :"Link", db.EmailProperty :"Email", db.GeoPtProperty :"GeoPt", db.IMProperty :"IM", db.PhoneNumberProperty :"PhoneNumber", db.PostalAddressProperty :"PostalAddress", db.RatingProperty :"Rating" } </code></pre>
0
2010-11-22T03:10:54Z
[ "python", "google-app-engine", "reflection", "inspection" ]
Why do I get error, KeyError: 'wsgi.input'?
1,441,038
<p>I'm using WSGI and trying to access the get/post data, using this code:</p> <pre><code>import os import cgi from traceback import format_exception from sys import exc_info def application(environ, start_response): try: f = cgi.FieldStorage(fp=os.environ['wsgi.input'], environ=os.environ) output = 'Test: %s' % f['test'].value except: output = ''.join(format_exception(*exc_info())) status = '200 OK' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] </code></pre> <p>However I get the following error:</p> <pre><code>Traceback (most recent call last): File "/srv/www/vm/custom/gettest.wsgi", line 9, in application f = cgi.FieldStorage(fp=os.environ['wsgi.input'], environ=os.environ) File "/usr/lib64/python2.4/UserDict.py", line 17, in __getitem__ def __getitem__(self, key): return self.data[key] KeyError: 'wsgi.input' </code></pre> <p>Is it because wsgi.input does not exist in my version?</p>
1
2009-09-17T20:02:45Z
1,441,080
<p>You're misusing the <a href="http://www.python.org/dev/peps/pep-0333/#specification-details">WSGI API</a>. </p> <p>Please create a minimal ("hello world") function that shows this error so we can comment on your code. [Don't post your entire application, it may be too big and unwieldy for us to comment on.]</p> <p>The <code>os.environ</code> is not what you should be using. WSGI replaces this with an enriched environment. A WSGI application gets two arguments: one is a dictionary that includes <code>'wsgi.input'</code>.</p> <p><hr /></p> <p>In your code...</p> <pre><code>def application(environ, start_response): try: f = cgi.FieldStorage(fp=os.environ['wsgi.input'], environ=os.environ) </code></pre> <p>Per the WSGI API specification (<a href="http://www.python.org/dev/peps/pep-0333/#specification-details">http://www.python.org/dev/peps/pep-0333/#specification-details</a>), don't use <code>os.environ</code>. Use <code>environ</code>, the first positional parameter to your application.</p> <blockquote> <p>The environ parameter is a dictionary object, containing CGI-style environment variables. This object must be a builtin Python dictionary (not a subclass, UserDict or other dictionary emulation), and the application is allowed to modify the dictionary in any way it desires. The dictionary must also include certain WSGI-required variables (described in a later section), and may also include server-specific extension variables, named according to a convention that will be described below.</p> </blockquote>
6
2009-09-17T20:11:33Z
[ "python", "mod-wsgi" ]
Hiding Vertical Scrollbar in wx.TextCtrl
1,441,502
<p>I have a wx.TextCtrl that I am using to represent a display with a fixed number of character rows and columns. I would like to hide the vertical scrollbar that is displayed to the right of the text pane since it is entirely unnecessary in my application. Is there a way to achieve this?</p> <p>Also...I would like to hide the blinking cursor that is displayed in the pane. Unfortunately, <code>wx.TextCtrl.GetCaret()</code> is returning <code>None</code> so I cannot call <code>wx.Caret.Hide()</code>.</p> <p>Environment info:</p> <ul> <li>Windows XP</li> <li>Python 2.5</li> <li>wxPython 2.8</li> </ul>
4
2009-09-17T21:47:20Z
1,442,312
<p>How about setting the style <code>wx.TE_NO_VSCROLL</code> for the wx.TxtCtrl?</p>
4
2009-09-18T02:25:54Z
[ "python", "wxpython", "wxtextctrl" ]
Plotting color map with zip codes in R or Python
1,441,717
<p>I have some US demographic and firmographic data.<br /> I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <a href="http://maps.huge.info/">http://maps.huge.info/</a> but a) with annotated text; b) pdf output; c) scriptable in R or Python.</p> <p>Is there any package and code that allows me to do this?</p>
25
2009-09-17T22:50:42Z
1,441,788
<p>Depending on your application, a long way around might be to use something like this:</p> <p><a href="http://googlemapsmania.blogspot.com/2006/07/new-google-maps-us-zip-code-mashups.html" rel="nofollow">http://googlemapsmania.blogspot.com/2006/07/new-google-maps-us-zip-code-mashups.html</a></p> <p>To map your data. If that wasn't quite what you wanted, you can get raw zip code shapefiles from census.gov and do it manually, which is quite a pain.</p> <p>Also, if you haven't seen it, this is a neat way to interact with similar data, and might offer some pointers:</p> <p><a href="http://benfry.com/zipdecode/" rel="nofollow">http://benfry.com/zipdecode/</a></p>
0
2009-09-17T23:11:05Z
[ "python", "graphics", "zipcode" ]
Plotting color map with zip codes in R or Python
1,441,717
<p>I have some US demographic and firmographic data.<br /> I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <a href="http://maps.huge.info/">http://maps.huge.info/</a> but a) with annotated text; b) pdf output; c) scriptable in R or Python.</p> <p>Is there any package and code that allows me to do this?</p>
25
2009-09-17T22:50:42Z
1,441,822
<p>Check out this excellent online visualization tool by IBM <a href="http://manyeyes.alphaworks.ibm.com/manyeyes/" rel="nofollow">http://manyeyes.alphaworks.ibm.com/manyeyes/</a></p> <p><strong>EDIT</strong> FYI, ManyEyes uses the <a href="http://prefuse.org/gallery/" rel="nofollow">Prefuse visualization toolkit</a> for some of its viz. Even though it is a java-based framework, they also provide a Flash/ActionScript tool for the web.</p>
0
2009-09-17T23:19:55Z
[ "python", "graphics", "zipcode" ]
Plotting color map with zip codes in R or Python
1,441,717
<p>I have some US demographic and firmographic data.<br /> I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <a href="http://maps.huge.info/">http://maps.huge.info/</a> but a) with annotated text; b) pdf output; c) scriptable in R or Python.</p> <p>Is there any package and code that allows me to do this?</p>
25
2009-09-17T22:50:42Z
1,441,833
<p>Someone may have something more direct for you, but I found O'Reilly's 'Data Mashups in R' very interesting... in part, it's a spatial mapping of home foreclosure auctions.</p> <p><a href="http://oreilly.com/catalog/9780596804770/" rel="nofollow">http://oreilly.com/catalog/9780596804770/</a></p>
3
2009-09-17T23:21:25Z
[ "python", "graphics", "zipcode" ]
Plotting color map with zip codes in R or Python
1,441,717
<p>I have some US demographic and firmographic data.<br /> I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <a href="http://maps.huge.info/">http://maps.huge.info/</a> but a) with annotated text; b) pdf output; c) scriptable in R or Python.</p> <p>Is there any package and code that allows me to do this?</p>
25
2009-09-17T22:50:42Z
1,442,241
<p>There is a rich and sophisticated series of packages in R to plot, do analysis, and other functions related to GIS. One place to get started is the CRAN task view on <a href="http://cran.r-project.org/web/views/Spatial.html" rel="nofollow">Spatial Data</a>: This is a complex and sometimes arcane world, and takes some work to understand. </p> <p>If you are looking for a free, very functional mapping application, may I suggest:</p> <p>MapWindow ( mapwindow.com)</p>
1
2009-09-18T01:48:30Z
[ "python", "graphics", "zipcode" ]
Plotting color map with zip codes in R or Python
1,441,717
<p>I have some US demographic and firmographic data.<br /> I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <a href="http://maps.huge.info/">http://maps.huge.info/</a> but a) with annotated text; b) pdf output; c) scriptable in R or Python.</p> <p>Is there any package and code that allows me to do this?</p>
25
2009-09-17T22:50:42Z
1,442,252
<p><a href="http://trends.techcrunch.com/" rel="nofollow">Daniel Levine at TechCrunch Trends</a> has done nice things with the <code>maps</code> package in R. He has code available on his site, too.</p> <p>Paul's suggestion of looking into Processing - which Ben Fry used to make zipdecode - is also a good one, if you're up for learning a (Java-like) new language.</p>
1
2009-09-18T01:50:41Z
[ "python", "graphics", "zipcode" ]
Plotting color map with zip codes in R or Python
1,441,717
<p>I have some US demographic and firmographic data.<br /> I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <a href="http://maps.huge.info/">http://maps.huge.info/</a> but a) with annotated text; b) pdf output; c) scriptable in R or Python.</p> <p>Is there any package and code that allows me to do this?</p>
25
2009-09-17T22:50:42Z
1,442,254
<p>There are many ways to do this in R (see the <a href="http://cran.r-project.org/web/views/Spatial.html">spatial view</a>); many of these <a href="http://cran.r-project.org/web/packages/maps/index.html">depend on the "maps" package</a>.</p> <ul> <li><p>Check out this <a href="http://www.ai.rug.nl/~hedderik/R/US2004/">cool example of the US 2004 election</a>. It ends up looking like this:<img src="http://www.ai.rug.nl/~hedderik/R/US2004/US04Election-PopGraded.png" alt="alt text" /></p></li> <li><p>Here's a slightly ugly example of a model <a href="http://addictedtor.free.fr/graphiques/sources/source_146.R">that uses the "maps" package with "lattice".</a></p></li> <li>Andrew Gelman made some very nice plots like this. See, for instance, <a href="http://www.stat.columbia.edu/~cook/movabletype/archives/2009/03/how_went_the_20.html">this blog post on red states/blue states</a> and <a href="http://www.stat.columbia.edu/~cook/movabletype/archives/2009/05/discussion_and.html">this follow up post</a>.</li> <li><p>Here's a very simple example <a href="http://cran.r-project.org/web/packages/gmaps/index.html">using the "gmaps" package</a>, which shows a map of Arrests by state for arrests per 100,000 for Murder:</p> <pre><code>require(gmaps) data(USArrests) attach(USArrests) grid.newpage() grid.frame(name="map") grid.pack("map",USALevelPlot(states=rownames(USArrests),levels=Murder,col.fun=reds),height=unit(1,'null')) grid.pack("map",gradientLegendGrob(at=quantile(Murder),col.fun=reds),side="bottom",height=unit(.2,'npc')) detach(USArrests) </code></pre></li> </ul>
9
2009-09-18T01:51:40Z
[ "python", "graphics", "zipcode" ]
Plotting color map with zip codes in R or Python
1,441,717
<p>I have some US demographic and firmographic data.<br /> I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <a href="http://maps.huge.info/">http://maps.huge.info/</a> but a) with annotated text; b) pdf output; c) scriptable in R or Python.</p> <p>Is there any package and code that allows me to do this?</p>
25
2009-09-17T22:50:42Z
1,446,144
<p>I am assuming you want static maps. </p> <p><img src="http://files.eduardoleoni.com/mapUS.png" alt="alt text" /></p> <p>1) Get the shapefiles of the <a href="http://www.census.gov/geo/www/cob/zt%5Fmetadata.html">zip</a> boundaries and <a href="http://www.census.gov/geo/www/cob/st2000.html">state</a> boundaries at census.gov: </p> <p>2) Use the plot.heat function I posted in this <a href="http://stackoverflow.com/questions/1260965/developing-geographic-thematic-maps-with-r">SO question</a>.</p> <p>For example (assumes you have the maryland shapefiles in the map subdirectory):</p> <pre><code>library(maptools) ##substitute your shapefiles here state.map &lt;- readShapeSpatial("maps/st24_d00.shp") zip.map &lt;- readShapeSpatial("maps/zt24_d00.shp") ## this is the variable we will be plotting zip.map@data$noise &lt;- rnorm(nrow(zip.map@data)) ## put the lab point x y locations of the zip codes in the data frame for easy retrieval labelpos &lt;- data.frame(do.call(rbind, lapply(zip.map@polygons, function(x) x@labpt))) names(labelpos) &lt;- c("x","y") zip.map@data &lt;- data.frame(zip.map@data, labelpos) ## plot it png(file="map.png") ## plot colors plot.heat(zip.map,state.map,z="noise",breaks=c(-Inf,-2,-1,0,1,2,Inf)) ## plot text with(zip.map@data[sample(1:nrow(zip.map@data), 10),] , text(x,y,NAME)) dev.off() </code></pre>
33
2009-09-18T18:21:07Z
[ "python", "graphics", "zipcode" ]
Plotting color map with zip codes in R or Python
1,441,717
<p>I have some US demographic and firmographic data.<br /> I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <a href="http://maps.huge.info/">http://maps.huge.info/</a> but a) with annotated text; b) pdf output; c) scriptable in R or Python.</p> <p>Is there any package and code that allows me to do this?</p>
25
2009-09-17T22:50:42Z
1,871,605
<p>In Python, you can use shapefiles from the US census along with the <code>basemap</code> package. Here is an example of <a href="http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/toolkits/basemap/examples/fillstates.py?view=markup" rel="nofollow">filling in states</a> according to population.</p>
1
2009-12-09T04:38:07Z
[ "python", "graphics", "zipcode" ]
How can I omit words in the middle of a regular expression in Python?
1,441,866
<p>I have a multi-line string like this:</p> <pre><code>"...Togo...Togo...Togo...ACTIVE..." </code></pre> <p>I want to get everything between the third 'Togo' and 'ACTIVE' and the remainder of the string. I am unable to create a regular expression that can do this. If I try something like </p> <pre><code>reg = "(Togo^[Togo]*?)(ACTIVE.*)" </code></pre> <p>nothing is captured (the first and last parentheses are needed for capturing groups).</p>
0
2009-09-17T23:32:35Z
1,441,879
<pre><code>reg = "Togo.*Togo.*Togo(.*)ACTIVE" </code></pre> <p>Alternatively, if you want to match the string between the last occurrence of Togo and the following occurence of ACTIVE, and the number of Togo occurences is not necessarily three, try this:</p> <pre><code>reg = "Togo(([^T]|T[^o]|To[^g]|Tog[^o])*T?.?.?)ACTIVE" </code></pre>
1
2009-09-17T23:36:18Z
[ "python", "string" ]
How can I omit words in the middle of a regular expression in Python?
1,441,866
<p>I have a multi-line string like this:</p> <pre><code>"...Togo...Togo...Togo...ACTIVE..." </code></pre> <p>I want to get everything between the third 'Togo' and 'ACTIVE' and the remainder of the string. I am unable to create a regular expression that can do this. If I try something like </p> <pre><code>reg = "(Togo^[Togo]*?)(ACTIVE.*)" </code></pre> <p>nothing is captured (the first and last parentheses are needed for capturing groups).</p>
0
2009-09-17T23:32:35Z
1,441,929
<p>This matches just the desired parts:</p> <pre><code>.*(Togo.*?)(ACTIVE.*) </code></pre> <p>The leading <code>.*</code> is greedy, so the following <code>Togo</code> matches at the last possible place. The captured part starts at the last <code>Togo</code>.</p> <p>In your expression <code>^[Togo]*?</code> doesn't do the right thing. <code>^</code> tries to match the beginning of a line and <code>[Togo]</code> matches any of the characters <code>T</code>, <code>o</code> or <code>g</code>. Even <code>[^Togo]</code> wouldn't work since this just matches any character that is not <code>T</code>, <code>o</code> or <code>g</code>.</p>
1
2009-09-17T23:50:37Z
[ "python", "string" ]
How can I omit words in the middle of a regular expression in Python?
1,441,866
<p>I have a multi-line string like this:</p> <pre><code>"...Togo...Togo...Togo...ACTIVE..." </code></pre> <p>I want to get everything between the third 'Togo' and 'ACTIVE' and the remainder of the string. I am unable to create a regular expression that can do this. If I try something like </p> <pre><code>reg = "(Togo^[Togo]*?)(ACTIVE.*)" </code></pre> <p>nothing is captured (the first and last parentheses are needed for capturing groups).</p>
0
2009-09-17T23:32:35Z
1,449,813
<pre><code>"(Togo(?:(?!Togo).)*)(ACTIVE.*)" </code></pre> <p>The square brackets in your regex form a character class that matches one of the characters 'T', 'o', or 'g'. The caret ('^') matches the beginning of the input if it's not in a character class, and it can be used inside the square brackets to invert the character class.</p> <p>In my regex, after matching the word "Togo" I match one character at a time, but only after I check that it isn't the start of another instance of "Togo". <code>(?!Togo)</code> is called a <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">negative lookahead</a>. </p>
1
2009-09-19T23:43:08Z
[ "python", "string" ]
Is it possible to have a python app authentication with a remote linux server?
1,441,875
<p>The idea here is to have a python app, that when started, asks for a user/password combination. This user/password combination should be the same as the user/password of the remote linux server or in such case, and authentication system.</p> <p>Is this possible? How? Which APIs can I use?</p> <p>Thanks a lot.</p>
0
2009-09-17T23:34:58Z
1,441,889
<p>I would recommend looking into <a href="http://en.wikipedia.org/wiki/Lightweight%5FDirectory%5FAccess%5FProtocol" rel="nofollow">LDAP</a> and <a href="http://www.linuxjournal.com/article/6988" rel="nofollow">python-ldap</a></p>
0
2009-09-17T23:39:39Z
[ "python", "authentication", "login" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
1,442,011
<p>PIL can do good resizing. Make sure your source image is in RGB mode, not palette colors, and try the different algorithm choices.</p>
1
2009-09-18T00:17:46Z
[ "python", "command-line", "libraries", "imaging" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
1,442,034
<p>While imagemagick seems to be the de facto open-source imaging library, possibly <a href="http://openil.sourceforge.net/features.php" rel="nofollow">DevIL</a> (cross platform, seems to do simple image operations) or <a href="http://freeimage.sourceforge.net/features.html" rel="nofollow">FreeImage</a>.</p>
1
2009-09-18T00:25:12Z
[ "python", "command-line", "libraries", "imaging" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
1,442,062
<blockquote> <p>I've used PIL, and the resample/resize results are TERRIBLE.</p> </blockquote> <p>They shouldn't be, as long as you:</p> <ol> <li>use only Image.ANTIALIAS filtering for downscaling operations</li> <li>use only Image.BICUBIC filtering for upscaling operations.</li> <li>remember to convert to 'RGB' colour mode before the resize if you are using a paletted image</li> <li>don't use .thumbnail(). it's crap</li> <li>set the <code>quality=</code> level to something appropriate when saving JPEGs (the default is quite low)</li> </ol>
16
2009-09-18T00:37:44Z
[ "python", "command-line", "libraries", "imaging" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
1,442,110
<p>Have you checked <a href="http://pypi.python.org/pypi/" rel="nofollow">pypi</a>? A cursory search shows some image related tools there, I also discovered python-gd, no clue how useful it might be though.</p> <p>I've never had any issues with PIL myself, but some kind of variety might be interesting.</p>
1
2009-09-18T00:53:31Z
[ "python", "command-line", "libraries", "imaging" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
1,442,286
<p>GIMP has a reasonable command-line interface, I think.</p>
1
2009-09-18T02:10:00Z
[ "python", "command-line", "libraries", "imaging" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
1,545,544
<p>Take a look at some of these imaging libraries:</p> <p>hxxp://pypi.python.org/pypi/collective.croppingimagefield/0.1beta</p> <p>hxxp://pypi.python.org/pypi/cropresize/0.1.1</p> <p>hxxp://pypi.python.org/pypi/image_resize/1.0</p>
1
2009-10-09T19:03:58Z
[ "python", "command-line", "libraries", "imaging" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
2,986,465
<p>Last time I compared, this downscaler's output is almost identical to that of GIMP's "cubic" option:</p> <pre><code> import Image def stretch(im, size, filter=Image.NEAREST): im.load() im = im._new(im.im.stretch(size, filter)) return im </code></pre> <p>IIRC, the differences are visually indistinguishable -- some pixel values +/-1 due to rounding, and they tend to be round the edges. It's not slow either.</p> <p>cf: <a href="http://www.mail-archive.com/image-sig@python.org/msg00248.html" rel="nofollow">http://www.mail-archive.com/image-sig@python.org/msg00248.html</a></p>
0
2010-06-07T00:13:36Z
[ "python", "command-line", "libraries", "imaging" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
5,598,396
<p>I'm unsure as to why Image.thumbnail is getting such flak. In the present release that I'm running off of it does little more than figure out the desired size and resize the image in place. As long as you're using the proper resample filter and convert to RGB first (as bobince says) thumbnail shouldn't be any different than resize. </p> <p>Here's the actual source for the thumbnail method:</p> <pre><code>def thumbnail(self, size, resample=NEAREST): # preserve aspect ratio x, y = self.size if x &gt; size[0]: y = max(y * size[0] / x, 1); x = size[0] if y &gt; size[1]: x = max(x * size[1] / y, 1); y = size[1] size = x, y if size == self.size: return self.draft(None, size) self.load() try: im = self.resize(size, resample) except ValueError: if resample != ANTIALIAS: raise im = self.resize(size, NEAREST) # fallback self.im = im.im self.mode = im.mode self.size = size self.readonly = 0 </code></pre>
2
2011-04-08T17:01:52Z
[ "python", "command-line", "libraries", "imaging" ]
Python imaging alternatives
1,441,967
<p>I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set of stairs at a keyboard.</p> <p>I'm looking for something which is not PIL or Imagemagick that I can use with python to do simple, high-quality image transformations. For that matter, it doesn't even have to have python bindings if the command line interface is good.</p> <p>Oh, and it needs to be relatively platform agnostic, our production servers are linux, but some of our devs develop on windows. It can't require the installation of a bunch of silly gui code to use as a library, either.</p>
10
2009-09-18T00:05:57Z
39,942,859
<blockquote> <p>I've used PIL, and the resample/resize results are TERRIBLE.</p> </blockquote> <p>Resizing in PIL was broken in many ways and PIL is not maintained for a long time. Starting from <a href="https://pillow.readthedocs.io/en/3.4.x/releasenotes/2.7.0.html" rel="nofollow">Pillow 2.7</a> most of the problems are fixed along with dramatically performance improvement. Make sure you are using <a href="https://pillow.readthedocs.io" rel="nofollow">latest Pillow</a>.</p>
0
2016-10-09T11:03:48Z
[ "python", "command-line", "libraries", "imaging" ]
Whats the error in this python code?
1,441,979
<p>What do i do to solve it? Terminal output is: </p> <p><code><pre> abhi@abhi-desktop:~/Desktop/sslstrip-0.1$ python sslstrip.py --listen=3130 Traceback (most recent call last): File "sslstrip.py", line 254, in main(sys.argv[1:]) File "sslstrip.py", line 246, in main server = ThreadingHTTPServer(('', listenPort), StripProxy) File "/usr/lib/python2.6/SocketServer.py", line 400, in <strong>init</strong> self.server_bind() File "/usr/lib/python2.6/BaseHTTPServer.py", line 108, in server_bind SocketServer.TCPServer.server_bind(self) File "/usr/lib/python2.6/SocketServer.py", line 411, in server_bind self.socket.bind(self.server_address) File "", line 1, in bind TypeError: an integer is required abhi@abhi-desktop:~/Desktop/sslstrip-0.1$ </pre></code></p> <p>Here is a 21kb code given... <a href="http://www.thoughtcrime.org/software/sslstrip/sslstrip-0.5.tar.gz" rel="nofollow">Download link</a></p>
0
2009-09-18T00:08:57Z
1,442,002
<p>Does it fail when you don't specify a port?</p> <p>My guess is that listenPort is coming out of the option parsing as a string and needs to be cast to an in sslstrip.py on line 77.</p>
2
2009-09-18T00:15:19Z
[ "python", "session-hijacking" ]
Whats the error in this python code?
1,441,979
<p>What do i do to solve it? Terminal output is: </p> <p><code><pre> abhi@abhi-desktop:~/Desktop/sslstrip-0.1$ python sslstrip.py --listen=3130 Traceback (most recent call last): File "sslstrip.py", line 254, in main(sys.argv[1:]) File "sslstrip.py", line 246, in main server = ThreadingHTTPServer(('', listenPort), StripProxy) File "/usr/lib/python2.6/SocketServer.py", line 400, in <strong>init</strong> self.server_bind() File "/usr/lib/python2.6/BaseHTTPServer.py", line 108, in server_bind SocketServer.TCPServer.server_bind(self) File "/usr/lib/python2.6/SocketServer.py", line 411, in server_bind self.socket.bind(self.server_address) File "", line 1, in bind TypeError: an integer is required abhi@abhi-desktop:~/Desktop/sslstrip-0.1$ </pre></code></p> <p>Here is a 21kb code given... <a href="http://www.thoughtcrime.org/software/sslstrip/sslstrip-0.5.tar.gz" rel="nofollow">Download link</a></p>
0
2009-09-18T00:08:57Z
1,442,144
<p>The provided link is to sslstrip-0.5. You are using sslstrip-0.1. These are <em>very</em> different (sslstrip-0.5 uses twisted). This bug was fixed in sslstrip-0.2. If you don't have twisted or don't want to install twisted, I suggest that you get <a href="http://www.thoughtcrime.org/software/sslstrip/sslstrip-0.4.tar.gz" rel="nofollow">sslstrip-0.4</a>.</p>
2
2009-09-18T01:06:45Z
[ "python", "session-hijacking" ]
Subdomains and Logins
1,442,017
<p>If you multiple subdomains e.g.:</p> <blockquote> <p>sub1.domain_name.com</p> <p>sub2.domain_name.com</p> </blockquote> <p>Is there a way to have a user be able to log into both of these without issues and double login issue?</p> <p>The platform is Python, Django.</p>
4
2009-09-18T00:19:48Z
1,442,029
<p>Without information regarding what platform you are using, it is difficult to say. If you use cookies to store authentication information, and you are using subdomains as you describe, then you can force the cookie to be issued for the highest level domain, e.g. domain_name.com.</p> <p>This will be accessable by both sub1 and sub2, and they could each use that for their authentication.</p> <p><strong>EDIT:</strong></p> <p>In the settings.py for each application running under the subdomains, you need to put <code>SESSION_COOKIE_DOMAIN = ".domain_name.com"</code> as per <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-domain">the django docs</a></p>
10
2009-09-18T00:23:13Z
[ "python", "django", "login", "subdomain", "login-control" ]
Subdomains and Logins
1,442,017
<p>If you multiple subdomains e.g.:</p> <blockquote> <p>sub1.domain_name.com</p> <p>sub2.domain_name.com</p> </blockquote> <p>Is there a way to have a user be able to log into both of these without issues and double login issue?</p> <p>The platform is Python, Django.</p>
4
2009-09-18T00:19:48Z
1,442,058
<p>Yes. Just set the cookie on the domain ".domain_name.com" and the cookie will be available to sub1.domain_name.com, and sub2.domain_name.com.</p> <p>As long as you maintain your session information on both domains, you should be fine.</p> <p>This is a very common practice, and is why you can log into your Google Account at <a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a> and still be logged in at <a href="http://mail.google.com" rel="nofollow">http://mail.google.com</a>.</p>
6
2009-09-18T00:35:26Z
[ "python", "django", "login", "subdomain", "login-control" ]
Python execute program change path
1,442,024
<p>I'm trying to make a python script run another program from its own path. I've got the execution of the other program working using os.system, but the program will crash because it cannot find its reasources (wrong path, I assume). I tried adding the folder harboring the executable to the path, but that didn't help.</p>
1
2009-09-18T00:22:14Z
1,442,077
<p>You can change the current directory of your script with <code>os.chdir</code>(). You can also set environment variables with <code>os.environ</code></p>
3
2009-09-18T00:41:55Z
[ "python", "path", "executable" ]
Python execute program change path
1,442,024
<p>I'm trying to make a python script run another program from its own path. I've got the execution of the other program working using os.system, but the program will crash because it cannot find its reasources (wrong path, I assume). I tried adding the folder harboring the executable to the path, but that didn't help.</p>
1
2009-09-18T00:22:14Z
1,442,309
<p>Use the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess module</a>, and use the <code>cwd</code> argument to set the child's working directory.</p>
1
2009-09-18T02:24:35Z
[ "python", "path", "executable" ]
transforming Jython's source / ast
1,442,084
<p>I've got a problem to solve in Jython. The function I've got looks like this:</p> <pre><code>ok = whatever1(x, ...) self.assertTrue("whatever1 failed: "+x...(), ok) ok = whatever2(x, ...) self.assertTrue("whatever2 failed: "+x...(), ok) [ many many lines ] ... </code></pre> <p>There are many tests that look like this, they contain mostly ok=... tests, but there are some other things done too. I know which functions are testable, because they come from only one namespace (or I can leave the "ok = " part). The question is - how to transform the source automatically, so that I write only:</p> <pre><code>ok = whatever1(x, ...) # this is transformed ok = whatever2(x, ...) # this too something_else(...) # this one isn't </code></pre> <p>and the rest is generated automatically?</p> <p>I know about unparse and ast - is there any better way to approach this problem? (yeah, I know - Maybe-like monad) I'm looking at the <code>rope</code> library too and cannot decide... which way is the best one to choose here? The transformation I described is the only one I need and I don't mind creating a temporary file that will get included in the real code.</p>
1
2009-09-18T00:44:53Z
1,442,141
<p>Are you sure you need an AST? If the only lines of interest are the ones starting with "ok = ", then maybe simple string work on the source files would be enough?</p>
2
2009-09-18T01:04:26Z
[ "python", "jython", "abstract-syntax-tree" ]
Python Web-Scrape Loop via CSV list of URLs?
1,442,097
<p>HI, I've got a list of 10 websites in CSV. All of the sites have the same general format, including a large table. I only want the the data in the 7th columns. I am able to extract the html and filter the 7th column data (via RegEx) on an individual basis but I can't figure out how to loop through the CSV. I think I'm close but my script won't run. I would really appreciate it if someone could help me figure-out how to do this. Here's what i've got:</p> <pre><code>#Python v2.6.2 import csv import urllib2 import re urls = csv.reader(open('list.csv')) n =0 while n &lt;=10: for url in urls: response = urllib2.urlopen(url[n]) html = response.read() print re.findall('td7.*?td',html) n +=1 </code></pre>
1
2009-09-18T00:48:00Z
1,442,151
<p>When I copied your routine, I did get a white space / tab error error. Check your tabs. You were indexing into the URL string incorrectly using your loop counter. This would have also messed you up.</p> <p>Also, you don't really need to control the loop with a counter. This will loop for each line entry in your CSV file.</p> <pre><code>#Python v2.6.2 import csv import urllib2 import re urls = csv.reader(open('list.csv')) for url in urls: response = urllib2.urlopen(url[0]) html = response.read() print re.findall('td7.*?td',html) </code></pre> <p>Lastly, be sure that your URLs are properly formed:</p> <pre><code>http://www.cnn.com http://www.fark.com http://www.cbc.ca </code></pre>
2
2009-09-18T01:09:04Z
[ "python", "list", "csv", "loops" ]
Multiple Windows in PyQt4
1,442,128
<p>I have a PyQt program used to visualize some python objects. I would like to do display multiple objects, each in its own window. </p> <p>What is the best way to achieve multi-window applications in PyQt4?</p> <p>Currently I have the following:</p> <pre><code>from PyQt4 import QtGui class MainWindow(QtGui.QMainWindow): windowList = [] def __init__(self, animal): pass def addwindow(self, animal) win = MainWindow(animal) windowList.append(win) if __name__=="__main__": import sys app = QtGui.QApplication(sys.argv) win = QMainWindow(dog) win.addWindow(fish) win.addWindow(cat) app.exec_() </code></pre> <p>However, this approach is not satisfactory, as I am facing problems when I try to factor out the MultipleWindows part in its own class. For example:</p> <pre><code>class MultiWindows(QtGui.QMainWindow): windowList = [] def __init__(self, param): raise NotImplementedError() def addwindow(self, param) win = MainWindow(param) # How to call the initializer of the subclass from here? windowList.append(win) class PlanetApp(MultiWindows): def __init__(self, planet): pass class AnimalApp(MultiWindows): def __init__(self, planet): pass if __name__=="__main__": import sys app = QtGui.QApplication(sys.argv) win = PlanetApp(mercury) win.addWindow(venus) win.addWindow(jupiter) app.exec_() </code></pre> <p>The above code will call the initializer of the MainWindow class, rather than that of the appropriate subclass, and will thus throw an exception. </p> <p>How can I call the initializer of the subclass? Is there a more elegant way to do this?</p>
2
2009-09-18T00:57:14Z
1,442,522
<p>In order to reference the subclass that is inheriting the super-class from inside the super-class, I am using <code>self.__class__()</code>, so the MultiWindows class now reads:</p> <pre><code>class MultiWindows(QtGui.QMainWindow): windowList = [] def __init__(self, param): raise NotImplementedError() def addwindow(self, param) win = self.__class__(param) windowList.append(win) </code></pre>
0
2009-09-18T03:57:36Z
[ "python", "inheritance", "pyqt4" ]
Multiple Windows in PyQt4
1,442,128
<p>I have a PyQt program used to visualize some python objects. I would like to do display multiple objects, each in its own window. </p> <p>What is the best way to achieve multi-window applications in PyQt4?</p> <p>Currently I have the following:</p> <pre><code>from PyQt4 import QtGui class MainWindow(QtGui.QMainWindow): windowList = [] def __init__(self, animal): pass def addwindow(self, animal) win = MainWindow(animal) windowList.append(win) if __name__=="__main__": import sys app = QtGui.QApplication(sys.argv) win = QMainWindow(dog) win.addWindow(fish) win.addWindow(cat) app.exec_() </code></pre> <p>However, this approach is not satisfactory, as I am facing problems when I try to factor out the MultipleWindows part in its own class. For example:</p> <pre><code>class MultiWindows(QtGui.QMainWindow): windowList = [] def __init__(self, param): raise NotImplementedError() def addwindow(self, param) win = MainWindow(param) # How to call the initializer of the subclass from here? windowList.append(win) class PlanetApp(MultiWindows): def __init__(self, planet): pass class AnimalApp(MultiWindows): def __init__(self, planet): pass if __name__=="__main__": import sys app = QtGui.QApplication(sys.argv) win = PlanetApp(mercury) win.addWindow(venus) win.addWindow(jupiter) app.exec_() </code></pre> <p>The above code will call the initializer of the MainWindow class, rather than that of the appropriate subclass, and will thus throw an exception. </p> <p>How can I call the initializer of the subclass? Is there a more elegant way to do this?</p>
2
2009-09-18T00:57:14Z
1,443,181
<p>Why not using dialogs? In Qt you do not need to use the main window unless you want to use docks etc.. Using dialogs will have the same effect. </p> <p>I can also see a problem in your logic regarding the fact that you want your super class to be calling the constructor of its children, which of course can be any type. I recommend you rewrite it like the following: <code></p> <pre><code>class MultiWindows(QtGui.QMainWindow): def __init__(self, param): self.__windows = [] def addwindow(self, window): self.__windows.append(window) def show(): for current_child_window in self.__windows: current_child_window.exec_() # probably show will do the same trick class PlanetApp(QtGui.QDialog): def __init__(self, parent, planet): QtGui.QDialog.__init__(self, parent) # do cool stuff here class AnimalApp(QtGui.QDialog): def __init__(self, parent, animal): QtGui.QDialog.__init__(self, parent) # do cool stuff here if __name__=="__main__": import sys # really need this here?? app = QtGui.QApplication(sys.argv) jupiter = PlanetApp(None, "jupiter") venus = PlanetApp(None, "venus") windows = MultiWindows() windows.addWindow(jupiter) windows.addWindow(venus) windows.show() app.exec_() </code></pre> <p></code> It is not a nice idea to expect the super class to know the parameter to be used in the <strong>init</strong> of its subclasses since it is really hard to ensure that all the constructor will be the same (maybe the animal dialog/window takes diff parameters).</p> <p>Hope it helps.</p>
5
2009-09-18T08:15:15Z
[ "python", "inheritance", "pyqt4" ]
Accessing a Python variable in a list
1,442,250
<p>I think this is probably something really simple, but I'd appreciate a hint:</p> <p>I am using a python list to hold some some database insert statements:</p> <pre><code>list = [ "table_to_insert_to" ],["column1","column2"],[getValue.value1],["value2"]] </code></pre> <p>The problem is one of the values isn't evaluated until runtime-- so before the page even gets run, it breaks when it tries to import the function.</p> <p>How do you handle this?</p>
0
2009-09-18T01:50:35Z
1,442,333
<p>Just wrap it in a function and call the function when you have the data to initialize it.</p> <pre><code># module.py def setstatement(value1): global sql sql = ['select', 'column1', 'column2', value1] # some other file import module module.setstatement(1) # now you can use it. &gt;&gt;&gt; module.sql ['select', 'column1', 'column2', 1] </code></pre>
2
2009-09-18T02:38:08Z
[ "python", "list", "variables" ]
Accessing a Python variable in a list
1,442,250
<p>I think this is probably something really simple, but I'd appreciate a hint:</p> <p>I am using a python list to hold some some database insert statements:</p> <pre><code>list = [ "table_to_insert_to" ],["column1","column2"],[getValue.value1],["value2"]] </code></pre> <p>The problem is one of the values isn't evaluated until runtime-- so before the page even gets run, it breaks when it tries to import the function.</p> <p>How do you handle this?</p>
0
2009-09-18T01:50:35Z
1,442,524
<p>You've just pointed out one (out of a zillion) problems with global variables: not using global variables is the best solution to this problem and many others. If you still mistakenly believe you must use a global variable, put a placeholder (e.g. <code>None</code>) in the place where the value you don't yet know will go, and assign the right value there when it's finally known.</p>
3
2009-09-18T03:58:19Z
[ "python", "list", "variables" ]
Accessing a Python variable in a list
1,442,250
<p>I think this is probably something really simple, but I'd appreciate a hint:</p> <p>I am using a python list to hold some some database insert statements:</p> <pre><code>list = [ "table_to_insert_to" ],["column1","column2"],[getValue.value1],["value2"]] </code></pre> <p>The problem is one of the values isn't evaluated until runtime-- so before the page even gets run, it breaks when it tries to import the function.</p> <p>How do you handle this?</p>
0
2009-09-18T01:50:35Z
1,442,553
<p>May be put functions instead of value, these functions should be called at run time and will give correct results e.g.</p> <pre><code>def getValue1Func(): return getValue.value1 my_list = [ "table_to_insert_to" ],["column1","column2"],[getValue1Func],["value2"]] </code></pre> <p>now I do not know how you use this list(I think there will be better alternatives if you state the whole problem), so while using list just check if value is callable and call it to get value</p> <p>e.g.</p> <pre><code>if isinstance(val, collections.Callable): val = val() </code></pre> <p>edit: for python &lt; 2.6, you should use operator.isCallable</p>
1
2009-09-18T04:09:57Z
[ "python", "list", "variables" ]
Full-featured date and time library
1,442,264
<p>I'm wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:</p> <ul> <li><strong>Microsecond resolution</strong></li> <li><strong>Daylight savings</strong> <ul> <li><em>Example:</em> it knows that 2:30am did not exist in the US on 8 March 2009 for timezones that respect daylight savings.</li> <li>I should be able to specify a timezone like "US/Eastern" and it should be smart enough to know whether a given timestamp should correspond to EST or EDT.</li> </ul></li> <li><strong>Custom date ranges</strong> <ul> <li>The ability to create specialized business calendars that skip over weekends and holidays.</li> </ul></li> <li><strong>Custom time ranges</strong> <ul> <li>The ability to define business hours so that times requested outside the business hours can be rounded up or down to the next or previous valid hour.</li> </ul></li> <li><strong>Arithmetic</strong> <ul> <li>Be able to add and subtract integer amounts of all units (years, months, weeks, days, hours, minutes, ...). Note that adding something like 0.5 days isn't well-defined because it could mean 12 hours or it could mean half the duration of a day (which isn't 24 hours on daylight savings changes). </li> </ul></li> <li><strong>Natural boundary alignment</strong> <ul> <li>Given a timestamp, I'd like be able to do things like round down to the nearest decade, year, month, week, ..., quarter hour, hour, etc. </li> </ul></li> </ul> <p>I'm currently using Python, though I'm happy to have a solution in another language like perl, C, or C++.</p> <p>I've found that the built-in Python libraries lack sophistication with their daylight savings logic and there isn't an obvious way (to me) to set up things like custom time ranges.</p>
7
2009-09-18T02:00:01Z
1,442,299
<p>Take a look at the <a href="http://labix.org/python-dateutil">dateutil</a> and possibly <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/">mx.DateTime</a> packages.</p>
6
2009-09-18T02:19:34Z
[ "python", "c", "datetime" ]
Full-featured date and time library
1,442,264
<p>I'm wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:</p> <ul> <li><strong>Microsecond resolution</strong></li> <li><strong>Daylight savings</strong> <ul> <li><em>Example:</em> it knows that 2:30am did not exist in the US on 8 March 2009 for timezones that respect daylight savings.</li> <li>I should be able to specify a timezone like "US/Eastern" and it should be smart enough to know whether a given timestamp should correspond to EST or EDT.</li> </ul></li> <li><strong>Custom date ranges</strong> <ul> <li>The ability to create specialized business calendars that skip over weekends and holidays.</li> </ul></li> <li><strong>Custom time ranges</strong> <ul> <li>The ability to define business hours so that times requested outside the business hours can be rounded up or down to the next or previous valid hour.</li> </ul></li> <li><strong>Arithmetic</strong> <ul> <li>Be able to add and subtract integer amounts of all units (years, months, weeks, days, hours, minutes, ...). Note that adding something like 0.5 days isn't well-defined because it could mean 12 hours or it could mean half the duration of a day (which isn't 24 hours on daylight savings changes). </li> </ul></li> <li><strong>Natural boundary alignment</strong> <ul> <li>Given a timestamp, I'd like be able to do things like round down to the nearest decade, year, month, week, ..., quarter hour, hour, etc. </li> </ul></li> </ul> <p>I'm currently using Python, though I'm happy to have a solution in another language like perl, C, or C++.</p> <p>I've found that the built-in Python libraries lack sophistication with their daylight savings logic and there isn't an obvious way (to me) to set up things like custom time ranges.</p>
7
2009-09-18T02:00:01Z
1,442,519
<p>Python's standard library's <code>datetime</code> module is deliberately limited to non-controversial aspects that aren't changing all the time by legislative fiat -- that's why it deliberately excludes direct support for timezones, DST, fuzzy parsing and ill-defined arithmetic (such as "one month later"...) and the like. On top of it, <a href="http://labix.org/python-dateutil">dateutil</a> for many kinds of manipulations, and <a href="http://pytz.sourceforge.net/">pytz</a> for timezones (including DST issues), add most of what you're asking for, though not <em>extremely</em> explosive things like "holidays" which vary so wildly not just across political jurisdictions but even across employers within a simgle jurisdiction (e.g. in the US some employers consider "Columbus Day" a holiday, but many don't -- and some, with offices in many locations, have it as a holiday on some locations but not in others; given this utter, total chaos, to expect to find a general-purpose library that somehow magically makes sense of the chaos is pretty weird).</p>
11
2009-09-18T03:55:47Z
[ "python", "c", "datetime" ]
Full-featured date and time library
1,442,264
<p>I'm wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:</p> <ul> <li><strong>Microsecond resolution</strong></li> <li><strong>Daylight savings</strong> <ul> <li><em>Example:</em> it knows that 2:30am did not exist in the US on 8 March 2009 for timezones that respect daylight savings.</li> <li>I should be able to specify a timezone like "US/Eastern" and it should be smart enough to know whether a given timestamp should correspond to EST or EDT.</li> </ul></li> <li><strong>Custom date ranges</strong> <ul> <li>The ability to create specialized business calendars that skip over weekends and holidays.</li> </ul></li> <li><strong>Custom time ranges</strong> <ul> <li>The ability to define business hours so that times requested outside the business hours can be rounded up or down to the next or previous valid hour.</li> </ul></li> <li><strong>Arithmetic</strong> <ul> <li>Be able to add and subtract integer amounts of all units (years, months, weeks, days, hours, minutes, ...). Note that adding something like 0.5 days isn't well-defined because it could mean 12 hours or it could mean half the duration of a day (which isn't 24 hours on daylight savings changes). </li> </ul></li> <li><strong>Natural boundary alignment</strong> <ul> <li>Given a timestamp, I'd like be able to do things like round down to the nearest decade, year, month, week, ..., quarter hour, hour, etc. </li> </ul></li> </ul> <p>I'm currently using Python, though I'm happy to have a solution in another language like perl, C, or C++.</p> <p>I've found that the built-in Python libraries lack sophistication with their daylight savings logic and there isn't an obvious way (to me) to set up things like custom time ranges.</p>
7
2009-09-18T02:00:01Z
1,442,541
<blockquote> <p>I should be able to specify a timezone like "US/Eastern" and it should be smart enough to know whether a given timestamp should correspond to EST or EDT.</p> </blockquote> <p>This part isn't always possible - in the same way that 2:30am doesn't exist for one day of the year (in timezones with daylight saving that switches at 2:00am), 2:30am exists <em>twice</em> for another day - once in EDT and then an hour later in EST. If you pass that date/time to the library, how does it know which of the two times you're talking about?</p>
4
2009-09-18T04:04:44Z
[ "python", "c", "datetime" ]
Full-featured date and time library
1,442,264
<p>I'm wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:</p> <ul> <li><strong>Microsecond resolution</strong></li> <li><strong>Daylight savings</strong> <ul> <li><em>Example:</em> it knows that 2:30am did not exist in the US on 8 March 2009 for timezones that respect daylight savings.</li> <li>I should be able to specify a timezone like "US/Eastern" and it should be smart enough to know whether a given timestamp should correspond to EST or EDT.</li> </ul></li> <li><strong>Custom date ranges</strong> <ul> <li>The ability to create specialized business calendars that skip over weekends and holidays.</li> </ul></li> <li><strong>Custom time ranges</strong> <ul> <li>The ability to define business hours so that times requested outside the business hours can be rounded up or down to the next or previous valid hour.</li> </ul></li> <li><strong>Arithmetic</strong> <ul> <li>Be able to add and subtract integer amounts of all units (years, months, weeks, days, hours, minutes, ...). Note that adding something like 0.5 days isn't well-defined because it could mean 12 hours or it could mean half the duration of a day (which isn't 24 hours on daylight savings changes). </li> </ul></li> <li><strong>Natural boundary alignment</strong> <ul> <li>Given a timestamp, I'd like be able to do things like round down to the nearest decade, year, month, week, ..., quarter hour, hour, etc. </li> </ul></li> </ul> <p>I'm currently using Python, though I'm happy to have a solution in another language like perl, C, or C++.</p> <p>I've found that the built-in Python libraries lack sophistication with their daylight savings logic and there isn't an obvious way (to me) to set up things like custom time ranges.</p>
7
2009-09-18T02:00:01Z
1,443,308
<p>Although the book is over ten years old, I would strongly recommend reading <a href="http://rads.stackoverflow.com/amzn/click/0879304960" rel="nofollow"><strong>Standard C Date/Time Library: Programming the World's Calendars and Clocks</strong></a> by Lance Latham. This is one of those books that you will pick back up from time to time in amazement that it got written at all. The author goes into more detail than you want about calenders and time keeping systems, and along the way develops the source code to a library (written in C) to handle all of the calculations.</p> <p>Amazingly, it seems to be still in print...</p>
2
2009-09-18T08:50:36Z
[ "python", "c", "datetime" ]
Full-featured date and time library
1,442,264
<p>I'm wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:</p> <ul> <li><strong>Microsecond resolution</strong></li> <li><strong>Daylight savings</strong> <ul> <li><em>Example:</em> it knows that 2:30am did not exist in the US on 8 March 2009 for timezones that respect daylight savings.</li> <li>I should be able to specify a timezone like "US/Eastern" and it should be smart enough to know whether a given timestamp should correspond to EST or EDT.</li> </ul></li> <li><strong>Custom date ranges</strong> <ul> <li>The ability to create specialized business calendars that skip over weekends and holidays.</li> </ul></li> <li><strong>Custom time ranges</strong> <ul> <li>The ability to define business hours so that times requested outside the business hours can be rounded up or down to the next or previous valid hour.</li> </ul></li> <li><strong>Arithmetic</strong> <ul> <li>Be able to add and subtract integer amounts of all units (years, months, weeks, days, hours, minutes, ...). Note that adding something like 0.5 days isn't well-defined because it could mean 12 hours or it could mean half the duration of a day (which isn't 24 hours on daylight savings changes). </li> </ul></li> <li><strong>Natural boundary alignment</strong> <ul> <li>Given a timestamp, I'd like be able to do things like round down to the nearest decade, year, month, week, ..., quarter hour, hour, etc. </li> </ul></li> </ul> <p>I'm currently using Python, though I'm happy to have a solution in another language like perl, C, or C++.</p> <p>I've found that the built-in Python libraries lack sophistication with their daylight savings logic and there isn't an obvious way (to me) to set up things like custom time ranges.</p>
7
2009-09-18T02:00:01Z
16,908,406
<p>Saw this the other day, I havn't used it myself... looks promising. <a href="http://crsmithdev.com/arrow/">http://crsmithdev.com/arrow/</a> </p>
6
2013-06-04T01:25:41Z
[ "python", "c", "datetime" ]
Full-featured date and time library
1,442,264
<p>I'm wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:</p> <ul> <li><strong>Microsecond resolution</strong></li> <li><strong>Daylight savings</strong> <ul> <li><em>Example:</em> it knows that 2:30am did not exist in the US on 8 March 2009 for timezones that respect daylight savings.</li> <li>I should be able to specify a timezone like "US/Eastern" and it should be smart enough to know whether a given timestamp should correspond to EST or EDT.</li> </ul></li> <li><strong>Custom date ranges</strong> <ul> <li>The ability to create specialized business calendars that skip over weekends and holidays.</li> </ul></li> <li><strong>Custom time ranges</strong> <ul> <li>The ability to define business hours so that times requested outside the business hours can be rounded up or down to the next or previous valid hour.</li> </ul></li> <li><strong>Arithmetic</strong> <ul> <li>Be able to add and subtract integer amounts of all units (years, months, weeks, days, hours, minutes, ...). Note that adding something like 0.5 days isn't well-defined because it could mean 12 hours or it could mean half the duration of a day (which isn't 24 hours on daylight savings changes). </li> </ul></li> <li><strong>Natural boundary alignment</strong> <ul> <li>Given a timestamp, I'd like be able to do things like round down to the nearest decade, year, month, week, ..., quarter hour, hour, etc. </li> </ul></li> </ul> <p>I'm currently using Python, though I'm happy to have a solution in another language like perl, C, or C++.</p> <p>I've found that the built-in Python libraries lack sophistication with their daylight savings logic and there isn't an obvious way (to me) to set up things like custom time ranges.</p>
7
2009-09-18T02:00:01Z
21,643,548
<p>I just released a Python library called Fleming (<a href="https://github.com/ambitioninc/fleming" rel="nofollow">https://github.com/ambitioninc/fleming</a>), and it appears to solve two of your problems with sophistication in regards to Daylight Savings Time.</p> <p>Problem 1, Arithmetic - Fleming has an add_timedelta function that takes a timedelta (from Python's datetime module) or a relativedelta from python-dateutil and adds it to a datetime object. The add_timedelta function handles the case when the datetime object crosses a DST boundary. Check out <a href="https://github.com/ambitioninc/fleming#add_timedelta" rel="nofollow">https://github.com/ambitioninc/fleming#add_timedelta</a> for a complete explanation and examples. Here is a short example:</p> <pre><code>import fleming import datetime import timedelta dt = fleming.add_timedelta(dt, datetime.timedelta(weeks=2, days=1)) print dt 2013-03-29 20:00:00-04:00 # Do timedelta arithmetic such that it starts in DST and crosses over into no DST. # Note that the hours stay in tact and the timezone changes dt = fleming.add_timedelta(dt, datetime.timedelta(weeks=-4)) print dt 2013-03-01 20:00:00-05:00 </code></pre> <p>Problem 2, Natural Boundary Alignment - Fleming has a floor function that can take an arbitrary alignment. Let's say your time was datetime(2013, 2, 3) and you gave it a floor interval of month=3. This means it will round to the nearest trimonth (quarter). You could similarly specify nearest decade by using year=10 in the arguments. Check out (<a href="https://github.com/ambitioninc/fleming#floordt-within_tznone-yearnone-monthnone-weeknone-daynone-hournone-minutenone-secondnone-microsecondnone" rel="nofollow">https://github.com/ambitioninc/fleming#floordt-within_tznone-yearnone-monthnone-weeknone-daynone-hournone-minutenone-secondnone-microsecondnone</a>) for complete examples and illustrations. Here is a quick one:</p> <pre><code>import fleming import datetime # Get the starting of a quarter by using month=3 print fleming.floor(datetime.datetime(2013, 2, 4), month=3) 2013-01-01 00:00:00 </code></pre>
1
2014-02-08T07:59:16Z
[ "python", "c", "datetime" ]
Python program to split a list into two lists with alternating elements
1,442,782
<p>Can you make it more simple/elegant?</p> <pre><code>def zigzag(seq): """Return two sequences with alternating elements from `seq`""" x, y = [], [] p, q = x, y for e in seq: p.append(e) p, q = q, p return x, y </code></pre>
11
2009-09-18T05:53:08Z
1,442,788
<pre><code>def zigzag(seq): return seq[::2], seq[1::2] </code></pre>
7
2009-09-18T05:55:46Z
[ "python", "algorithm", "list" ]
Python program to split a list into two lists with alternating elements
1,442,782
<p>Can you make it more simple/elegant?</p> <pre><code>def zigzag(seq): """Return two sequences with alternating elements from `seq`""" x, y = [], [] p, q = x, y for e in seq: p.append(e) p, q = q, p return x, y </code></pre>
11
2009-09-18T05:53:08Z
1,442,794
<p>If <code>seq</code>, as you say, is a list, then:</p> <pre><code>def zigzag(seq): return seq[::2], seq[1::2] </code></pre> <p>If <code>seq</code> is a totally generic iterable, such as possibly a generator:</p> <pre><code>def zigzag(seq): results = [], [] for i, e in enumerate(seq): results[i%2].append(e) return results </code></pre>
34
2009-09-18T05:57:45Z
[ "python", "algorithm", "list" ]
Python program to split a list into two lists with alternating elements
1,442,782
<p>Can you make it more simple/elegant?</p> <pre><code>def zigzag(seq): """Return two sequences with alternating elements from `seq`""" x, y = [], [] p, q = x, y for e in seq: p.append(e) p, q = q, p return x, y </code></pre>
11
2009-09-18T05:53:08Z
1,443,595
<p>This takes an iterator and returns two iterators:</p> <pre><code> import itertools def zigzag(seq): t1,t2 = itertools.tee(seq) even = itertools.islice(t1,0,None,2) odd = itertools.islice(t2,1,None,2) return even,odd </code></pre> <p>If you prefer lists then you can <code>return list(even),list(odd)</code>.</p>
9
2009-09-18T10:04:10Z
[ "python", "algorithm", "list" ]
Lauch default editor (like 'webbrowser' module)
1,442,841
<p>Is there a simple way to lauch the systems default editor from a Python command-line tool, like the <a href="http://docs.python.org/library/webbrowser.html">webbrowser</a> module?</p>
7
2009-09-18T06:18:43Z
1,442,894
<p>If you need to open a file for editing, you could be interested in <a href="http://stackoverflow.com/questions/434597/open-document-with-default-application-in-python">this question</a>.</p>
2
2009-09-18T06:41:45Z
[ "python", "command-line", "editor" ]
Lauch default editor (like 'webbrowser' module)
1,442,841
<p>Is there a simple way to lauch the systems default editor from a Python command-line tool, like the <a href="http://docs.python.org/library/webbrowser.html">webbrowser</a> module?</p>
7
2009-09-18T06:18:43Z
1,443,128
<p>Under windows you can simply "execute" the file and the default action will be taken: </p> <p><code>os.system('c:/tmp/sample.txt')</code></p> <p>For this example a default editor will spawn. Under UNIX there is an environment variable called <code>EDITOR</code>, so you need to use something like: </p> <p><code>os.system('%s %s' % (os.getenv('EDITOR'), filename))</code></p>
10
2009-09-18T08:01:24Z
[ "python", "command-line", "editor" ]
Lauch default editor (like 'webbrowser' module)
1,442,841
<p>Is there a simple way to lauch the systems default editor from a Python command-line tool, like the <a href="http://docs.python.org/library/webbrowser.html">webbrowser</a> module?</p>
7
2009-09-18T06:18:43Z
1,443,498
<p>The modern Linux way to open a file is using <code>xdg-open</code>; however it does not guarantee that a text editor will open the file. Using <code>$EDITOR</code> is appropriate if your program is command-line oriented (and your users).</p>
3
2009-09-18T09:38:48Z
[ "python", "command-line", "editor" ]
Lauch default editor (like 'webbrowser' module)
1,442,841
<p>Is there a simple way to lauch the systems default editor from a Python command-line tool, like the <a href="http://docs.python.org/library/webbrowser.html">webbrowser</a> module?</p>
7
2009-09-18T06:18:43Z
25,984,833
<p>You can actually use the webbrowser module to do this. All the answers given so far for both this and the linked question are just the same things the webbrowser module does behind the hood. </p> <p>The ONLY difference is if they have <code>$EDITOR</code> set. (which is rare). So perhaps a better flow would be:</p> <pre><code>editor = os.getenv('EDITOR') if editor: ps.system(editor + ' ' + filename) else: webbrowser.open(filename) </code></pre> <p>Ok, now that I’ve told you that, I should let you know that the webbrowser module does state that it does not support this case, meaning if it doesn't work, don’t submit a bug report. But for most uses, it should work.</p>
1
2014-09-22T23:57:21Z
[ "python", "command-line", "editor" ]
Radix 64 and encryption
1,442,896
<p>Need to share my problem that is : A PGP public key server gives me the key in Radix64 format . And i searching for any method which can encrypt my message using this Radix64 format public key .</p> <p>any alternate suggestions or documents are welcome .........</p>
0
2009-09-18T06:42:20Z
1,442,907
<p><a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">exPyCrypto</a> looks good.</p> <p>This <a href="http://stackoverflow.com/questions/1387867/how-to-convert-base64-radix64-public-key-to-a-pem-format-in-python">previous SO question</a> addresses Radix64 format specifically for public keys.</p> <p>To convert the actual base/radix64 encoded characters, see <a href="http://stackoverflow.com/questions/1397799/how-to-recover-the-binary-streamoriginal-form-from-radix-64-encoding">this question</a>:</p> <pre><code>import base64 decoded_bytes = base64.b64decode(ascii_chars) </code></pre>
0
2009-09-18T06:47:05Z
[ "python" ]
Radix 64 and encryption
1,442,896
<p>Need to share my problem that is : A PGP public key server gives me the key in Radix64 format . And i searching for any method which can encrypt my message using this Radix64 format public key .</p> <p>any alternate suggestions or documents are welcome .........</p>
0
2009-09-18T06:42:20Z
1,442,911
<p>You can decode the key by using the <a href="http://docs.python.org/library/base64.html" rel="nofollow">base64</a> module and then encrypt the message.</p>
0
2009-09-18T06:48:18Z
[ "python" ]
Completely wrap an object in Python
1,443,129
<p>I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it's wrapping, but also overriding any methods or variables that I want, as well as providing some of my own methods. This wrapper class should appear 100% as the existing class (<code>isinstance</code> must act as if it is actually the class), however subclassing in itself is not going to cut it, as I want to wrap an existing <em>object</em>. Is there some solution in Python to do this? I was thinking something along the lines of:</p> <pre><code>class ObjectWrapper(BaseClass): def __init__(self, baseObject): self.baseObject = baseObject def overriddenMethod(self): ... def myOwnMethod1(self): ... ... def __getattr__(self, attr): if attr in ['overriddenMethod', 'myOwnMethod1', 'myOwnMethod2', ...] # return the requested method else: return getattr(self.baseObject, attr) </code></pre> <p>But I'm not that familiar with overriding <code>__getattr__</code>, <code>__setattr__</code> and <code>__hasattr__</code>, so I'm not sure how to get that right.</p>
15
2009-09-18T08:01:42Z
1,443,165
<p><code>__getattr__</code> is only called for things that Python can't find in <code>__dict__</code>, so you don't have to worry about <code>overriddenMethod</code>, etc.</p> <p>For more details, see section 5 "Proxy" in <a href="http://www.python.org/workshops/1997-10/proceedings/savikko.html" rel="nofollow">this article</a>.</p>
1
2009-09-18T08:09:55Z
[ "python", "reflection" ]
Completely wrap an object in Python
1,443,129
<p>I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it's wrapping, but also overriding any methods or variables that I want, as well as providing some of my own methods. This wrapper class should appear 100% as the existing class (<code>isinstance</code> must act as if it is actually the class), however subclassing in itself is not going to cut it, as I want to wrap an existing <em>object</em>. Is there some solution in Python to do this? I was thinking something along the lines of:</p> <pre><code>class ObjectWrapper(BaseClass): def __init__(self, baseObject): self.baseObject = baseObject def overriddenMethod(self): ... def myOwnMethod1(self): ... ... def __getattr__(self, attr): if attr in ['overriddenMethod', 'myOwnMethod1', 'myOwnMethod2', ...] # return the requested method else: return getattr(self.baseObject, attr) </code></pre> <p>But I'm not that familiar with overriding <code>__getattr__</code>, <code>__setattr__</code> and <code>__hasattr__</code>, so I'm not sure how to get that right.</p>
15
2009-09-18T08:01:42Z
1,443,170
<p><code>__getattr__</code> has the advantage that it's only called when the attribute does not exist, so you should not need an explicit list -- anything you don't define will automatically get proxied.</p> <p><code>__setattr__</code> is trickier because it's always called. Make sure you use a superclass call or <code>object.__setattr__</code> when setting your own attributes; using <code>setattr()</code> within <code>__setattr__</code> will cause infinite recursion.</p> <p>The final bit, affecting isinstance, is very difficult. You can do it with an assigment to your wrapper instance's .<code>__class__</code> variable (but this also overrides class dictionary resolution order), or by dynamically constructing your wrapper type using a metaclass. Since isinstance is so rare in Python code, it seems overkill to actually try to trick it.</p> <p><a href="http://python.org/doc/2.2/ref/attribute-access.html" rel="nofollow">More information on special attribute access methods.</a></p> <p><a href="http://docs.python.org/reference/datamodel.html#customizing-class-creation" rel="nofollow">Even more information on them, plus some help with metaclasses.</a></p>
3
2009-09-18T08:12:01Z
[ "python", "reflection" ]
Completely wrap an object in Python
1,443,129
<p>I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it's wrapping, but also overriding any methods or variables that I want, as well as providing some of my own methods. This wrapper class should appear 100% as the existing class (<code>isinstance</code> must act as if it is actually the class), however subclassing in itself is not going to cut it, as I want to wrap an existing <em>object</em>. Is there some solution in Python to do this? I was thinking something along the lines of:</p> <pre><code>class ObjectWrapper(BaseClass): def __init__(self, baseObject): self.baseObject = baseObject def overriddenMethod(self): ... def myOwnMethod1(self): ... ... def __getattr__(self, attr): if attr in ['overriddenMethod', 'myOwnMethod1', 'myOwnMethod2', ...] # return the requested method else: return getattr(self.baseObject, attr) </code></pre> <p>But I'm not that familiar with overriding <code>__getattr__</code>, <code>__setattr__</code> and <code>__hasattr__</code>, so I'm not sure how to get that right.</p>
15
2009-09-18T08:01:42Z
1,443,179
<p>By 'existing object' you mean an instance of another class? Sounds to me as though you just need to inherit from the base class. When you create your new object, pass in the details of the base object, or add a method in your new class which copies the data of the base class instance into itself.</p>
0
2009-09-18T08:14:31Z
[ "python", "reflection" ]
Completely wrap an object in Python
1,443,129
<p>I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it's wrapping, but also overriding any methods or variables that I want, as well as providing some of my own methods. This wrapper class should appear 100% as the existing class (<code>isinstance</code> must act as if it is actually the class), however subclassing in itself is not going to cut it, as I want to wrap an existing <em>object</em>. Is there some solution in Python to do this? I was thinking something along the lines of:</p> <pre><code>class ObjectWrapper(BaseClass): def __init__(self, baseObject): self.baseObject = baseObject def overriddenMethod(self): ... def myOwnMethod1(self): ... ... def __getattr__(self, attr): if attr in ['overriddenMethod', 'myOwnMethod1', 'myOwnMethod2', ...] # return the requested method else: return getattr(self.baseObject, attr) </code></pre> <p>But I'm not that familiar with overriding <code>__getattr__</code>, <code>__setattr__</code> and <code>__hasattr__</code>, so I'm not sure how to get that right.</p>
15
2009-09-18T08:01:42Z
1,443,389
<p>Start with this and mess with stuff in the loop to suit your needs:</p> <pre><code>import inspect class Delegate(object): def __init__(self, implementation): self.__class__ = implementation.__class__ for n, m in inspect.getmembers(implementation, callable): if not n.startswith('_'): setattr(self, n, m) </code></pre> <p>The ability to wrap not-new-style-objects is left as an exercise to the reader :)</p>
1
2009-09-18T09:14:12Z
[ "python", "reflection" ]
Completely wrap an object in Python
1,443,129
<p>I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it's wrapping, but also overriding any methods or variables that I want, as well as providing some of my own methods. This wrapper class should appear 100% as the existing class (<code>isinstance</code> must act as if it is actually the class), however subclassing in itself is not going to cut it, as I want to wrap an existing <em>object</em>. Is there some solution in Python to do this? I was thinking something along the lines of:</p> <pre><code>class ObjectWrapper(BaseClass): def __init__(self, baseObject): self.baseObject = baseObject def overriddenMethod(self): ... def myOwnMethod1(self): ... ... def __getattr__(self, attr): if attr in ['overriddenMethod', 'myOwnMethod1', 'myOwnMethod2', ...] # return the requested method else: return getattr(self.baseObject, attr) </code></pre> <p>But I'm not that familiar with overriding <code>__getattr__</code>, <code>__setattr__</code> and <code>__hasattr__</code>, so I'm not sure how to get that right.</p>
15
2009-09-18T08:01:42Z
1,445,289
<p>The simplest way in most cases is probably:</p> <pre><code>class ObjectWrapper(BaseClass): def __init__(self, baseObject): self.__class__ = type(baseObject.__class__.__name__, (self.__class__, baseObject.__class__), {}) self.__dict__ = baseObject.__dict__ def overriddenMethod(self): ... </code></pre> <p>Working in this way, i.e. by reassigning self's <code>__class__</code> and <code>__dict__</code> in this fashion, you need only provide your overrides -- Python's normal attribute getting and setting mechanisms will do the rest... <em>mostly</em>.</p> <p>You'll be in trouble only if <code>baseObject.__class__</code> defines <code>__slots__</code>, in which case the multiple inheritance approach doesn't work and you do need the cumbersome <code>__getattr__</code> (as others said, at least you don't need to worry that it will be called with attributes you're overriding, as it won't!-), <code>__setattr__</code> (a greater pain, as it DOES get called for every attribute), etc; and making <code>isinstance</code> and special methods work takes painstaking and cumbersome detailed work.</p> <p>Essentially, <code>__slots__</code> means that a class is a special, each instance a lightweight "value object" NOT to be subject to further sophisticated manipulation, wrapping, etc, because the need to save a few bytes per instance of that class overrides all the normal concerns about flexibility and so on; it's therefore not surprising that dealing with such extreme, rare classes in the same smooth and flexible way as you can deal with 99%+ of Python objects is truly a pain. So DO you need to deal with <code>__slots__</code> (to the point of writing, testing, debugging and maintaining hundreds of lines of code just for those corner cases), or will the 99% solution in half a dozen lines suffice?-)</p> <p>It should also be noted that this may lead to memory leaks, as creating a subclass adds the subclass to the base class' list of subclasses, and isn't removed when all instances of the subclass are GC'd.</p>
27
2009-09-18T15:30:42Z
[ "python", "reflection" ]
Completely wrap an object in Python
1,443,129
<p>I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it's wrapping, but also overriding any methods or variables that I want, as well as providing some of my own methods. This wrapper class should appear 100% as the existing class (<code>isinstance</code> must act as if it is actually the class), however subclassing in itself is not going to cut it, as I want to wrap an existing <em>object</em>. Is there some solution in Python to do this? I was thinking something along the lines of:</p> <pre><code>class ObjectWrapper(BaseClass): def __init__(self, baseObject): self.baseObject = baseObject def overriddenMethod(self): ... def myOwnMethod1(self): ... ... def __getattr__(self, attr): if attr in ['overriddenMethod', 'myOwnMethod1', 'myOwnMethod2', ...] # return the requested method else: return getattr(self.baseObject, attr) </code></pre> <p>But I'm not that familiar with overriding <code>__getattr__</code>, <code>__setattr__</code> and <code>__hasattr__</code>, so I'm not sure how to get that right.</p>
15
2009-09-18T08:01:42Z
31,437,314
<p>The following approach is similar to <a href="http://stackoverflow.com/a/1445289/17523">the one by Alex Martelli</a>, but is more readable to me:</p> <p>Instead of creating a new class, I create a class-like function that instantiates the underlying object and overwrites needed functions, as follows:</p> <pre><code>class C1: def __init__(self, p): self.p = p def f(self): print("This is C1, p=%s" % self.p) def C2(p): c = C1(p) def new_f(): print("This is C2, p is %s" % c.p) c.f = new_f def g(param): print("This is C2.g(%s), p is %s" % (param, c.p)) c.g = g return c c1 = C1('abc') c1.f() c2 = C2('cde') c2.f() c2.g('xyz') </code></pre> <p>The output:</p> <pre><code>This is C1, p=abc This is C2, p is cde This is C2.g(xyz), p is cde </code></pre>
1
2015-07-15T17:38:13Z
[ "python", "reflection" ]
Completely wrap an object in Python
1,443,129
<p>I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it's wrapping, but also overriding any methods or variables that I want, as well as providing some of my own methods. This wrapper class should appear 100% as the existing class (<code>isinstance</code> must act as if it is actually the class), however subclassing in itself is not going to cut it, as I want to wrap an existing <em>object</em>. Is there some solution in Python to do this? I was thinking something along the lines of:</p> <pre><code>class ObjectWrapper(BaseClass): def __init__(self, baseObject): self.baseObject = baseObject def overriddenMethod(self): ... def myOwnMethod1(self): ... ... def __getattr__(self, attr): if attr in ['overriddenMethod', 'myOwnMethod1', 'myOwnMethod2', ...] # return the requested method else: return getattr(self.baseObject, attr) </code></pre> <p>But I'm not that familiar with overriding <code>__getattr__</code>, <code>__setattr__</code> and <code>__hasattr__</code>, so I'm not sure how to get that right.</p>
15
2009-09-18T08:01:42Z
32,188,347
<p>Please look at <a href="http://code.activestate.com/recipes/577555-object-wrapper-class/" rel="nofollow">http://code.activestate.com/recipes/577555-object-wrapper-class/</a> for the complete code, including important comments. It boils down to:</p> <pre><code>class Wrapper(object): def __init__(self, obj): self._wrapped_obj = obj def __getattr__(self, attr): if attr in self.__dict__: return getattr(self, attr) return getattr(self._wrapped_obj, attr) </code></pre>
1
2015-08-24T17:38:45Z
[ "python", "reflection" ]
How do I protect my Python codebase so that guests can't see certain modules but so it still works?
1,443,146
<p>We're starting a new project in Python with a few proprietary algorithms and sensitive bits of logic that we'd like to keep private. We also will have a few outsiders (select members of the public) working on the code. We cannot grant the outsiders access to the small, private bits of code, but we'd like a public version to work well enough for them.</p> <p>Say that our project, Foo, has a module, <code>bar</code>, with one function, <code>get_sauce()</code>. What really happens in <code>get_sauce()</code> is secret, but we want a public version of <code>get_sauce()</code> to return an acceptable, albeit incorrect, result.</p> <p>We also run our own Subversion server so we have total control over who can access what.</p> <p><strong>Symlinks</strong></p> <p>My first thought was symlinking — Instead of <code>bar.py</code>, provide <code>bar_public.py</code> to everybody and <code>bar_private.py</code> to internal developers only. Unfortunately, creating symlinks is tedious, manual work — especially when there are really going to be about two dozen of these private modules.</p> <p>More importantly, it makes management of the Subversion authz file difficult, since for each module we want to protect an exception must be added on the server. Someone might forget to do this and accidentally check in secrets... Then the module is in the repo and we have to rebuild the repository without it and hope that an outsider didn't download it in the meantime.</p> <p><strong>Multiple repositories</strong></p> <p>The next thought was to have two repositories:</p> <pre><code>private └── trunk/ ├── __init__.py └── foo/ ├── __init__.py └── bar.py public └── trunk/ ├── __init__.py └── foo/ ├── __init__.py ├── bar.py ├── baz.py └── quux.py </code></pre> <p>The idea is that only internal developers will be able to checkout both <code>private/</code> and <code>public/</code>. Internal developers will set their <code>PYTHONPATH=private/trunk:public/trunk</code>, but everyone else will just set <code>PYTHONPATH=public/trunk</code>. Then, both insiders and outsiders can <code>from foo import bar</code> and get the right module, right?</p> <p>Let's try this:</p> <pre><code>% PYTHONPATH=private/trunk:public/trunk python Python 2.5.1 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import foo.bar &gt;&gt;&gt; foo.bar.sauce() 'a private bar' &gt;&gt;&gt; import foo.quux Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named quux </code></pre> <p>I'm not a Python expert, but it seems that Python has already made up its mind about module <code>foo</code> and searches relative to that:</p> <pre><code>&gt;&gt;&gt; foo &lt;module 'foo' from '/path/to/private/trunk/foo/__init__.py'&gt; </code></pre> <p>Not even deleting <code>foo</code> helps:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; del foo &gt;&gt;&gt; del sys.modules['foo'] &gt;&gt;&gt; import foo.quux Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named quux </code></pre> <p>Can you provide me with a better solution or suggestion?</p>
3
2009-09-18T08:05:22Z
1,443,266
<p><a href="http://docs.python.org/tutorial/modules.html#packages-in-multiple-directories" rel="nofollow">In the <code>__init__</code> method of the <code>foo</code> package you can change <code>__path__</code> to make it look for its modules in other directories.</a></p> <p>So create a directory called <code>secret</code> and put it in your private Subversion repository. In <code>secret</code> put your proprietary <code>bar.py</code>. In the <code>__init__.py</code> of the public <code>foo</code> package put in something like:</p> <pre><code>__path__.insert(0,'secret') </code></pre> <p>This will mean for users who have the private repository and so the <code>secret</code> directory they will get the proprietary <code>bar.py</code> as <code>foo.bar</code> as <code>secret</code> is the first directory in the search path. For other users, Python won't find <code>secret</code> and will look as the next directory in <code>__path__</code> and so will load the normal <code>bar.py</code> from <code>foo</code>. </p> <p>So it will look something like this:</p> <pre><code> private └── trunk/ └── secret/ └── bar.py public └── trunk/ ├── __init__.py └── foo/ ├── __init__.py ├── bar.py ├── baz.py └── quux.py </code></pre>
3
2009-09-18T08:36:49Z
[ "python", "svn", "project-management", "repository", "modularity" ]
How do I protect my Python codebase so that guests can't see certain modules but so it still works?
1,443,146
<p>We're starting a new project in Python with a few proprietary algorithms and sensitive bits of logic that we'd like to keep private. We also will have a few outsiders (select members of the public) working on the code. We cannot grant the outsiders access to the small, private bits of code, but we'd like a public version to work well enough for them.</p> <p>Say that our project, Foo, has a module, <code>bar</code>, with one function, <code>get_sauce()</code>. What really happens in <code>get_sauce()</code> is secret, but we want a public version of <code>get_sauce()</code> to return an acceptable, albeit incorrect, result.</p> <p>We also run our own Subversion server so we have total control over who can access what.</p> <p><strong>Symlinks</strong></p> <p>My first thought was symlinking — Instead of <code>bar.py</code>, provide <code>bar_public.py</code> to everybody and <code>bar_private.py</code> to internal developers only. Unfortunately, creating symlinks is tedious, manual work — especially when there are really going to be about two dozen of these private modules.</p> <p>More importantly, it makes management of the Subversion authz file difficult, since for each module we want to protect an exception must be added on the server. Someone might forget to do this and accidentally check in secrets... Then the module is in the repo and we have to rebuild the repository without it and hope that an outsider didn't download it in the meantime.</p> <p><strong>Multiple repositories</strong></p> <p>The next thought was to have two repositories:</p> <pre><code>private └── trunk/ ├── __init__.py └── foo/ ├── __init__.py └── bar.py public └── trunk/ ├── __init__.py └── foo/ ├── __init__.py ├── bar.py ├── baz.py └── quux.py </code></pre> <p>The idea is that only internal developers will be able to checkout both <code>private/</code> and <code>public/</code>. Internal developers will set their <code>PYTHONPATH=private/trunk:public/trunk</code>, but everyone else will just set <code>PYTHONPATH=public/trunk</code>. Then, both insiders and outsiders can <code>from foo import bar</code> and get the right module, right?</p> <p>Let's try this:</p> <pre><code>% PYTHONPATH=private/trunk:public/trunk python Python 2.5.1 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import foo.bar &gt;&gt;&gt; foo.bar.sauce() 'a private bar' &gt;&gt;&gt; import foo.quux Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named quux </code></pre> <p>I'm not a Python expert, but it seems that Python has already made up its mind about module <code>foo</code> and searches relative to that:</p> <pre><code>&gt;&gt;&gt; foo &lt;module 'foo' from '/path/to/private/trunk/foo/__init__.py'&gt; </code></pre> <p>Not even deleting <code>foo</code> helps:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; del foo &gt;&gt;&gt; del sys.modules['foo'] &gt;&gt;&gt; import foo.quux Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named quux </code></pre> <p>Can you provide me with a better solution or suggestion?</p>
3
2009-09-18T08:05:22Z
1,443,289
<p>Use some sort of plugin system, and keep your plugins to your self, but also have publically available plugins that gets shipped with the open code.</p> <p>Plugin systems abound. You can easily make dead simple ones yourself. If you want something more advanced I prefer the Zope Component Architecture, but there are also options like setuptools entry_points, etc.</p> <p>Which one to use in your case would be a good second question.</p>
2
2009-09-18T08:44:21Z
[ "python", "svn", "project-management", "repository", "modularity" ]
How do I protect my Python codebase so that guests can't see certain modules but so it still works?
1,443,146
<p>We're starting a new project in Python with a few proprietary algorithms and sensitive bits of logic that we'd like to keep private. We also will have a few outsiders (select members of the public) working on the code. We cannot grant the outsiders access to the small, private bits of code, but we'd like a public version to work well enough for them.</p> <p>Say that our project, Foo, has a module, <code>bar</code>, with one function, <code>get_sauce()</code>. What really happens in <code>get_sauce()</code> is secret, but we want a public version of <code>get_sauce()</code> to return an acceptable, albeit incorrect, result.</p> <p>We also run our own Subversion server so we have total control over who can access what.</p> <p><strong>Symlinks</strong></p> <p>My first thought was symlinking — Instead of <code>bar.py</code>, provide <code>bar_public.py</code> to everybody and <code>bar_private.py</code> to internal developers only. Unfortunately, creating symlinks is tedious, manual work — especially when there are really going to be about two dozen of these private modules.</p> <p>More importantly, it makes management of the Subversion authz file difficult, since for each module we want to protect an exception must be added on the server. Someone might forget to do this and accidentally check in secrets... Then the module is in the repo and we have to rebuild the repository without it and hope that an outsider didn't download it in the meantime.</p> <p><strong>Multiple repositories</strong></p> <p>The next thought was to have two repositories:</p> <pre><code>private └── trunk/ ├── __init__.py └── foo/ ├── __init__.py └── bar.py public └── trunk/ ├── __init__.py └── foo/ ├── __init__.py ├── bar.py ├── baz.py └── quux.py </code></pre> <p>The idea is that only internal developers will be able to checkout both <code>private/</code> and <code>public/</code>. Internal developers will set their <code>PYTHONPATH=private/trunk:public/trunk</code>, but everyone else will just set <code>PYTHONPATH=public/trunk</code>. Then, both insiders and outsiders can <code>from foo import bar</code> and get the right module, right?</p> <p>Let's try this:</p> <pre><code>% PYTHONPATH=private/trunk:public/trunk python Python 2.5.1 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import foo.bar &gt;&gt;&gt; foo.bar.sauce() 'a private bar' &gt;&gt;&gt; import foo.quux Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named quux </code></pre> <p>I'm not a Python expert, but it seems that Python has already made up its mind about module <code>foo</code> and searches relative to that:</p> <pre><code>&gt;&gt;&gt; foo &lt;module 'foo' from '/path/to/private/trunk/foo/__init__.py'&gt; </code></pre> <p>Not even deleting <code>foo</code> helps:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; del foo &gt;&gt;&gt; del sys.modules['foo'] &gt;&gt;&gt; import foo.quux Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named quux </code></pre> <p>Can you provide me with a better solution or suggestion?</p>
3
2009-09-18T08:05:22Z
3,192,648
<p>Here's an alternate solution I noticed when reading the docs for <a href="http://flask.pocoo.org/docs/" rel="nofollow">Flask</a>:</p> <blockquote> <p><strong><code>flaskext/__init__.py</code></strong></p> <p>The only purpose of this file is to mark the package as namespace package. This is required so that multiple modules from different PyPI packages can reside in the same Python package:</p> <pre><code>__import__('pkg_resources').declare_namespace(__name__) </code></pre> <p>If you want to know exactly what is happening there, checkout the distribute or setuptools docs which explain how this works.</p> </blockquote>
0
2010-07-07T07:19:03Z
[ "python", "svn", "project-management", "repository", "modularity" ]
Is it possible to divert a module in python? (ResourceX diverted to ResourceXSimulated)
1,443,173
<p>I want to simulate MyApp that imports a module (ResourceX) which requires a resource that is not available at the time and will not work. </p> <p>A solution for this is to make and import a mock module of ResourceX (named ResourceXSimulated) and divert it to MyApp as ResourceX. I want to do this in order to avoid breaking a lot of code and get all kinds of exception from MyApp.</p> <p>I am using Python and It should be something like:</p> <p>"Import ResourceXSimulated as ResourceX"</p> <p>"ResourceX.getData()", actually calls ResourceXSimultated.getData()</p> <p>Looking forward to find out if Python supports this kind of redirection.</p> <p>Cheers.</p> <p>ADDITIONAL INFO: I have access to the source files.</p> <p>UPDATE: I am thinking of adding as little code as possible to MyApp regarding using the fake module and add this code near the import statements.</p>
1
2009-09-18T08:12:47Z
1,443,195
<p>Yes, Python can do that, and so long as the methods exposed in the ResourceXSimulated module "look and smell" like these of the original module, the application should not see much any difference (other than, I'm assuming, bogus data fillers, different response times and such).</p>
0
2009-09-18T08:20:33Z
[ "python", "testing", "mocking", "module", "monkeypatching" ]
Is it possible to divert a module in python? (ResourceX diverted to ResourceXSimulated)
1,443,173
<p>I want to simulate MyApp that imports a module (ResourceX) which requires a resource that is not available at the time and will not work. </p> <p>A solution for this is to make and import a mock module of ResourceX (named ResourceXSimulated) and divert it to MyApp as ResourceX. I want to do this in order to avoid breaking a lot of code and get all kinds of exception from MyApp.</p> <p>I am using Python and It should be something like:</p> <p>"Import ResourceXSimulated as ResourceX"</p> <p>"ResourceX.getData()", actually calls ResourceXSimultated.getData()</p> <p>Looking forward to find out if Python supports this kind of redirection.</p> <p>Cheers.</p> <p>ADDITIONAL INFO: I have access to the source files.</p> <p>UPDATE: I am thinking of adding as little code as possible to MyApp regarding using the fake module and add this code near the import statements.</p>
1
2009-09-18T08:12:47Z
1,443,257
<p>This is called monkey-patching, and it's a fairly widely-used technique in dynamic languages like Python.</p> <p>So presumably you have a class:</p> <pre><code>class MyOriginal(object): def method_x(self): do_something_expensive_you_dont_want_in_testing() obj = MyOriginal() obj.method_x() </code></pre> <p>so in testing you want to do something else instead of <code>method_x</code>, but it should be transparent. So you just take advantage of Python's dynamic language:</p> <pre><code>def new_method_x(self): pretend_were_doing_something_expensive() test_obj = MyOriginal() test_obj.method_x = new_method_x # here's the monkeypatch test_obj_method_x() # calls the new method </code></pre>
1
2009-09-18T08:35:32Z
[ "python", "testing", "mocking", "module", "monkeypatching" ]
Is it possible to divert a module in python? (ResourceX diverted to ResourceXSimulated)
1,443,173
<p>I want to simulate MyApp that imports a module (ResourceX) which requires a resource that is not available at the time and will not work. </p> <p>A solution for this is to make and import a mock module of ResourceX (named ResourceXSimulated) and divert it to MyApp as ResourceX. I want to do this in order to avoid breaking a lot of code and get all kinds of exception from MyApp.</p> <p>I am using Python and It should be something like:</p> <p>"Import ResourceXSimulated as ResourceX"</p> <p>"ResourceX.getData()", actually calls ResourceXSimultated.getData()</p> <p>Looking forward to find out if Python supports this kind of redirection.</p> <p>Cheers.</p> <p>ADDITIONAL INFO: I have access to the source files.</p> <p>UPDATE: I am thinking of adding as little code as possible to MyApp regarding using the fake module and add this code near the import statements.</p>
1
2009-09-18T08:12:47Z
1,443,281
<p>Yes, it's possible. Some starters:</p> <p>You can "divert" modules by manipulating sys.modules. It keeps a list of imported modules, and there you can make your module appear under the same name as the original one. You must do this manipulating before any module that imports the module you want to fake though.</p> <p>You can also make a package called a different name, but in that package actually use the original module name, for your completely different module. This works well as long as the original module isn't installed.</p> <p>In none of these cases you can use both modules at the same time. For that you need to monkey-patch the original module.</p> <p>And of course: It' perfectly possible to just call the new module with the old name. But it might be confusing.</p>
1
2009-09-18T08:41:06Z
[ "python", "testing", "mocking", "module", "monkeypatching" ]
Is it possible to divert a module in python? (ResourceX diverted to ResourceXSimulated)
1,443,173
<p>I want to simulate MyApp that imports a module (ResourceX) which requires a resource that is not available at the time and will not work. </p> <p>A solution for this is to make and import a mock module of ResourceX (named ResourceXSimulated) and divert it to MyApp as ResourceX. I want to do this in order to avoid breaking a lot of code and get all kinds of exception from MyApp.</p> <p>I am using Python and It should be something like:</p> <p>"Import ResourceXSimulated as ResourceX"</p> <p>"ResourceX.getData()", actually calls ResourceXSimultated.getData()</p> <p>Looking forward to find out if Python supports this kind of redirection.</p> <p>Cheers.</p> <p>ADDITIONAL INFO: I have access to the source files.</p> <p>UPDATE: I am thinking of adding as little code as possible to MyApp regarding using the fake module and add this code near the import statements.</p>
1
2009-09-18T08:12:47Z
1,443,288
<p>Just change all lines <code>import ResourceX</code> in <code>MyApp</code> to <code>import ResourceXSimulated as ResourceX</code>, and lines like <code>from ResourceX import Y</code> to <code>from ResourceXSimulated import Y</code>.</p> <p>However if don't have access to <code>MyApp</code> source or there are other reasons not to change it, you can put your module into <code>sys.modules</code> before <code>MyApp</code> is loaded itself:</p> <pre><code>import ResourceXSimulated sys.modules['ResourceX'] = ResourceXSimulated </code></pre> <p>Note: if <code>ResourceX</code> is a package, it might require more effort.</p>
4
2009-09-18T08:42:26Z
[ "python", "testing", "mocking", "module", "monkeypatching" ]
Is it possible to divert a module in python? (ResourceX diverted to ResourceXSimulated)
1,443,173
<p>I want to simulate MyApp that imports a module (ResourceX) which requires a resource that is not available at the time and will not work. </p> <p>A solution for this is to make and import a mock module of ResourceX (named ResourceXSimulated) and divert it to MyApp as ResourceX. I want to do this in order to avoid breaking a lot of code and get all kinds of exception from MyApp.</p> <p>I am using Python and It should be something like:</p> <p>"Import ResourceXSimulated as ResourceX"</p> <p>"ResourceX.getData()", actually calls ResourceXSimultated.getData()</p> <p>Looking forward to find out if Python supports this kind of redirection.</p> <p>Cheers.</p> <p>ADDITIONAL INFO: I have access to the source files.</p> <p>UPDATE: I am thinking of adding as little code as possible to MyApp regarding using the fake module and add this code near the import statements.</p>
1
2009-09-18T08:12:47Z
1,443,324
<p>It's possible with the <code>sys.modules</code> hack, as already said.</p> <p>Note that if you have control over module <code>ResourceX</code> it's certainly better that it takes care of it itself. This is actually a common pattern when writing modules that work better when some resource is present, e.g.: </p> <pre><code># foo.py '''A module that provides interface to foo. Falls back to a dummy interface if foo is not available. ''' try: from _foo import * except ImportError: from _foo_dummy import * </code></pre> <p>Sometimes people do it in a more object-oriented way:</p> <pre><code># foo.py '''A module that provides interface to foo if it exists or to a dummy interface. Provides: frobnicate() self-explanatory ... ''' class DummyFoo: def frobnicate(self): pass ... class UnixFoo(DummyFoo): def frobnicate(self): a_posix_call() ... class GenericFoo(DummyFoo): def frobnicate(self): do_something_complicated() ... # Create a default instance. try: if (system == UNIX) instance = UnixFoo(system) else: instance = GenericFoo() except Exception: instance = DummyFoo() # Now export the public interface. frobnicate = instance.frobnicate </code></pre>
1
2009-09-18T08:55:00Z
[ "python", "testing", "mocking", "module", "monkeypatching" ]
Django : Iterate over a query set without cache
1,443,279
<p>I have a dumb simple loop</p> <pre><code>for alias in models.Alias.objects.all() : alias.update_points() </code></pre> <p>but looking into the django QuerySet it seems to keep around a <code>_result_cache</code> of all the previous results. This is eating Gigs and Gigs of my machine and eventually everything blows up. </p> <p>How can I throw away all the stuff that I won't ever care about?</p>
5
2009-09-18T08:40:47Z
1,443,304
<p>Use the queryset's <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#iterator"><code>iterator()</code></a> method to return the models in chunks, without populating the result cache:</p> <pre><code>for alias in models.Alias.objects.iterator() : alias.update_points() </code></pre>
11
2009-09-18T08:49:48Z
[ "python", "django", "caching" ]
Django : Iterate over a query set without cache
1,443,279
<p>I have a dumb simple loop</p> <pre><code>for alias in models.Alias.objects.all() : alias.update_points() </code></pre> <p>but looking into the django QuerySet it seems to keep around a <code>_result_cache</code> of all the previous results. This is eating Gigs and Gigs of my machine and eventually everything blows up. </p> <p>How can I throw away all the stuff that I won't ever care about?</p>
5
2009-09-18T08:40:47Z
1,443,682
<p>You should consider saving your changes back to the database.</p> <pre><code>for alias in models.Alias.objects.all() : alias.update_points() alias.save() </code></pre>
0
2009-09-18T10:22:48Z
[ "python", "django", "caching" ]
regular expression to parse network interface config
1,443,433
<p>I am wondering if problem down here can be solved with one regular expression or I should make standard loop and evaluate line by line,</p> <p>when I run included code I get <code>['Ethernet0/22', 'Ethernet0/24']</code>, only result should be <code>['Ethernet0/23', 'Ethernet0/25']</code>.</p> <p>any advice on this? </p> <pre><code> import re txt='''# interface Ethernet0/22 stp disable broadcast-suppression 5 mac-address max-mac-count 1 port access vlan 452 # interface Ethernet0/23 stp disable description BTO broadcast-suppression 5 port access vlan 2421 # interface Ethernet0/24 stp disable description Avaya G700 broadcast-suppression 5 port access vlan 452 # interface Ethernet0/25 stp disable description BTO broadcast-suppression 5 port access vlan 2421 # ''' re1 = '''^interface (.*?$).*?BTO.*?^#$''' rg = re.compile(re1,re.IGNORECASE|re.DOTALL|re.MULTILINE) m = rg.findall(txt) if m: print m </code></pre>
2
2009-09-18T09:24:21Z
1,443,517
<p>Your problem is that the regex is continuing to find the BTO in the next group. As a quick workaround, you could just prohibit the "#" character in the interface id (assuming this isn't valid within records, and only seperates them).</p> <pre><code>re1 = '''^interface ([^#]*?$)[^#]*?BTO.*?^#$''' </code></pre>
4
2009-09-18T09:41:11Z
[ "python", "regex" ]
regular expression to parse network interface config
1,443,433
<p>I am wondering if problem down here can be solved with one regular expression or I should make standard loop and evaluate line by line,</p> <p>when I run included code I get <code>['Ethernet0/22', 'Ethernet0/24']</code>, only result should be <code>['Ethernet0/23', 'Ethernet0/25']</code>.</p> <p>any advice on this? </p> <pre><code> import re txt='''# interface Ethernet0/22 stp disable broadcast-suppression 5 mac-address max-mac-count 1 port access vlan 452 # interface Ethernet0/23 stp disable description BTO broadcast-suppression 5 port access vlan 2421 # interface Ethernet0/24 stp disable description Avaya G700 broadcast-suppression 5 port access vlan 452 # interface Ethernet0/25 stp disable description BTO broadcast-suppression 5 port access vlan 2421 # ''' re1 = '''^interface (.*?$).*?BTO.*?^#$''' rg = re.compile(re1,re.IGNORECASE|re.DOTALL|re.MULTILINE) m = rg.findall(txt) if m: print m </code></pre>
2
2009-09-18T09:24:21Z
1,443,518
<p>Rather than trying to make a pattern between the ^ and $ anchors, and relying on the # you could use the newlines break down the 'sublines' inside the single block match</p> <p>e.g. identify the clauses in terms of a sequence of literal not-newlines leading up to a newline.</p> <p>something like</p> <pre><code> re1 = '''\ninterface ([^\n]+?)\n[^\n]+?\n[^\n]+BTO\n''' </code></pre> <p>will produce the result you are after, from the source text provided.</p>
1
2009-09-18T09:42:33Z
[ "python", "regex" ]
regular expression to parse network interface config
1,443,433
<p>I am wondering if problem down here can be solved with one regular expression or I should make standard loop and evaluate line by line,</p> <p>when I run included code I get <code>['Ethernet0/22', 'Ethernet0/24']</code>, only result should be <code>['Ethernet0/23', 'Ethernet0/25']</code>.</p> <p>any advice on this? </p> <pre><code> import re txt='''# interface Ethernet0/22 stp disable broadcast-suppression 5 mac-address max-mac-count 1 port access vlan 452 # interface Ethernet0/23 stp disable description BTO broadcast-suppression 5 port access vlan 2421 # interface Ethernet0/24 stp disable description Avaya G700 broadcast-suppression 5 port access vlan 452 # interface Ethernet0/25 stp disable description BTO broadcast-suppression 5 port access vlan 2421 # ''' re1 = '''^interface (.*?$).*?BTO.*?^#$''' rg = re.compile(re1,re.IGNORECASE|re.DOTALL|re.MULTILINE) m = rg.findall(txt) if m: print m </code></pre>
2
2009-09-18T09:24:21Z
1,443,540
<h2>An example without regular expressions:</h2> <pre><code>print [ stanza.split()[0] for stanza in txt.split("interface ") if stanza.lower().startswith( "ethernet" ) and stanza.lower().find("bto") &gt; -1 ] </code></pre> <h2>Explanation:</h2> <p>I find compositions are best read "inside-out":</p> <pre><code>for stanza in txt.split("interface ") </code></pre> <p>Split the text on each occurrence of "interface " (including the following space). A resulting stanza will look like this:</p> <pre><code>Ethernet0/22 stp disable broadcast-suppression 5 mac-address max-mac-count 1 port access vlan 452 # </code></pre> <p>Next, filter the stanzas:</p> <pre><code>if stanza.lower().startswith( "ethernet" ) and stanza.lower().find("bto") &gt; -1 </code></pre> <p>This should be self-explanatory.</p> <pre><code>stanza.split()[0] </code></pre> <p>Split the mathing stanzas on whitespace, and take the first element into the resulting list. This, in tandem with the filter <code>startswith</code> will prevent <code>IndexError</code>s</p>
2
2009-09-18T09:49:05Z
[ "python", "regex" ]
regular expression to parse network interface config
1,443,433
<p>I am wondering if problem down here can be solved with one regular expression or I should make standard loop and evaluate line by line,</p> <p>when I run included code I get <code>['Ethernet0/22', 'Ethernet0/24']</code>, only result should be <code>['Ethernet0/23', 'Ethernet0/25']</code>.</p> <p>any advice on this? </p> <pre><code> import re txt='''# interface Ethernet0/22 stp disable broadcast-suppression 5 mac-address max-mac-count 1 port access vlan 452 # interface Ethernet0/23 stp disable description BTO broadcast-suppression 5 port access vlan 2421 # interface Ethernet0/24 stp disable description Avaya G700 broadcast-suppression 5 port access vlan 452 # interface Ethernet0/25 stp disable description BTO broadcast-suppression 5 port access vlan 2421 # ''' re1 = '''^interface (.*?$).*?BTO.*?^#$''' rg = re.compile(re1,re.IGNORECASE|re.DOTALL|re.MULTILINE) m = rg.findall(txt) if m: print m </code></pre>
2
2009-09-18T09:24:21Z
1,444,113
<p>Here is a little pyparsing parser for your file. Not only does this show a solution to your immediate problem, but the parser gives you a nice set of objects that you can use to easily access the data in each interface.</p> <p>Here is the parser:</p> <pre><code>from pyparsing import * # set up the parser comment = "#" + Optional(restOfLine) keyname = Word(alphas,alphanums+'-') value = Combine(empty + SkipTo(LineEnd() | comment)) INTERFACE = Keyword("interface") interfaceDef = Group(INTERFACE + value("name") + \ Dict(OneOrMore(Group(~INTERFACE + keyname + value)))) # ignore comments (could be anywhere) interfaceDef.ignore(comment) # parse the source text ifcdata = OneOrMore(interfaceDef).parseString(txt) </code></pre> <p>Now how to use it:</p> <pre><code># use dump() to list all of the named fields created at parse time for ifc in ifcdata: print ifc.dump() # first the answer to the OP's question print [ifc.name for ifc in ifcdata if ifc.description == "BTO"] # how to access fields that are not legal Python identifiers print [(ifc.name,ifc['broadcast-suppression']) for ifc in ifcdata if 'broadcast-suppression' in ifc] # using names to index into a mapping with string interpolation print ', '.join(["(%(name)s, '%(port)s')" % ifc for ifc in ifcdata ]) </code></pre> <p>Prints out:</p> <pre><code>['interface', 'Ethernet0/22', ['stp', 'disable'], ['broadcast-suppression', '5'], ['mac-address', 'max-mac-count 1'], ['port', 'access vlan 452']] - broadcast-suppression: 5 - mac-address: max-mac-count 1 - name: Ethernet0/22 - port: access vlan 452 - stp: disable ['interface', 'Ethernet0/23', ['stp', 'disable'], ['description', 'BTO'], ['broadcast-suppression', '5'], ['port', 'access vlan 2421']] - broadcast-suppression: 5 - description: BTO - name: Ethernet0/23 - port: access vlan 2421 - stp: disable ['interface', 'Ethernet0/24', ['stp', 'disable'], ['description', 'Avaya G700'], ['broadcast-suppression', '5'], ['port', 'access vlan 452']] - broadcast-suppression: 5 - description: Avaya G700 - name: Ethernet0/24 - port: access vlan 452 - stp: disable ['interface', 'Ethernet0/25', ['stp', 'disable'], ['description', 'BTO'], ['broadcast-suppression', '5'], ['port', 'access vlan 2421']] - broadcast-suppression: 5 - description: BTO - name: Ethernet0/25 - port: access vlan 2421 - stp: disable ['Ethernet0/23', 'Ethernet0/25'] [('Ethernet0/22', '5'), ('Ethernet0/23', '5'), ('Ethernet0/24', '5'), ('Ethernet0/25', '5')] (Ethernet0/22, 'access vlan 452'), (Ethernet0/23, 'access vlan 2421'), (Ethernet0/24, 'access vlan 452'), (Ethernet0/25, 'access vlan 2421') </code></pre>
5
2009-09-18T11:58:40Z
[ "python", "regex" ]
How to read a structure containing an array using Python's ctypes and readinto?
1,444,159
<p>We have some binary files created by a C program.</p> <p>One type of file is created by calling fwrite to write the following C structure to file:</p> <pre><code>typedef struct { unsigned long int foo; unsigned short int bar; unsigned short int bow; } easyStruc; </code></pre> <p>In Python, I read the structs of this file as follows:</p> <pre><code>class easyStruc(Structure): _fields_ = [ ("foo", c_ulong), ("bar", c_ushort), ("bow", c_ushort) ] f = open (filestring, 'rb') record = censusRecord() while (f.readinto(record) != 0): ##do stuff f.close() </code></pre> <p>That works fine. Our other type of file is created using the following structure:</p> <pre><code>typedef struct { // bin file (one file per year) unsigned long int foo; float barFloat[4]; float bowFloat[17]; } strucWithArrays; </code></pre> <p>I'm not sure how to create the structure in Python. </p>
4
2009-09-18T12:05:54Z
1,444,339
<p>According to this <a href="http://docs.activestate.com/activepython/3.1/python/library/ctypes.html" rel="nofollow">documentation page</a> (section: 15.15.1.13. Arrays), it should be something like:</p> <pre><code>class strucWithArrays(Structure): _fields_ = [ ("foo", c_ulong), ("barFloat", c_float * 4), ("bowFloat", c_float * 17)] </code></pre> <p>Check that documentation page for other examples.</p>
8
2009-09-18T12:43:48Z
[ "python", "ctypes" ]
How to read a structure containing an array using Python's ctypes and readinto?
1,444,159
<p>We have some binary files created by a C program.</p> <p>One type of file is created by calling fwrite to write the following C structure to file:</p> <pre><code>typedef struct { unsigned long int foo; unsigned short int bar; unsigned short int bow; } easyStruc; </code></pre> <p>In Python, I read the structs of this file as follows:</p> <pre><code>class easyStruc(Structure): _fields_ = [ ("foo", c_ulong), ("bar", c_ushort), ("bow", c_ushort) ] f = open (filestring, 'rb') record = censusRecord() while (f.readinto(record) != 0): ##do stuff f.close() </code></pre> <p>That works fine. Our other type of file is created using the following structure:</p> <pre><code>typedef struct { // bin file (one file per year) unsigned long int foo; float barFloat[4]; float bowFloat[17]; } strucWithArrays; </code></pre> <p>I'm not sure how to create the structure in Python. </p>
4
2009-09-18T12:05:54Z
1,444,349
<p>There's a section about <a href="http://docs.python.org/library/ctypes.html#arrays" rel="nofollow">arrays in ctypes</a> in the documentation. Basically this means:</p> <pre><code>class structWithArray(Structure): _fields_ = [ ("foo", c_ulong), ("barFloat", c_float * 4), ("bowFloat", c_float * 17) ] </code></pre>
2
2009-09-18T12:46:08Z
[ "python", "ctypes" ]
Django Models internal methods
1,444,222
<p>I'm new to Django so I just made up an project to get to know it but I'm having a little problem with this code, I want to be able to as the car obj if it is available so I do a:</p> <pre><code>&gt;&gt;&gt;cars = Car.objects.all() &gt;&gt;&gt;print cars[0].category &gt;&gt;&gt;'A' &gt;&gt;&gt;cars[0].available(fr, to) </code></pre> <p>that results in a:</p> <pre><code>&gt;&gt;&gt;global name 'category' is not defined </code></pre> <p>So it seems that I don't have access to the self.category within the class, any ideas? </p> <pre><code>from django.db import models class Car(models.Model): TRANSMISSION_CHOICES = ( ('M', 'Manual'), ('A', 'Automatic'), ) category = models.CharField("Category",max_length=1,primary_key=True) description = models.CharField("Description",max_length=200) numberOfCars = models.IntegerField("Number of cars") numberOfDoors = models.IntegerField("Number of doors") transmission = models.CharField("Transmission", max_length=1, choices=TRANSMISSION_CHOICES) passengers = models.IntegerField("Number of passengers") image = models.ImageField("Image", upload_to="photos/%Y/%m/%d") def available(self, fr, to): rents = Rent.objects.filter(car=self.category) rents = rents.excludes(start &lt; fr) rents = rents.exclude(end &gt; to) return cont(rents) def __unicode__(self): return "Class " + self.category class Rent(models.Model): car = models.ForeignKey(Car) start = models.DateTimeField() end = models.DateTimeField() childrenSeat = models.BooleanField() extraDriver = models.BooleanField() def __unicode__(self): return str(self.car) + " From: " + str(self.start) + " To: " + str(self.end) </code></pre>
0
2009-09-18T12:20:58Z
1,444,390
<p>Although I can't see how the error you are getting relates to it, the filter you are using doesn't look correct.</p> <p>You define category as a string in the Car model:</p> <pre><code>category = models.CharField("Category",max_length=1,primary_key=True) </code></pre> <p>And define car as a foreignkey in the Rent model:</p> <pre><code>car = models.ForeignKey(Car) </code></pre> <p>And then you try and filter Rents:</p> <pre><code>rents = Rent.objects.filter(car=self.category) </code></pre> <p>But car should be a model here, not a charfield. Perhaps you meant to say car=self?</p>
0
2009-09-18T12:55:02Z
[ "python", "django", "django-models" ]
Example code for a python server wrapper
1,444,358
<p>I have a command line server for which I want to create a wrapper in python. The idea is that the wrapper receives commands like:</p> <pre><code>my_wrapper start my_wrapper stop my_wrapper restart my_wrapper status </code></pre> <p>And handles the server in background, unlinked to the terminal that launched it from the wrapper.</p> <p>I was about to start thinking on how to do it and thought on the golden rule, DRY. </p> <p>Do you know of any example code I should start reading before starting my first line?</p> <p>Update:</p> <p>I noticed I didn't include that the server is a jar file, so I'll have to run it using subprocess or something similar.</p> <p>I'd prefer not to use modules that are not included in python's standard lib.</p>
1
2009-09-18T12:48:18Z
1,444,373
<p>You could use an implementation of <a href="http://www.python.org/dev/peps/pep-3143/" rel="nofollow">PEP 3143 - Standard daemon process library</a>. One existing is <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">python-daemon</a>.</p>
1
2009-09-18T12:52:42Z
[ "python", "wrapper" ]
Differences between Framework and non-Framework builds of Python on Mac OS X
1,444,543
<h3>Question</h3> <p>What are the differences between a Framework build and a non-Framework build (i.e., standard UNIX build) of Python on Mac OS X? Also, what are the advantages and disadvantages of each?</p> <h3>Preliminary Research</h3> <p>Here is the information that I found prior to posting this question:</p> <ul> <li><a href="http://www.mail-archive.com/pythonmac-sig@python.org/msg08954.html">[Pythonmac-SIG] Why is Framework build of Python needed</a> <ul> <li>B. Grainger: "I seem to recall that a Framework build of Python is needed if you want to do anything with the native Mac GUI. Is my understanding correct?"</li> <li>C. Barker: "Pretty much -- to access the Mac GUI, an app needs to be in a proper Mac application bundle. The Framework build supplies that."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/Framework.html">Apple Developer Connection: Framework Definition</a> <ul> <li>"A framework is a bundle (a structured directory) that contains a dynamic shared library along with associated resources, such as nib files, image files, and header files. When you develop an application, your project links to one or more frameworks. For example, iPhone application projects link by default to the Foundation, UIKit, and Core Graphics frameworks. Your code accesses the capabilities of a framework through the application programming interface (API), which is published by the framework through its header files. Because the library is dynamically shared, multiple applications can access the framework code and resources simultaneously. The system loads the code and resources of a framework into memory, as needed, and shares the one copy of a resource among all applications."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html#//apple%5Fref/doc/uid/20002303">Framework Programming Guide: What are Frameworks?</a> <ul> <li>"Frameworks offer the following advantages over static-linked libraries and other types of dynamic shared libraries: <ul> <li>Frameworks group related, but separate, resources together. This grouping makes it easier to install, uninstall, and locate those resources.</li> <li>Frameworks can include a wider variety of resource types than libraries. For example, a framework can include any relevant header files and documentation. Multiple versions of a framework can be included in the same bundle. This makes it possible to be backward compatible with older programs.</li> <li>Only one copy of a framework’s read-only resources reside physically in-memory at any given time, regardless of how many processes are using those resources. This sharing of resources reduces the memory footprint of the system and helps improve performance."</li> </ul></li> </ul></li> </ul> <h3>Background</h3> <p>Prior to Mac OS X 10.6 Snow Leopard, I hadn't thought much about this, as I simply would download and install the <a href="http://www.python.org/download/">Python 2.6.2 Mac Installer Disk Image</a>, which is a framework build, and go about my business using virtualenv, pip, etc. However, with the changes in Snow Leopard to 64-bit, gcc, etc., I've noticed some issues that have made me want to build/compile Python 2.6.2+ myself from source, which leads me to my question of the differences and advantages/disadvantages of building Python as a MacOSX|Darwin framework.</p>
44
2009-09-18T13:27:54Z
1,445,711
<p>You've already listed all important advantages of making a framework (congratulations for excellent research and reporting thereof!); the only flip side is that it's harder to arrange to build one properly, but if you take your clues from the examples in the installer you quote, it should be doable.</p> <p>BTW, what's wrong with the system Python that comes with Snow Leopard? I haven't upgraded from Leopard yet (long story... I do have the "family license" upgrade DVD, but need Snow Leopard to fix some things before I can upgrade), so I have no first-hand experience with that yet, but I do know it's a 2.6 build and it comes in both 32-bit and 64-bit versions... so why do you need to build your own framework?</p>
11
2009-09-18T16:53:24Z
[ "python", "osx", "frameworks" ]
Differences between Framework and non-Framework builds of Python on Mac OS X
1,444,543
<h3>Question</h3> <p>What are the differences between a Framework build and a non-Framework build (i.e., standard UNIX build) of Python on Mac OS X? Also, what are the advantages and disadvantages of each?</p> <h3>Preliminary Research</h3> <p>Here is the information that I found prior to posting this question:</p> <ul> <li><a href="http://www.mail-archive.com/pythonmac-sig@python.org/msg08954.html">[Pythonmac-SIG] Why is Framework build of Python needed</a> <ul> <li>B. Grainger: "I seem to recall that a Framework build of Python is needed if you want to do anything with the native Mac GUI. Is my understanding correct?"</li> <li>C. Barker: "Pretty much -- to access the Mac GUI, an app needs to be in a proper Mac application bundle. The Framework build supplies that."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/Framework.html">Apple Developer Connection: Framework Definition</a> <ul> <li>"A framework is a bundle (a structured directory) that contains a dynamic shared library along with associated resources, such as nib files, image files, and header files. When you develop an application, your project links to one or more frameworks. For example, iPhone application projects link by default to the Foundation, UIKit, and Core Graphics frameworks. Your code accesses the capabilities of a framework through the application programming interface (API), which is published by the framework through its header files. Because the library is dynamically shared, multiple applications can access the framework code and resources simultaneously. The system loads the code and resources of a framework into memory, as needed, and shares the one copy of a resource among all applications."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html#//apple%5Fref/doc/uid/20002303">Framework Programming Guide: What are Frameworks?</a> <ul> <li>"Frameworks offer the following advantages over static-linked libraries and other types of dynamic shared libraries: <ul> <li>Frameworks group related, but separate, resources together. This grouping makes it easier to install, uninstall, and locate those resources.</li> <li>Frameworks can include a wider variety of resource types than libraries. For example, a framework can include any relevant header files and documentation. Multiple versions of a framework can be included in the same bundle. This makes it possible to be backward compatible with older programs.</li> <li>Only one copy of a framework’s read-only resources reside physically in-memory at any given time, regardless of how many processes are using those resources. This sharing of resources reduces the memory footprint of the system and helps improve performance."</li> </ul></li> </ul></li> </ul> <h3>Background</h3> <p>Prior to Mac OS X 10.6 Snow Leopard, I hadn't thought much about this, as I simply would download and install the <a href="http://www.python.org/download/">Python 2.6.2 Mac Installer Disk Image</a>, which is a framework build, and go about my business using virtualenv, pip, etc. However, with the changes in Snow Leopard to 64-bit, gcc, etc., I've noticed some issues that have made me want to build/compile Python 2.6.2+ myself from source, which leads me to my question of the differences and advantages/disadvantages of building Python as a MacOSX|Darwin framework.</p>
44
2009-09-18T13:27:54Z
1,493,606
<p>I use <a href="http://www.macports.org/install.php" rel="nofollow" title="Macports">Macports</a> on 10.6, which makes it very simple to install multiple versions of python and switch between them and Apple's version:</p> <pre><code>sudo port install python26 sudo port install python_select sudo python_select -l </code></pre> <p>The most recent version of python26 is 2.6.2, and compiles and runs fine on 10.6.1: trac.macports.org/browser/trunk/dports/lang/python26/Portfile</p>
0
2009-09-29T16:24:02Z
[ "python", "osx", "frameworks" ]
Differences between Framework and non-Framework builds of Python on Mac OS X
1,444,543
<h3>Question</h3> <p>What are the differences between a Framework build and a non-Framework build (i.e., standard UNIX build) of Python on Mac OS X? Also, what are the advantages and disadvantages of each?</p> <h3>Preliminary Research</h3> <p>Here is the information that I found prior to posting this question:</p> <ul> <li><a href="http://www.mail-archive.com/pythonmac-sig@python.org/msg08954.html">[Pythonmac-SIG] Why is Framework build of Python needed</a> <ul> <li>B. Grainger: "I seem to recall that a Framework build of Python is needed if you want to do anything with the native Mac GUI. Is my understanding correct?"</li> <li>C. Barker: "Pretty much -- to access the Mac GUI, an app needs to be in a proper Mac application bundle. The Framework build supplies that."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/Framework.html">Apple Developer Connection: Framework Definition</a> <ul> <li>"A framework is a bundle (a structured directory) that contains a dynamic shared library along with associated resources, such as nib files, image files, and header files. When you develop an application, your project links to one or more frameworks. For example, iPhone application projects link by default to the Foundation, UIKit, and Core Graphics frameworks. Your code accesses the capabilities of a framework through the application programming interface (API), which is published by the framework through its header files. Because the library is dynamically shared, multiple applications can access the framework code and resources simultaneously. The system loads the code and resources of a framework into memory, as needed, and shares the one copy of a resource among all applications."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html#//apple%5Fref/doc/uid/20002303">Framework Programming Guide: What are Frameworks?</a> <ul> <li>"Frameworks offer the following advantages over static-linked libraries and other types of dynamic shared libraries: <ul> <li>Frameworks group related, but separate, resources together. This grouping makes it easier to install, uninstall, and locate those resources.</li> <li>Frameworks can include a wider variety of resource types than libraries. For example, a framework can include any relevant header files and documentation. Multiple versions of a framework can be included in the same bundle. This makes it possible to be backward compatible with older programs.</li> <li>Only one copy of a framework’s read-only resources reside physically in-memory at any given time, regardless of how many processes are using those resources. This sharing of resources reduces the memory footprint of the system and helps improve performance."</li> </ul></li> </ul></li> </ul> <h3>Background</h3> <p>Prior to Mac OS X 10.6 Snow Leopard, I hadn't thought much about this, as I simply would download and install the <a href="http://www.python.org/download/">Python 2.6.2 Mac Installer Disk Image</a>, which is a framework build, and go about my business using virtualenv, pip, etc. However, with the changes in Snow Leopard to 64-bit, gcc, etc., I've noticed some issues that have made me want to build/compile Python 2.6.2+ myself from source, which leads me to my question of the differences and advantages/disadvantages of building Python as a MacOSX|Darwin framework.</p>
44
2009-09-18T13:27:54Z
1,493,981
<p>If you are going to ship your code (have it running on another machine), you'd better use the system version of python otherwise your program behavior will be undefined on the other machines.</p>
1
2009-09-29T17:38:22Z
[ "python", "osx", "frameworks" ]
Differences between Framework and non-Framework builds of Python on Mac OS X
1,444,543
<h3>Question</h3> <p>What are the differences between a Framework build and a non-Framework build (i.e., standard UNIX build) of Python on Mac OS X? Also, what are the advantages and disadvantages of each?</p> <h3>Preliminary Research</h3> <p>Here is the information that I found prior to posting this question:</p> <ul> <li><a href="http://www.mail-archive.com/pythonmac-sig@python.org/msg08954.html">[Pythonmac-SIG] Why is Framework build of Python needed</a> <ul> <li>B. Grainger: "I seem to recall that a Framework build of Python is needed if you want to do anything with the native Mac GUI. Is my understanding correct?"</li> <li>C. Barker: "Pretty much -- to access the Mac GUI, an app needs to be in a proper Mac application bundle. The Framework build supplies that."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/Framework.html">Apple Developer Connection: Framework Definition</a> <ul> <li>"A framework is a bundle (a structured directory) that contains a dynamic shared library along with associated resources, such as nib files, image files, and header files. When you develop an application, your project links to one or more frameworks. For example, iPhone application projects link by default to the Foundation, UIKit, and Core Graphics frameworks. Your code accesses the capabilities of a framework through the application programming interface (API), which is published by the framework through its header files. Because the library is dynamically shared, multiple applications can access the framework code and resources simultaneously. The system loads the code and resources of a framework into memory, as needed, and shares the one copy of a resource among all applications."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html#//apple%5Fref/doc/uid/20002303">Framework Programming Guide: What are Frameworks?</a> <ul> <li>"Frameworks offer the following advantages over static-linked libraries and other types of dynamic shared libraries: <ul> <li>Frameworks group related, but separate, resources together. This grouping makes it easier to install, uninstall, and locate those resources.</li> <li>Frameworks can include a wider variety of resource types than libraries. For example, a framework can include any relevant header files and documentation. Multiple versions of a framework can be included in the same bundle. This makes it possible to be backward compatible with older programs.</li> <li>Only one copy of a framework’s read-only resources reside physically in-memory at any given time, regardless of how many processes are using those resources. This sharing of resources reduces the memory footprint of the system and helps improve performance."</li> </ul></li> </ul></li> </ul> <h3>Background</h3> <p>Prior to Mac OS X 10.6 Snow Leopard, I hadn't thought much about this, as I simply would download and install the <a href="http://www.python.org/download/">Python 2.6.2 Mac Installer Disk Image</a>, which is a framework build, and go about my business using virtualenv, pip, etc. However, with the changes in Snow Leopard to 64-bit, gcc, etc., I've noticed some issues that have made me want to build/compile Python 2.6.2+ myself from source, which leads me to my question of the differences and advantages/disadvantages of building Python as a MacOSX|Darwin framework.</p>
44
2009-09-18T13:27:54Z
1,494,311
<p>Framework builds are owned by the 'root' account when installed. A source build will be owned by the account installing it. The advantage (and disadvantage) of having ownership of the Python installation is that you don't need to change accounts to modify it.</p> <p>A small difference is that Framework builds are built against the EditLine library. Source builds are usually compiled against the Readline library. Depending upon which library Python is compiled against, the readline module in the standard library works slightly differently. See 'man python' on Mac OS X for more details on this.</p> <p>There is a nice buildout for automating the compile of Python 2.4, 2.5 and 2.6 from source on Mac OS X, which is <a href="http://reinout.vanrees.org/weblog/2009/09/28/python-snowleopard-rescue.html" rel="nofollow">explained here</a>. This will compile against a custom build of readline. However, the usefulness of scripting the source install is that you can make additional tweaks to your custom Python builds, e.g. installing essential distributions such as virtualenv, or harder to install distributions such as PIL.</p>
-1
2009-09-29T18:56:04Z
[ "python", "osx", "frameworks" ]
Differences between Framework and non-Framework builds of Python on Mac OS X
1,444,543
<h3>Question</h3> <p>What are the differences between a Framework build and a non-Framework build (i.e., standard UNIX build) of Python on Mac OS X? Also, what are the advantages and disadvantages of each?</p> <h3>Preliminary Research</h3> <p>Here is the information that I found prior to posting this question:</p> <ul> <li><a href="http://www.mail-archive.com/pythonmac-sig@python.org/msg08954.html">[Pythonmac-SIG] Why is Framework build of Python needed</a> <ul> <li>B. Grainger: "I seem to recall that a Framework build of Python is needed if you want to do anything with the native Mac GUI. Is my understanding correct?"</li> <li>C. Barker: "Pretty much -- to access the Mac GUI, an app needs to be in a proper Mac application bundle. The Framework build supplies that."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/Framework.html">Apple Developer Connection: Framework Definition</a> <ul> <li>"A framework is a bundle (a structured directory) that contains a dynamic shared library along with associated resources, such as nib files, image files, and header files. When you develop an application, your project links to one or more frameworks. For example, iPhone application projects link by default to the Foundation, UIKit, and Core Graphics frameworks. Your code accesses the capabilities of a framework through the application programming interface (API), which is published by the framework through its header files. Because the library is dynamically shared, multiple applications can access the framework code and resources simultaneously. The system loads the code and resources of a framework into memory, as needed, and shares the one copy of a resource among all applications."</li> </ul></li> <li><a href="http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html#//apple%5Fref/doc/uid/20002303">Framework Programming Guide: What are Frameworks?</a> <ul> <li>"Frameworks offer the following advantages over static-linked libraries and other types of dynamic shared libraries: <ul> <li>Frameworks group related, but separate, resources together. This grouping makes it easier to install, uninstall, and locate those resources.</li> <li>Frameworks can include a wider variety of resource types than libraries. For example, a framework can include any relevant header files and documentation. Multiple versions of a framework can be included in the same bundle. This makes it possible to be backward compatible with older programs.</li> <li>Only one copy of a framework’s read-only resources reside physically in-memory at any given time, regardless of how many processes are using those resources. This sharing of resources reduces the memory footprint of the system and helps improve performance."</li> </ul></li> </ul></li> </ul> <h3>Background</h3> <p>Prior to Mac OS X 10.6 Snow Leopard, I hadn't thought much about this, as I simply would download and install the <a href="http://www.python.org/download/">Python 2.6.2 Mac Installer Disk Image</a>, which is a framework build, and go about my business using virtualenv, pip, etc. However, with the changes in Snow Leopard to 64-bit, gcc, etc., I've noticed some issues that have made me want to build/compile Python 2.6.2+ myself from source, which leads me to my question of the differences and advantages/disadvantages of building Python as a MacOSX|Darwin framework.</p>
44
2009-09-18T13:27:54Z
13,324,455
<p>There is another difference: typically the Framework installation provided by the installer from python.org has several architectures. </p> <blockquote> <p><code>$ file libpython2.7.dylib</code> </p> <p><code>libpython2.7.dylib: Mach-O universal binary with 2 architectures</code> <code>libpython2.7.dylib (for architecture i386): Mach-O dynamically linked shared library i386</code> <code>libpython2.7.dylib (for architecture x86_64): Mach-O 64-bit dynamically linked shared library x86_64</code></p> </blockquote> <p>If you install from source and you do not deliberately change this, your libpython has only one architecture. I have had cases where the two architectures actually resulted in problems (at least I believe that this was the reason), namely when installing the HDF5 python bindings (h5py).</p> <p>And there is yet another difference: some tools require the framework installation. For instance PyQt, and in particular sip. While it is possible to install sip and PyQt even for the non-framework version of python, it is much more complicated. </p> <p>As for the decision what to prefer, I still do not know. At the moment, I went for the non-framework option, but I must say, that it also caused me some headache. </p>
3
2012-11-10T17:42:04Z
[ "python", "osx", "frameworks" ]
Django admin choice field dynamically populated by generic foreign key's model fields
1,444,587
<p>Say I have the following simple models for some tagging application (this is simplified from the actual code):</p> <pre><code># Model of tag templates class TagTemplate(models.Model): name = models.CharField() content_type = models.ForeignKey(ContentType) class Tag(models.Model): template = models.ForeignKey(TagTemplate) object_id = models.PositiveIntegerField() * content_object = generic.GenericForeignKey('template__content_type', 'object_id') # Each tag may display the class TagTemplateItemDisplay(models.Model): template = models.ForeignKey(TagTemplate) content_type_field = models.CharField() font_size = models.IntegerField() </code></pre> <p>I have two questions:</p> <p>1) In the line marked with the *, I understand from the documentation that I need to pass the two field names as per the contenttype framework. In my case the content_type field is specified within the template model. I'd like to avoind a duplicate content_type field within the 'tag' model to get the GenericForeignKey working. Is this possible? Or do I need some custom manager to implement a duplicate content_type within the tag model?</p> <p>2) I'd like to use the admin site with these models. Is it possible to dynamically create a choice dropdown for the 'content_type_field' field where the contents corresponds to a list of fields from the chosen content_type of the parent model (ie. tagTemplate) when using Tabularinline layout?</p> <p>eg. in the admin site I pick a model (content_type field) for a new tagTemplate record that contains the fields ('name', 'age', 'dob'), I'd like the TabularInline forms to dynamically update the 'content_type_field' to contain the choices name, age and dob. If i then pick a different model in the parent tagTemplate content_type field, the choices in the child tagTemplateItemDisplay content_type_field of the inline are updated again.</p>
3
2009-09-18T13:35:04Z
5,981,489
<p>You can subclass the form for that model</p> <pre><code>class TagTemplateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TagTemplateForm, self).__init__(*args, **kwargs) if self.instance.content_type == SomeContentType: **dynamically create your fields here** elif self.instance.content_type == SomeOtherContentType: **dynamically create your other fields here** </code></pre> <p>Then in your TagAdmin model you need to have:</p> <pre><code>form = TagTemplateForm </code></pre> <p>to override the default form created for the admin site.</p> <p>Not a complete solution but should get you started.</p> <p>For the dynamic form generation, you might start by <a href="http://jacobian.org/writing/dynamic-form-generation/" rel="nofollow">reading over this</a></p>
1
2011-05-12T16:45:23Z
[ "python", "django", "django-models", "django-admin" ]
Pydev code browsing?
1,444,651
<p>I've been -trying- to use pydev to do some python (can't say I'm having good times so far). I finally got code completion working for the libraries I'm using, but I'm still wondering about a couple of things... </p> <p>So the library I'm using is called orange. Say I call the function orange.MakeRandomIndices2, but I'm not sure how it works... I want to see the source code of this function, or at least some useful information as to it's usage.. Is there any way to do this from my ide?</p> <p>Also while debugging, I might want to do just the same.. step into that function and debug it internally... I cannot seem to be able to do this and I just don't understand WHY seeing I have the source code on my hard disk.</p> <p>Thanks. JC</p>
2
2009-09-18T13:47:57Z
1,445,869
<p>When you hover your cursor over a function or class, Pydev should show you the docstring. Click on the function/class, then press F3, and it will take you to the definition of that function/class. If that is not happening, you probably have not configured Pydev correctly. Look over the documentation again, making sure you have done all the steps. If that still does not work, the Pydev author is very active and helpful on the pydev mailinglists.</p> <p>When you are debugging code, F5 will step into a function. F6 will step over.</p>
2
2009-09-18T17:28:17Z
[ "python", "eclipse", "pydev" ]
Werkzeug and SQLAlchemy 0.5x session
1,444,735
<p>Updated:</p> <p>Going through the Werkzeug <a href="http://werkzeug.pocoo.org/documentation/0.5.1" rel="nofollow">link text</a> tutorial, got stack with creating SQLAlchemy session using sessionmaker() instead of create_session() as recommended.</p> <p>Note: it is not about SA, it is about Werkzeug.</p> <p>Werkzeug tutorial:</p> <pre><code>session = scoped_session(lambda: create_session(bind=application.database_engine, autoflush=True, autocommit=False), local_manager.get_ident) </code></pre> <p>I asked how to achieve the same using sessionmaker():</p> <p>As a result guys from #pocoo RCI helped me with this:</p> <pre><code>session = scoped_session(lambda: sessionmaker(bind=application.database_engine)(), local_manager.get_ident) </code></pre> <p>without <strong>()</strong> at the end of sessionmaker(**args) it kept giving me an error:</p> <p>RuntimeError: no object bound to application</p> <p>P.S. if delete <strong>lambda</strong> it will not work.</p>
0
2009-09-18T14:02:38Z
1,444,931
<p><code>sessionmaker()</code> returns a session factory, not a session itself. <code>scoped_session()</code> takes a session factory as argument. So just omit the <code>lambda:</code> and pass the result of <code>sessionmaker()</code> directly to <code>scoped_session()</code>.</p>
4
2009-09-18T14:30:57Z
[ "python", "sqlalchemy", "werkzeug" ]
Python: module for creating PID-based lockfile?
1,444,790
<p>I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile… But I don't want to re-invent the wheel if there is already code to do this.</p> <p>So, is there a Python module out there which will manage the details of a PID-based lockfile?</p>
16
2009-09-18T14:10:52Z
1,444,850
<p>This might be of help to you: <a href="http://pypi.python.org/pypi/zc.lockfile">lockfile</a></p>
9
2009-09-18T14:18:47Z
[ "python", "pid", "lockfile" ]
Python: module for creating PID-based lockfile?
1,444,790
<p>I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile… But I don't want to re-invent the wheel if there is already code to do this.</p> <p>So, is there a Python module out there which will manage the details of a PID-based lockfile?</p>
16
2009-09-18T14:10:52Z
1,444,860
<p>If you can use GPLv2, Mercurial has a module for that:</p> <p><a href="http://bitbucket.org/mirror/mercurial/src/tip/mercurial/lock.py">http://bitbucket.org/mirror/mercurial/src/tip/mercurial/lock.py</a></p> <p>Example usage:</p> <pre><code>from mercurial import error, lock try: l = lock.lock("/path/to/lock", timeout=600) # wait at most 10 minutes # do something except error.LockHeld: # couldn't take the lock else: l.release() </code></pre>
8
2009-09-18T14:19:54Z
[ "python", "pid", "lockfile" ]
Python: module for creating PID-based lockfile?
1,444,790
<p>I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile… But I don't want to re-invent the wheel if there is already code to do this.</p> <p>So, is there a Python module out there which will manage the details of a PID-based lockfile?</p>
16
2009-09-18T14:10:52Z
1,444,862
<p>I believe you will find the necessary information <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">here</a>. The page in question refers to a package for building daemons in python: this process involves creating a PID lockfile.</p>
3
2009-09-18T14:20:16Z
[ "python", "pid", "lockfile" ]
Python: module for creating PID-based lockfile?
1,444,790
<p>I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile… But I don't want to re-invent the wheel if there is already code to do this.</p> <p>So, is there a Python module out there which will manage the details of a PID-based lockfile?</p>
16
2009-09-18T14:10:52Z
1,444,890
<p>There is a <a href="http://code.activestate.com/recipes/498171/" rel="nofollow">recipe on ActiveState on creating lockfiles</a>.</p> <p>To generate the filename you can use <a href="http://docs.python.org/library/os.html#os.getpid" rel="nofollow">os.getpid()</a> to get the PID.</p>
2
2009-09-18T14:23:15Z
[ "python", "pid", "lockfile" ]
Python: module for creating PID-based lockfile?
1,444,790
<p>I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile… But I don't want to re-invent the wheel if there is already code to do this.</p> <p>So, is there a Python module out there which will manage the details of a PID-based lockfile?</p>
16
2009-09-18T14:10:52Z
23,837,022
<p>i've been pretty unhappy with all of those, so i wrote this:</p> <pre><code>class Pidfile(): def __init__(self, path, log=sys.stdout.write, warn=sys.stderr.write): self.pidfile = path self.log = log self.warn = warn def __enter__(self): try: self.pidfd = os.open(self.pidfile, os.O_CREAT|os.O_WRONLY|os.O_EXCL) self.log('locked pidfile %s' % self.pidfile) except OSError as e: if e.errno == errno.EEXIST: pid = self._check() if pid: self.pidfd = None raise ProcessRunningException('process already running in %s as pid %s' % (self.pidfile, pid)); else: os.remove(self.pidfile) self.warn('removed staled lockfile %s' % (self.pidfile)) self.pidfd = os.open(self.pidfile, os.O_CREAT|os.O_WRONLY|os.O_EXCL) else: raise os.write(self.pidfd, str(os.getpid())) os.close(self.pidfd) return self def __exit__(self, t, e, tb): # return false to raise, true to pass if t is None: # normal condition, no exception self._remove() return True elif t is PidfileProcessRunningException: # do not remove the other process lockfile return False else: # other exception if self.pidfd: # this was our lockfile, removing self._remove() return False def _remove(self): self.log('removed pidfile %s' % self.pidfile) os.remove(self.pidfile) def _check(self): """check if a process is still running the process id is expected to be in pidfile, which should exist. if it is still running, returns the pid, if not, return False.""" with open(self.pidfile, 'r') as f: try: pidstr = f.read() pid = int(pidstr) except ValueError: # not an integer self.log("not an integer: %s" % pidstr) return False try: os.kill(pid, 0) except OSError: self.log("can't deliver signal to %s" % pid) return False else: return pid class ProcessRunningException(BaseException): pass </code></pre> <p>to be used something like this:</p> <pre><code>try: with Pidfile(args.pidfile): process(args) except ProcessRunningException: print "the pid file is in use, oops." </code></pre>
1
2014-05-23T19:23:50Z
[ "python", "pid", "lockfile" ]
In Django Admin, I want to change how foreign keys are displayed in a Many-Many Relationship admin widget
1,444,912
<p>I have a ManyToMany relationship:</p> <pre> class Book: title = models.CharField(...) isbn = models.CharField(...) def unicode(self): return self.title def ISBN(self): return self.isbn class Author: name = models.CharField(...) books = models.ManyToManyField(Book...) </pre> <p>In the admin interface for Author I get a multiple select list that uses the unicode display for books. I want to change the list in two ways:<br/><br/> 1) Only for the admin interface I want to display the ISBN number, everywhere else I just print out a "Book" object I want the title displayed.<br/><br/> 2) How could I use a better widget than MultipleSelectList for the ManyToMany. How could I specify to use a CheckBoxSelectList instead?<br/><br/></p>
2
2009-09-18T14:27:13Z
1,445,536
<p>For 2), use this in your AuthorAdmin class:</p> <pre><code>raw_id_fields = ['books'] </code></pre> <p>Check here: <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin</a> for instructions on creating a custom ModelAdmin class. I've thought about this a lot myself for my own Django project, and I think 1) would require modifying the admin template for viewing Author objects.</p>
1
2009-09-18T16:12:50Z
[ "python", "django", "django-admin", "django-widget" ]
In Django Admin, I want to change how foreign keys are displayed in a Many-Many Relationship admin widget
1,444,912
<p>I have a ManyToMany relationship:</p> <pre> class Book: title = models.CharField(...) isbn = models.CharField(...) def unicode(self): return self.title def ISBN(self): return self.isbn class Author: name = models.CharField(...) books = models.ManyToManyField(Book...) </pre> <p>In the admin interface for Author I get a multiple select list that uses the unicode display for books. I want to change the list in two ways:<br/><br/> 1) Only for the admin interface I want to display the ISBN number, everywhere else I just print out a "Book" object I want the title displayed.<br/><br/> 2) How could I use a better widget than MultipleSelectList for the ManyToMany. How could I specify to use a CheckBoxSelectList instead?<br/><br/></p>
2
2009-09-18T14:27:13Z
1,447,266
<p>To display the ISBN you could make a custom field like this:</p> <pre><code> class BooksField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.isbn </code></pre> <p>There's a <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple" rel="nofollow">CheckboxSelectMultiple</a> for the ManyToManyField but it doesn't display correctly on the admin, so you could also write some css to fix that.</p> <p>You need to create a form for the model, and use that in your admin class:</p> <pre><code> class AuthorForm(forms.ModelForm): books = BooksField(Book.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Author class Media: css = { 'all': ('booksfield.css',) } class AuthorAdmin(admin.ModelAdmin): form = AuthorForm </code></pre>
1
2009-09-18T23:58:21Z
[ "python", "django", "django-admin", "django-widget" ]
What is the best-maintained generic functions implementation for Python?
1,445,065
<p>A <a href="http://en.wikipedia.org/wiki/Generic%5Ffunctions">generic function</a> is dispatched based on the type of all its arguments. The programmer defines several implementations of a function. The correct one is chosen at call time based on the types of its arguments. This is useful for object adaptation among other things. Python has a few generic functions including <code>len()</code>.</p> <p>These packages tend to allow code that looks like this:</p> <pre><code>@when(int) def dumbexample(a): return a * 2 @when(list) def dumbexample(a): return [("%s" % i) for i in a] dumbexample(1) # calls first implementation dumbexample([1,2,3]) # calls second implementation </code></pre> <p>A less dumb example I've been thinking about lately would be a web component that requires a User. Instead of requiring a particular web framework, the integrator would just need to write something like:</p> <pre><code>class WebComponentUserAdapter(object): def __init__(self, guest): self.guest = guest def canDoSomething(self): return guest.member_of("something_group") @when(my.webframework.User) componentNeedsAUser(user): return WebComponentUserAdapter(user) </code></pre> <p>Python has a few generic functions implementations. Why would I chose one over the others? How is that implementation being used in applications?</p> <p>I'm familiar with Zope's <code>zope.component.queryAdapter(object, ISomething)</code>. The programmer registers a callable adapter that takes a particular class of object as its argument and returns something compatible with the interface. It's a useful way to allow plugins. Unlike monkey patching, it works even if an object needs to adapt to multiple interfaces with the same method names.</p>
7
2009-09-18T14:54:28Z
1,445,119
<p>I'd recommend the <a href="http://pypi.python.org/pypi/PEAK-Rules">PEAK-Rules</a> library by P. Eby. By the same author (deprecated though) is the <a href="http://peak.telecommunity.com/">RuleDispatch</a> package (the predecessor of PEAK-Rules). The latter being no longer maintained IIRC. </p> <p>PEAK-Rules has a lot of nice features, one being, that it is (well, not easily, but) extensible. Besides "classic" dispatch on types ony, it features dispatch on arbitrary expressions as "guardians".</p> <p>The <code>len()</code> function is not a true generic function (at least in the sense of the packages mentioned above, and also in the sense, this term is used in languages like <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26%5Fglo%5Fg.htm#generic%5Ffunction">Common Lisp</a>, <a href="http://www.opendylan.org/books/drm/Functions%5FOverview#HEADING-48-7">Dylan</a> or <a href="http://www.cs.washington.edu/research/projects/cecil/www/cecil.html">Cecil</a>), as it is simply a convenient syntax for a call to specially named (but otherwise regular) method:</p> <pre><code>len(s) == s.__len__() </code></pre> <p>Also note, that this is single-dispatch only, that is, the actual receiver (<code>s</code> in the code above) determines the method implementation called. And even a hypothetical</p> <pre><code>def call_special(receiver, *args, **keys): return receiver.__call_special__(*args, **keys) </code></pre> <p>is still a single-dispatch function, as only the receiver is used when the method to be called is resolved. The remaining arguments are simply passed on, but they don't affect the method selection. </p> <p>This is different from multiple-dispatch, where there is no dedicated receiver, and all arguments are used in order to find the actual method implementation to call. This is, what actually makes the whole thing worthwhile. If it were only some odd kind of syntactic sugar, nobody would bother with using it, IMHO.</p> <pre><code>from peak.rules import abstract, when @abstract def serialize_object(object, target): pass @when(serialize_object, (MyStuff, BinaryStream)) def serialize_object(object, target): target.writeUInt32(object.identifier) target.writeString(object.payload) @when(serialize_object, (MyStuff, XMLStream)) def serialize_object(object, target): target.openElement("my-stuff") target.writeAttribute("id", str(object.identifier)) target.writeText(object.payload) target.closeElement() </code></pre> <p>In this example, a call like</p> <pre><code>serialize_object(MyStuff(10, "hello world"), XMLStream()) </code></pre> <p>considers <strong>both</strong> arguments in order to decide, which method must actually be called.</p> <p>For a nice usage scenario of generic functions in Python I'd recommend reading the refactored code of the <a href="http://svn.eby-sarna.com/PEAK/src/peak/security/"><code>peak.security</code></a> which gives a very elegant solution to access permission checking using generic functions (using <code>RuleDispatch</code>).</p>
7
2009-09-18T15:02:01Z
[ "python", "generics" ]
What is the best-maintained generic functions implementation for Python?
1,445,065
<p>A <a href="http://en.wikipedia.org/wiki/Generic%5Ffunctions">generic function</a> is dispatched based on the type of all its arguments. The programmer defines several implementations of a function. The correct one is chosen at call time based on the types of its arguments. This is useful for object adaptation among other things. Python has a few generic functions including <code>len()</code>.</p> <p>These packages tend to allow code that looks like this:</p> <pre><code>@when(int) def dumbexample(a): return a * 2 @when(list) def dumbexample(a): return [("%s" % i) for i in a] dumbexample(1) # calls first implementation dumbexample([1,2,3]) # calls second implementation </code></pre> <p>A less dumb example I've been thinking about lately would be a web component that requires a User. Instead of requiring a particular web framework, the integrator would just need to write something like:</p> <pre><code>class WebComponentUserAdapter(object): def __init__(self, guest): self.guest = guest def canDoSomething(self): return guest.member_of("something_group") @when(my.webframework.User) componentNeedsAUser(user): return WebComponentUserAdapter(user) </code></pre> <p>Python has a few generic functions implementations. Why would I chose one over the others? How is that implementation being used in applications?</p> <p>I'm familiar with Zope's <code>zope.component.queryAdapter(object, ISomething)</code>. The programmer registers a callable adapter that takes a particular class of object as its argument and returns something compatible with the interface. It's a useful way to allow plugins. Unlike monkey patching, it works even if an object needs to adapt to multiple interfaces with the same method names.</p>
7
2009-09-18T14:54:28Z
1,445,132
<p>You can use a construction like this:</p> <pre><code>def my_func(*args, **kwargs): pass </code></pre> <p>In this case args will be a list of any unnamed arguments, and kwargs will be a dictionary of the named ones. From here you can detect their types and act as appropriate.</p>
0
2009-09-18T15:04:21Z
[ "python", "generics" ]
What is the best-maintained generic functions implementation for Python?
1,445,065
<p>A <a href="http://en.wikipedia.org/wiki/Generic%5Ffunctions">generic function</a> is dispatched based on the type of all its arguments. The programmer defines several implementations of a function. The correct one is chosen at call time based on the types of its arguments. This is useful for object adaptation among other things. Python has a few generic functions including <code>len()</code>.</p> <p>These packages tend to allow code that looks like this:</p> <pre><code>@when(int) def dumbexample(a): return a * 2 @when(list) def dumbexample(a): return [("%s" % i) for i in a] dumbexample(1) # calls first implementation dumbexample([1,2,3]) # calls second implementation </code></pre> <p>A less dumb example I've been thinking about lately would be a web component that requires a User. Instead of requiring a particular web framework, the integrator would just need to write something like:</p> <pre><code>class WebComponentUserAdapter(object): def __init__(self, guest): self.guest = guest def canDoSomething(self): return guest.member_of("something_group") @when(my.webframework.User) componentNeedsAUser(user): return WebComponentUserAdapter(user) </code></pre> <p>Python has a few generic functions implementations. Why would I chose one over the others? How is that implementation being used in applications?</p> <p>I'm familiar with Zope's <code>zope.component.queryAdapter(object, ISomething)</code>. The programmer registers a callable adapter that takes a particular class of object as its argument and returns something compatible with the interface. It's a useful way to allow plugins. Unlike monkey patching, it works even if an object needs to adapt to multiple interfaces with the same method names.</p>
7
2009-09-18T14:54:28Z
1,445,246
<p>I'm unable to see the point in these "generic" functions. It sounds like simple polymorphism.</p> <p>Your "generic" features can be implemented like this without resorting to any run-time type identification. </p> <pre><code>class intWithDumbExample( int ): def dumbexample( self ): return self*2 class listWithDumbExmaple( list ): def dumpexample( self ): return [("%s" % i) for i in self] def dumbexample( a ): return a.dumbexample() </code></pre>
0
2009-09-18T15:23:24Z
[ "python", "generics" ]
Why can't a Python class definition assign a closure variable to itself?
1,445,207
<p>Why doesn't the following work in Python?</p> <pre><code>def make_class(a): class A(object): a=a return A </code></pre>
2
2009-09-18T15:17:37Z
1,445,230
<p>Both appear to work fine (in Python 2.5, at least):</p> <pre><code>&gt;&gt;&gt; def make_class(a): ... class A(object): ... _a = a ... return A ... &gt;&gt;&gt; make_class(10)._a 10 &gt;&gt;&gt; def make_class(b): ... class B(object): ... def get_b(self): ... return b ... return B ... &gt;&gt;&gt; make_class(10)().get_b() 10 </code></pre>
2
2009-09-18T15:21:22Z
[ "python", "closures" ]