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
sequence |
---|---|---|---|---|---|---|---|---|---|
Putting Copyright Symbol into a Python File | 221,376 | <p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="nofollow">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
| 11 | 2008-10-21T10:15:16Z | 1,235,665 | <p>For Python 2, the "right" thing to do is to specify the encoding, or never use non-ASCII characters. Specifying the encoding makes it simpler on the compiler and on humans. Sorry, but Python originally specified ASCII as the default, back in the Dark Ages.</p>
<p>For Python 3, UTF-8 is the default encoding, so you should be fine. In that case I would recommend not specifying the encoding if you use the default.</p>
<p>Whether a language allows/requires an encoding specification or not, in the age of Unicode this is an issue we need to keep in mind for every "text" file.</p>
| 1 | 2009-08-05T20:48:45Z | [
"python",
"encoding"
] |
Putting Copyright Symbol into a Python File | 221,376 | <p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="nofollow">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
| 11 | 2008-10-21T10:15:16Z | 19,210,542 | <p>Put this line at first:</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
| 1 | 2013-10-06T15:32:56Z | [
"python",
"encoding"
] |
Removing a sequence of characters from a large binary file using python | 221,386 | <p>I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?</p>
| 3 | 2008-10-21T10:21:46Z | 221,407 | <p>If two copies fit in memory, then you can easily make a copy. The second copy is the compressed version. Sure, you can use numpy, but you can also use the <a href="http://www.python.org/doc/2.5.2/lib/module-array.html" rel="nofollow">array</a> package. Additionally, you can treat your big binary object as a string of bytes and manipulate it directly. </p>
<p>It sounds like your file may be <em>REALLY</em> large, and you can't fit two copies into memory. (You didn't provide a lot of details, so this is just a guess.) You'll have to do your compression in chunks. You'll read in a chunk, do some processing on that chunk and write it out. Again, numpy, array or simple string of bytes will work fine.</p>
| 2 | 2008-10-21T10:33:57Z | [
"python",
"numpy",
"binaryfiles"
] |
Removing a sequence of characters from a large binary file using python | 221,386 | <p>I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?</p>
| 3 | 2008-10-21T10:21:46Z | 221,696 | <p>You need to make your question more precise. Do you know the values you want to trim ahead of time?</p>
<p>Assuming you do, I would probably search for the matching sections using <code>subprocess</code> to run "<code>fgrep -o -b <search string></code>" and then change the relevant sections of the file using the python <code>file</code> object's <code>seek</code>, <code>read</code> and <code>write</code> methods.</p>
| 0 | 2008-10-21T12:48:00Z | [
"python",
"numpy",
"binaryfiles"
] |
Removing a sequence of characters from a large binary file using python | 221,386 | <p>I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?</p>
| 3 | 2008-10-21T10:21:46Z | 221,851 | <p>If you don't have the memory to do <code>open("big.file").read()</code>, then numpy wont really help.. It uses the same memory as python variables do (if you have 1GB of RAM, you can only load 1GB of data into numpy)</p>
<p>The solution is simple - read the file in chunks.. <code>f = open("big.file", "rb")</code>, then do a series of <code>f.read(500)</code>, remove the sequence and write it back out to another file object. Pretty much how you do file reading/writing in C..</p>
<p>The problem then is if you miss the pattern you are replacing.. For example:</p>
<pre><code>target_seq = "567"
input_file = "1234567890"
target_seq.read(5) # reads 12345, doesn't contain 567
target_seq.read(5) # reads 67890, doesn't contain 567
</code></pre>
<p>The obvious solution is to start at the first character in the file, check <code>len(target_seq)</code> characters, then go forward one character, check forward again.</p>
<p>For example (pseudo code!):</p>
<pre><code>while cur_data != "":
seek_start = 0
chunk_size = len(target_seq)
input_file.seek(offset = seek_start, whence = 1) #whence=1 means seek from start of file (0 + offset)
cur_data = input_file.read(chunk_size) # reads 123
if target_seq == cur_data:
# Found it!
out_file.write("replacement_string")
else:
# not it, shove it in the new file
out_file.write(cur_data)
seek_start += 1
</code></pre>
<p>It's not exactly the most efficient way, but it will work, and not require keeping a copy of the file in memory (or two).</p>
| 4 | 2008-10-21T13:18:37Z | [
"python",
"numpy",
"binaryfiles"
] |
Removing a sequence of characters from a large binary file using python | 221,386 | <p>I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?</p>
| 3 | 2008-10-21T10:21:46Z | 1,008,370 | <p>dbr's solution is a good idea but a bit overly complicated all you really have to do is rewind the file pointer the length of the sequence you are searching for, before you read your next chunk.</p>
<pre><code>def ReplaceSequence(inFilename, outFilename, oldSeq, newSeq):
inputFile = open(inFilename, "rb")
outputFile = open(outFilename, "wb")
data = ""
chunk = 1024
while 1:
data = inputFile.read(chunk)
data = data.replace(oldSeq, newSeq)
outputFile.write(data)
inputFile.seek(-len(oldSequence), 1)
outputFile.seek(-len(oldSequence), 1)
if len(data) < chunk:
break
inputFile.close()
outputFile.close()
</code></pre>
| 1 | 2009-06-17T17:04:42Z | [
"python",
"numpy",
"binaryfiles"
] |
Removing a sequence of characters from a large binary file using python | 221,386 | <p>I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?</p>
| 3 | 2008-10-21T10:21:46Z | 1,008,461 | <p>This generator-based version will keep exactly one character of the file content in memory at a time.</p>
<p>Note that I am taking your question title quite literally - you want to reduce runs of the same <em>character</em> to a single character. For replacing patterns in general, this does not work:</p>
<pre><code>import StringIO
def gen_chars(stream):
while True:
ch = stream.read(1)
if ch:
yield ch
else:
break
def gen_unique_chars(stream):
lastchar = ''
for char in gen_chars(stream):
if char != lastchar:
yield char
lastchar=char
def remove_seq(infile, outfile):
for ch in gen_unique_chars(infile):
outfile.write(ch)
# Represents a file open for reading
infile = StringIO.StringIO("1122233333444555")
# Represents a file open for writing
outfile = StringIO.StringIO()
# Will print "12345"
remove_seq(infile, outfile)
outfile.seek(0)
print outfile.read()
</code></pre>
| 0 | 2009-06-17T17:23:38Z | [
"python",
"numpy",
"binaryfiles"
] |
Removing a sequence of characters from a large binary file using python | 221,386 | <p>I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?</p>
| 3 | 2008-10-21T10:21:46Z | 13,611,980 | <p>AJMayorga suggestion is fine unless the sizes of the replacement strings are different. Or the replacement string is at the end of the chunk.</p>
<p>I fixed it like this:</p>
<pre><code>def ReplaceSequence(inFilename, outFilename, oldSeq, newSeq):
inputFile = open(inFilename, "rb")
outputFile = open(outFilename, "wb")
data = ""
chunk = 1024
oldSeqLen = len(oldSeq)
while 1:
data = inputFile.read(chunk)
dataSize = len(data)
seekLen= dataSize - data.rfind(oldSeq) - oldSeqLen
if seekLen > oldSeqLen:
seekLen = oldSeqLen
data = data.replace(oldSeq, newSeq)
outputFile.write(data)
inputFile.seek(-seekLen, 1)
outputFile.seek(-seekLen, 1)
if dataSize < chunk:
break
inputFile.close()
outputFile.close()
</code></pre>
| 1 | 2012-11-28T18:30:10Z | [
"python",
"numpy",
"binaryfiles"
] |
Is it possible to set a timeout on a socket in Twisted? | 221,745 | <p>I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks</p>
| 8 | 2008-10-21T12:56:32Z | 221,832 | <p>Since Twisted is event driven, you don't need a timeout per se. You simply need to set a state variable (like datagramRecieved) when you receive a datagram and register a <a href="http://twistedmatrix.com/projects/core/documentation/howto/time.html" rel="nofollow">looping call</a> that checks the state variable, stops the reactor if appropriate then clears state variable:</p>
<pre><code>from twisted.internet import task
from twisted.internet import reactor
datagramRecieved = False
timeout = 1.0 # One second
# UDP code here
def testTimeout():
global datagramRecieved
if not datagramRecieved:
reactor.stop()
datagramRecieved = False
l = task.LoopingCall(testTimeout)
l.start(timeout) # call every second
# l.stop() will stop the looping calls
reactor.run()
</code></pre>
| 5 | 2008-10-21T13:15:01Z | [
"python",
"networking",
"sockets",
"twisted"
] |
Is it possible to set a timeout on a socket in Twisted? | 221,745 | <p>I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks</p>
| 8 | 2008-10-21T12:56:32Z | 251,302 | <p>I think <code>reactor.callLater</code> would work better than <code>LoopingCall</code>. Something like this:</p>
<pre><code>class Protocol(DatagramProtocol):
def __init__(self, timeout):
self.timeout = timeout
def datagramReceived(self, datagram):
self.timeout.cancel()
# ...
timeout = reactor.callLater(5, timedOut)
reactor.listenUDP(Protocol(timeout))
</code></pre>
| 13 | 2008-10-30T18:52:01Z | [
"python",
"networking",
"sockets",
"twisted"
] |
Is it possible to set a timeout on a socket in Twisted? | 221,745 | <p>I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks</p>
| 8 | 2008-10-21T12:56:32Z | 11,810,177 | <p>with reactor we must use callLater.
Start timeout countdown when connectionMade.
Reset timeout countdown when lineReceived.</p>
<p>Here's the </p>
<pre><code># -*- coding: utf-8 -*-
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor, defer
_timeout = 27
class ServiceProtocol(LineReceiver):
def __init__(self, users):
self.users = users
def connectionLost(self, reason):
if self.users.has_key(self.name):
del self.users[self.name]
def timeOut(self):
if self.users.has_key(self.name):
del self.users[self.name]
self.sendLine("\nOUT: 9 - Disconnected, reason: %s" % 'Connection Timed out')
print "%s - Client disconnected: %s. Reason: %s" % (datetime.now(), self.client_ip, 'Connection Timed out' )
self.transport.loseConnection()
def connectionMade(self):
self.timeout = reactor.callLater(_timeout, self.timeOut)
self.sendLine("\nOUT: 7 - Welcome to CAED")
def lineReceived(self, line):
# a simple timeout procrastination
self.timeout.reset(_timeout)
class ServFactory(Factory):
def __init__(self):
self.users = {} # maps user names to Chat instances
def buildProtocol(self, addr):
return ServiceProtocol(self.users)
port = 8123
reactor.listenTCP(port, ServFactory())
print "Started service at port %d\n" % port
reactor.run()
</code></pre>
| 3 | 2012-08-04T16:26:20Z | [
"python",
"networking",
"sockets",
"twisted"
] |
Is it possible to set a timeout on a socket in Twisted? | 221,745 | <p>I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks</p>
| 8 | 2008-10-21T12:56:32Z | 24,895,751 | <p>A better way to do this is with <code>twisted.protocols.policies.TimeoutMixin</code>. It's essentially doing a <code>callLater</code> but abstracted into a <code>Mixin</code>.</p>
| 0 | 2014-07-22T19:09:07Z | [
"python",
"networking",
"sockets",
"twisted"
] |
Best approach with dynamic classes using Python globals() | 222,133 | <p>I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output.</p>
<p>Pulling the class dynamically from the global namespace works:</p>
<pre><code>result = globals()[classname](param).html
</code></pre>
<p>And it's certainly more succinct than:</p>
<pre><code>if classname == 'Foo':
result = Foo(param).html
elif classname == 'Bar':
...
</code></pre>
<p>What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?</p>
| 6 | 2008-10-21T14:41:54Z | 222,307 | <p>First of all, it sounds like you may be reinventing the wheel a little bit... most Python web frameworks (CherryPy/TurboGears is what I know) already include a way to dispatch requests to specific classes based on the contents of the URL, or the user input.</p>
<p>There is nothing <strong>wrong</strong> with the way that you do it, really, but in my experience it tends to indicate some kind of "missing abstraction" in your program. You're basically relying on the Python interpreter to store a list of the objects you might need, rather than storing it yourself.</p>
<p>So, as a first step, you might want to just make a dictionary of all the classes that you might want to call:</p>
<pre><code>dispatch = {'Foo': Foo, 'Bar': Bar, 'Bizbaz': Bizbaz}
</code></pre>
<p>Initially, this won't make much of a difference. But as your web app grows, you may find several advantages: (a) you won't run into namespace clashes, (b) using <code>globals()</code> you may have security issues where an attacker can, in essence, access any global symbol in your program if they can find a way to inject an arbitrary <code>classname</code> into your program, (c) if you ever want to have <code>classname</code> be something other than the actual exact classname, using your own dictionary will be more flexible, (d) you can replace the <code>dispatch</code> dictionary with a more-flexible user-defined class that does database access or something like that if you find the need.</p>
<p>The security issues are particularly salient for a web app. Doing <code>globals()[variable]</code> where <code>variable</code> is input from a web form is just <strong>asking for trouble</strong>.</p>
| 4 | 2008-10-21T15:32:59Z | [
"python",
"coding-style",
"namespaces"
] |
Best approach with dynamic classes using Python globals() | 222,133 | <p>I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output.</p>
<p>Pulling the class dynamically from the global namespace works:</p>
<pre><code>result = globals()[classname](param).html
</code></pre>
<p>And it's certainly more succinct than:</p>
<pre><code>if classname == 'Foo':
result = Foo(param).html
elif classname == 'Bar':
...
</code></pre>
<p>What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?</p>
| 6 | 2008-10-21T14:41:54Z | 222,334 | <p>A flaw with this approach is that it may give the user the ability to to more than you want them to. They can call <em>any</em> single-parameter function in that namespace just by providing the name. You can help guard against this with a few checks (eg. isinstance(SomeBaseClass, theClass), but its probably better to avoid this approach. Another disadvantage is that it constrains your class placement. If you end up with dozens of such classes and decide to group them into modules, your lookup code will stop working.</p>
<p>You have several alternative options:</p>
<ol>
<li><p>Create an explicit mapping:</p>
<pre><code> class_lookup = {'Class1' : Class1, ... }
...
result = class_lookup[className](param).html
</code></pre>
<p>though this has the disadvantage that you have to re-list all the classes.</p></li>
<li><p>Nest the classes in an enclosing scope. Eg. define them within their own module, or within an outer class:</p>
<pre><code>class Namespace(object):
class Class1(object):
...
class Class2(object):
...
...
result = getattr(Namespace, className)(param).html
</code></pre>
<p>You do inadvertantly expose a couple of additional class variables here though (__bases__, __getattribute__ etc) - probably not exploitable, but not perfect.</p></li>
<li><p>Construct a lookup dict from the subclass tree. Make all your classes inherit from a single baseclass. When all classes have been created, examine all baseclasses and populate a dict from them. This has the advantage that you can define your classes anywhere (eg. in seperate modules), and so long as you create the registry after all are created, you will find them.</p>
<pre><code>def register_subclasses(base):
d={}
for cls in base.__subclasses__():
d[cls.__name__] = cls
d.update(register_subclasses(cls))
return d
class_lookup = register_subclasses(MyBaseClass)
</code></pre>
<p>A more advanced variation on the above is to use self-registering classes - create a metaclass than automatically registers any created classes in a dict. This is probably overkill for this case - its useful in some "user-plugins" scenarios though.</p></li>
</ol>
| 6 | 2008-10-21T15:43:46Z | [
"python",
"coding-style",
"namespaces"
] |
Best approach with dynamic classes using Python globals() | 222,133 | <p>I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output.</p>
<p>Pulling the class dynamically from the global namespace works:</p>
<pre><code>result = globals()[classname](param).html
</code></pre>
<p>And it's certainly more succinct than:</p>
<pre><code>if classname == 'Foo':
result = Foo(param).html
elif classname == 'Bar':
...
</code></pre>
<p>What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?</p>
| 6 | 2008-10-21T14:41:54Z | 224,641 | <p>Another way to build the map between class names and classes:</p>
<p>When defining classes, add an attribute to any class that you want to put in the lookup table, e.g.:</p>
<pre><code>class Foo:
lookup = True
def __init__(self, params):
# and so on
</code></pre>
<p>Once this is done, building the lookup map is:</p>
<pre><code>class_lookup = zip([(c, globals()[c]) for c in dir() if hasattr(globals()[c], "lookup")])
</code></pre>
| 0 | 2008-10-22T06:18:41Z | [
"python",
"coding-style",
"namespaces"
] |
ElementTree XPath - Select Element based on attribute | 222,375 | <p>I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the <a href="http://effbot.org/zone/element-xpath.htm">Documentation</a></p>
<p>Here's some sample code</p>
<p><strong>XML</strong></p>
<pre><code><root>
<target name="1">
<a></a>
<b></b>
</target>
<target name="2">
<a></a>
<b></b>
</target>
</root>
</code></pre>
<p><strong>Python</strong></p>
<pre><code>def parse(document):
root = et.parse(document)
for target in root.findall("//target[@name='a']"):
print target._children
</code></pre>
<p>I am receiving the following Exception:</p>
<pre><code>expected path separator ([)
</code></pre>
| 34 | 2008-10-21T15:52:51Z | 222,466 | <p>Looks like findall only supports a subset XPath. See the mailing list discussion <a href="http://codespeak.net/pipermail/lxml-dev/2006-May/001294.html" rel="nofollow">here</a></p>
| 3 | 2008-10-21T16:14:28Z | [
"python",
"elementtree"
] |
ElementTree XPath - Select Element based on attribute | 222,375 | <p>I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the <a href="http://effbot.org/zone/element-xpath.htm">Documentation</a></p>
<p>Here's some sample code</p>
<p><strong>XML</strong></p>
<pre><code><root>
<target name="1">
<a></a>
<b></b>
</target>
<target name="2">
<a></a>
<b></b>
</target>
</root>
</code></pre>
<p><strong>Python</strong></p>
<pre><code>def parse(document):
root = et.parse(document)
for target in root.findall("//target[@name='a']"):
print target._children
</code></pre>
<p>I am receiving the following Exception:</p>
<pre><code>expected path separator ([)
</code></pre>
| 34 | 2008-10-21T15:52:51Z | 222,473 | <p>The syntax you're trying to use is new in <strong><a href="http://effbot.org/zone/element-xpath.htm">ElementTree 1.3</a></strong>.</p>
<p>Such version is shipped with <strong>Python 2.7</strong> or higher.
If you have Python 2.6 or less you still have ElementTree 1.2.6 or less.</p>
| 32 | 2008-10-21T16:16:06Z | [
"python",
"elementtree"
] |
ElementTree XPath - Select Element based on attribute | 222,375 | <p>I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the <a href="http://effbot.org/zone/element-xpath.htm">Documentation</a></p>
<p>Here's some sample code</p>
<p><strong>XML</strong></p>
<pre><code><root>
<target name="1">
<a></a>
<b></b>
</target>
<target name="2">
<a></a>
<b></b>
</target>
</root>
</code></pre>
<p><strong>Python</strong></p>
<pre><code>def parse(document):
root = et.parse(document)
for target in root.findall("//target[@name='a']"):
print target._children
</code></pre>
<p>I am receiving the following Exception:</p>
<pre><code>expected path separator ([)
</code></pre>
| 34 | 2008-10-21T15:52:51Z | 16,105,230 | <p>There are several problems in this code.</p>
<ol>
<li><p>Python's buildin ElementTree (ET for short) has no real XPATH support; only a limited subset By example, it doesn't support <em>find-from-root</em> expressions like <code>//target</code>. </p>
<p>Notice: the <a href="http://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax">documentation</a>
mentions "<strong>//</strong>", but only for children: So an expression as
<code>.//target</code> is valid; <code>//...</code> is not!</p>
<p>There is an alternative implementation: <a href="http://lxml.de"><strong>lxml</strong></a> which is more rich. It's seams that documentation is used, for the build-in code. That does not match/work.</p></li>
<li><p>The <code>@name</code> notation selects xml-<strong>attributes</strong>; the <code>key=value</code> expression within an xml-tag.</p>
<p>So that name-value has to be 1 or 2 to select something in the given document. Or, one can search for targets with a child <strong>element</strong> <em>'a'</em>: <code>target[a]</code> (no @).</p></li>
</ol>
<p>For the given document, parsed with the build-in ElementTree (v1.3) to root, the following code is correct and working:</p>
<ul>
<li><code>root.findall(".//target")</code> Find both targets</li>
<li><code>root.findall(".//target/a")</code> Find two a-element</li>
<li><code>root.findall(".//target[a]")</code> This finds both target-element again, as both have an a-element</li>
<li><code>root.findall(".//target[@name='1']")</code> Find only the <em>first</em> target. Notice the quotes around 1 are needed; else a SyntaxError is raised</li>
<li><code>root.findall(".//target[a][@name='1']")</code> Also valid; to find that target</li>
<li><code>root.findall(".//target[@name='1']/a")</code> Finds only one a-element; ...</li>
</ul>
| 8 | 2013-04-19T13:00:16Z | [
"python",
"elementtree"
] |
How to script Visual Studio 2008 from Python? | 222,450 | <p>I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use <code>win32com.client.Dispatch</code>. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:</p>
<pre><code>import win32com.client
app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok
app2 = win32com.client.Dispatch( 'Word.Application' ) # ok
app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error
</code></pre>
<p>Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?</p>
| 7 | 2008-10-21T16:08:55Z | 222,459 | <p>You can try <em>.Net</em>'s own version, <a href="http://www.codeplex.com/ironpython" rel="nofollow">IronPython</a>.
It has a <em>VS</em> addon, <a href="http://www.codeplex.com/IronPythonStudio" rel="nofollow">IronPythonStudio</a>.</p>
<p>Being a <em>.Net</em> language, you can access all the available assemblies, including <a href="http://msdn.microsoft.com/en-us/office/aa905533.aspx" rel="nofollow">Visual Studio Tools for Office</a>.</p>
| 2 | 2008-10-21T16:12:04Z | [
"python",
"visual-studio",
"visual-studio-2008",
"visual-c++"
] |
How to script Visual Studio 2008 from Python? | 222,450 | <p>I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use <code>win32com.client.Dispatch</code>. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:</p>
<pre><code>import win32com.client
app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok
app2 = win32com.client.Dispatch( 'Word.Application' ) # ok
app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error
</code></pre>
<p>Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?</p>
| 7 | 2008-10-21T16:08:55Z | 223,002 | <p>Depending on what exactly you're trying to do, <a href="http://www.autoitscript.com/autoit3/index.shtml" rel="nofollow">AutoIt</a> may meet your needs. In fact, I'm sure it will do anything you need it to do.</p>
<p>Taken from my <a href="http://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python#155587">other post</a> about how to use AutoIt with Python:</p>
<pre><code>import win32com.client
oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" )
oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title
width = oAutoItX.WinGetClientSizeWidth("Firefox")
height = oAutoItX.WinGetClientSizeHeight("Firefox")
print width, height
</code></pre>
<p>You can of course use any of the <a href="http://www.autoitscript.com/autoit3/docs/functions.htm" rel="nofollow">AutoItX functions</a> (note that that link goes to the AutoIt function reference, the com version of AutoIt - AutoItX has a subset of that list...the documentation is included in the download) in this way. I don't know what you're wanting to do, so I can't point you towards the appropriate functions, but this should get you started.</p>
| 3 | 2008-10-21T18:49:14Z | [
"python",
"visual-studio",
"visual-studio-2008",
"visual-c++"
] |
How to script Visual Studio 2008 from Python? | 222,450 | <p>I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use <code>win32com.client.Dispatch</code>. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:</p>
<pre><code>import win32com.client
app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok
app2 = win32com.client.Dispatch( 'Word.Application' ) # ok
app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error
</code></pre>
<p>Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?</p>
| 7 | 2008-10-21T16:08:55Z | 223,886 | <p>I don't know if this will help you with 2008, but with Visual Studio 2005 and win32com I'm able to do this:</p>
<pre><code>>>> import win32com.client
>>> b = win32com.client.Dispatch('VisualStudio.DTE')
>>> b
<COMObject VisualStudio.DTE>
>>> b.name
u'Microsoft Visual Studio'
>>> b.Version
u'8.0'
</code></pre>
<p>Unfortunately I don't have 2008 to test with though.</p>
| 3 | 2008-10-21T23:08:12Z | [
"python",
"visual-studio",
"visual-studio-2008",
"visual-c++"
] |
How to script Visual Studio 2008 from Python? | 222,450 | <p>I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use <code>win32com.client.Dispatch</code>. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:</p>
<pre><code>import win32com.client
app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok
app2 = win32com.client.Dispatch( 'Word.Application' ) # ok
app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error
</code></pre>
<p>Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?</p>
| 7 | 2008-10-21T16:08:55Z | 982,565 | <p>ryan_s has the right answer. You might rethink using win32com.</p>
<p>I prefer the comtypes module to win32com. It fits in better with ctypes and python in general.</p>
<p>Using either approach with vs 2008 will work. Here is an example that prints the names and keyboard shortcuts for all the commands in Visual Studio.</p>
<pre><code>import comtypes.client as client
vs = client.CreateObject('VisualStudio.DTE')
commands = [command for command in vs.Commands if bool(command.Name) or bool(command.Bindings)]
commands.sort(key=lambda cmd : cmd.Name)
f= open('bindings.csv','w')
for command in commands:
f.write(command.Name+"," +";".join(command.Bindings)+ "\n")
f.close()
</code></pre>
| 3 | 2009-06-11T17:42:16Z | [
"python",
"visual-studio",
"visual-studio-2008",
"visual-c++"
] |
How to script Visual Studio 2008 from Python? | 222,450 | <p>I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use <code>win32com.client.Dispatch</code>. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:</p>
<pre><code>import win32com.client
app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok
app2 = win32com.client.Dispatch( 'Word.Application' ) # ok
app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error
</code></pre>
<p>Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?</p>
| 7 | 2008-10-21T16:08:55Z | 20,095,416 | <p>As of year 2013, better option can be to script <code>Visual Studio</code> via <code>IronPython</code> cause better <code>CLR</code>/<code>COM</code> and other MS stuff integration:</p>
<pre><code>
import clr
import System
t = System.Type.GetTypeFromProgID("AutoItX3.Control")
oAutoItX = System.Activator.CreateInstance(t)
oAutoItX.Opt("WinTitleMatchMode", 2)
width = oAutoItX.WinGetClientSizeWidth("IronPythonApplication1 - Microsoft Visual Studio (Administrator)")
height = oAutoItX.WinGetClientSizeHeight("IronPythonApplication1 - Microsoft Visual Studio (Administrator)")
print width, height
</code></pre>
| 0 | 2013-11-20T12:00:39Z | [
"python",
"visual-studio",
"visual-studio-2008",
"visual-c++"
] |
What is the meaning of '(?i)password' in python regular expression? | 222,536 | <p>Pexpect can be used to automate tasks in python (does not need TCL to be installed). One of the simplest routines of this class is the 'run()' routine. It accepts a dictionary of expected question patterns as keys and the responses as values. For example</p>
<p>pexpect.run ('scp foo [email protected]:.', events={'(?i)password': mypassword})</p>
<p>I know that usually '?' is used to indicate 0 or 1 occurrences of previous literal in the string (for regular expressions that is). However, over here, this does not seem to be the meaning. </p>
<p>Can experts comment on what is it?</p>
| 4 | 2008-10-21T16:29:51Z | 222,556 | <p><a href="https://docs.python.org/library/re.html#regular-expression-syntax" rel="nofollow">https://docs.python.org/library/re.html#regular-expression-syntax</a></p>
<blockquote>
<p>(?...) This is an extension
notation (a "?" following a "(" is not
meaningful otherwise). The first
character after the "?" determines
what the meaning and further syntax of
the construct is. Extensions usually
do not create a new group;
(?P...) is the only exception to
this rule. Following are the currently
supported extensions. </p>
<p>(?iLmsux) (One or more letters from
the set "i", "L", "m", "s", "u", "x".)
The group matches the empty string;
the letters set the corresponding
flags (re.I, re.L, re.M, re.S, re.U,
re.X) for the entire regular
expression. This is useful if you wish
to include the flags as part of the
regular expression, instead of passing
a flag argument to the compile()
function.</p>
<p>Note that the (?x) flag changes how
the expression is parsed. It should be
used first in the expression string,
or after one or more whitespace
characters. If there are
non-whitespace characters before the
flag, the results are undefined.</p>
</blockquote>
<p>So in this case the string is a regular expression, and is set to be case-insensitive.</p>
| 7 | 2008-10-21T16:34:50Z | [
"python",
"regex",
"pattern-matching"
] |
What is the meaning of '(?i)password' in python regular expression? | 222,536 | <p>Pexpect can be used to automate tasks in python (does not need TCL to be installed). One of the simplest routines of this class is the 'run()' routine. It accepts a dictionary of expected question patterns as keys and the responses as values. For example</p>
<p>pexpect.run ('scp foo [email protected]:.', events={'(?i)password': mypassword})</p>
<p>I know that usually '?' is used to indicate 0 or 1 occurrences of previous literal in the string (for regular expressions that is). However, over here, this does not seem to be the meaning. </p>
<p>Can experts comment on what is it?</p>
| 4 | 2008-10-21T16:29:51Z | 222,586 | <p>This is an extension in the regular expression syntax in the re module of Python. The "i" means "ignore case". This means a case insensitive search for "password" is done.</p>
<p>from <a href="https://docs.python.org/library/re.html#regular-expression-syntax" rel="nofollow">https://docs.python.org/library/re.html#regular-expression-syntax</a></p>
<blockquote>
<p>(?iLmsux)
(One or more letters from the set "i", "L", "m", "s", "u", "x".) The
group matches the empty string; the
letters set the corresponding flags
(re.I, re.L, re.M, re.S, re.U, re.X)
for the entire regular expression.
This is useful if you wish to include
the flags as part of the regular
expression, instead of passing a flag
argument to the compile() function.</p>
<p>Note that the (?x) flag changes how the expression is parsed. It
should be used first in the expression
string, or after one or more
whitespace characters. If there are
non-whitespace characters before the
flag, the results are undefined.</p>
</blockquote>
| 4 | 2008-10-21T16:43:07Z | [
"python",
"regex",
"pattern-matching"
] |
cherrypy not closing the sockets | 222,736 | <p>I am using cherrypy as a webserver. It gives good performance for my application but there is a very big problem with it. cherrypy crashes after couple of hours stating that it could not create a socket as there are too many files open:</p>
<pre><code>[21/Oct/2008:12:44:25] ENGINE HTTP Server
cherrypy._cpwsgi_server.CPWSGIServer(('0.0.0.0', 8080)) shut down
[21/Oct/2008:12:44:25] ENGINE Stopped thread '_TimeoutMonitor'.
[21/Oct/2008:12:44:25] ENGINE Stopped thread 'Autoreloader'.
[21/Oct/2008:12:44:25] ENGINE Bus STOPPED
[21/Oct/2008:12:44:25] ENGINE Bus EXITING
[21/Oct/2008:12:44:25] ENGINE Bus EXITED
Exception in thread HTTPServer Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.3/threading.py", line 436, in __bootstrap
self.run()
File "/usr/lib/python2.3/threading.py", line 416, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.3/site-packages/cherrypy/process/servers.py", line 73, in
_start_http_thread
self.httpserver.start()
File "/usr/lib/python2.3/site-packages/cherrypy/wsgiserver/__init__.py", line 1388, in start
self.tick()
File "/usr/lib/python2.3/site-packages/cherrypy/wsgiserver/__init__.py", line 1417, in tick
s, addr = self.socket.accept()
File "/usr/lib/python2.3/socket.py", line 167, in accept
sock, addr = self._sock.accept()
error: (24, 'Too many open files')
[21/Oct/2008:12:44:25] ENGINE Waiting for child threads to terminate..
</code></pre>
<p>I tried to figure out what was happening. My application does not open any file or any socket etc. My file only opens couple of berkeley dbs. I investigated this issue further. I saw the file descriptors used by my cherrypy process with id 4536 in /proc/4536/fd/
Initially there were new sockets created and cleaned up properly but after an hour I found that it had about 509 sockets that were not cleaned. All the sockets were in CLOSE_WAIT state. I got this information using the following command:</p>
<pre><code>netstat -ap | grep "4536" | grep CLOSE_WAIT | wc -l
</code></pre>
<p>CLOSE_WAIT state means that the remote client has closed the connection. Why is cherrypy then not closing the socket and free the file descriptors? What can I do to resolve the problem? </p>
<p>I tried to play with the following:</p>
<pre><code>cherrypy.config.update({'server.socketQueueSize': '10'})
</code></pre>
<p>I thought that this would restrict the number of sockets open at any time to 10 but it was not effective at all. This is the only config I have set, so , rest of the configs hold their default values.</p>
<p>Could somebody throw light on this? Do you think its a bug in cherrypy? How can I resolve it? Is there a way I can close these sockets myself?</p>
<p>Following is my systems info:</p>
<p>CherryPy-3.1.0</p>
<p>python 2.3.4 </p>
<p>Red Hat Enterprise Linux ES release 4 (Nahant Update 7)</p>
<p>Thanks in advance!</p>
| 2 | 2008-10-21T17:33:26Z | 223,137 | <p>I imagine you're storing (in-memory) some piece of data which has a reference to the socket; if you store the request objects anywhere, for instance, that would likely do it.</p>
<p>The last-ditch chance for sockets to be closed is when they're garbage-collected; if you're doing anything that would prevent garbage collection from reaching them, there's your problem. I suggest that you try to reproduce with a Hello World program written in CherryPy; if you can't reproduce there, you know it's in your code -- look for places where you're persisting information which could (directly or otherwise) reference the socket.</p>
| 4 | 2008-10-21T19:22:18Z | [
"python",
"sockets",
"cherrypy"
] |
Sorting a tuple that contains tuples | 222,752 | <p>I have the following tuple, which contains tuples:</p>
<pre><code>MY_TUPLE = (
('A','Apple'),
('C','Carrot'),
('B','Banana'),
)
</code></pre>
<p>I'd like to sort this tuple based upon the <strong>second</strong> value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).</p>
<p>Any thoughts?</p>
| 12 | 2008-10-21T17:40:51Z | 222,762 | <pre><code>from operator import itemgetter
MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))
</code></pre>
<p>or without <code>itemgetter</code>:</p>
<pre><code>MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
</code></pre>
| 21 | 2008-10-21T17:44:08Z | [
"python",
"sorting",
"tuples"
] |
Sorting a tuple that contains tuples | 222,752 | <p>I have the following tuple, which contains tuples:</p>
<pre><code>MY_TUPLE = (
('A','Apple'),
('C','Carrot'),
('B','Banana'),
)
</code></pre>
<p>I'd like to sort this tuple based upon the <strong>second</strong> value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).</p>
<p>Any thoughts?</p>
| 12 | 2008-10-21T17:40:51Z | 222,769 | <pre><code>sorted(my_tuple, key=lambda tup: tup[1])
</code></pre>
<p>In other words, when comparing two elements of the tuple you're sorting, sort based on the return value of the function passed as the key parameter.</p>
| 2 | 2008-10-21T17:45:12Z | [
"python",
"sorting",
"tuples"
] |
Sorting a tuple that contains tuples | 222,752 | <p>I have the following tuple, which contains tuples:</p>
<pre><code>MY_TUPLE = (
('A','Apple'),
('C','Carrot'),
('B','Banana'),
)
</code></pre>
<p>I'd like to sort this tuple based upon the <strong>second</strong> value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).</p>
<p>Any thoughts?</p>
| 12 | 2008-10-21T17:40:51Z | 222,776 | <p>From <a href="http://wiki.python.org/moin/HowTo/Sorting#head-d121eed08556ad7cb2a02a886788656dadb709bd">Sorting Mini-HOW TO</a></p>
<blockquote>
<p>Often there's a built-in that will
match your needs, such as str.lower().
The operator module contains a number
of functions useful for this purpose.
For example, you can sort tuples based
on their second element using
operator.itemgetter():</p>
</blockquote>
<pre><code>>>> import operator
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
>>> map(operator.itemgetter(1), L)
[2, 1, 4, 3]
>>> sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
</code></pre>
<p>Hope this helps.</p>
| 7 | 2008-10-21T17:45:56Z | [
"python",
"sorting",
"tuples"
] |
Sorting a tuple that contains tuples | 222,752 | <p>I have the following tuple, which contains tuples:</p>
<pre><code>MY_TUPLE = (
('A','Apple'),
('C','Carrot'),
('B','Banana'),
)
</code></pre>
<p>I'd like to sort this tuple based upon the <strong>second</strong> value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).</p>
<p>Any thoughts?</p>
| 12 | 2008-10-21T17:40:51Z | 222,789 | <p>I achieved the same thing using this code, but your suggestion is great. Thanks!</p>
<pre><code>templist = [ (line[1], line) for line in MY_TUPLE ]
templist.sort()
SORTED_MY_TUPLE = [ line[1] for line in templist ]
</code></pre>
| -2 | 2008-10-21T17:52:01Z | [
"python",
"sorting",
"tuples"
] |
How to use 'super' in Python? | 222,877 | <p>Can someone explain to me the difference between doing:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
</code></pre>
<p>and this:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
</code></pre>
<p>I've seen <code>super</code> being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.</p>
| 221 | 2008-10-21T18:13:15Z | 222,922 | <p>The benefits of <code>super()</code> in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.</p>
<p>However, it's almost impossible to use multiple-inheritance without <code>super()</code>. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended <code>Child</code> and a mixin, their code would not work properly.</p>
| 156 | 2008-10-21T18:24:50Z | [
"python",
"inheritance",
"super"
] |
How to use 'super' in Python? | 222,877 | <p>Can someone explain to me the difference between doing:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
</code></pre>
<p>and this:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
</code></pre>
<p>I've seen <code>super</code> being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.</p>
| 221 | 2008-10-21T18:13:15Z | 224,020 | <p>Doesn't all of this assume that the base class is inherited from <code>object</code>?</p>
<pre><code>class A:
def __init__(self):
print "A.__init__()"
class B(A):
def __init__(self):
print "B.__init__()"
super(B, self).__init__()
</code></pre>
<p>Will not work. <code>class A</code> must be derived from <code>object</code>, i.e: <code>class A(object)</code></p>
| 23 | 2008-10-22T00:06:32Z | [
"python",
"inheritance",
"super"
] |
How to use 'super' in Python? | 222,877 | <p>Can someone explain to me the difference between doing:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
</code></pre>
<p>and this:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
</code></pre>
<p>I've seen <code>super</code> being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.</p>
| 221 | 2008-10-21T18:13:15Z | 33,469,090 | <blockquote>
<p>Can someone explain to me the difference between doing:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
</code></pre>
<p>and this:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
</code></pre>
</blockquote>
<h1>Indirection with Forward Compatibility</h1>
<p>What does it give you? For single inheritance, the above is practically identical from a static analysis point of view. However, using <code>super</code> gives you a layer of indirection with forward compatibility.</p>
<p>Forward compatibility is very important to seasoned developers. You want your code to keep working with minimal changes as you change it. When you look at your revision history, you want to see precisely what changed when. </p>
<p>You may start off with single inheritance, but if you decide to add another base class, you only have to change the line with the bases - if the bases change in a class you inherit from (say a mixin is added) you'd change nothing in this class. Particularly in Python 2, getting the arguments to super and the correct method arguments right can be difficult. If you know you're using <code>super</code> correctly with single inheritance, that makes debugging less difficult going forward.</p>
<h1>Dependency Injection</h1>
<p>Other people can use your code and inject parents into the method resolution:</p>
<pre><code>class SomeBaseClass(object):
def __init__(self):
print('SomeBaseClass.__init__(self) called')
class UnsuperChild(SomeBaseClass):
def __init__(self):
print('Child.__init__(self) called')
SomeBaseClass.__init__(self)
class SuperChild(SomeBaseClass):
def __init__(self):
print('SuperChild.__init__(self) called')
super(SuperChild, self).__init__()
</code></pre>
<p>Say you add another class to your object, and want to inject a class between Foo and Bar (for testing or some other reason):</p>
<pre><code>class InjectMe(SomeBaseClass):
def __init__(self):
print('InjectMe.__init__(self) called')
super(InjectMe, self).__init__()
class UnsuperInjector(UnsuperChild, InjectMe): pass
class SuperInjector(SuperChild, InjectMe): pass
</code></pre>
<p>Using the un-super child fails to inject the dependency because the child you're using has hard-coded the method to be called after its own:</p>
<pre><code>>>> o = UnsuperInjector()
UnsuperChild.__init__(self) called
SomeBaseClass.__init__(self) called
</code></pre>
<p>However, the class with the child that uses <code>super</code> can correctly inject the dependency:</p>
<pre><code>>>> o2 = SuperInjector()
SuperChild.__init__(self) called
InjectMe.__init__(self) called
SomeBaseClass.__init__(self) called
</code></pre>
<h2>Conclusion</h2>
<p>Always use <code>super</code> to reference the parent class. </p>
<p>What you intend is to reference the parent class that is next-in-line, not specifically the one you see the child inheriting from.</p>
<p>Not using <code>super</code> can put unnecessary constraints on users of your code.</p>
| 41 | 2015-11-02T00:53:24Z | [
"python",
"inheritance",
"super"
] |
How to use 'super' in Python? | 222,877 | <p>Can someone explain to me the difference between doing:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
</code></pre>
<p>and this:</p>
<pre><code>class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
</code></pre>
<p>I've seen <code>super</code> being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.</p>
| 221 | 2008-10-21T18:13:15Z | 39,376,081 | <p>When calling <code>super()</code> to resolve to a parent's version of a classmethod, instance method, or staticmethod, we want to pass the current class whose scope we are in as the first argument, to indicate which parent's scope we're trying to resolve to, and as a second argument the object of interest to indicate which object we're trying to apply that scope to.</p>
<p>Consider a class hierarchy <code>A</code>, <code>B</code>, and <code>C</code> where each class is the parent of the one following it, and <code>a</code>, <code>b</code>, and <code>c</code> respective instances of each.</p>
<pre><code>super(B, b)
# resolves to the scope of B's parent i.e. A
# and applies that scope to b, as if b was an instance of A
super(C, c)
# resolves to the scope of C's parent i.e. B
# and applies that scope to c
super(B, c)
# resolves to the scope of B's parent i.e. A
# and applies that scope to c
</code></pre>
<h2>Using <code>super</code> with a staticmethod</h2>
<p>e.g. using <code>super()</code> from within the <code>__new__()</code> method</p>
<pre><code>class A(object):
def __new__(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
return super(A, cls).__new__(cls, *a, **kw)
</code></pre>
<p>Explanation: </p>
<p>1- even though it's usual for <code>__new__()</code> to take as its first param a reference to the calling class, it is <em>not</em> implemented in Python as a classmethod, but rather a staticmethod. That is, a reference to a class has to be passed explicitly as the first argument when calling <code>__new__()</code> directly:</p>
<pre><code># if you defined this
class A(object):
def __new__(cls):
pass
# calling this would raise a TypeError due to the missing argument
A.__new__()
# whereas this would be fine
A.__new__(A)
</code></pre>
<p>2- when calling <code>super()</code> to get to the parent class we pass the child class <code>A</code> as its first argument, then we pass a reference to the object of interest, in this case it's the class reference that was passed when <code>A.__new__(cls)</code> was called. In most cases it also happens to be a reference to the child class. In some situations it might not be, for instance in the case of multiple generation inheritances.</p>
<pre><code>super(A, cls)
</code></pre>
<p>3- since as a general rule <code>__new__()</code> is a staticmethod, <code>super(A, cls).__new__</code> will also return a staticmethod and needs to be supplied all arguments explicitly, including the reference to the object of insterest, in this case <code>cls</code>.</p>
<pre><code>super(A, cls).__new__(cls, *a, **kw)
</code></pre>
<p>4- doing the same thing without <code>super</code></p>
<pre><code>class A(object):
def __new__(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
return object.__new__(cls, *a, **kw)
</code></pre>
<h2>Using <code>super</code> with an instance method</h2>
<p>e.g. using <code>super()</code> from within <code>__init__()</code></p>
<pre><code>class A(object):
def __init__(self, *a, **kw):
# ...
# you make some changes here
# ...
super(A, self).__init__(*a, **kw)
</code></pre>
<p>Explanation:</p>
<p>1- <code>__init__</code> is an instance method, meaning that it takes as its first argument a reference to an instance. When called directly from the instance, the reference is passed implicitly, that is you don't need to specify it:</p>
<pre><code># you try calling `__init__()` from the class without specifying an instance
# and a TypeError is raised due to the expected but missing reference
A.__init__() # TypeError ...
# you create an instance
a = A()
# you call `__init__()` from that instance and it works
a.__init__()
# you can also call `__init__()` with the class and explicitly pass the instance
A.__init__(a)
</code></pre>
<p>2- when calling <code>super()</code> within <code>__init__()</code> we pass the child class as the first argument and the object of interest as a second argument, which in general is a reference to an instance of the child class.</p>
<pre><code>super(A, self)
</code></pre>
<p>3- The call <code>super(A, self)</code> returns a proxy that will resolve the scope and apply it to <code>self</code> as if it's now an instance of the parent class. Let's call that proxy <code>s</code>. Since <code>__init__()</code> is an instance method the call <code>s.__init__(...)</code> will implicitly pass a reference of <code>self</code> as the first argument to the parent's <code>__init__()</code>.</p>
<p>4- to do the same without <code>super</code> we need to pass a reference to an instance explicitly to the parent's version of <code>__init__()</code>.</p>
<pre><code>class A(object):
def __init__(self, *a, **kw):
# ...
# you make some changes here
# ...
object.__init__(self, *a, **kw)
</code></pre>
<h2>Using <code>super</code> with a classmethod</h2>
<pre><code>class A(object):
@classmethod
def alternate_constructor(cls, *a, **kw):
print "A.alternate_constructor called"
return cls(*a, **kw)
class B(A):
@classmethod
def alternate_constructor(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
print "B.alternate_constructor called"
return super(B, cls).alternate_constructor(*a, **kw)
</code></pre>
<p>Explanation:</p>
<p>1- A classmethod can be called from the class directly and takes as its first parameter a reference to the class. </p>
<pre><code># calling directly from the class is fine,
# a reference to the class is passed implicitly
a = A.alternate_constructor()
b = B.alternate_constructor()
</code></pre>
<p>2- when calling <code>super()</code> within a classmethod to resolve to its parent's version of it, we want to pass the current child class as the first argument to indicate which parent's scope we're trying to resolve to, and the object of interest as the second argument to indicate which object we want to apply that scope to, which in general is a reference to the child class itself or one of its subclasses.</p>
<pre><code>super(B, cls_or_subcls)
</code></pre>
<p>3- The call <code>super(B, cls)</code> resolves to the scope of <code>A</code> and applies it to <code>cls</code>. Since <code>alternate_constructor()</code> is a classmethod the call <code>super(B, cls).alternate_constructor(...)</code> will implicitly pass a reference of <code>cls</code> as the first argument to <code>A</code>'s version of <code>alternate_constructor()</code></p>
<pre><code>super(B, cls).alternate_constructor()
</code></pre>
<p>4- to do the same without using <code>super()</code> you would need to get a reference to the <em>unbound</em> version of <code>A.alternate_constructor()</code> (i.e. the explicit version of the function). Simply doing this would not work:</p>
<pre><code>class B(A):
@classmethod
def alternate_constructor(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
print "B.alternate_constructor called"
return A.alternate_constructor(cls, *a, **kw)
</code></pre>
<p>The above would not work because the <code>A.alternate_constructor()</code> method takes an implicit reference to <code>A</code> as its first argument. The <code>cls</code> being passed here would be its second argument.</p>
<pre><code>class B(A):
@classmethod
def alternate_constructor(cls, *a, **kw):
# ...
# whatever you want to specialize or override here
# ...
print "B.alternate_constructor called"
# first we get a reference to the unbound
# `A.alternate_constructor` function
unbound_func = A.alternate_constructor.im_func
# now we call it and pass our own `cls` as its first argument
return unbound_func(cls, *a, **kw)
</code></pre>
| 3 | 2016-09-07T17:33:28Z | [
"python",
"inheritance",
"super"
] |
How do you get the text from an HTML 'datacell' using BeautifulSoup | 223,328 | <p>I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell':</p>
<p>here is my htm snip</p>
<p>headerRows[0][10].contents</p>
<pre><code> [<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3">
</font></font></font>]
</code></pre>
<p>Note that this is a list item from Python [].</p>
<p>I need the value Apples Produced but can't get to it.</p>
<p>Any suggestions would be appreciated</p>
<p>Suggestions on a good book that explains this would earn my eternal gratitude</p>
<hr>
<p>Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute</p>
<p>say it is:</p>
<pre><code> [<font size="+0"><font face="serif" size="1"><I>Apples Produced</I><font size="3">
</font></font></font>]
</code></pre>
<p><I>Apples Produced</I><br>
</p>
<p>I am trying to learn to read/understand the documentation and your response will help</p>
<p>I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and I while I am enjoying learning python and am amzed at its power-BeautifulSoup is an example. making a cohernet whole of the documentation is tough for me.</p>
<p>Cheers</p>
| 6 | 2008-10-21T20:16:13Z | 223,534 | <p>The <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html" rel="nofollow">BeautifulSoup documentation</a> should cover everything you need - in this case it looks like you want to use <code>findNext</code>:</p>
<pre><code>headerRows[0][10].findNext('b').string
</code></pre>
<p>A more generic solution which doesn't rely on the <code><b></code> tag would be to use the <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text" rel="nofollow">text</a> argument to <code>findAll</code>, which allows you to search only for <code>NavigableString</code> objects:</p>
<pre><code>>>> s = BeautifulSoup(u'<p>Test 1 <span>More</span> Test 2</p>')
>>> u''.join([s.string for s in s.findAll(text=True)])
u'Test 1 More Test 2'
</code></pre>
| 5 | 2008-10-21T21:14:21Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
How do you get the text from an HTML 'datacell' using BeautifulSoup | 223,328 | <p>I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell':</p>
<p>here is my htm snip</p>
<p>headerRows[0][10].contents</p>
<pre><code> [<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3">
</font></font></font>]
</code></pre>
<p>Note that this is a list item from Python [].</p>
<p>I need the value Apples Produced but can't get to it.</p>
<p>Any suggestions would be appreciated</p>
<p>Suggestions on a good book that explains this would earn my eternal gratitude</p>
<hr>
<p>Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute</p>
<p>say it is:</p>
<pre><code> [<font size="+0"><font face="serif" size="1"><I>Apples Produced</I><font size="3">
</font></font></font>]
</code></pre>
<p><I>Apples Produced</I><br>
</p>
<p>I am trying to learn to read/understand the documentation and your response will help</p>
<p>I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and I while I am enjoying learning python and am amzed at its power-BeautifulSoup is an example. making a cohernet whole of the documentation is tough for me.</p>
<p>Cheers</p>
| 6 | 2008-10-21T20:16:13Z | 223,994 | <p>I have a base class that I extend all Beautiful Soup classes with a bunch of methods that help me get at text within a group of elements that I don't necessarily want to rely on the structure of. One of those methods is the following:</p>
<pre><code> def clean(self, val):
if type(val) is not StringType: val = str(val)
val = re.sub(r'<.*?>', '', s) #remove tags
val = re.sub("\s+" , " ", val) #collapse internal whitespace
return val.strip() #remove leading & trailing whitespace
</code></pre>
| 0 | 2008-10-21T23:57:03Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
How do you get the text from an HTML 'datacell' using BeautifulSoup | 223,328 | <p>I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell':</p>
<p>here is my htm snip</p>
<p>headerRows[0][10].contents</p>
<pre><code> [<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3">
</font></font></font>]
</code></pre>
<p>Note that this is a list item from Python [].</p>
<p>I need the value Apples Produced but can't get to it.</p>
<p>Any suggestions would be appreciated</p>
<p>Suggestions on a good book that explains this would earn my eternal gratitude</p>
<hr>
<p>Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute</p>
<p>say it is:</p>
<pre><code> [<font size="+0"><font face="serif" size="1"><I>Apples Produced</I><font size="3">
</font></font></font>]
</code></pre>
<p><I>Apples Produced</I><br>
</p>
<p>I am trying to learn to read/understand the documentation and your response will help</p>
<p>I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and I while I am enjoying learning python and am amzed at its power-BeautifulSoup is an example. making a cohernet whole of the documentation is tough for me.</p>
<p>Cheers</p>
| 6 | 2008-10-21T20:16:13Z | 629,326 | <pre><code>headerRows[0][10].contents[0].find('b').string
</code></pre>
| 3 | 2009-03-10T08:30:14Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
When does urllib2 actually download a file from a url? | 223,356 | <pre><code>url = "http://example.com/file.xml"
data = urllib2.urlopen(url)
data.read()
</code></pre>
<p>The question is, when exactly will the file be downloaded from the internet? When i do urlopen or .read()? On my network interface I see high traffic both times. </p>
| 2 | 2008-10-21T20:23:02Z | 223,389 | <p>Witout looking at the code, I'd expect that the following happens:</p>
<ol>
<li><code>urlopen()</code> opens the connection, and sends the query. Then the server starts feeding the reply. At this point, the data accumulates in buffers until they are full and the operating system tells the server to hold on for a while.</li>
<li>Then <code>data.read()</code> empties the buffer, so the operating system tells the server to go on, and the rest of the reply gets downloaded.</li>
</ol>
<p>Naturally, if the reply is short enough, or if the <code>.read()</code> happens quickly enough, then the buffers do not have time to fill up and the download happens in one go.</p>
| 5 | 2008-10-21T20:31:01Z | [
"python"
] |
When does urllib2 actually download a file from a url? | 223,356 | <pre><code>url = "http://example.com/file.xml"
data = urllib2.urlopen(url)
data.read()
</code></pre>
<p>The question is, when exactly will the file be downloaded from the internet? When i do urlopen or .read()? On my network interface I see high traffic both times. </p>
| 2 | 2008-10-21T20:23:02Z | 223,974 | <p>I agree with ddaa. However, if you want to understand this sort of thing, you can set up a dummy server using something like <code>nc</code> (in *nix) and then open the URL in the interactive Python interpreter.</p>
<p>In one terminal, run <code>nc -l 1234</code> which will open a socket and listen for connections on port 1234 of the local machine. <code>nc</code> will accept an incoming connection and display whatever it reads from the socket. Anything you type into <code>nc</code> will be sent over the socket to the remote connection, in this case Python's <code>urlopen()</code>.</p>
<p>Run Python in another terminal and enter your code, i.e.</p>
<pre><code>data = urllib2.urlopen('http://127.0.0.1:1234')
data.read()
</code></pre>
<p>The call to <code>urlopen()</code> will establish the connection to the server, send the request and then block waiting for a response. You will see that <code>nc</code> prints the HTTP request into it's terminal.</p>
<p>Now type something into the terminal that is running <code>nc</code>. The call to <code>urlopen()</code> will still block until you press ENTER in <code>nc</code>, that is, until it receives a new line character. So <code>urlopen()</code> will not return until it has read at least one new line character. (For those concerned about possible buffering by <code>nc</code>, this is not an issue. <code>urlopen()</code> will block until it sees the first new line character.)</p>
<p>So it should be noted that <code>urlopen()</code> will block until the first new line character is received, after which data can be read from the connection. In practice, HTTP responses are short multiline responses, so <code>urlopen()</code> should return quite quickly.</p>
| 5 | 2008-10-21T23:48:31Z | [
"python"
] |
Using Variables for Class Names in Python? | 223,559 | <p>I want to know how to use variables for objects and function names in Python. In PHP, you can do this:</p>
<pre><code>$className = "MyClass";
$newObject = new $className();
</code></pre>
<p>How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?</p>
| 27 | 2008-10-21T21:24:24Z | 223,566 | <p>In Python,</p>
<pre><code>className = MyClass
newObject = className()
</code></pre>
<p>The first line makes the variable <code>className</code> refer to the same thing as <code>MyClass</code>. Then the next line calls the <code>MyClass</code> constructor through the <code>className</code> variable.</p>
<p>As a concrete example:</p>
<pre><code>>>> className = list
>>> newObject = className()
>>> newObject
[]
</code></pre>
<p>(In Python, <code>list</code> is the constructor for the <code>list</code> class.)</p>
<p>The difference is that in PHP, you represent the name of the class you want to refer to as a string, while in Python you can reference the same class directly. If you <em>must</em> use a string (for example if the name of the class is created dynamically), then you will need to use other techniques.</p>
| 27 | 2008-10-21T21:26:09Z | [
"python",
"dynamic-typing"
] |
Using Variables for Class Names in Python? | 223,559 | <p>I want to know how to use variables for objects and function names in Python. In PHP, you can do this:</p>
<pre><code>$className = "MyClass";
$newObject = new $className();
</code></pre>
<p>How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?</p>
| 27 | 2008-10-21T21:24:24Z | 223,584 | <p>If you have this:</p>
<pre><code>class MyClass:
def __init__(self):
print "MyClass"
</code></pre>
<p>Then you usually do this:</p>
<pre><code>>>> x = MyClass()
MyClass
</code></pre>
<p>But you could also do this, which is what I think you're asking:</p>
<pre><code>>>> a = "MyClass"
>>> y = eval(a)()
MyClass
</code></pre>
<p>But, be very careful about where you get the string that you use "eval()" on -- if it's come from the user, you're essentially creating an enormous security hole.</p>
| 3 | 2008-10-21T21:32:34Z | [
"python",
"dynamic-typing"
] |
Using Variables for Class Names in Python? | 223,559 | <p>I want to know how to use variables for objects and function names in Python. In PHP, you can do this:</p>
<pre><code>$className = "MyClass";
$newObject = new $className();
</code></pre>
<p>How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?</p>
| 27 | 2008-10-21T21:24:24Z | 223,586 | <p>Assuming that some_module has a class named "class_name":</p>
<pre><code>import some_module
klass = getattr(some_module, "class_name")
some_object = klass()
</code></pre>
<p>I should note that you should be careful here: turning strings into code can be dangerous if the string came from the user, so you should keep security in mind in this situation. :)</p>
<p>One other method (assuming that we still are using "class_name"):</p>
<pre><code>class_lookup = { 'class_name' : class_name }
some_object = class_lookup['class_name']() #call the object once we've pulled it out of the dict
</code></pre>
<p>The latter method is probably the most secure way of doing this, so it's probably what you should use if at all possible.</p>
| 41 | 2008-10-21T21:33:05Z | [
"python",
"dynamic-typing"
] |
Using Variables for Class Names in Python? | 223,559 | <p>I want to know how to use variables for objects and function names in Python. In PHP, you can do this:</p>
<pre><code>$className = "MyClass";
$newObject = new $className();
</code></pre>
<p>How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?</p>
| 27 | 2008-10-21T21:24:24Z | 2,875,113 | <p>If you need to create a dynamic class in Python (i.e. one whose name is a variable) you can use type() which takes 3 params:
name, bases, attrs</p>
<pre><code>>>> class_name = 'MyClass'
>>> klass = type(class_name, (object,), {'msg': 'foobarbaz'})
<class '__main__.MyClass'>
>>> inst = klass()
>>> inst.msg
foobarbaz
</code></pre>
<ul>
<li>Note however, that this does not 'instantiate' the object (i.e. does not call constructors etc. It creates a new(!) class with the same name.</li>
</ul>
| 15 | 2010-05-20T15:14:38Z | [
"python",
"dynamic-typing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 223,904 | <p>Using multiline, commented regexs can mitigate the maintainance problem somewhat. Try and avoid the one line super regex!</p>
<p>Also, consider breaking the regex down into individual tasks, one for each 'thing' you want to get. eg.</p>
<pre><code>visitor = text.find(/Visitor:(.*)/)
operator = text.find(/Operator:(.*)/)
body = text.find(/whatever....)
</code></pre>
<p>instead of </p>
<pre><code>text.match(/Visitor:(.*)\nOperator:(.*)...whatever to giant regex/m) do
visitor = $1
operator = $2
etc.
end
</code></pre>
<p>Then it makes it easy to change how any particular item is parsed. As far as parsing through a file with many "chat blocks", just have a single simple regex that matches a single chat block, iterate over the text and pass the match data from this to your group of other matchers.</p>
<p>This will obviously affect performance, but unless you processing <em>enormous</em> files i wouldnt worry.</p>
| 4 | 2008-10-21T23:18:14Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 223,925 | <p>No and in fact, for the specific type of task you describe, I doubt there's a "cleaner" way to do it than regular expressions. It looks like your files have embedded line breaks so typically what we'll do here is make the line your unit of decomposition, applying per-line regexes. Meanwhile, you create a small state machine and use regex matches to trigger transitions in that state machine. This way you know where you are in the file, and what types of character data you can expect. Also, consider using named capture groups and loading the regexes from an external file. That way if the format of your transcript changes, it's a simple matter of tweaking the regex, rather than writing new parse-specific code.</p>
| 12 | 2008-10-21T23:25:53Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 224,014 | <p><a href="http://pyparsing.wikispaces.com/" rel="nofollow">Build a parser</a>? I can't decide if your data is regular enough for that, but it might be worth looking into.</p>
| 5 | 2008-10-22T00:03:23Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 224,033 | <p>Just a quick post, I've only glanced at your transcript example but I've recently also had to look into text parsing and hoped to avoid going the route of hand rolled parsing. I did happen across <a href="http://www.complang.org/ragel/" rel="nofollow">Ragel</a> which I've only started to get my head around but it's looking to be pretty useful.</p>
| 0 | 2008-10-22T00:11:12Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 224,052 | <p>You might want to consider a full parser generator. </p>
<p>Regular expressions are good for searching text for small substrings but they're woefully under-powered if you're really interested in parsing the entire file into meaningful data. </p>
<p>They are especially insufficient if the context of the substring is important.</p>
<p>Most people throw regexes at everything because that's what they know. They've never learned any parser generating tools and they end up coding a lot of the production rule composition and semantic action handling that you can get for free with a parser generator. </p>
<p>Regexes are great and all, but if you need a parser they're no substitute.</p>
| 5 | 2008-10-22T00:23:33Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 224,073 | <p>Consider using Ragel <a href="http://www.complang.org/ragel/" rel="nofollow">http://www.complang.org/ragel/</a></p>
<p>That's what powers mongrel under the hood. Parsing a string multiple times is going to slow things down dramatically. </p>
| 2 | 2008-10-22T00:36:12Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 224,344 | <p>With Perl, you can use <a href="http://search.cpan.org/perldoc?Parse::RecDescent" rel="nofollow">Parse::RecDescent</a></p>
<p>It is simple, and your grammar will be maintainable later on.</p>
| 11 | 2008-10-22T03:01:20Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 226,711 | <p>I have used Paul McGuire's pyParsing class library and I continue to be impressed by it, in that it's well-documented, easy to get started, and the rules are easy to tweak and maintain. BTW, the rules are expressed in your python code. It certainly appears that the log file has enough regularity to parse each line as a stand-alone unit.</p>
| 2 | 2008-10-22T17:05:41Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
Elegant structured text file parsing | 223,866 | <p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p>
<p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p>
<p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p>
<p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p>
<p>Here is an example of a transcript file:</p>
<pre><code>Chat Transcript
Visitor: Random Website Visitor
Operator: Milton
Company: Initech
Started: 16 Oct 2008 9:13:58
Finished: 16 Oct 2008 9:45:44
Random Website Visitor: Where do i get the cover sheet for the TPS report?
* There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button
* Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.
Milton: Y-- Excuse me. You-- I believe you have my stapler?
Random Website Visitor: I really just need the cover sheet, okay?
Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...
Random Website Visitor: oh i found it, thanks anyway.
* Random Website Visitor is now off-line and may not reply. Currently in room: Milton.
Milton: Well, Ok. But⦠that's the last straw.
* Milton has left the conversation. Currently in room: room is empty.
Visitor Details
---------------
Your Name: Random Website Visitor
Your Question: Where do i get the cover sheet for the TPS report?
IP Address: 255.255.255.255
Host Name: 255.255.255.255
Referrer: Unknown
Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
</code></pre>
| 19 | 2008-10-21T23:00:20Z | 1,657,561 | <p>Here's two parsers based on <a href="http://www.acooke.org/lepl/" rel="nofollow"><code>lepl</code></a> parser generator library. They both produce the same result.</p>
<pre><code>from pprint import pprint
from lepl import AnyBut, Drop, Eos, Newline, Separator, SkipTo, Space
# field = name , ":" , value
name, value = AnyBut(':\n')[1:,...], AnyBut('\n')[::'n',...]
with Separator(~Space()[:]):
field = name & Drop(':') & value & ~(Newline() | Eos()) > tuple
header_start = SkipTo('Chat Transcript' & Newline()[2])
header = ~header_start & field[1:] > dict
server_message = Drop('* ') & AnyBut('\n')[:,...] & ~Newline() > 'Server'
conversation = (server_message | field)[1:] > list
footer_start = 'Visitor Details' & Newline() & '-'*15 & Newline()
footer = ~footer_start & field[1:] > dict
chat_log = header & ~Newline() & conversation & ~Newline() & footer
pprint(chat_log.parse_file(open('chat.log')))
</code></pre>
<h3>Stricter Parser</h3>
<pre><code>from pprint import pprint
from lepl import And, Drop, Newline, Or, Regexp, SkipTo
def Field(name, value=Regexp(r'\s*(.*?)\s*?\n')):
"""'name , ":" , value' matcher"""
return name & Drop(':') & value > tuple
Fields = lambda names: reduce(And, map(Field, names))
header_start = SkipTo(Regexp(r'^Chat Transcript$') & Newline()[2])
header_fields = Fields("Visitor Operator Company Started Finished".split())
server_message = Regexp(r'^\* (.*?)\n') > 'Server'
footer_fields = Fields(("Your Name, Your Question, IP Address, "
"Host Name, Referrer, Browser/OS").split(', '))
with open('chat.log') as f:
# parse header to find Visitor and Operator's names
headers, = (~header_start & header_fields > dict).parse_file(f)
# only Visitor, Operator and Server may take part in the conversation
message = reduce(Or, [Field(headers[name])
for name in "Visitor Operator".split()])
conversation = (message | server_message)[1:]
messages, footers = ((conversation > list)
& Drop('\nVisitor Details\n---------------\n')
& (footer_fields > dict)).parse_file(f)
pprint((headers, messages, footers))
</code></pre>
<p>Output:</p>
<pre><code>({'Company': 'Initech',
'Finished': '16 Oct 2008 9:45:44',
'Operator': 'Milton',
'Started': '16 Oct 2008 9:13:58',
'Visitor': 'Random Website Visitor'},
[('Random Website Visitor',
'Where do i get the cover sheet for the TPS report?'),
('Server',
'There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button'),
('Server',
'Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.'),
('Milton', 'Y-- Excuse me. You-- I believe you have my stapler?'),
('Random Website Visitor', 'I really just need the cover sheet, okay?'),
('Milton',
"it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire..."),
('Random Website Visitor', 'oh i found it, thanks anyway.'),
('Server',
'Random Website Visitor is now off-line and may not reply. Currently in room: Milton.'),
('Milton', "Well, Ok. But⦠that's the last straw."),
('Server',
'Milton has left the conversation. Currently in room: room is empty.')],
{'Browser/OS': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)',
'Host Name': '255.255.255.255',
'IP Address': '255.255.255.255',
'Referrer': 'Unknown',
'Your Name': 'Random Website Visitor',
'Your Question': 'Where do i get the cover sheet for the TPS report?'})
</code></pre>
| 6 | 2009-11-01T16:17:57Z | [
"python",
"ruby",
"perl",
"text-parsing"
] |
How do I perform query filtering in django templates | 223,990 | <p>I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:</p>
<pre><code>queryset = Modelclass.objects.filter(somekey=foo)
</code></pre>
<p>In my template I would like to do</p>
<pre><code>{% for object in data.somekey_set.FILTER %}
</code></pre>
<p>but I just can't seem to find out how to write FILTER.</p>
| 50 | 2008-10-21T23:55:57Z | 224,003 | <p>You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.</p>
<p>So you have several options. The easiest is to do the filtering, then pass the result to <code>render_to_response</code>. Or you could write a method in your model so that you can say <code>{% for object in data.filtered_set %}</code>. Finally, you could write your own template tag, although in this specific case I would advise against that.</p>
| 83 | 2008-10-22T00:00:27Z | [
"python",
"django",
"django-templates"
] |
How do I perform query filtering in django templates | 223,990 | <p>I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:</p>
<pre><code>queryset = Modelclass.objects.filter(somekey=foo)
</code></pre>
<p>In my template I would like to do</p>
<pre><code>{% for object in data.somekey_set.FILTER %}
</code></pre>
<p>but I just can't seem to find out how to write FILTER.</p>
| 50 | 2008-10-21T23:55:57Z | 230,615 | <p>I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.</p>
<p>Some other possible solutions:</p>
<ol>
<li><p>Use the {% expr <expression> as <var_name> %} template tag found at <a href="http://www.djangosnippets.org/snippets/9/">http://www.djangosnippets.org/snippets/9/</a> The expression is any legal Python expression with your template's Context as your local scope.</p></li>
<li><p>Change your template processor. Jinja2 (<a href="http://jinja.pocoo.org/2/">http://jinja.pocoo.org/2/</a>) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that <em>you</em> are working on, but use Django's "safer" templates for designer-maintained pages.</p></li>
</ol>
| 10 | 2008-10-23T17:22:35Z | [
"python",
"django",
"django-templates"
] |
How do I perform query filtering in django templates | 223,990 | <p>I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:</p>
<pre><code>queryset = Modelclass.objects.filter(somekey=foo)
</code></pre>
<p>In my template I would like to do</p>
<pre><code>{% for object in data.somekey_set.FILTER %}
</code></pre>
<p>but I just can't seem to find out how to write FILTER.</p>
| 50 | 2008-10-21T23:55:57Z | 12,350,892 | <p>The other option is that if you have a filter that you always want applied, to add a <a href="https://docs.djangoproject.com/en/1.4/topics/db/managers/#custom-managers">custom manager</a> on the model in question which always applies the filter to the results returned.</p>
<p>A good example of this is a <code>Event</code> model, where for 90% of the queries you do on the model you are going to want something like <code>Event.objects.filter(date__gte=now)</code>, i.e. you're normally interested in <code>Events</code> that are upcoming. This would look like:</p>
<pre><code>class EventManager(models.Manager):
def get_query_set(self):
now = datetime.now()
return super(EventManager,self).get_query_set().filter(date__gte=now)
</code></pre>
<p>And in the model:</p>
<pre><code>class Event(models.Model):
...
objects = EventManager()
</code></pre>
<p>But again, this applies the same filter against all default queries done on the <code>Event</code> model and so isn't as flexible some of the techniques described above. </p>
| 5 | 2012-09-10T11:37:01Z | [
"python",
"django",
"django-templates"
] |
How do I perform query filtering in django templates | 223,990 | <p>I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:</p>
<pre><code>queryset = Modelclass.objects.filter(somekey=foo)
</code></pre>
<p>In my template I would like to do</p>
<pre><code>{% for object in data.somekey_set.FILTER %}
</code></pre>
<p>but I just can't seem to find out how to write FILTER.</p>
| 50 | 2008-10-21T23:55:57Z | 14,010,929 | <p>This can be solved with an assignment tag:</p>
<pre><code>from django import template
register = template.Library()
@register.assignment_tag
def query(qs, **kwargs):
""" template tag which allows queryset filtering. Usage:
{% query books author=author as mybooks %}
{% for book in mybooks %}
...
{% endfor %}
"""
return qs.filter(**kwargs)
</code></pre>
| 7 | 2012-12-23T12:27:28Z | [
"python",
"django",
"django-templates"
] |
How do I perform query filtering in django templates | 223,990 | <p>I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:</p>
<pre><code>queryset = Modelclass.objects.filter(somekey=foo)
</code></pre>
<p>In my template I would like to do</p>
<pre><code>{% for object in data.somekey_set.FILTER %}
</code></pre>
<p>but I just can't seem to find out how to write FILTER.</p>
| 50 | 2008-10-21T23:55:57Z | 16,429,027 | <p>I just add an extra template tag like this:</p>
<pre><code>@register.filter
def in_category(things, category):
return things.filter(category=category)
</code></pre>
<p>Then I can do:</p>
<pre><code>{% for category in categories %}
{% for thing in things|in_category:category %}
{{ thing }}
{% endfor %}
{% endfor %}
</code></pre>
| 14 | 2013-05-07T21:41:18Z | [
"python",
"django",
"django-templates"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 224,051 | <p>As far as I know, Python classes use dictionaries to store their attributes anyway (that's hidden from the programmer), so it looks to me that what you've done there is effectively emulate a Python class... using a python class. </p>
| 3 | 2008-10-22T00:22:11Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 224,071 | <p>I like dot notation a lot better than dictionary fields personally. The reason being that it makes autocompletion work a lot better.</p>
| 1 | 2008-10-22T00:34:59Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 224,080 | <p>With regards to the <code>DictObj</code>, would the following work for you? A blank class will allow you to arbitrarily add to or replace stuff in a container object.</p>
<pre><code>class Container(object):
pass
>>> myContainer = Container()
>>> myContainer.spam = "in a can"
>>> myContainer.eggs = "in a shell"
</code></pre>
<p>If you want to not throw an AttributeError when there is no attribute, what do you think about the following? Personally, I'd prefer to use a dict for clarity, or to use a try/except clause.</p>
<pre><code>class QuietContainer(object):
def __getattr__(self, attribute):
try:
return object.__getattr__(self,attribute)
except AttributeError:
return None
>>> cont = QuietContainer()
>>> print cont.me
None
</code></pre>
<p>Right?</p>
| 12 | 2008-10-22T00:40:31Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 224,722 | <p>This is a simpler version of your DictObj class:</p>
<pre><code>class DictObj(object):
def __getattr__(self, attr):
return self.__dict__.get(attr)
>>> d = DictObj()
>>> d.something = 'one'
>>> print d.something
one
>>> print d.somethingelse
None
>>>
</code></pre>
| 8 | 2008-10-22T07:06:02Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 224,787 | <p>It's not bad if it serves your purpose. "Practicality beats purity".</p>
<p>I saw such approach elserwhere (eg. in <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">Paver</a>), so this can be considered <em>common need</em> (or desire).</p>
| 1 | 2008-10-22T07:55:24Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 224,876 | <p>Your DictObj example is actually quite common. Object-style dot-notation access can be a win if you are dealing with âthings that resemble objectsâ, ie. they have fixed property names containing only characters valid in Python identifiers. Stuff like database rows or form submissions can be usefully stored in this kind of object, making code a little more readable without the excess of ['item access'].</p>
<p>The implementation is a bit limited - you don't get the nice constructor syntax of dict, len(), comparisons, 'in', iteration or nice reprs. You can of course implement those things yourself, but in the new-style-classes world you can get them for free by simply subclassing dict:</p>
<pre><code>class AttrDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
</code></pre>
<p>To get the default-to-None behaviour, simply subclass Python 2.5's collections.defaultdict class instead of dict.</p>
| 22 | 2008-10-22T08:29:47Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 235,675 | <p>The one major disadvantage of using something like your DictObj is you either have to limit allowable keys or you can't have methods on your DictObj such as <code>.keys()</code>, <code>.values()</code>, <code>.items()</code>, etc.</p>
| 2 | 2008-10-25T00:17:16Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 235,686 | <p>It's not "wrong" to do this, and it can be nicer if your dictionaries have a strong possibility of turning into objects at some point, but be wary of the reasons for having bracket access in the first place:</p>
<ol>
<li>Dot access can't use keywords as keys.</li>
<li>Dot access has to use Python-identifier-valid characters in the keys.</li>
<li>Dictionaries can hold any hashable element -- not just strings.</li>
</ol>
<p>Also keep in mind you can always make your objects access like dictionaries if you decide to switch to objects later on.</p>
<p>For a case like this I would default to the "readability counts" mantra: presumably other Python programmers will be reading your code and they probably won't be expecting dictionary/object hybrids everywhere. If it's a good design decision for a particular situation, use it, but I wouldn't use it without necessity to do so.</p>
| 3 | 2008-10-25T00:33:25Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 11,350,835 | <p>Because you ask for undesirable side-effects:</p>
<p>A disadvantage is that in visual editors like eclipse+pyDev, you will see many undefined variable errors on lines using the dot notation. Pydef will not be able to find such runtime "object" definitions. Whereas in the case of a normal dictionary, it knows that you are just getting a dictionary entry.</p>
<p>You would need to 1) ignore those errors and live with red crosses; 2) suppress those warnings on a line by line basis using #@UndefinedVariable or 3) disable undefined variable error entirely, causing you to miss real undefined variable definitions.</p>
| 0 | 2012-07-05T19:01:28Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 11,620,531 | <p>There's a symmetry between <a href="http://stackoverflow.com/a/224876/1413374">this</a> and <a href="http://stackoverflow.com/a/224080/1413374">this</a> answer:</p>
<pre><code>class dotdict(dict):
__getattr__= dict.__getitem__
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
</code></pre>
<p>The same interface, just implemented the other way round...</p>
<pre><code>class container(object):
__getitem__ = object.__getattribute__
__setitem__ = object.__setattr__
__delitem__ = object.__delattr__
</code></pre>
| 2 | 2012-07-23T21:07:16Z | [
"python",
"coding-style"
] |
Javascript style dot notation for dictionary keys unpythonic? | 224,026 | <p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
| 25 | 2008-10-22T00:08:01Z | 26,553,870 | <p>Don't overlook <a href="https://pypi.python.org/pypi/bunch/1.0.1" rel="nofollow" title="Bunch">Bunch</a>. </p>
<p>It is a child of dictionary and can import YAML or JSON, or convert any existing dictionary to a Bunch and vice-versa. Once "bunchify"'d, a dictionary gains dot notations without losing any other dictionary methods.</p>
| 0 | 2014-10-24T18:15:52Z | [
"python",
"coding-style"
] |
What would be a better implementation of all combinations in lexicographic order of a jagged list? | 224,145 | <p>I was put in a position today in which I needed to enumerate all possible combinations of jagged list. For instance, a naive approach would be:</p>
<pre><code>for a in [1,2,3]:
for b in [4,5,6,7,8,9]:
for c in [1,2]:
yield (a,b,c)
</code></pre>
<p>This is functional, but not general in terms of the number of lists that can be used. Here is a more generalized approach:</p>
<pre><code>from numpy import zeros, array, nonzero, max
make_subset = lambda x,y: [x[i][j] for i,j in enumerate(y)]
def combinations(items):
num_items = [len(i) - 1 for i in items]
state = zeros(len(items), dtype=int)
finished = array(num_items, dtype=int)
yield grab_items(items, state)
while True:
if state[-1] != num_items[-1]:
state[-1] += 1
yield make_subset(items, state)
else:
incrementable = nonzero(state != finished)[0]
if not len(incrementable):
raise StopIteration
rightmost = max(incrementable)
state[rightmost] += 1
state[rightmost+1:] = 0
yield make_subset(items, state)
</code></pre>
<p>Any recommendations on a better approach or reasons against the above approach?</p>
| 2 | 2008-10-22T01:19:39Z | 224,187 | <p>The naive approach can be written more compactly as a generator expression:</p>
<pre><code>((a,b,c) for a in [1,2,3] for b in [4,5,6,7,8,9] for c in [1,2])
</code></pre>
<p>The general approach can be written much more simply using a recursive function:</p>
<pre><code>def combinations(*seqs):
if not seqs: return (item for item in ())
first, rest = seqs[0], seqs[1:]
if not rest: return ((item,) for item in first)
return ((item,) + items for item in first for items in combinations(*rest))
</code></pre>
<p>Sample usage:</p>
<pre><code>>>> for pair in combinations('abc', [1,2,3]):
... print pair
...
('a', 1)
('a', 2)
('a', 3)
('b', 1)
('b', 2)
('b', 3)
('c', 1)
('c', 2)
('c', 3)
</code></pre>
| 6 | 2008-10-22T01:49:15Z | [
"python",
"algorithm"
] |
Alternatives to a wizard | 224,337 | <p>I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.</p>
<p>However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.</p>
<p>I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.</p>
<p>However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.</p>
<p>Are there any tutorials for making "dynamic panels" or better management of a wizard?</p>
| 3 | 2008-10-22T02:54:17Z | 224,800 | <p>Here is a simple example. This way you can make your "wizard" work like a finite state machine where states are different pages that are initialized on demand. Also, the data is shared between pages.</p>
<pre><code>import wx
import wx.lib.newevent
(PageChangeEvent, EVT_PAGE_CHANGE) = wx.lib.newevent.NewEvent()
class Data:
foo = None
bar = None
class Page1(wx.Panel):
def __init__(self, parent, data):
wx.Panel.__init__(self, parent)
self.parent = parent
self.data = data
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
label = wx.StaticText(self, label="Page 1 - foo")
self.foo = wx.TextCtrl(self)
goto_page2 = wx.Button(self, label="Go to page 2")
for c in (label, self.foo, goto_page2):
sizer.Add(c, 0, wx.TOP, 5)
goto_page2.Bind(wx.EVT_BUTTON, self.OnPage2)
def OnPage2(self, event):
self.data.foo = self.foo.Value
wx.PostEvent(self.parent, PageChangeEvent(page=Page2))
class Page2(wx.Panel):
def __init__(self, parent, data):
wx.Panel.__init__(self, parent)
self.parent = parent
self.data = data
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
label = wx.StaticText(self, label="Page 2 - bar")
self.bar = wx.TextCtrl(self)
goto_finish = wx.Button(self, label="Finish")
for c in (label, self.bar, goto_finish):
sizer.Add(c, 0, wx.TOP, 5)
goto_finish.Bind(wx.EVT_BUTTON, self.OnFinish)
def OnFinish(self, event):
self.data.bar = self.bar.Value
wx.PostEvent(self.parent, PageChangeEvent(page=finish))
def finish(parent, data):
wx.MessageBox("foo = %s\nbar = %s" % (data.foo, data.bar))
wx.GetApp().ExitMainLoop()
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.data = Data()
self.current_page = None
self.Bind(EVT_PAGE_CHANGE, self.OnPageChange)
wx.PostEvent(self, PageChangeEvent(page=Page1))
def OnPageChange(self, event):
page = event.page(self, self.data)
if page == None:
return
if self.current_page:
self.current_page.Destroy()
self.current_page = page
page.Layout()
page.Fit()
page.Refresh()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()
</code></pre>
| 5 | 2008-10-22T08:04:52Z | [
"python",
"wxpython",
"wizard"
] |
Alternatives to a wizard | 224,337 | <p>I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.</p>
<p>However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.</p>
<p>I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.</p>
<p>However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.</p>
<p>Are there any tutorials for making "dynamic panels" or better management of a wizard?</p>
| 3 | 2008-10-22T02:54:17Z | 225,479 | <p>You could try using a workflow engine like <a href="http://www.vivtek.com/wftk/" rel="nofollow">WFTK</a>. In this particular case author has done some work on wx-based apps using WFTK and can probably direct you to examples.</p>
| 0 | 2008-10-22T12:06:03Z | [
"python",
"wxpython",
"wizard"
] |
Alternatives to a wizard | 224,337 | <p>I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.</p>
<p>However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.</p>
<p>I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.</p>
<p>However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.</p>
<p>Are there any tutorials for making "dynamic panels" or better management of a wizard?</p>
| 3 | 2008-10-22T02:54:17Z | 247,409 | <p>The wxPython demo has an example of a "dynamic" wizard. Pages override GetNext() and GetPrev() to show pages dynamically. This shows the basic technique; you can extend it to add and remove pages, change pages on the fly, and rearrange pages dynamically.</p>
<p>The wizard class is just a convenience, though. You can modify it, or create your own implementation. A style that seems popular nowadays is to use an HTML-based presentation; you can emulate this with the wxHtml control, or the IEHtmlWindow control if your app is Windows only.</p>
| 1 | 2008-10-29T16:09:32Z | [
"python",
"wxpython",
"wizard"
] |
Alternatives to a wizard | 224,337 | <p>I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.</p>
<p>However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.</p>
<p>I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.</p>
<p>However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.</p>
<p>Are there any tutorials for making "dynamic panels" or better management of a wizard?</p>
| 3 | 2008-10-22T02:54:17Z | 247,633 | <p>I'd get rid of wizard in whole. They are the most unpleasant things I've ever used.</p>
<p>The problem that requires a wizard-application where you click 'next' is perhaps a problem where you could apply a better user interface in a bit different manner. Instead of bringing up a dialog with annoying 'next' -button. Do this:</p>
<p>Bring up a page. When the user inserts the information to the page, extend or shorten it according to the input. If your application needs to do some processing to continue, and it's impossible to revert after that, write a new page or disable the earlier section of the current page. When you don't need any input from the user anymore or the app is finished, you can show a button or enable an existing such.</p>
<p>I don't mean you should implement it all in browser. Make simply a scrolling container that can contain buttons and labels in a flat list.</p>
<p>Benefit: The user can just click a tab, and you are encouraged to put all the processing into the end of filling the page.</p>
| 0 | 2008-10-29T17:14:33Z | [
"python",
"wxpython",
"wizard"
] |
Alternatives to a wizard | 224,337 | <p>I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.</p>
<p>However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.</p>
<p>I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.</p>
<p>However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.</p>
<p>Are there any tutorials for making "dynamic panels" or better management of a wizard?</p>
| 3 | 2008-10-22T02:54:17Z | 247,711 | <p>It should be noted that a Wizard should be the interface for mutli-step, infrequently-performed tasks. The wizard is used to guide the user through something they don't really understand, because they almost never do it.</p>
<p>And if some users might do the task frequently, you want to give those power users a lightweight interface to do the same thing - even if it less self explanatory.</p>
<p>See: <strong><a href="http://msdn.microsoft.com/en-us/library/aa511331.aspx#wizards" rel="nofollow">Windows Vista User Experience Guidelines - Top Violations</a></strong></p>
<blockquote>
<p><strong>Wizards</strong></p>
<p><strong>Consider lightweight alternatives first, such as dialog boxes, task
panes, or single pages.</strong> Wizards are
a heavy UI, best used for multi-step,
infrequently performed task. You don't
have to use wizardsâyou can provide
helpful information and assistance in
any UI.</p>
</blockquote>
| 0 | 2008-10-29T17:38:48Z | [
"python",
"wxpython",
"wizard"
] |
Incoming poplib refactoring using windows python 2.3 | 224,660 | <p>Hi Guys could you please help me refactor this so that it is sensibly pythonic.</p>
<pre><code>import sys
import poplib
import string
import StringIO, rfc822
import datetime
import logging
def _dump_pop_emails(self):
self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1]))
self.popinstance = poplib.POP3(self.account[0])
self.logger.info(self.popinstance.getwelcome())
self.popinstance.user(self.account[1])
self.popinstance.pass_(self.account[2])
try:
(numMsgs, totalSize) = self.popinstance.stat()
for thisNum in range(1, numMsgs+1):
(server_msg, body, octets) = self.popinstance.retr(thisNum)
text = string.join(body, '\n')
mesg = StringIO.StringIO(text)
msg = rfc822.Message(mesg)
name, email = msg.getaddr("From")
emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml")
emailpath = self._replace_whitespace(emailpath)
file = open(emailpath,"wb")
file.write(text)
file.close()
self.popinstance.dele(thisNum)
finally:
self.logger.info(self.popinstance.quit())
def _replace_whitespace(self,name):
name = str(name)
return name.replace(" ", "_")
</code></pre>
<p>Also in the _replace_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing.</p>
<p>Basically I want to write the email to the inbox directory in a standard way.</p>
<p>Am i doing something wrong here?</p>
| 1 | 2008-10-22T06:26:33Z | 224,713 | <p>I don't see anything significant wrong with that code -- is it behaving incorrectly, or are you just looking for general style guidelines?</p>
<p>A few notes:</p>
<ol>
<li>Instead of <code>logger.info ("foo %s %s" % (bar, baz))</code>, use <code>"foo %s %s", bar, baz</code>. This avoids the overhead of string formatting if the message won't be printed.</li>
<li>Put a <code>try...finally</code> around opening <code>emailpath</code>.</li>
<li>Use <code>'\n'.join (body)</code>, instead of <code>string.join (body, '\n')</code>.</li>
<li>Instead of <code>msg.getaddr("From")</code>, just <code>msg.From</code>.</li>
</ol>
| 3 | 2008-10-22T06:58:57Z | [
"python",
"email",
"refactoring",
"poplib"
] |
Incoming poplib refactoring using windows python 2.3 | 224,660 | <p>Hi Guys could you please help me refactor this so that it is sensibly pythonic.</p>
<pre><code>import sys
import poplib
import string
import StringIO, rfc822
import datetime
import logging
def _dump_pop_emails(self):
self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1]))
self.popinstance = poplib.POP3(self.account[0])
self.logger.info(self.popinstance.getwelcome())
self.popinstance.user(self.account[1])
self.popinstance.pass_(self.account[2])
try:
(numMsgs, totalSize) = self.popinstance.stat()
for thisNum in range(1, numMsgs+1):
(server_msg, body, octets) = self.popinstance.retr(thisNum)
text = string.join(body, '\n')
mesg = StringIO.StringIO(text)
msg = rfc822.Message(mesg)
name, email = msg.getaddr("From")
emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml")
emailpath = self._replace_whitespace(emailpath)
file = open(emailpath,"wb")
file.write(text)
file.close()
self.popinstance.dele(thisNum)
finally:
self.logger.info(self.popinstance.quit())
def _replace_whitespace(self,name):
name = str(name)
return name.replace(" ", "_")
</code></pre>
<p>Also in the _replace_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing.</p>
<p>Basically I want to write the email to the inbox directory in a standard way.</p>
<p>Am i doing something wrong here?</p>
| 1 | 2008-10-22T06:26:33Z | 224,752 | <p>Further to my comment on John's answer</p>
<p>I found out what the issue was, there were illegal characters in the name field and Subject field, which caused python to get the hiccups, as it tried to write the email as a directory, after seeing ":" and "/".</p>
<p>John point number 4 doesnt work! so I left it as before.
Also is point no 1 correct, have I implemented your suggestion correctly?</p>
<pre><code>def _dump_pop_emails(self):
self.logger.info("open pop account %s with username: %s", self.account[0], self.account[1])
self.popinstance = poplib.POP3(self.account[0])
self.logger.info(self.popinstance.getwelcome())
self.popinstance.user(self.account[1])
self.popinstance.pass_(self.account[2])
try:
(numMsgs, totalSize) = self.popinstance.stat()
for thisNum in range(1, numMsgs+1):
(server_msg, body, octets) = self.popinstance.retr(thisNum)
text = '\n'.join(body)
mesg = StringIO.StringIO(text)
msg = rfc822.Message(mesg)
name, email = msg.getaddr("From")
emailpath = str(self._emailpath + self._inboxfolder + "\\" + self._sanitize_string(email + " " + msg.getheader("Subject") + ".eml"))
emailpath = self._replace_whitespace(emailpath)
print emailpath
file = open(emailpath,"wb")
file.write(text)
file.close()
self.popinstance.dele(thisNum)
finally:
self.logger.info(self.popinstance.quit())
def _replace_whitespace(self,name):
name = str(name)
return name.replace(" ", "_")
def _sanitize_string(self,name):
illegal_chars = ":", "/", "\\"
name = str(name)
for item in illegal_chars:
name = name.replace(item, "_")
return name
</code></pre>
| 0 | 2008-10-22T07:30:20Z | [
"python",
"email",
"refactoring",
"poplib"
] |
Incoming poplib refactoring using windows python 2.3 | 224,660 | <p>Hi Guys could you please help me refactor this so that it is sensibly pythonic.</p>
<pre><code>import sys
import poplib
import string
import StringIO, rfc822
import datetime
import logging
def _dump_pop_emails(self):
self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1]))
self.popinstance = poplib.POP3(self.account[0])
self.logger.info(self.popinstance.getwelcome())
self.popinstance.user(self.account[1])
self.popinstance.pass_(self.account[2])
try:
(numMsgs, totalSize) = self.popinstance.stat()
for thisNum in range(1, numMsgs+1):
(server_msg, body, octets) = self.popinstance.retr(thisNum)
text = string.join(body, '\n')
mesg = StringIO.StringIO(text)
msg = rfc822.Message(mesg)
name, email = msg.getaddr("From")
emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml")
emailpath = self._replace_whitespace(emailpath)
file = open(emailpath,"wb")
file.write(text)
file.close()
self.popinstance.dele(thisNum)
finally:
self.logger.info(self.popinstance.quit())
def _replace_whitespace(self,name):
name = str(name)
return name.replace(" ", "_")
</code></pre>
<p>Also in the _replace_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing.</p>
<p>Basically I want to write the email to the inbox directory in a standard way.</p>
<p>Am i doing something wrong here?</p>
| 1 | 2008-10-22T06:26:33Z | 225,029 | <p>This isn't refactoring (it doesn't need refactoring as far as I can see), but some suggestions:</p>
<p>You should use the email package rather than rfc822. Replace rfc822.Message with email.Message, and use email.Utils.parseaddr(msg["From"]) to get the name and email address, and msg["Subject"] to get the subject.</p>
<p>Use os.path.join to create the path. This:</p>
<pre><code>emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml")
</code></pre>
<p>Becomes:</p>
<pre><code>emailpath = os.path.join(self._emailpath + self._inboxfolder, email + "_" + msg.getheader("Subject") + ".eml")
</code></pre>
<p>(If self._inboxfolder starts with a slash or self._emailpath ends with one, you could replace the first + with a comma also).</p>
<p>It doesn't really hurt anything, but you should probably not use "file" as a variable name, since it shadows a built-in type (checkers like pylint or pychecker would warn you about that).</p>
<p>If you're not using self.popinstance outside of this function (seems unlikely given that you connect and quit within the function), then there's no point making it an attribute of self. Just use "popinstance" by itself.</p>
<p>Use xrange instead of range.</p>
<p>Instead of just importing StringIO, do this:</p>
<pre><code>try:
import cStringIO as StringIO
except ImportError:
import StringIO
</code></pre>
<p>If this is a POP mailbox that can be accessed by more than one client at a time, you might want to put a try/except around the RETR call to continue on if you can't retrieve one message.</p>
<p>As John said, use "\n".join rather than string.join, use try/finally to only close the file if it is opened, and pass the logging parameters separately.</p>
<p>The one refactoring issue I could think of would be that you don't really need to parse the whole message, since you're just dumping a copy of the raw bytes, and all you want is the From and Subject headers. You could instead use popinstance.top(0) to get the headers, create the message (blank body) from that, and use that for the headers. Then do a full RETR to get the bytes. This would only be worth doing if your messages were large (and so parsing them took a long time). I would definitely measure before I made this optimisation.</p>
<p>For your function to sanitise for the names, it depends how nice you want the names to be, and how certain you are that the email and subject make the filename unique (seems fairly unlikely). You could do something like:</p>
<pre><code>emailpath = "".join([c for c in emailpath if c in (string.letters + string.digits + "_ ")])
</code></pre>
<p>And you'd end up with just alphanumeric characters and the underscore and space, which seems like a readable set. Given that your filesystem (with Windows) is probably case insensitive, you could lowercase that also (add .lower() to the end). You could use emailpath.translate if you want something more complex.</p>
| 1 | 2008-10-22T09:32:26Z | [
"python",
"email",
"refactoring",
"poplib"
] |
Open Source Profiling Frameworks? | 224,735 | <p>Have you ever wanted to test and quantitatively show whether your application would perform better as a static build or shared build, stripped or non-stripped, upx or no upx, gcc -O2 or gcc -O3, hash or btree, etc etc. If so this is the thread for you. There are hundreds of ways to tune an application, but how do we collect, organize, process, visualize the consequences of each experiment. </p>
<p>I have been looking for several months for an open source application performance engineering/profiling framework similar in concept to Mozilla's <a href="http://graphs.mozilla.org" rel="nofollow">Perftastic</a> where I can develop/build/test/profile hundreds of incarnations of different tuning experiments. </p>
<p>Some requirements:</p>
<h2>Platform</h2>
<p>SUSE32 and SUSE64</p>
<h2>Data Format</h2>
<p>Very flexible, compact, simple, hierarchical. There are several possibilities including</p>
<ul>
<li>Custom <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow">CSV</a></li>
<li><a href="http://en.wikipedia.org/wiki/RRDtool" rel="nofollow">RRD</a></li>
<li><a href="http://en.wikipedia.org/wiki/Protocol_buffers" rel="nofollow">Protocol Buffers</a></li>
<li><a href="http://en.wikipedia.org/wiki/Json" rel="nofollow">JSON</a></li>
<li>No XML. There is lots of data and XML is tooo verbose</li>
</ul>
<h2>Data Acquisition</h2>
<p>Flexible and Customizable plugins. There is lots of data to collect from the application including performance data from /proc, sys time, wall time, cpu utilization, memory profile, leaks, valgrind logs, arena fragmentation, I/O, localhost sockets, binary size, open fds, etc. And some from the host system. My language of choice for this is Python, and I would develop these plugins to monitor and/or parse data in all different formats and store them in the data format of the framework.</p>
<h2>Tagging</h2>
<p>All experiments would be tagged including data like GCC version and compile options, platform, host, app options, experiment, build tag, etc.</p>
<h2>Graphing</h2>
<p>History, Comparative, Hierarchical, Dynamic and Static.</p>
<ul>
<li>The application builds are done by a custom CI sever which releases a new app version several times per day the last 3 years straight. This is why we need a continuous trend analysis. When we add new features, make bug fixes, change build options, we want to automatically gather profiling data and see the trend. This is where generating various static builds is needed. </li>
<li>For analysis <a href="http://graphs.mozilla.org" rel="nofollow">Mozilla dynamic graphs</a> are great for doing comparative graphing. It would be great to have comparative graphing between different tags. For example compare N build versions, compare platforms, compare build options, etc. </li>
<li>We have a test suite of 3K tests, data will be gathered per test, and grouped from inter-test data, to per test, to per tagged group, to complete regression suite. </li>
<li>Possibilities include <a href="http://oss.oetiker.ch/rrdtool/index.en.html" rel="nofollow">RRDTool</a>, <a href="http://www.orcaware.com/orca/example_sites.html" rel="nofollow">Orca</a>, <a href="http://graphite.wikidot.com/screen-shots" rel="nofollow">Graphite</a></li>
</ul>
<h2>Analysis on a grouping basis</h2>
<ul>
<li>Min</li>
<li>Max</li>
<li>Median</li>
<li>Avg</li>
<li>Standard Deviation</li>
<li>etc</li>
</ul>
<h2>Presentation</h2>
<p>All of this would be presented and controlled through a app server, preferably Django or TG would be best.</p>
<h2>Inspiration</h2>
<ul>
<li><a href="http://www.centreon.com/Product/Pre-requisits-Centreon-2.x.html" rel="nofollow">Centreon</a></li>
<li><a href="http://cactiusers.org/index.php" rel="nofollow">Cacti</a></li>
</ul>
| 6 | 2008-10-22T07:16:23Z | 225,649 | <p>I'm not sure what your question is precisely, but for profiling Java (web)applications you can use the netbeans profiler and profiler4j (available on sourceforge). I have used both and can recommend them over eclipse tptp.</p>
<p>See <a href="http://stackoverflow.com/questions/186615/how-to-set-up-eclipse-tptp">http://stackoverflow.com/questions/186615/how-to-set-up-eclipse-tptp</a></p>
<p>and <a href="http://profiler4j.sourceforge.net/" rel="nofollow">http://profiler4j.sourceforge.net/</a></p>
<p>edit: Sorry, just noticed you tagged this as Python question, so this must not be a valid answer for you.</p>
| 0 | 2008-10-22T13:05:50Z | [
"python",
"mozilla",
"profiling"
] |
Open Source Profiling Frameworks? | 224,735 | <p>Have you ever wanted to test and quantitatively show whether your application would perform better as a static build or shared build, stripped or non-stripped, upx or no upx, gcc -O2 or gcc -O3, hash or btree, etc etc. If so this is the thread for you. There are hundreds of ways to tune an application, but how do we collect, organize, process, visualize the consequences of each experiment. </p>
<p>I have been looking for several months for an open source application performance engineering/profiling framework similar in concept to Mozilla's <a href="http://graphs.mozilla.org" rel="nofollow">Perftastic</a> where I can develop/build/test/profile hundreds of incarnations of different tuning experiments. </p>
<p>Some requirements:</p>
<h2>Platform</h2>
<p>SUSE32 and SUSE64</p>
<h2>Data Format</h2>
<p>Very flexible, compact, simple, hierarchical. There are several possibilities including</p>
<ul>
<li>Custom <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow">CSV</a></li>
<li><a href="http://en.wikipedia.org/wiki/RRDtool" rel="nofollow">RRD</a></li>
<li><a href="http://en.wikipedia.org/wiki/Protocol_buffers" rel="nofollow">Protocol Buffers</a></li>
<li><a href="http://en.wikipedia.org/wiki/Json" rel="nofollow">JSON</a></li>
<li>No XML. There is lots of data and XML is tooo verbose</li>
</ul>
<h2>Data Acquisition</h2>
<p>Flexible and Customizable plugins. There is lots of data to collect from the application including performance data from /proc, sys time, wall time, cpu utilization, memory profile, leaks, valgrind logs, arena fragmentation, I/O, localhost sockets, binary size, open fds, etc. And some from the host system. My language of choice for this is Python, and I would develop these plugins to monitor and/or parse data in all different formats and store them in the data format of the framework.</p>
<h2>Tagging</h2>
<p>All experiments would be tagged including data like GCC version and compile options, platform, host, app options, experiment, build tag, etc.</p>
<h2>Graphing</h2>
<p>History, Comparative, Hierarchical, Dynamic and Static.</p>
<ul>
<li>The application builds are done by a custom CI sever which releases a new app version several times per day the last 3 years straight. This is why we need a continuous trend analysis. When we add new features, make bug fixes, change build options, we want to automatically gather profiling data and see the trend. This is where generating various static builds is needed. </li>
<li>For analysis <a href="http://graphs.mozilla.org" rel="nofollow">Mozilla dynamic graphs</a> are great for doing comparative graphing. It would be great to have comparative graphing between different tags. For example compare N build versions, compare platforms, compare build options, etc. </li>
<li>We have a test suite of 3K tests, data will be gathered per test, and grouped from inter-test data, to per test, to per tagged group, to complete regression suite. </li>
<li>Possibilities include <a href="http://oss.oetiker.ch/rrdtool/index.en.html" rel="nofollow">RRDTool</a>, <a href="http://www.orcaware.com/orca/example_sites.html" rel="nofollow">Orca</a>, <a href="http://graphite.wikidot.com/screen-shots" rel="nofollow">Graphite</a></li>
</ul>
<h2>Analysis on a grouping basis</h2>
<ul>
<li>Min</li>
<li>Max</li>
<li>Median</li>
<li>Avg</li>
<li>Standard Deviation</li>
<li>etc</li>
</ul>
<h2>Presentation</h2>
<p>All of this would be presented and controlled through a app server, preferably Django or TG would be best.</p>
<h2>Inspiration</h2>
<ul>
<li><a href="http://www.centreon.com/Product/Pre-requisits-Centreon-2.x.html" rel="nofollow">Centreon</a></li>
<li><a href="http://cactiusers.org/index.php" rel="nofollow">Cacti</a></li>
</ul>
| 6 | 2008-10-22T07:16:23Z | 696,151 | <p>There was a talk at PyCon this week discussing the various profiling methods on Python today. I don't think anything is as complete as what your looking for, but it may be worth a look.
<a href="http://us.pycon.org/2009/conference/schedule/event/15/" rel="nofollow">http://us.pycon.org/2009/conference/schedule/event/15/</a></p>
<p>You should be able to find the actual talk later this week on blip.tv
<a href="http://blip.tv/search?q=pycon&x=0&y=0" rel="nofollow">http://blip.tv/search?q=pycon&x=0&y=0</a></p>
| 2 | 2009-03-30T06:14:29Z | [
"python",
"mozilla",
"profiling"
] |
Open Source Profiling Frameworks? | 224,735 | <p>Have you ever wanted to test and quantitatively show whether your application would perform better as a static build or shared build, stripped or non-stripped, upx or no upx, gcc -O2 or gcc -O3, hash or btree, etc etc. If so this is the thread for you. There are hundreds of ways to tune an application, but how do we collect, organize, process, visualize the consequences of each experiment. </p>
<p>I have been looking for several months for an open source application performance engineering/profiling framework similar in concept to Mozilla's <a href="http://graphs.mozilla.org" rel="nofollow">Perftastic</a> where I can develop/build/test/profile hundreds of incarnations of different tuning experiments. </p>
<p>Some requirements:</p>
<h2>Platform</h2>
<p>SUSE32 and SUSE64</p>
<h2>Data Format</h2>
<p>Very flexible, compact, simple, hierarchical. There are several possibilities including</p>
<ul>
<li>Custom <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow">CSV</a></li>
<li><a href="http://en.wikipedia.org/wiki/RRDtool" rel="nofollow">RRD</a></li>
<li><a href="http://en.wikipedia.org/wiki/Protocol_buffers" rel="nofollow">Protocol Buffers</a></li>
<li><a href="http://en.wikipedia.org/wiki/Json" rel="nofollow">JSON</a></li>
<li>No XML. There is lots of data and XML is tooo verbose</li>
</ul>
<h2>Data Acquisition</h2>
<p>Flexible and Customizable plugins. There is lots of data to collect from the application including performance data from /proc, sys time, wall time, cpu utilization, memory profile, leaks, valgrind logs, arena fragmentation, I/O, localhost sockets, binary size, open fds, etc. And some from the host system. My language of choice for this is Python, and I would develop these plugins to monitor and/or parse data in all different formats and store them in the data format of the framework.</p>
<h2>Tagging</h2>
<p>All experiments would be tagged including data like GCC version and compile options, platform, host, app options, experiment, build tag, etc.</p>
<h2>Graphing</h2>
<p>History, Comparative, Hierarchical, Dynamic and Static.</p>
<ul>
<li>The application builds are done by a custom CI sever which releases a new app version several times per day the last 3 years straight. This is why we need a continuous trend analysis. When we add new features, make bug fixes, change build options, we want to automatically gather profiling data and see the trend. This is where generating various static builds is needed. </li>
<li>For analysis <a href="http://graphs.mozilla.org" rel="nofollow">Mozilla dynamic graphs</a> are great for doing comparative graphing. It would be great to have comparative graphing between different tags. For example compare N build versions, compare platforms, compare build options, etc. </li>
<li>We have a test suite of 3K tests, data will be gathered per test, and grouped from inter-test data, to per test, to per tagged group, to complete regression suite. </li>
<li>Possibilities include <a href="http://oss.oetiker.ch/rrdtool/index.en.html" rel="nofollow">RRDTool</a>, <a href="http://www.orcaware.com/orca/example_sites.html" rel="nofollow">Orca</a>, <a href="http://graphite.wikidot.com/screen-shots" rel="nofollow">Graphite</a></li>
</ul>
<h2>Analysis on a grouping basis</h2>
<ul>
<li>Min</li>
<li>Max</li>
<li>Median</li>
<li>Avg</li>
<li>Standard Deviation</li>
<li>etc</li>
</ul>
<h2>Presentation</h2>
<p>All of this would be presented and controlled through a app server, preferably Django or TG would be best.</p>
<h2>Inspiration</h2>
<ul>
<li><a href="http://www.centreon.com/Product/Pre-requisits-Centreon-2.x.html" rel="nofollow">Centreon</a></li>
<li><a href="http://cactiusers.org/index.php" rel="nofollow">Cacti</a></li>
</ul>
| 6 | 2008-10-22T07:16:23Z | 1,649,316 | <p>You may have to build what you're looking for, but you might start from</p>
<ul>
<li><a href="http://stackoverflow.com/questions/tagged/valgrind">Valgrind</a></li>
<li>Luke Stackwalker</li>
<li>lots of other open-source projects</li>
</ul>
<p>Also, when the purpose is not so much to <em>measure</em> performance as to <em>improve</em> it, you might get some ideas from <a href="http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024">this</a>, where <a href="http://stackoverflow.com/questions/926266/performance-optimization-strategies-of-last-resort/927773#927773">this</a> is an example of its use.</p>
| 0 | 2009-10-30T11:37:11Z | [
"python",
"mozilla",
"profiling"
] |
How do you use the cursor for reading multiple files in database in python | 224,771 | <p>In python how do you read multiple files from a mysql database using the cursor or loop one by one and store the output in a separate table?</p>
| 0 | 2008-10-22T07:41:50Z | 224,801 | <p>I don't understand your question (what are files?, what's your table structure?), but here goes a simple sample:</p>
<pre><code>>>> import MySQLdb
>>> conn = MySQLdb.connect(host="localhost",
user="root",
password="merlin",
db="files")
>>> cursor = conn.cursor()
>>> cursor.execute("SELECT * FROM files")
5L
>>> rows = cursor.fetchall()
>>> cursor.execute("CREATE TABLE destination (file varchar(255))")
0L
>>> for row in rows:
... cursor.execute("INSERT INTO destination VALUES (%s)" % row[0])
...
1L
1L
1L
1L
1L
</code></pre>
| 1 | 2008-10-22T08:05:50Z | [
"python",
"mysql"
] |
How do you use the cursor for reading multiple files in database in python | 224,771 | <p>In python how do you read multiple files from a mysql database using the cursor or loop one by one and store the output in a separate table?</p>
| 0 | 2008-10-22T07:41:50Z | 224,844 | <p>Here is an example, assuming you have created the table you want to move to, with descriptive names:</p>
<pre><code>>>> import MySQLdb
>>> conn = MySQLdb.connect(user='username', db='dbname')
>>> cur = conn.cursor()
>>> cur.execute('select files from old_table where conditions=met')
>>> a = cur.fetchall()
>>> for item in a:
... cur.execute('update new_table set new_field = %s' % item) # `item` should be tuple with one value, else use "(item,)" with comma
</code></pre>
| 0 | 2008-10-22T08:19:48Z | [
"python",
"mysql"
] |
How can I generate a report file (ODF, PDF) from a django view | 224,796 | <p>I would like to generate a report file from a view&template in django.
Preferred file formats would be OpenOffice/ODF or PDF.</p>
<p>What is the best way to do this?</p>
<p>I do want to reuse the page layout defined in the template, possibly by redefining some blocks in a derived template.</p>
<p>Ideally, the report should be inserted into an existing template file so I can provide the overall page layout, headers and footer in the generated output format.</p>
| 6 | 2008-10-22T08:02:06Z | 224,951 | <p><a href="http://www.htmltopdf.org/" rel="nofollow">pisa/xhtml2pdf</a> should get you covered for PDF. It even includes an example Django project.</p>
| 4 | 2008-10-22T09:05:22Z | [
"python",
"django",
"pdf",
"pdf-generation"
] |
How can I generate a report file (ODF, PDF) from a django view | 224,796 | <p>I would like to generate a report file from a view&template in django.
Preferred file formats would be OpenOffice/ODF or PDF.</p>
<p>What is the best way to do this?</p>
<p>I do want to reuse the page layout defined in the template, possibly by redefining some blocks in a derived template.</p>
<p>Ideally, the report should be inserted into an existing template file so I can provide the overall page layout, headers and footer in the generated output format.</p>
| 6 | 2008-10-22T08:02:06Z | 226,168 | <p>Try ReportLab for PDF output:</p>
<p><a href="http://www.reportlab.org/" rel="nofollow">http://www.reportlab.org/</a></p>
| 3 | 2008-10-22T15:05:08Z | [
"python",
"django",
"pdf",
"pdf-generation"
] |
RFC 1123 Date Representation in Python? | 225,086 | <p>Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format</p>
<pre><code>Sun, 06 Nov 1994 08:49:37 GMT
</code></pre>
<p>Using <code>strftime</code> does not work, since the strings are locale-dependant. Do I have to build the string by hand?</p>
| 45 | 2008-10-22T09:59:21Z | 225,101 | <p>You can set LC_TIME to force stftime() to use a specific locale:</p>
<pre><code>>>> locale.setlocale(locale.LC_TIME, 'en_US')
'en_US'
>>> datetime.datetime.now().strftime(locale.nl_langinfo(locale.D_T_FMT))
'Wed 22 Oct 2008 06:05:39 AM '
</code></pre>
| 1 | 2008-10-22T10:05:46Z | [
"python",
"http",
"datetime"
] |
RFC 1123 Date Representation in Python? | 225,086 | <p>Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format</p>
<pre><code>Sun, 06 Nov 1994 08:49:37 GMT
</code></pre>
<p>Using <code>strftime</code> does not work, since the strings are locale-dependant. Do I have to build the string by hand?</p>
| 45 | 2008-10-22T09:59:21Z | 225,106 | <p>You can use wsgiref.handlers.format_date_time from the stdlib which does not rely on locale settings</p>
<pre><code>from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
now = datetime.now()
stamp = mktime(now.timetuple())
print format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:40 GMT
</code></pre>
<p>You can use email.utils.formatdate from the stdlib which does not rely on locale settings </p>
<pre><code>from email.utils import formatdate
from datetime import datetime
from time import mktime
now = datetime.now()
stamp = mktime(now.timetuple())
print formatdate(
timeval = stamp,
localtime = False,
usegmt = True
) #--> Wed, 22 Oct 2008 10:55:46 GMT
</code></pre>
<p>If you can set the locale process wide then you can do:</p>
<pre><code>import locale, datetime
locale.setlocale(locale.LC_TIME, 'en_US')
datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
</code></pre>
<p>If you don't want to set the locale process wide you could use <a href="http://babel.edgewall.org/">Babel</a> <a href="http://babel.edgewall.org/wiki/Documentation/dates.html">date formating</a></p>
<pre><code>from datetime import datetime
from babel.dates import format_datetime
now = datetime.utcnow()
format = 'EEE, dd LLL yyyy hh:mm:ss'
print format_datetime(now, format, locale='en') + ' GMT'
</code></pre>
<p>A manual way to format it which is identical with wsgiref.handlers.format_date_time is:</p>
<pre><code>def httpdate(dt):
"""Return a string representation of a date according to RFC 1123
(HTTP/1.1).
The supplied date must be in UTC.
"""
weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"][dt.month - 1]
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
dt.year, dt.hour, dt.minute, dt.second)
</code></pre>
| 66 | 2008-10-22T10:07:19Z | [
"python",
"http",
"datetime"
] |
RFC 1123 Date Representation in Python? | 225,086 | <p>Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format</p>
<pre><code>Sun, 06 Nov 1994 08:49:37 GMT
</code></pre>
<p>Using <code>strftime</code> does not work, since the strings are locale-dependant. Do I have to build the string by hand?</p>
| 45 | 2008-10-22T09:59:21Z | 225,177 | <p>You can use the formatdate() function from the Python standard email module:</p>
<pre><code>from email.utils import formatdate
print formatdate(timeval=None, localtime=False, usegmt=True)
</code></pre>
<p>Gives the current time in the desired format:</p>
<pre><code>Wed, 22 Oct 2008 10:32:33 GMT
</code></pre>
<p>In fact, this function does it "by hand" without using strftime()</p>
| 26 | 2008-10-22T10:34:04Z | [
"python",
"http",
"datetime"
] |
RFC 1123 Date Representation in Python? | 225,086 | <p>Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format</p>
<pre><code>Sun, 06 Nov 1994 08:49:37 GMT
</code></pre>
<p>Using <code>strftime</code> does not work, since the strings are locale-dependant. Do I have to build the string by hand?</p>
| 45 | 2008-10-22T09:59:21Z | 225,191 | <p>Well, here is a manual function to format it:</p>
<pre><code>def httpdate(dt):
"""Return a string representation of a date according to RFC 1123
(HTTP/1.1).
The supplied date must be in UTC.
"""
weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"][dt.month - 1]
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
dt.year, dt.hour, dt.minute, dt.second)
</code></pre>
| 1 | 2008-10-22T10:40:11Z | [
"python",
"http",
"datetime"
] |
RFC 1123 Date Representation in Python? | 225,086 | <p>Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format</p>
<pre><code>Sun, 06 Nov 1994 08:49:37 GMT
</code></pre>
<p>Using <code>strftime</code> does not work, since the strings are locale-dependant. Do I have to build the string by hand?</p>
| 45 | 2008-10-22T09:59:21Z | 37,191,167 | <p>If anybody reading this is working on a <strong>Django</strong> project, Django provides a function <a href="https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.http.http_date" rel="nofollow"><code>django.utils.http.http_date(epoch_seconds)</code></a>.</p>
<pre><code>from django.utils.http import http_date
some_datetime = some_object.last_update
response['Last-Modified'] = http_date(some_datetime.timestamp())
</code></pre>
| 1 | 2016-05-12T15:18:56Z | [
"python",
"http",
"datetime"
] |
Parsing different date formats from feedparser in python? | 225,274 | <p>I'm trying to get the dates from entries in two different RSS feeds through <a href="http://feedparser.org">feedparser</a>.</p>
<p>Here is what I'm doing:</p>
<pre><code>import feedparser as fp
reddit = fp.parse("http://www.reddit.com/.rss")
cc = fp.parse("http://contentconsumer.com/feed")
print reddit.entries[0].date
print cc.entries[0].date
</code></pre>
<p>And here's how they come out:</p>
<pre><code>2008-10-21T22:23:28.033841+00:00
Wed, 15 Oct 2008 10:06:10 +0000
</code></pre>
<p>I want to get to the point where I can find out which is newer easily.</p>
<p>I've tried using the datetime module of Python and searching through the feedparser documentation, but I can't get past this problem. Any help would be much appreciated.</p>
| 8 | 2008-10-22T11:09:20Z | 225,382 | <p>Parsing of dates is a pain with RSS feeds in-the-wild, and that's where <code>feedparser</code> can be a big help.</p>
<p>If you use the <code>*_parsed</code> properties (like <code>updated_parsed</code>), <code>feedparser</code> will have done the work and will return a 9-tuple Python date in UTC.</p>
<p>See <a href="http://packages.python.org/feedparser/date-parsing.html" rel="nofollow">http://packages.python.org/feedparser/date-parsing.html</a> for more gory details.</p>
| 14 | 2008-10-22T11:35:42Z | [
"python",
"datetime",
"parsing",
"rss",
"feedparser"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 225,788 | <p>Don't know if it would do : <a href="http://bitten.edgewall.org/">Bitten</a> is made by the guys who write Trac and is integrated with Trac. <a href="http://gump.apache.org/">Apache Gump</a> is the CI tool used by Apache. It is written in Python.</p>
| 10 | 2008-10-22T13:46:55Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 228,196 | <p>We've had great success with <a href="http://www.jetbrains.com/teamcity/">TeamCity</a> as our CI server and using nose as our test runner. <a href="http://pypi.python.org/pypi/teamcity-nose">Teamcity plugin for nosetests</a> gives you count pass/fail, readable display for failed test( that can be E-Mailed). You can even see details of the test failures while you stack is running. </p>
<p>If of course supports things like running on multiple machines, and it's much simpler to setup and maintain than buildbot.</p>
| 9 | 2008-10-23T01:30:17Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 667,800 | <p>You might want to check out <a href="http://somethingaboutorange.com/mrl/projects/nose/">Nose</a> and <a href="http://nose.readthedocs.org/en/latest/plugins/xunit.html">the Xunit output plugin</a>. You can have it run your unit tests, and coverage checks with this command:</p>
<pre><code>nosetests --with-xunit --enable-cover
</code></pre>
<p>That'll be helpful if you want to go the Jenkins route, or if you want to use another CI server that has support for JUnit test reporting.</p>
<p>Similarly you can capture the output of pylint using the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Violations">violations plugin for Jenkins</a></p>
| 40 | 2009-03-20T20:13:24Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 2,026,520 | <p>Buildbot's waterfall page can be considerably prettified. Here's a nice example <a href="http://build.chromium.org/buildbot/waterfall/waterfall">http://build.chromium.org/buildbot/waterfall/waterfall</a></p>
| 8 | 2010-01-08T09:16:55Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 2,213,516 | <p>We have used bitten quite a bit. It is pretty and integrates well with Trac, but it is a pain in the butt to customize if you have any nonstandard workflow. Also there just aren't as many plugins as there are for the more popular tools. Currently we are evaluating Hudson as a replacement.</p>
| 0 | 2010-02-06T15:03:28Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 2,535,738 | <p>Signal is another option. You can know more about it and watch a video also <a href="http://www.diegocarrion.com/2009/10/30/really-easy-continuous-integration-with-signal/" rel="nofollow">here</a>.</p>
| 2 | 2010-03-29T04:05:02Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 5,119,040 | <p>I guess this thread is quite old but here is my take on it with hudson:</p>
<p>I decided to go with pip and set up a repo (the painful to get working but nice looking eggbasket), which hudson auto uploads to with a successful tests. Here is my rough and ready script for use with a hudson config execute script like: /var/lib/hudson/venv/main/bin/hudson_script.py -w $WORKSPACE -p my.package -v $BUILD_NUMBER, just put in **/coverage.xml, pylint.txt and nosetests.xml in the config bits:</p>
<pre><code>#!/var/lib/hudson/venv/main/bin/python
import os
import re
import subprocess
import logging
import optparse
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s')
#venvDir = "/var/lib/hudson/venv/main/bin/"
UPLOAD_REPO = "http://ldndev01:3442"
def call_command(command, cwd, ignore_error_code=False):
try:
logging.info("Running: %s" % command)
status = subprocess.call(command, cwd=cwd, shell=True)
if not ignore_error_code and status != 0:
raise Exception("Last command failed")
return status
except:
logging.exception("Could not run command %s" % command)
raise
def main():
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option("-w", "--workspace", dest="workspace",
help="workspace folder for the job")
parser.add_option("-p", "--package", dest="package",
help="the package name i.e., back_office.reconciler")
parser.add_option("-v", "--build_number", dest="build_number",
help="the build number, which will get put at the end of the package version")
options, args = parser.parse_args()
if not options.workspace or not options.package:
raise Exception("Need both args, do --help for info")
venvDir = options.package + "_venv/"
#find out if venv is there
if not os.path.exists(venvDir):
#make it
call_command("virtualenv %s --no-site-packages" % venvDir,
options.workspace)
#install the venv/make sure its there plus install the local package
call_command("%sbin/pip install -e ./ --extra-index %s" % (venvDir, UPLOAD_REPO),
options.workspace)
#make sure pylint, nose and coverage are installed
call_command("%sbin/pip install nose pylint coverage epydoc" % venvDir,
options.workspace)
#make sure we have an __init__.py
#this shouldn't be needed if the packages are set up correctly
#modules = options.package.split(".")
#if len(modules) > 1:
# call_command("touch '%s/__init__.py'" % modules[0],
# options.workspace)
#do the nosetests
test_status = call_command("%sbin/nosetests %s --with-xunit --with-coverage --cover-package %s --cover-erase" % (venvDir,
options.package.replace(".", "/"),
options.package),
options.workspace, True)
#produce coverage report -i for ignore weird missing file errors
call_command("%sbin/coverage xml -i" % venvDir,
options.workspace)
#move it so that the code coverage plugin can find it
call_command("mv coverage.xml %s" % (options.package.replace(".", "/")),
options.workspace)
#run pylint
call_command("%sbin/pylint --rcfile ~/pylint.rc -f parseable %s > pylint.txt" % (venvDir,
options.package),
options.workspace, True)
#remove old dists so we only have the newest at the end
call_command("rm -rfv %s" % (options.workspace + "/dist"),
options.workspace)
#if the build passes upload the result to the egg_basket
if test_status == 0:
logging.info("Success - uploading egg")
upload_bit = "upload -r %s/upload" % UPLOAD_REPO
else:
logging.info("Failure - not uploading egg")
upload_bit = ""
#create egg
call_command("%sbin/python setup.py egg_info --tag-build=.0.%s --tag-svn-revision --tag-date sdist %s" % (venvDir,
options.build_number,
upload_bit),
options.workspace)
call_command("%sbin/epydoc --html --graph all %s" % (venvDir, options.package),
options.workspace)
logging.info("Complete")
if __name__ == "__main__":
main()
</code></pre>
<p>When it comes to deploying stuff you can do something like:</p>
<pre><code>pip -E /location/of/my/venv/ install my_package==X.Y.Z --extra-index http://my_repo
</code></pre>
<p>And then people can develop stuff using:</p>
<pre><code>pip -E /location/of/my/venv/ install -e ./ --extra-index http://my_repo
</code></pre>
<p>This stuff assumes you have a repo structure per package with a setup.py and dependencies all set up then you can just check out the trunk and run this stuff on it.</p>
<p>I hope this helps someone out.</p>
<p>------update---------</p>
<p>I've added epydoc which fits in really nicely with hudson. Just add javadoc to your config with the html folder</p>
<p>Note that pip doesn't support the -E flag properly these days, so you have to create your venv separately</p>
| 6 | 2011-02-25T15:25:37Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 6,511,097 | <p>Atlassian's <a href="http://www.atlassian.com/software/bamboo">Bamboo</a> is also definitely worth checking out. The entire Atlassian suite (JIRA, Confluence, FishEye, etc) is pretty sweet.</p>
| 5 | 2011-06-28T18:08:12Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 8,572,594 | <p>another one : <a href="https://www.shiningpanda.com/" rel="nofollow">Shining Panda</a> is a hosted tool for python</p>
| 3 | 2011-12-20T08:28:42Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
"Pretty" Continuous Integration for Python | 225,598 | <p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p>
<p>For example, compared to..</p>
<ul>
<li><a href="http://phpundercontrol.org/about.html">phpUnderControl</a></li>
<li><a href="http://jenkins-ci.org/content/about-jenkins-ci">Jenkins</a>
<ul>
<li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson">Hudson</a></li>
</ul></li>
<li><a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl.rb</a></li>
</ul>
<p>..and others, <a href="http://buildbot.python.org/stable/">BuildBot</a> looks rather.. archaic</p>
<p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p>
<p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p>
<hr>
<p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org">Jenkins</a> is different.</p>
<p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p>
<p>Setting Hudson up for a Python project was pretty simple:</p>
<ul>
<li>Download Hudson from <a href="http://hudson-ci.org/">http://hudson-ci.org/</a></li>
<li>Run it with <code>java -jar hudson.war</code></li>
<li>Open the web interface on the default address of <code>http://localhost:8080</code></li>
<li>Go to Manage Hudson, Plugins, click "Update" or similar</li>
<li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li>
<li>Create a new project, enter the repository, SCM polling intervals and so on</li>
<li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li>
<li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li>
<li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li>
</ul>
<p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p>
<ul>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/">sloccount</a> separately</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li>
<li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li>
</ul>
| 112 | 2008-10-22T12:49:54Z | 10,363,583 | <p>If you're considering hosted CI solution, and doing open source, you should look into <a href="http://travis-ci.org/" rel="nofollow">Travis CI</a> as well - it has very nice integration with GitHub. While it started as a Ruby tool, they have <a href="http://about.travis-ci.org/blog/announcing_python_and_perl_support_on_travis_ci/" rel="nofollow">added Python support</a> a while ago.</p>
| 3 | 2012-04-28T12:43:00Z | [
"python",
"jenkins",
"continuous-integration",
"buildbot"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.