title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Appengine - Possible to get an entity using only key string without model name?
776,324
<p>I want to be able to have a view that will act upon a number of different types of objects</p> <p>all the view will get is the key string eg:</p> <p>agpwb2xsdGhyZWFkchULEg9wb2xsY29yZV9hbnN3ZXIYAww</p> <p>without knowing the model type, is it possible to retrieve the entity from just that key string?</p> <p>thanks</p>
3
2009-04-22T09:15:04Z
918,507
<p>No superclassing required, just use db.get():</p> <pre><code>from google.appengine.ext import db key_str = 'agpwb2xsdGhyZWFkchULEg9wb2xsY29yZV9hbnN3ZXIYAww' entity = db.get(key_str) </code></pre>
11
2009-05-27T23:34:25Z
[ "python", "google-app-engine" ]
Qt-style documentation using Doxygen?
776,388
<p>How do I produce Qt-style documentation (Trolltech's C++ Qt or Riverbank's PyQt docs) with Doxygen? I am documenting Python, and I would like to be able to improve the default function brief that it produces.</p> <p>In particular, I would like to be able to see the return type (which can be user specified) and the parameters in the function brief.</p> <p>For example:</p> <pre><code> Functions: int getNumber(self) str getString(self) tuple getTuple(self, int numberOfElements=2) Function Documentation: int getNumber(self) gets the number of items within a list as specified... Definition at line 63 of .... etc... </code></pre> <p>If this isn't possible without modifying the source, maybe there is another tool other than Doxygen that handles Python documentation in this kind of way?</p>
3
2009-04-22T09:38:34Z
776,468
<p>If you're doing anything documentation related when it comes to Python I recommend <a href="http://sphinx.pocoo.org/" rel="nofollow" title="Sphinx">Sphinx</a>. It's what the developers of python use for their documentation.</p>
1
2009-04-22T10:01:16Z
[ "python", "documentation", "doxygen" ]
Qt-style documentation using Doxygen?
776,388
<p>How do I produce Qt-style documentation (Trolltech's C++ Qt or Riverbank's PyQt docs) with Doxygen? I am documenting Python, and I would like to be able to improve the default function brief that it produces.</p> <p>In particular, I would like to be able to see the return type (which can be user specified) and the parameters in the function brief.</p> <p>For example:</p> <pre><code> Functions: int getNumber(self) str getString(self) tuple getTuple(self, int numberOfElements=2) Function Documentation: int getNumber(self) gets the number of items within a list as specified... Definition at line 63 of .... etc... </code></pre> <p>If this isn't possible without modifying the source, maybe there is another tool other than Doxygen that handles Python documentation in this kind of way?</p>
3
2009-04-22T09:38:34Z
776,577
<p><a href="http://doc.trolltech.com/4.4/qthelp.html" rel="nofollow">This page</a> seem to detail the method of creating a qt-style docs.<br /> basically there's a tool you get with qt called <code>qhelpgenerator</code> which creates a <code>.qch</code> file, edible by the qt assistant.<br /> I haven't used it before but it looks fairly simple.</p>
0
2009-04-22T10:44:12Z
[ "python", "documentation", "doxygen" ]
Qt-style documentation using Doxygen?
776,388
<p>How do I produce Qt-style documentation (Trolltech's C++ Qt or Riverbank's PyQt docs) with Doxygen? I am documenting Python, and I would like to be able to improve the default function brief that it produces.</p> <p>In particular, I would like to be able to see the return type (which can be user specified) and the parameters in the function brief.</p> <p>For example:</p> <pre><code> Functions: int getNumber(self) str getString(self) tuple getTuple(self, int numberOfElements=2) Function Documentation: int getNumber(self) gets the number of items within a list as specified... Definition at line 63 of .... etc... </code></pre> <p>If this isn't possible without modifying the source, maybe there is another tool other than Doxygen that handles Python documentation in this kind of way?</p>
3
2009-04-22T09:38:34Z
777,981
<p>Then just use Doxygen? <a href="http://internetducttape.com/2007/03/20/automatic%5Fdocumentation%5Fpython%5Fdoxygen/" rel="nofollow">This will get you started</a>:</p> <blockquote> <p>This is a guide for automatically generating documentation off of Python source code using Doxygen.</p> </blockquote> <p>Obviously, since Python is not strongly typed, specifying the return type and the expected type of the parameters will be up to you, the documentation writer. That's just best practices anyway.</p>
2
2009-04-22T16:00:26Z
[ "python", "documentation", "doxygen" ]
Qt-style documentation using Doxygen?
776,388
<p>How do I produce Qt-style documentation (Trolltech's C++ Qt or Riverbank's PyQt docs) with Doxygen? I am documenting Python, and I would like to be able to improve the default function brief that it produces.</p> <p>In particular, I would like to be able to see the return type (which can be user specified) and the parameters in the function brief.</p> <p>For example:</p> <pre><code> Functions: int getNumber(self) str getString(self) tuple getTuple(self, int numberOfElements=2) Function Documentation: int getNumber(self) gets the number of items within a list as specified... Definition at line 63 of .... etc... </code></pre> <p>If this isn't possible without modifying the source, maybe there is another tool other than Doxygen that handles Python documentation in this kind of way?</p>
3
2009-04-22T09:38:34Z
778,010
<p>You do not have to put doxygen comments in the code. You can put the documentation in other places. Check out <a href="http://www.stack.nl/~dimitri/doxygen/docblocks.html#structuralcommands" rel="nofollow">this</a> page in the doxygen manual. </p>
0
2009-04-22T16:07:32Z
[ "python", "documentation", "doxygen" ]
Simple webserver or web testing framework
776,495
<p>Need to testcase a complex webapp which does some interacting with a remote 3rd party cgi based webservices. Iam planing to implement some of the 3rd party services in a dummy webserver, so that i have full controll about the testcases. Looking for a simple python http webserver or framework to emulate the 3rd party interface.</p>
2
2009-04-22T10:17:32Z
776,505
<p>I would look into <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>.</p>
0
2009-04-22T10:20:07Z
[ "python", "web-services", "testing", "web-applications" ]
Simple webserver or web testing framework
776,495
<p>Need to testcase a complex webapp which does some interacting with a remote 3rd party cgi based webservices. Iam planing to implement some of the 3rd party services in a dummy webserver, so that i have full controll about the testcases. Looking for a simple python http webserver or framework to emulate the 3rd party interface.</p>
2
2009-04-22T10:17:32Z
776,553
<p>You might be happiest with a WSGI service, since it's most like CGI.</p> <p>Look at <a href="http://werkzeug.pocoo.org/" rel="nofollow">werkzeug</a>.</p>
2
2009-04-22T10:36:19Z
[ "python", "web-services", "testing", "web-applications" ]
Simple webserver or web testing framework
776,495
<p>Need to testcase a complex webapp which does some interacting with a remote 3rd party cgi based webservices. Iam planing to implement some of the 3rd party services in a dummy webserver, so that i have full controll about the testcases. Looking for a simple python http webserver or framework to emulate the 3rd party interface.</p>
2
2009-04-22T10:17:32Z
776,604
<p>Take a look the standard module wsgiref:</p> <p><a href="https://docs.python.org/2.6/library/wsgiref.html" rel="nofollow">https://docs.python.org/2.6/library/wsgiref.html</a></p> <p>At the end of that page is a small example. Something like this could already be sufficient for your needs.</p>
2
2009-04-22T10:50:53Z
[ "python", "web-services", "testing", "web-applications" ]
Simple webserver or web testing framework
776,495
<p>Need to testcase a complex webapp which does some interacting with a remote 3rd party cgi based webservices. Iam planing to implement some of the 3rd party services in a dummy webserver, so that i have full controll about the testcases. Looking for a simple python http webserver or framework to emulate the 3rd party interface.</p>
2
2009-04-22T10:17:32Z
776,891
<p>Use <a href="http://cherrypy.org" rel="nofollow">cherrypy</a>, take a look at Hello World:</p> <pre><code>import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.exposed = True cherrypy.quickstart(HelloWorld()) </code></pre> <p>Run this code and you have a very fast Hello World server ready on <code>localhost</code> port <code>8080</code>!! Pretty easy huh?</p>
4
2009-04-22T12:06:00Z
[ "python", "web-services", "testing", "web-applications" ]
Simple webserver or web testing framework
776,495
<p>Need to testcase a complex webapp which does some interacting with a remote 3rd party cgi based webservices. Iam planing to implement some of the 3rd party services in a dummy webserver, so that i have full controll about the testcases. Looking for a simple python http webserver or framework to emulate the 3rd party interface.</p>
2
2009-04-22T10:17:32Z
794,358
<p>It might be simpler sense to mock (or stub, or whatever the term is) urllib, or whatever module you are using to communicate with the remote web-service?</p> <p>Even simply overriding <code>urllib.urlopen</code> might be enough:</p> <pre><code>import urllib from StringIO import StringIO class mock_response(StringIO): def info(self): raise NotImplementedError("mocked urllib response has no info method") def getinfo(): raise NotImplementedError("mocked urllib response has no getinfo method") def urlopen(url): if url == "http://example.com/api/something": resp = mock_response("&lt;xml&gt;&lt;/xml&gt;") return resp else: urllib.urlopen(url) is_unittest = True if is_unittest: urllib.urlopen = urlopen print urllib.urlopen("http://example.com/api/something").read() </code></pre> <p>I used something very similar <a href="http://github.com/dbr/themoviedb/blob/cc6fbb3c67df9bcedc14e2bcdfc1e56c06da0c33/stub%5Furllib.py" rel="nofollow">here</a>, to emulate a simple API, before I got an API key.</p>
0
2009-04-27T16:52:21Z
[ "python", "web-services", "testing", "web-applications" ]
Using Twisted's twisted.web classes, how do I flush my outgoing buffers?
776,631
<p>I've made a simple http server using Twisted, which sends the Content-Type: multipart/x-mixed-replace header. I'm using this to test an http client which I want to set up to accept a long-term stream.</p> <p>The problem that has arisen is that my client request hangs until the <em>http.Request</em> calls self.finish(), then it receives all multipart documents at once.</p> <p>Is there a way to manually flush the output buffers down to the client? I'm assuming this is why I'm not receiving the individual multipart documents.</p> <pre><code>#!/usr/bin/env python import time from twisted.web import http from twisted.internet import protocol class StreamHandler(http.Request): BOUNDARY = 'BOUNDARY' def writeBoundary(self): self.write("--%s\n" % (self.BOUNDARY)) def writeStop(self): self.write("--%s--\n" % (self.BOUNDARY)) def process(self): self.setHeader('Connection', 'Keep-Alive') self.setHeader('Content-Type', "multipart/x-mixed-replace;boundary=%s" % (self.BOUNDARY)) self.writeBoundary() self.write("Content-Type: text/html\n") s = "&lt;html&gt;foo&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeBoundary() time.sleep(2) self.write("Content-Type: text/html\n") s = "&lt;html&gt;bar&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeBoundary() time.sleep(2) self.write("Content-Type: text/html\n") s = "&lt;html&gt;baz&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeStop() self.finish() class StreamProtocol(http.HTTPChannel): requestFactory = StreamHandler class StreamFactory(http.HTTPFactory): protocol = StreamProtocol if __name__ == '__main__': from twisted.internet import reactor reactor.listenTCP(8800, StreamFactory()) reactor.run() </code></pre>
9
2009-04-22T10:57:50Z
800,427
<p>The reason seems to be explained in the <a href="http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#WhydoesittakealongtimefordataIsendwithtransport.writetoarriveattheothersideoftheconnection" rel="nofollow">FAQ for twisted</a>. The twisted server does not actually write anything to the underlining connection until the reactor thread is free to run, in this case at the end of your method. However you can use <a href="http://twistedmatrix.com/documents/current/api/twisted.internet.default.SelectReactor.html#doSelect" rel="nofollow">reactor.doSelect(timeout)</a> before each of your sleeps to make the reactor write what it has to the connection.</p>
1
2009-04-29T00:41:01Z
[ "python", "twisted", "multipart-mixed-replace" ]
Using Twisted's twisted.web classes, how do I flush my outgoing buffers?
776,631
<p>I've made a simple http server using Twisted, which sends the Content-Type: multipart/x-mixed-replace header. I'm using this to test an http client which I want to set up to accept a long-term stream.</p> <p>The problem that has arisen is that my client request hangs until the <em>http.Request</em> calls self.finish(), then it receives all multipart documents at once.</p> <p>Is there a way to manually flush the output buffers down to the client? I'm assuming this is why I'm not receiving the individual multipart documents.</p> <pre><code>#!/usr/bin/env python import time from twisted.web import http from twisted.internet import protocol class StreamHandler(http.Request): BOUNDARY = 'BOUNDARY' def writeBoundary(self): self.write("--%s\n" % (self.BOUNDARY)) def writeStop(self): self.write("--%s--\n" % (self.BOUNDARY)) def process(self): self.setHeader('Connection', 'Keep-Alive') self.setHeader('Content-Type', "multipart/x-mixed-replace;boundary=%s" % (self.BOUNDARY)) self.writeBoundary() self.write("Content-Type: text/html\n") s = "&lt;html&gt;foo&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeBoundary() time.sleep(2) self.write("Content-Type: text/html\n") s = "&lt;html&gt;bar&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeBoundary() time.sleep(2) self.write("Content-Type: text/html\n") s = "&lt;html&gt;baz&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeStop() self.finish() class StreamProtocol(http.HTTPChannel): requestFactory = StreamHandler class StreamFactory(http.HTTPFactory): protocol = StreamProtocol if __name__ == '__main__': from twisted.internet import reactor reactor.listenTCP(8800, StreamFactory()) reactor.run() </code></pre>
9
2009-04-22T10:57:50Z
802,632
<p>Using <code>time.sleep()</code> prevents twisted from doing its job. To make it work you can't use <code>time.sleep()</code>, you must return control to twisted instead. The easiest way to modify your existing code to do that is by using <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.defer.html#inlineCallbacks"><code>twisted.internet.defer.inlineCallbacks</code></a>, which is the next best thing since sliced bread:</p> <pre><code>#!/usr/bin/env python import time from twisted.web import http from twisted.internet import protocol from twisted.internet import reactor from twisted.internet import defer def wait(seconds, result=None): """Returns a deferred that will be fired later""" d = defer.Deferred() reactor.callLater(seconds, d.callback, result) return d class StreamHandler(http.Request): BOUNDARY = 'BOUNDARY' def writeBoundary(self): self.write("--%s\n" % (self.BOUNDARY)) def writeStop(self): self.write("--%s--\n" % (self.BOUNDARY)) @defer.inlineCallbacks def process(self): self.setHeader('Connection', 'Keep-Alive') self.setHeader('Content-Type', "multipart/x-mixed-replace;boundary=%s" % (self.BOUNDARY)) self.writeBoundary() self.write("Content-Type: text/html\n") s = "&lt;html&gt;foo&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeBoundary() yield wait(2) self.write("Content-Type: text/html\n") s = "&lt;html&gt;bar&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeBoundary() yield wait(2) self.write("Content-Type: text/html\n") s = "&lt;html&gt;baz&lt;/html&gt;\n" self.write("Content-Length: %s\n\n" % (len(s))) self.write(s) self.writeStop() self.finish() class StreamProtocol(http.HTTPChannel): requestFactory = StreamHandler class StreamFactory(http.HTTPFactory): protocol = StreamProtocol if __name__ == '__main__': reactor.listenTCP(8800, StreamFactory()) reactor.run() </code></pre> <p>That works in firefox, I guess it answers your question correctly.</p>
9
2009-04-29T14:30:35Z
[ "python", "twisted", "multipart-mixed-replace" ]
fastest way to store comment data python
777,090
<p>Hi I have a small comment shoutbox type cgi process running on a server and currently when someone leaves a comment I simply format that comment into html i.e</p> <p><code>&lt;p class="title"&gt;$title&lt;/p&gt; &lt;p class="comment"&gt;$comment&lt;/p&gt;</code></p> <p>and store in a flat file. Would it be faster and acceptably low in LOC to reimplement the storage in xml or json, in a simple spec of my own or stick with the simple html route?. </p> <p>I don't want to use relational database for this.</p>
1
2009-04-22T12:56:55Z
777,119
<p>If a flat file is fast enough, then go with that, since it's very simple and accessible. Storing as XML and JSON but still using a flat file probably is very comparable in performance.</p> <p>You might want to consider (ignore this if you just left it out of your question) sanitizing/filtering the text, so that users can't break your HTML by e.g. entering "&lt;/p>" in the comment text.</p>
3
2009-04-22T13:04:24Z
[ "python", "xml", "json" ]
fastest way to store comment data python
777,090
<p>Hi I have a small comment shoutbox type cgi process running on a server and currently when someone leaves a comment I simply format that comment into html i.e</p> <p><code>&lt;p class="title"&gt;$title&lt;/p&gt; &lt;p class="comment"&gt;$comment&lt;/p&gt;</code></p> <p>and store in a flat file. Would it be faster and acceptably low in LOC to reimplement the storage in xml or json, in a simple spec of my own or stick with the simple html route?. </p> <p>I don't want to use relational database for this.</p>
1
2009-04-22T12:56:55Z
777,173
<p>XML is nice, clean way to store this type of data. In Python, you could use <a href="http://codespeak.net/lxml/tutorial.html" rel="nofollow">lxml</a> to create/update the file:</p> <pre><code>from lxml import etree P_XML = 'xml_file_path.xml' def save_comment(title_text, comment_text): comment = etree.Element('comment') title = etree.SubElement(comment, 'title') title.text = title_text comment.text = comment_text f = open(P_XML, 'a') f.write(etree.tostring(comment, pretty_print=True)) f.close() save_comment("FIRST!", "FIRST COMMENT!!!") save_comment("Awesome", "I love this site!") </code></pre> <p>That's a simple start, but you could do a lot more (i.e. set up an ID for each comment, read in the XML using lxml parser and add to it instead of just appending the file).</p>
1
2009-04-22T13:19:06Z
[ "python", "xml", "json" ]
fastest way to store comment data python
777,090
<p>Hi I have a small comment shoutbox type cgi process running on a server and currently when someone leaves a comment I simply format that comment into html i.e</p> <p><code>&lt;p class="title"&gt;$title&lt;/p&gt; &lt;p class="comment"&gt;$comment&lt;/p&gt;</code></p> <p>and store in a flat file. Would it be faster and acceptably low in LOC to reimplement the storage in xml or json, in a simple spec of my own or stick with the simple html route?. </p> <p>I don't want to use relational database for this.</p>
1
2009-04-22T12:56:55Z
777,388
<p>A flat-file is the fastest form of persistence. Period. There's no formatting, encoding, indexing, locking, or anything.</p> <p>JSON (and YAML) impose some overheads. They will be slower. There's some formatting that must be done.</p> <p>XML imposes more overheads than JSON/YAML. It will be slower still. There's a fair amount of formatting that must be done.</p> <p>The more overhead, the slower it will be.</p> <p>None of these have anything to do with sanitizing the comment input so that it will display as valid HTML. You should use <a href="http://docs.python.org/library/cgi.html#cgi.escape" rel="nofollow">cgi.escape</a> to escape any HTML-like character sequences in the comment before saving the text to a file.</p>
1
2009-04-22T14:08:08Z
[ "python", "xml", "json" ]
Python reflection - Can I use this to get the source code of a method definition
777,371
<p><strong>Duplicate of..</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/427453/how-can-i-get-the-code-of-python-function">How can I get the code of python function?</a></li> <li><a href="http://stackoverflow.com/questions/334851/print-the-code-which-defined-a-lambda-function">print the code which defined a lambda function</a></li> <li><a href="http://stackoverflow.com/questions/399991/python-how-do-you-get-python-to-write-down-the-code-of-a-function-it-has-in-memo">Python: How do you get Python to write down the code of a function it has in memory?</a></li> </ul> <p><hr /></p> <p>I have a method definition which is successfully running, but would like to modify it in runtime.</p> <p>for eg: If i have a method</p> <pre><code>def sayHello(): print "Hello" </code></pre> <p>type(sayHello) gives me the answer 'type function'. Will I able to get the source code string of this function object. Is it considered a security issue ?</p>
8
2009-04-22T14:05:23Z
777,395
<p><code>sayHello.func_code.co_code</code> returns a string that I think contains the compiled code of the method. Since Python is internally compiling the code to virtual machine bytecode, this might be all that's left.</p> <p>You can disassemble it, though:</p> <pre><code>import dis def sayHello(): print "hello" dis.dis(sayHello) </code></pre> <p>This prints:</p> <pre> 1 0 LOAD_CONST 1 ('hello') 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE </pre> <p>Have a look at <a href="http://www.crazy-compilers.com/decompyle/" rel="nofollow">Decompyle</a> for a de-compiler.</p>
2
2009-04-22T14:09:07Z
[ "python", "reflection" ]
Python reflection - Can I use this to get the source code of a method definition
777,371
<p><strong>Duplicate of..</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/427453/how-can-i-get-the-code-of-python-function">How can I get the code of python function?</a></li> <li><a href="http://stackoverflow.com/questions/334851/print-the-code-which-defined-a-lambda-function">print the code which defined a lambda function</a></li> <li><a href="http://stackoverflow.com/questions/399991/python-how-do-you-get-python-to-write-down-the-code-of-a-function-it-has-in-memo">Python: How do you get Python to write down the code of a function it has in memory?</a></li> </ul> <p><hr /></p> <p>I have a method definition which is successfully running, but would like to modify it in runtime.</p> <p>for eg: If i have a method</p> <pre><code>def sayHello(): print "Hello" </code></pre> <p>type(sayHello) gives me the answer 'type function'. Will I able to get the source code string of this function object. Is it considered a security issue ?</p>
8
2009-04-22T14:05:23Z
777,403
<p>There is not a built-in function to get source code of a function, however, you could build you own if you have access to the source-code (it would be in your Python/lib directory).</p>
0
2009-04-22T14:10:02Z
[ "python", "reflection" ]
Python reflection - Can I use this to get the source code of a method definition
777,371
<p><strong>Duplicate of..</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/427453/how-can-i-get-the-code-of-python-function">How can I get the code of python function?</a></li> <li><a href="http://stackoverflow.com/questions/334851/print-the-code-which-defined-a-lambda-function">print the code which defined a lambda function</a></li> <li><a href="http://stackoverflow.com/questions/399991/python-how-do-you-get-python-to-write-down-the-code-of-a-function-it-has-in-memo">Python: How do you get Python to write down the code of a function it has in memory?</a></li> </ul> <p><hr /></p> <p>I have a method definition which is successfully running, but would like to modify it in runtime.</p> <p>for eg: If i have a method</p> <pre><code>def sayHello(): print "Hello" </code></pre> <p>type(sayHello) gives me the answer 'type function'. Will I able to get the source code string of this function object. Is it considered a security issue ?</p>
8
2009-04-22T14:05:23Z
777,875
<p>Use the inspect module:</p> <pre><code>import inspect import mymodule print inspect.getsource(mymodule.sayHello) </code></pre> <p>The function must be defined in a module that you import.</p>
16
2009-04-22T15:37:27Z
[ "python", "reflection" ]
Python reflection - Can I use this to get the source code of a method definition
777,371
<p><strong>Duplicate of..</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/427453/how-can-i-get-the-code-of-python-function">How can I get the code of python function?</a></li> <li><a href="http://stackoverflow.com/questions/334851/print-the-code-which-defined-a-lambda-function">print the code which defined a lambda function</a></li> <li><a href="http://stackoverflow.com/questions/399991/python-how-do-you-get-python-to-write-down-the-code-of-a-function-it-has-in-memo">Python: How do you get Python to write down the code of a function it has in memory?</a></li> </ul> <p><hr /></p> <p>I have a method definition which is successfully running, but would like to modify it in runtime.</p> <p>for eg: If i have a method</p> <pre><code>def sayHello(): print "Hello" </code></pre> <p>type(sayHello) gives me the answer 'type function'. Will I able to get the source code string of this function object. Is it considered a security issue ?</p>
8
2009-04-22T14:05:23Z
23,086,681
<p>To get the source of a method on a class instance do:</p> <pre><code>import inspect myobj = MyModel() print inspect.getsource(myobj.my_method) </code></pre> <p>Read more: <a href="https://docs.python.org/2/library/inspect.html#inspect.getsource" rel="nofollow">https://docs.python.org/2/library/inspect.html#inspect.getsource</a></p>
0
2014-04-15T14:28:37Z
[ "python", "reflection" ]
Django Form values without HTML escape
777,458
<p>I need to set the Django forms.ChoiceField to display the currency symbols. Since django forms escape all the HTML ASCII characters, I can't get the &amp;#36; ( <strong>&euro;</strong> ) or the &amp;pound; ( <strong>&pound;</strong> ) to display the currency symbol.</p> <pre><code>&lt;select id="id_currency" name="currency"&gt; &lt;option value="&amp;amp;#36;"&gt;&amp;#36;&lt;/option&gt; &lt;option value="&amp;amp;pound;"&gt;&amp;pound;&lt;/option&gt; &lt;option value="&amp;amp;euro;"&gt;&amp;euro;&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Could you suggest any methods to display the actual HTML Currency character at least for the value part of the option?</p> <pre><code>&lt;select name="currency" id="id_currency"&gt; &lt;option value="&amp;amp;#36;"&gt;$&lt;/option&gt; &lt;option value="&amp;amp;pound;"&gt;£&lt;/option&gt; &lt;option value="&amp;amp;euro;"&gt;€&lt;/option&gt; &lt;/select&gt; </code></pre> <p><strong>Update:</strong> Please note I use <strong>Django 0.96</strong> as my application is running on Google App Engine.<br> And the <strong><em>&lt;SELECT&gt;</em></strong> above is rendered using Django Forms.</p> <pre><code>currencies = (('&amp;#36;', '&amp;#36;'), ('&amp;pound;', '&amp;pound;'), ('&amp;euro;', '&amp;euro;')) currency = forms.ChoiceField(choices=currencies, required=False) </code></pre> <p>Thanks,<br> <strong><em>Arun.</em></strong></p>
2
2009-04-22T14:22:14Z
777,528
<p>You can use "<a href="http://docs.djangoproject.com/en/dev/topics/templates/#how-to-turn-it-off" rel="nofollow">safe</a>" in the template or "<a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#filters-and-auto-escaping" rel="nofollow">mark_safe</a>" in the view</p> <p><b>update</b></p> <pre><code>from django.utils.safestring import mark_safe currencies = ((mark_safe('&amp;#36;'), mark_safe('&amp;#36;')), (mark_safe('&amp;pound;'), mark_safe('&amp;pound;')), (mark_safe('&amp;euro;'), mark_safe('&amp;euro;'))) </code></pre> <p><b>update 2</b></p> <p>As an alternative in your template you can <a href="http://docs.djangoproject.com/en/dev/topics/templates/#for-template-blocks" rel="nofollow">turn off escaping for a block of code</a> everything between tags {% autoescape off %} and {% endautoescape %} will not be escaped.</p> <p><b>update 3</b></p> <p>When nothing else works try the following. In the file that contains your currencies tuple put the following line as the very first or second line:</p> <pre><code># coding=utf-8 </code></pre> <p>and then in your currencies tuple put the actual unicode characters:</p> <pre><code>currencies = (('$', '$'), ('£', '£'), ('€', '€')) </code></pre>
7
2009-04-22T14:36:34Z
[ "python", "django-forms", "currency", "symbols" ]
Efficient arbitrary-sized integer packing in Python
777,525
<p>The struct.pack() function allows converting integers of up to 64 bit to byte strings. What's the most efficient way to pack an even larger integer? I'd rather not add a dependency on non-standard modules like PyCrypto (which provides num_to_bytes()).</p>
11
2009-04-22T14:36:12Z
777,583
<p>As suggested by S.Lott in a comment, just convert the number to a string and pack that string. For example,</p> <pre><code>x = 2 ** 12345 struct.pack("40s", str(x)) </code></pre>
1
2009-04-22T14:46:59Z
[ "python", "byte" ]
Efficient arbitrary-sized integer packing in Python
777,525
<p>The struct.pack() function allows converting integers of up to 64 bit to byte strings. What's the most efficient way to pack an even larger integer? I'd rather not add a dependency on non-standard modules like PyCrypto (which provides num_to_bytes()).</p>
11
2009-04-22T14:36:12Z
777,610
<p>Assuming the poster wants to pack a large integer as a binary string, i.e. not use one byte of storage per digit in the number. One way of doing this seems to be:</p> <pre><code>import marshal a = 47L print marshal.dumps(a) </code></pre> <p>This prints:</p> <pre><code>'l\x01\x00\x00\x00/\x00' </code></pre> <p>I can't say that I understand how to interpret these bits, right now ...</p>
3
2009-04-22T14:52:01Z
[ "python", "byte" ]
Efficient arbitrary-sized integer packing in Python
777,525
<p>The struct.pack() function allows converting integers of up to 64 bit to byte strings. What's the most efficient way to pack an even larger integer? I'd rather not add a dependency on non-standard modules like PyCrypto (which provides num_to_bytes()).</p>
11
2009-04-22T14:36:12Z
777,746
<p>I take it you mean you only want to use as many bytes as you need to represent the number? e.g. if the number is:</p> <ul> <li>255 or less you'd use only 1 byte</li> <li>65535 or less 2 bytes</li> <li>16777215 or less 3 bytes</li> <li>etc etc</li> </ul> <p>On the Psion PDA they'd usually have some of packing scheme in which you read the first byte, detect if it has the highest bit set and then read another byte if it has. That way you'd just keep reading bytes until you read the "full" number. That system works quite well if most of the numbers you are dealing with are fairly small, as you'll normally only use one or two bytes per number.</p> <p>The alternative is to have one (or more) bytes representing the number of total bytes used, but at that point it's basically a string in Python anyway. i.e. it's a string of base-256 digits.</p>
1
2009-04-22T15:12:39Z
[ "python", "byte" ]
Efficient arbitrary-sized integer packing in Python
777,525
<p>The struct.pack() function allows converting integers of up to 64 bit to byte strings. What's the most efficient way to pack an even larger integer? I'd rather not add a dependency on non-standard modules like PyCrypto (which provides num_to_bytes()).</p>
11
2009-04-22T14:36:12Z
777,774
<p>Do you mean <em>something</em> like this:</p> <pre><code>def num_to_bytes(num): bytes = [] num = abs(num) # Because I am unsure about negatives... while num &gt; 0: bytes.append(chr(num % 256)) num &gt;&gt;= 8 return ''.join(reversed(bytes)) def bytes_to_num(bytes): num = 0 for byte in bytes: num &lt;&lt;= 8 num += ord(byte) return num for n in (1, 16, 256, 257, 1234567890987654321): print n, print num_to_bytes(n).encode('hex'), print bytes_to_num(num_to_bytes(n)) </code></pre> <p>Which returns:</p> <pre><code>1 01 1 16 10 16 256 0100 256 257 0101 257 1234567890987654321 112210f4b16c1cb1 1234567890987654321 </code></pre> <p>I'm just not sure what to do about negatives... I'm not that familiar with bit twidling.</p> <p><strong>EDIT:</strong> Another solution (which runs about 30% faster by my tests):</p> <pre><code>def num_to_bytes(num): num = hex(num)[2:].rstrip('L') if len(num) % 2: return ('0%s' % num).decode('hex') return num.decode('hex') def bytes_to_num(bytes): return int(bytes.encode('hex'), 16) </code></pre>
5
2009-04-22T15:18:32Z
[ "python", "byte" ]
Efficient arbitrary-sized integer packing in Python
777,525
<p>The struct.pack() function allows converting integers of up to 64 bit to byte strings. What's the most efficient way to pack an even larger integer? I'd rather not add a dependency on non-standard modules like PyCrypto (which provides num_to_bytes()).</p>
11
2009-04-22T14:36:12Z
778,071
<p>This is a bit hacky, but you could go via the hex string representation, and there to binary with the hex codec:</p> <pre><code>&gt;&gt;&gt; a = 2**60 &gt;&gt;&gt; a 1152921504606846976L &gt;&gt;&gt; hex(a) '0x1000000000000000L' &gt;&gt;&gt; hex(a).rstrip("L")[2:].decode('hex') '\x10\x00\x00\x00\x00\x00\x00\x00' # 8bytes, as expected. &gt;&gt;&gt; int(_.encode('hex'), 16) 1152921504606846976L </code></pre> <p>It breaks a little because the hex codec requires an even number of digits, so you'll need to pad for that, and you'll need to set a flag to handle negative numbers. Here's a generic pack / unpack:</p> <pre><code>def pack(num): if num &lt;0: num = (abs(num) &lt;&lt; 1) | 1 # Hack - encode sign as lowest bit. else: num = num &lt;&lt; 1 hexval = hex(num).rstrip("L")[2:] if len(hexval)%2 ==1: hexval = '0' + hexval return hexval.decode('hex') def unpack(s): val = int(s.encode('hex'), 16) sign = -1 if (val &amp; 1) else 1 return sign * (val&gt;&gt;1) for i in [10,4534,23467, 93485093485, 2**50, 2**60-1, -1, -20, -2**60]: assert unpack(pack(i)) == i </code></pre> <p>With all the fiddling for padding etc required, I'm not sure it's much better than a hand-rolled solution though.</p>
1
2009-04-22T16:17:09Z
[ "python", "byte" ]
How do I set up a model to use an AutoField with a legacy database in Python?
777,778
<p>I have a legacy database with an integer set as a primary key. It was initially managed manually, but since we are wanting to move to django, the admin tool seemed to be the right place to start. I created the model and am trying to set the primary key to be an autofield. It doesn't seem to be remembering the old id in updates, and it doesn't create new id's on insert. What am I doing wrong?</p>
1
2009-04-22T15:18:59Z
778,346
<p>The <em>DB</em> is responsible for managing the value of the ID. If you want to use AutoField, you have to change the column in the DB to use that. Django is <em>not</em> responsible for managing the generated ID</p>
2
2009-04-22T17:31:23Z
[ "python", "django", "oracle", "autofield" ]
Other than basic python syntax, what other key areas should I learn to get a website live?
777,924
<p>Other than basic python syntax, what other key areas should I learn to get a website live?</p> <p>Is there a web.config in the python world?</p> <p>Which libraries handle things like authentication? or is that all done manually via session cookies and database tables?</p> <p>Are there any web specific libraries?</p> <p><b>Edit: sorry!</b> I am well versed in asp.net, I want to branch out and learn Python, hence this question (sorry, terrible start to this question I know).</p>
0
2009-04-22T15:46:24Z
777,951
<p>Basic Python syntax isn't half of what you need to know.</p> <ol> <li><p>All of the Python built-in data structures.</p></li> <li><p>Object-oriented design.</p></li> <li><p>What python module and packages are.</p></li> <li><p>The Python libraries -- almost everything you could ever want has already been written.</p></li> </ol> <p>To name a few things.</p> <p>If you've done some web development, you probably have some background in HTTP protocol, HTML, .CSS and Javascript and SQL.</p> <p>You should use a framework to handle the endless collection of mundane details, like authentication. Look at <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>.</p>
4
2009-04-22T15:51:59Z
[ "python" ]
Other than basic python syntax, what other key areas should I learn to get a website live?
777,924
<p>Other than basic python syntax, what other key areas should I learn to get a website live?</p> <p>Is there a web.config in the python world?</p> <p>Which libraries handle things like authentication? or is that all done manually via session cookies and database tables?</p> <p>Are there any web specific libraries?</p> <p><b>Edit: sorry!</b> I am well versed in asp.net, I want to branch out and learn Python, hence this question (sorry, terrible start to this question I know).</p>
0
2009-04-22T15:46:24Z
777,952
<p>Oh, golly.</p> <p>Look, this is gonna be real hard to answer because, read as you wrote it, you're missing a <i>lot</i> of steps. Like, you need a web server, a design, some HTML, and so on.</p> <p>Are you building from the ground up? Asking about Python makes me suspect you may be using something like Zope.</p>
0
2009-04-22T15:52:07Z
[ "python" ]
Other than basic python syntax, what other key areas should I learn to get a website live?
777,924
<p>Other than basic python syntax, what other key areas should I learn to get a website live?</p> <p>Is there a web.config in the python world?</p> <p>Which libraries handle things like authentication? or is that all done manually via session cookies and database tables?</p> <p>Are there any web specific libraries?</p> <p><b>Edit: sorry!</b> I am well versed in asp.net, I want to branch out and learn Python, hence this question (sorry, terrible start to this question I know).</p>
0
2009-04-22T15:46:24Z
777,965
<p><em>Answer replaced to correspond with the updated question.</em></p> <p>If you're already familiar with ASP.NET, the easiest way to jump into creating a website with Python is probably to look into one of the major web frameworks. <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> is very popular, working through <a href="http://docs.djangoproject.com/en/dev/intro/install/" rel="nofollow">the installation guide</a> and <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">the tutorial</a> will probably get you rolling pretty well.</p> <p>Really though, I'd personally suggest at least learning the language itself to a basic competency level before trying to dive right into using it inside a web framework. I think you'll be trying to force yourself to learn too much at once. In terms of just learning Python, the free book <a href="http://www.diveintopython.net/" rel="nofollow">Dive Into Python</a> is always spoken of highly.</p>
1
2009-04-22T15:54:25Z
[ "python" ]
Other than basic python syntax, what other key areas should I learn to get a website live?
777,924
<p>Other than basic python syntax, what other key areas should I learn to get a website live?</p> <p>Is there a web.config in the python world?</p> <p>Which libraries handle things like authentication? or is that all done manually via session cookies and database tables?</p> <p>Are there any web specific libraries?</p> <p><b>Edit: sorry!</b> I am well versed in asp.net, I want to branch out and learn Python, hence this question (sorry, terrible start to this question I know).</p>
0
2009-04-22T15:46:24Z
778,102
<p>Don't forget to give <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython</a> a try - your <code>.NET</code> experience can help making sense of newly learned <code>Python</code> idioms.</p> <blockquote> <p>IronPython is an implementation of the Python programming language running under .NET and Silverlight. It supports an interactive console with fully dynamic compilation. It's well integrated with the rest of the .NET Framework and makes all .NET libraries easily available to Python programmers, while maintaining compatibility with the Python language.</p> </blockquote>
0
2009-04-22T16:24:58Z
[ "python" ]
Other than basic python syntax, what other key areas should I learn to get a website live?
777,924
<p>Other than basic python syntax, what other key areas should I learn to get a website live?</p> <p>Is there a web.config in the python world?</p> <p>Which libraries handle things like authentication? or is that all done manually via session cookies and database tables?</p> <p>Are there any web specific libraries?</p> <p><b>Edit: sorry!</b> I am well versed in asp.net, I want to branch out and learn Python, hence this question (sorry, terrible start to this question I know).</p>
0
2009-04-22T15:46:24Z
778,807
<p>Of course the builtins. And become familiar with the standard library (until you start to remember what's in it, I'd suggest looking through it any time you're about to implement something... It might be there already!)</p> <p>You'll want some kind of framework, I'd recommend Django or TurboGears</p> <p>But you also need to learn the pythonic-way. For this, open up a Python interpreter and type:</p> <pre><code>import this </code></pre>
0
2009-04-22T19:31:53Z
[ "python" ]
Python subprocess "object has no attribute 'fileno'" error
777,996
<p>This code generates "AttributeError: 'Popen' object has no attribute 'fileno'" when run with Python 2.5.1 </p> <p>Code:</p> <pre><code>def get_blame(filename): proc = [] proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE)) proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['tr', r"'\040'", r"';'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['cut', r"-d", r"\;", '-f', '3'], stdin=proc[-1]), stdout=PIPE) return proc[-1].stdout.read() </code></pre> <p>Stack:</p> <pre><code>function walk_folder in blame.py at line 55 print_file(os.path.join(os.getcwd(), filename), path) function print_file in blame.py at line 34 users = get_blame(filename) function get_blame in blame.py at line 20 proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) function __init__ in subprocess.py at line 533 (p2cread, p2cwrite, function _get_handles in subprocess.py at line 830 p2cread = stdin.fileno() </code></pre> <p>This code should be working the python docs describe <a href="http://docs.python.org/library/subprocess.html#subprocess-replacements">this usage</a>.</p>
6
2009-04-22T16:05:06Z
778,030
<p>looks like syntax error. except first append the rest are erroneous (review brackets).</p>
-1
2009-04-22T16:11:38Z
[ "python", "pipe", "subprocess" ]
Python subprocess "object has no attribute 'fileno'" error
777,996
<p>This code generates "AttributeError: 'Popen' object has no attribute 'fileno'" when run with Python 2.5.1 </p> <p>Code:</p> <pre><code>def get_blame(filename): proc = [] proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE)) proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['tr', r"'\040'", r"';'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['cut', r"-d", r"\;", '-f', '3'], stdin=proc[-1]), stdout=PIPE) return proc[-1].stdout.read() </code></pre> <p>Stack:</p> <pre><code>function walk_folder in blame.py at line 55 print_file(os.path.join(os.getcwd(), filename), path) function print_file in blame.py at line 34 users = get_blame(filename) function get_blame in blame.py at line 20 proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) function __init__ in subprocess.py at line 533 (p2cread, p2cwrite, function _get_handles in subprocess.py at line 830 p2cread = stdin.fileno() </code></pre> <p>This code should be working the python docs describe <a href="http://docs.python.org/library/subprocess.html#subprocess-replacements">this usage</a>.</p>
6
2009-04-22T16:05:06Z
778,035
<p>You want the stdout of the process, so replace your <code>stdin=proc[-1]</code> with <code>stdin=proc[-1].stdout</code></p> <p>Also, you need to move your paren, it should come after the <code>stdout</code> argument.</p> <pre><code> proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) </code></pre> <p>should be:</p> <pre><code> proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1].stdout, stdout=PIPE)) </code></pre> <p>Fix your other <code>append</code> calls in the same way.</p>
1
2009-04-22T16:11:54Z
[ "python", "pipe", "subprocess" ]
Python subprocess "object has no attribute 'fileno'" error
777,996
<p>This code generates "AttributeError: 'Popen' object has no attribute 'fileno'" when run with Python 2.5.1 </p> <p>Code:</p> <pre><code>def get_blame(filename): proc = [] proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE)) proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['tr', r"'\040'", r"';'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['cut', r"-d", r"\;", '-f', '3'], stdin=proc[-1]), stdout=PIPE) return proc[-1].stdout.read() </code></pre> <p>Stack:</p> <pre><code>function walk_folder in blame.py at line 55 print_file(os.path.join(os.getcwd(), filename), path) function print_file in blame.py at line 34 users = get_blame(filename) function get_blame in blame.py at line 20 proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) function __init__ in subprocess.py at line 533 (p2cread, p2cwrite, function _get_handles in subprocess.py at line 830 p2cread = stdin.fileno() </code></pre> <p>This code should be working the python docs describe <a href="http://docs.python.org/library/subprocess.html#subprocess-replacements">this usage</a>.</p>
6
2009-04-22T16:05:06Z
778,059
<p>Three things</p> <p>First, your ()'s are wrong.</p> <p>Second, the result of <code>subprocess.Popen()</code> is a process object, not a file.</p> <pre><code>proc = [] proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE)) proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) </code></pre> <p>The value of <code>proc[-1]</code> isn't the file, it's the process that contains the file.</p> <pre><code>proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1].stdout, stdout=PIPE)) </code></pre> <p>Third, don't do all that <code>tr</code> and <code>cut</code> junk in the shell, few things could be slower. Write the <code>tr</code> and <code>cut</code> processing in Python -- it's faster and simpler.</p>
9
2009-04-22T16:15:09Z
[ "python", "pipe", "subprocess" ]
Python subprocess "object has no attribute 'fileno'" error
777,996
<p>This code generates "AttributeError: 'Popen' object has no attribute 'fileno'" when run with Python 2.5.1 </p> <p>Code:</p> <pre><code>def get_blame(filename): proc = [] proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE)) proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['tr', r"'\040'", r"';'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['cut', r"-d", r"\;", '-f', '3'], stdin=proc[-1]), stdout=PIPE) return proc[-1].stdout.read() </code></pre> <p>Stack:</p> <pre><code>function walk_folder in blame.py at line 55 print_file(os.path.join(os.getcwd(), filename), path) function print_file in blame.py at line 34 users = get_blame(filename) function get_blame in blame.py at line 20 proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) function __init__ in subprocess.py at line 533 (p2cread, p2cwrite, function _get_handles in subprocess.py at line 830 p2cread = stdin.fileno() </code></pre> <p>This code should be working the python docs describe <a href="http://docs.python.org/library/subprocess.html#subprocess-replacements">this usage</a>.</p>
6
2009-04-22T16:05:06Z
778,284
<p>There's a few weird things in the script,</p> <ul> <li><p>Why are you storing each process in a list? Wouldn't it be much more readable to simply use variables? Removing all the <code>.append()s</code> reveals an syntax error, several times you have passed stdout=PIPE to the <code>append</code> arguments, instead of Popen:</p> <pre><code>proc.append(Popen(...), stdout=PIPE) </code></pre> <p>So a straight-rewrite (still with errors I'll mention in a second) would become..</p> <pre><code>def get_blame(filename): blame = Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE) tr1 = Popen(['tr', '-s', r"'\040'"], stdin=blame, stdout=PIPE) tr2 = Popen(['tr', r"'\040'", r"';'"], stdin=tr1), stdout=PIPE) cut = Popen(['cut', r"-d", r"\;", '-f', '3'], stdin=tr2, stdout=PIPE) return cut.stdout.read() </code></pre></li> <li><p>On each subsequent command, you have passed the Popen object, <em>not</em> that processes <code>stdout</code>. From the <a href="http://docs.python.org/library/subprocess.html#replacing-shell-pipeline" rel="nofollow">"Replacing shell pipeline"</a> section of the subprocess docs, you do..</p> <pre><code>p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) </code></pre> <p>..whereas you were doing the equivalent of <code>stdin=p1</code>.</p> <p>The <code>tr1 =</code> (in the above rewritten code) line would become..</p> <pre><code>tr1 = Popen(['tr', '-s', r"'\040'"], stdin=blame.stdout, stdout=PIPE) </code></pre></li> <li><p>You do not need to escape commands/arguments with subprocess, as subprocess does not run the command in any shell (unless you specify <code>shell=True</code>). See the <a href="http://docs.python.org/library/subprocess.html#security" rel="nofollow">Security</a>section of the subprocess docs.</p> <p>Instead of..</p> <pre><code>proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE)) </code></pre> <p>..you can safely do..</p> <pre><code>Popen(['svn', 'blame', filename], stdout=PIPE) </code></pre></li> <li><p>As S.Lott suggested, don't use subprocess to do text-manipulations easier done in Python (the tr/cut commands). For one, tr/cut etc aren't hugely portable (different versions have different arguments), also they are quite hard to read (I've no idea what the tr's and cut are doing)</p> <p>If I were to rewrite the command, I would probably do something like..</p> <pre><code>def get_blame(filename): blame = Popen(['svn', 'blame', filename], stdout=PIPE) output = blame.communicate()[0] # preferred to blame.stdout.read() # process commands output: ret = [] for line in output.split("\n"): split_line = line.strip().split(" ") if len(split_line) &gt; 2: rev = split_line[0] author = split_line[1] line = " ".join(split_line[2:]) <pre><code> ret.append({'rev':rev, 'author':author, 'line':line}) return ret </code></pre> </code></pre></li> </ul>
1
2009-04-22T17:13:09Z
[ "python", "pipe", "subprocess" ]
Python subprocess "object has no attribute 'fileno'" error
777,996
<p>This code generates "AttributeError: 'Popen' object has no attribute 'fileno'" when run with Python 2.5.1 </p> <p>Code:</p> <pre><code>def get_blame(filename): proc = [] proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE)) proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['tr', r"'\040'", r"';'"], stdin=proc[-1]), stdout=PIPE) proc.append(Popen(['cut', r"-d", r"\;", '-f', '3'], stdin=proc[-1]), stdout=PIPE) return proc[-1].stdout.read() </code></pre> <p>Stack:</p> <pre><code>function walk_folder in blame.py at line 55 print_file(os.path.join(os.getcwd(), filename), path) function print_file in blame.py at line 34 users = get_blame(filename) function get_blame in blame.py at line 20 proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE) function __init__ in subprocess.py at line 533 (p2cread, p2cwrite, function _get_handles in subprocess.py at line 830 p2cread = stdin.fileno() </code></pre> <p>This code should be working the python docs describe <a href="http://docs.python.org/library/subprocess.html#subprocess-replacements">this usage</a>.</p>
6
2009-04-22T16:05:06Z
778,452
<p>Like S.Lott said, processing the text in Python is better.</p> <p>But if you want to use the cmdline utilities, you can keep it readable by using <code>shell=True</code>:</p> <pre><code>cmdline = r"svn blame %s | tr -s '\040' | tr '\040' ';' | cut -d \; -f 3" % shellquote(filename) return Popen(cmdline, shell=True, stdout=PIPE).communicate()[0] </code></pre>
-1
2009-04-22T18:01:31Z
[ "python", "pipe", "subprocess" ]
How to query any constraint's target list without knowing the constraint type?
778,083
<p>In Maya, I have a list of constraints gathered by the following code. I want to iterate the constraints and query the targets for each of them:</p> <pre><code>cons = ls(type='constraint') for con in cons: targets = constraint(query=True, targetList=True) </code></pre> <p>The problem, there is no general <code>constraint</code> command for manipulating all constraints. Instead, each constraint has its own unique MEL command associated with it.</p> <p>Is there any way to query the targets on a constraint without having to type check each constraint and tediously run its respective MEL command?</p>
2
2009-04-22T16:20:35Z
778,654
<p>listConnections on the .target attr</p> <p>the cleanup in mel:</p> <pre><code>string $cons[] = `ls -type "constraint"`; for ( $con in $cons ){ string $targetAttrString = ( $con+ ".target" ); string $connections[] = `listConnections $targetAttrString`; string $connectionsFlattened[] = stringArrayRemoveDuplicates($connections); for ( $f in $connectionsFlattened ) if ( $f != $con ) print ( $f+ " is a target\n" ); } </code></pre>
1
2009-04-22T18:54:22Z
[ "python", "3d", "constraints", "maya", "mel" ]
pyExcelerator or xlrd - How to FIND/SEARCH a row for the given few column data?
778,093
<p>Python communicating with EXCEL... i need to find a way so that I can find/search a row for given column datas. Now, i m scanning entire rows one by one... It would be useful, If there is some functions like FIND/SEARCH/REPLACE .... I dont see these features in pyExcelerator or xlrd modules.. I dont want to use win32com modules! it makes my tool windows based!</p> <p>FIND/SEARCH Excel rows through Python.... Any idea, anybody?</p>
1
2009-04-22T16:23:02Z
778,282
<p>"Now, i m scanning entire rows one by one"</p> <p>What's wrong with that? "search" -- in a spreadsheet context -- is really complicated. Search values? Search formulas? Search down rows then across columns? Search specific columns only? Search specific rows only?</p> <p>A spreadsheet isn't simple text -- simple text processing design patterns don't apply.</p> <p>Spreadsheet search is hard and you're doing it correctly. There's nothing better because it's hard. </p>
2
2009-04-22T17:12:38Z
[ "python", "excel", "search", "pyexcelerator", "xlrd" ]
pyExcelerator or xlrd - How to FIND/SEARCH a row for the given few column data?
778,093
<p>Python communicating with EXCEL... i need to find a way so that I can find/search a row for given column datas. Now, i m scanning entire rows one by one... It would be useful, If there is some functions like FIND/SEARCH/REPLACE .... I dont see these features in pyExcelerator or xlrd modules.. I dont want to use win32com modules! it makes my tool windows based!</p> <p>FIND/SEARCH Excel rows through Python.... Any idea, anybody?</p>
1
2009-04-22T16:23:02Z
779,030
<p>You can't. Those tools don't offer search capabilities. You must iterate over the data in a loop and search yourself. Sorry.</p>
1
2009-04-22T20:22:54Z
[ "python", "excel", "search", "pyexcelerator", "xlrd" ]
pyExcelerator or xlrd - How to FIND/SEARCH a row for the given few column data?
778,093
<p>Python communicating with EXCEL... i need to find a way so that I can find/search a row for given column datas. Now, i m scanning entire rows one by one... It would be useful, If there is some functions like FIND/SEARCH/REPLACE .... I dont see these features in pyExcelerator or xlrd modules.. I dont want to use win32com modules! it makes my tool windows based!</p> <p>FIND/SEARCH Excel rows through Python.... Any idea, anybody?</p>
1
2009-04-22T16:23:02Z
779,599
<p>With pyExcelerator you can do a simple optimization by finding the maximum row and column indices first (and storing them), so that you iterate over <code>(row, i) for i in range(maxcol+1)</code> instead of iterating over all the dictionary keys. That may be the best you get, unless you want to go through and build up a dictionary mapping value to set of keys.</p> <p>Incidentally, if you're using pyExcelerator to write spreadsheets, be aware that it has some bugs. I've encountered one involving writing integers between 2**30 and 2**32 (or thereabouts). The original author is apparently hard to contact these days, so <code>xlwt</code> is a fork that fixes the (known) bugs. For writing spreadsheets, it's a drop-in replacement for pyExcelerator; you could do <code>import xlwt as pyExcelerator</code> and change nothing else. It doesn't read spreadsheets, though.</p>
0
2009-04-22T22:55:56Z
[ "python", "excel", "search", "pyexcelerator", "xlrd" ]
pyExcelerator or xlrd - How to FIND/SEARCH a row for the given few column data?
778,093
<p>Python communicating with EXCEL... i need to find a way so that I can find/search a row for given column datas. Now, i m scanning entire rows one by one... It would be useful, If there is some functions like FIND/SEARCH/REPLACE .... I dont see these features in pyExcelerator or xlrd modules.. I dont want to use win32com modules! it makes my tool windows based!</p> <p>FIND/SEARCH Excel rows through Python.... Any idea, anybody?</p>
1
2009-04-22T16:23:02Z
958,903
<p>@John Fouhy: [I'm the maintainer of xlwt, and author of xlrd]</p> <p>The spreadsheet-reading part of pyExcelerator was so severely deprecated that it vanished completely out of xlwt. To read any XLS files created by Excel 2.0 up to 11.0 (Excel 2003) or compatible software, using Python 2.1+, use <a href="http://pypi.python.org/pypi/xlrd" rel="nofollow">xlrd</a></p> <p>That "simple optimi[sz]ation" isn't needed with xlrd:</p> <pre><code>import xlrd book = xlrd.open_workbook("foo.xls") sheet = book.sheet_by_number(0) # alternatively: sheet_by_name("Budget") for row_index in xrange(sheet.nrows): for col_index in xrange(sheet.ncols): </code></pre>
5
2009-06-06T03:12:29Z
[ "python", "excel", "search", "pyexcelerator", "xlrd" ]
problem opening a text document - unicode error
778,096
<p>i have probably rather simple question. however, i am just starting to use python and it just drives me crazy. i am following the instructions of a book and would like to open a simple text file. the code i am using:</p> <pre><code>import sys try: d = open("p0901aus.txt" , "W") except: print("Unsucessfull") sys.exit(0) </code></pre> <p>i am either getting the news, that i was unsucessfull in opening the document or pop up appears saying:</p> <p>(unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape</p> <p>i have no clue what the problem is. i tried to save the document in different codes, tried different path...always the same problem</p> <p>does anybody know any help? </p> <p>thank you very much in advance,</p> <p>georg ps: i am using windows vista</p>
2
2009-04-22T16:23:49Z
778,112
<p>Change that to</p> <pre><code># for Python 2.5+ import sys try: d = open("p0901aus.txt","w") except Exception, ex: print "Unsuccessful." print ex sys.exit(0) # for Python 3 import sys import codecs try: d = codecs.open("p0901aus.txt","w","utf-8") except Exception as ex: print("Unsuccessful.") print(ex) sys.exit(0) </code></pre> <p>The W is case-sensitive. I do not want to hit you with all the Python syntax at once, but it will be useful for you to know how to display what exception was raised, and this is one way to do it.</p> <p>Also, you are opening the file for writing, not reading. Is that what you wanted?</p> <p>If there is already a document named p0901aus.txt, and you want to read it, do this:</p> <pre><code>#for Python 2.5+ import sys try: d = open("p0901aus.txt","r") print "Awesome, I opened p0901aus.txt. Here is what I found there:" for l in d: print l except Exception, ex: print "Unsuccessful." print ex sys.exit(0) #for Python 3+ import sys import codecs try: d = codecs.open("p0901aus.txt","r","utf-8") print "Awesome, I opened p0901aus.txt. Here is what I found there:" for l in d: print(l) except Exception, ex: print("Unsuccessful.") print(ex) sys.exit(0) </code></pre> <p>You can of course use the codecs in Python 2.5 also, and your code will be higher quality ("correct") if you do. Python 3 appears to treat the Byte Order Mark as something between a curiosity and line noise which is a bummer.</p>
2
2009-04-22T16:27:56Z
[ "python", "unicode" ]
problem opening a text document - unicode error
778,096
<p>i have probably rather simple question. however, i am just starting to use python and it just drives me crazy. i am following the instructions of a book and would like to open a simple text file. the code i am using:</p> <pre><code>import sys try: d = open("p0901aus.txt" , "W") except: print("Unsucessfull") sys.exit(0) </code></pre> <p>i am either getting the news, that i was unsucessfull in opening the document or pop up appears saying:</p> <p>(unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape</p> <p>i have no clue what the problem is. i tried to save the document in different codes, tried different path...always the same problem</p> <p>does anybody know any help? </p> <p>thank you very much in advance,</p> <p>georg ps: i am using windows vista</p>
2
2009-04-22T16:23:49Z
778,188
<blockquote> <p>(unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape</p> </blockquote> <p>This probably means that the file you are trying to read is not in the encoding that open() expects. Apparently open() expects some Unicode encoding (most likely UTF-8 or UTF-16), but your file is not encoded like that.</p> <p>You should not normally use plain open() for reading text files, as it is impossible to correctly read a text file (unless it's pure ASCII) without specifying an encoding.</p> <p>Use codecs instead:</p> <pre><code>import codecs fileObj = codecs.open( "someFile", "r", "utf-8" ) u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file </code></pre>
5
2009-04-22T16:47:29Z
[ "python", "unicode" ]
problem opening a text document - unicode error
778,096
<p>i have probably rather simple question. however, i am just starting to use python and it just drives me crazy. i am following the instructions of a book and would like to open a simple text file. the code i am using:</p> <pre><code>import sys try: d = open("p0901aus.txt" , "W") except: print("Unsucessfull") sys.exit(0) </code></pre> <p>i am either getting the news, that i was unsucessfull in opening the document or pop up appears saying:</p> <p>(unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape</p> <p>i have no clue what the problem is. i tried to save the document in different codes, tried different path...always the same problem</p> <p>does anybody know any help? </p> <p>thank you very much in advance,</p> <p>georg ps: i am using windows vista</p>
2
2009-04-22T16:23:49Z
2,379,566
<pre><code>import csv data = csv.reader(open('c:\x\list.csv' )) for row in data: print(row) print('ready') </code></pre> <p>Brings up "(unicode error)'unicodeescape' codec can't decode bytes in position 2-4: truncated \xXX escape"</p> <p>Try <code>c:\\x\\list.csv</code> instead of <code>c:\x\list.csv</code></p> <p>This is Python 3 code.</p>
1
2010-03-04T13:29:10Z
[ "python", "unicode" ]
smtplib and gmail - python script problems
778,202
<p>Here's my script:</p> <pre><code>#!/usr/bin/python import smtplib msg = 'Hello world.' server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587 server.ehlo() server.starttls() server.ehlo() server.login('myname@gmail.com','mypass') server.sendmail('myname@gmail.com','somename@somewhere.com',msg) server.close() </code></pre> <p>I'm just trying to send an email from my gmail account. The script uses starttls because of gmail's requirement. I've tried this on two web hosts, 1and1 and webfaction. 1and1 gives me a 'connection refused' error and webfaction reports no error but just doesn't send the email. I can't see anything wrong with the script, so I'm thinking it might be related to the web hosts. Any thoughts and comments would be much appreciated.</p> <p>EDIT: I turned on debug mode. From the output, it looks like it sent the message successfully...I just never receive it.</p> <pre><code>send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-AUTH LOGIN PLAIN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME AUTH LOGIN PLAIN ENHANCEDSTATUSCODES PIPELINING send: 'AUTH PLAIN *****\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted send: 'mail FROM:&lt;myname@gmail.com&gt; size=12\r\n' reply: '250 2.1.0 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48 send: 'rcpt TO:&lt;myname@gmail.com&gt;\r\n' reply: '250 2.1.5 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48 send: 'data\r\n' reply: '354 Go ahead 4sm652580yxq.48\r\n' reply: retcode (354); Msg: Go ahead 4sm652580yxq.48 data: (354, 'Go ahead 4sm652580yxq.48') send: 'Hello world.\r\n.\r\n' reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48 data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48') </code></pre>
19
2009-04-22T16:52:17Z
778,220
<p>I think that the GMail SMTP server does a reverse DNS lookup on the IP address that you connect from, and refuses the connection if no domain can be found. This is to avoid spammer from using their SMTP server as an open relay.</p>
6
2009-04-22T16:57:05Z
[ "python", "smtp", "gmail", "smtplib" ]
smtplib and gmail - python script problems
778,202
<p>Here's my script:</p> <pre><code>#!/usr/bin/python import smtplib msg = 'Hello world.' server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587 server.ehlo() server.starttls() server.ehlo() server.login('myname@gmail.com','mypass') server.sendmail('myname@gmail.com','somename@somewhere.com',msg) server.close() </code></pre> <p>I'm just trying to send an email from my gmail account. The script uses starttls because of gmail's requirement. I've tried this on two web hosts, 1and1 and webfaction. 1and1 gives me a 'connection refused' error and webfaction reports no error but just doesn't send the email. I can't see anything wrong with the script, so I'm thinking it might be related to the web hosts. Any thoughts and comments would be much appreciated.</p> <p>EDIT: I turned on debug mode. From the output, it looks like it sent the message successfully...I just never receive it.</p> <pre><code>send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-AUTH LOGIN PLAIN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME AUTH LOGIN PLAIN ENHANCEDSTATUSCODES PIPELINING send: 'AUTH PLAIN *****\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted send: 'mail FROM:&lt;myname@gmail.com&gt; size=12\r\n' reply: '250 2.1.0 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48 send: 'rcpt TO:&lt;myname@gmail.com&gt;\r\n' reply: '250 2.1.5 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48 send: 'data\r\n' reply: '354 Go ahead 4sm652580yxq.48\r\n' reply: retcode (354); Msg: Go ahead 4sm652580yxq.48 data: (354, 'Go ahead 4sm652580yxq.48') send: 'Hello world.\r\n.\r\n' reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48 data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48') </code></pre>
19
2009-04-22T16:52:17Z
780,516
<p>Have you tried constructing a valid message?</p> <pre><code>from email.MIMEText import MIMEText msg = MIMEText('body') msg['Subject'] = 'subject' msg['From'] = "..." msg['Reply-to'] = "..." msg['To'] = "..." </code></pre>
7
2009-04-23T06:33:55Z
[ "python", "smtp", "gmail", "smtplib" ]
smtplib and gmail - python script problems
778,202
<p>Here's my script:</p> <pre><code>#!/usr/bin/python import smtplib msg = 'Hello world.' server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587 server.ehlo() server.starttls() server.ehlo() server.login('myname@gmail.com','mypass') server.sendmail('myname@gmail.com','somename@somewhere.com',msg) server.close() </code></pre> <p>I'm just trying to send an email from my gmail account. The script uses starttls because of gmail's requirement. I've tried this on two web hosts, 1and1 and webfaction. 1and1 gives me a 'connection refused' error and webfaction reports no error but just doesn't send the email. I can't see anything wrong with the script, so I'm thinking it might be related to the web hosts. Any thoughts and comments would be much appreciated.</p> <p>EDIT: I turned on debug mode. From the output, it looks like it sent the message successfully...I just never receive it.</p> <pre><code>send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-AUTH LOGIN PLAIN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME AUTH LOGIN PLAIN ENHANCEDSTATUSCODES PIPELINING send: 'AUTH PLAIN *****\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted send: 'mail FROM:&lt;myname@gmail.com&gt; size=12\r\n' reply: '250 2.1.0 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48 send: 'rcpt TO:&lt;myname@gmail.com&gt;\r\n' reply: '250 2.1.5 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48 send: 'data\r\n' reply: '354 Go ahead 4sm652580yxq.48\r\n' reply: retcode (354); Msg: Go ahead 4sm652580yxq.48 data: (354, 'Go ahead 4sm652580yxq.48') send: 'Hello world.\r\n.\r\n' reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48 data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48') </code></pre>
19
2009-04-22T16:52:17Z
1,287,612
<p>You'll need to check your "Sent" folder in GMail, as that's where a message sent from your account to your account will most probably show up.</p>
2
2009-08-17T12:12:20Z
[ "python", "smtp", "gmail", "smtplib" ]
smtplib and gmail - python script problems
778,202
<p>Here's my script:</p> <pre><code>#!/usr/bin/python import smtplib msg = 'Hello world.' server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587 server.ehlo() server.starttls() server.ehlo() server.login('myname@gmail.com','mypass') server.sendmail('myname@gmail.com','somename@somewhere.com',msg) server.close() </code></pre> <p>I'm just trying to send an email from my gmail account. The script uses starttls because of gmail's requirement. I've tried this on two web hosts, 1and1 and webfaction. 1and1 gives me a 'connection refused' error and webfaction reports no error but just doesn't send the email. I can't see anything wrong with the script, so I'm thinking it might be related to the web hosts. Any thoughts and comments would be much appreciated.</p> <p>EDIT: I turned on debug mode. From the output, it looks like it sent the message successfully...I just never receive it.</p> <pre><code>send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-AUTH LOGIN PLAIN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME AUTH LOGIN PLAIN ENHANCEDSTATUSCODES PIPELINING send: 'AUTH PLAIN *****\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted send: 'mail FROM:&lt;myname@gmail.com&gt; size=12\r\n' reply: '250 2.1.0 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48 send: 'rcpt TO:&lt;myname@gmail.com&gt;\r\n' reply: '250 2.1.5 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48 send: 'data\r\n' reply: '354 Go ahead 4sm652580yxq.48\r\n' reply: retcode (354); Msg: Go ahead 4sm652580yxq.48 data: (354, 'Go ahead 4sm652580yxq.48') send: 'Hello world.\r\n.\r\n' reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48 data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48') </code></pre>
19
2009-04-22T16:52:17Z
6,217,741
<p>save yourselves some headaches and use this:</p> <p><a href="http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt" rel="nofollow">http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt</a></p> <p><a href="http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt" rel="nofollow">Python SMTPHandler with GMail</a></p> <p>Ss</p>
3
2011-06-02T17:07:34Z
[ "python", "smtp", "gmail", "smtplib" ]
smtplib and gmail - python script problems
778,202
<p>Here's my script:</p> <pre><code>#!/usr/bin/python import smtplib msg = 'Hello world.' server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587 server.ehlo() server.starttls() server.ehlo() server.login('myname@gmail.com','mypass') server.sendmail('myname@gmail.com','somename@somewhere.com',msg) server.close() </code></pre> <p>I'm just trying to send an email from my gmail account. The script uses starttls because of gmail's requirement. I've tried this on two web hosts, 1and1 and webfaction. 1and1 gives me a 'connection refused' error and webfaction reports no error but just doesn't send the email. I can't see anything wrong with the script, so I'm thinking it might be related to the web hosts. Any thoughts and comments would be much appreciated.</p> <p>EDIT: I turned on debug mode. From the output, it looks like it sent the message successfully...I just never receive it.</p> <pre><code>send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-AUTH LOGIN PLAIN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME AUTH LOGIN PLAIN ENHANCEDSTATUSCODES PIPELINING send: 'AUTH PLAIN *****\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted send: 'mail FROM:&lt;myname@gmail.com&gt; size=12\r\n' reply: '250 2.1.0 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48 send: 'rcpt TO:&lt;myname@gmail.com&gt;\r\n' reply: '250 2.1.5 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48 send: 'data\r\n' reply: '354 Go ahead 4sm652580yxq.48\r\n' reply: retcode (354); Msg: Go ahead 4sm652580yxq.48 data: (354, 'Go ahead 4sm652580yxq.48') send: 'Hello world.\r\n.\r\n' reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48 data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48') </code></pre>
19
2009-04-22T16:52:17Z
24,358,795
<p>I went to the above mentioned link and had 3 different to addresses to send to but I received three emails to the same address and that being the #3 address. </p> <p><a href="http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt" rel="nofollow">http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt</a></p> <pre><code>import logging import logging.handlers class TlsSMTPHandler(logging.handlers.SMTPHandler): def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: import smtplib import string # for tls add this line try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port) msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getSubject(record), formatdate(), msg) if self.username: smtp.ehlo() # for tls add this line smtp.starttls() # for tls add this line smtp.ehlo() # for tls add this line smtp.login(self.username, self.password) smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.quit() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) logger = logging.getLogger() gm = TlsSMTPHandler(("smtp.gmail.com", 587), 'myusername@gmail.com', ['address1@gmail.com', 'address2@gmail.com', 'address3@gmail.com'], 'unable to find Error!', ('myusername@gmail.com', 'mypassword')) gm.setLevel(logging.ERROR) logger.addHandler(gm) try: 1/0 except: logger.exception('It NO work for me!!-') </code></pre>
0
2014-06-23T05:18:00Z
[ "python", "smtp", "gmail", "smtplib" ]
smtplib and gmail - python script problems
778,202
<p>Here's my script:</p> <pre><code>#!/usr/bin/python import smtplib msg = 'Hello world.' server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587 server.ehlo() server.starttls() server.ehlo() server.login('myname@gmail.com','mypass') server.sendmail('myname@gmail.com','somename@somewhere.com',msg) server.close() </code></pre> <p>I'm just trying to send an email from my gmail account. The script uses starttls because of gmail's requirement. I've tried this on two web hosts, 1and1 and webfaction. 1and1 gives me a 'connection refused' error and webfaction reports no error but just doesn't send the email. I can't see anything wrong with the script, so I'm thinking it might be related to the web hosts. Any thoughts and comments would be much appreciated.</p> <p>EDIT: I turned on debug mode. From the output, it looks like it sent the message successfully...I just never receive it.</p> <pre><code>send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-AUTH LOGIN PLAIN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME AUTH LOGIN PLAIN ENHANCEDSTATUSCODES PIPELINING send: 'AUTH PLAIN *****\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted send: 'mail FROM:&lt;myname@gmail.com&gt; size=12\r\n' reply: '250 2.1.0 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48 send: 'rcpt TO:&lt;myname@gmail.com&gt;\r\n' reply: '250 2.1.5 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48 send: 'data\r\n' reply: '354 Go ahead 4sm652580yxq.48\r\n' reply: retcode (354); Msg: Go ahead 4sm652580yxq.48 data: (354, 'Go ahead 4sm652580yxq.48') send: 'Hello world.\r\n.\r\n' reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48 data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48') </code></pre>
19
2009-04-22T16:52:17Z
28,990,761
<p>I don't know if OP still cares about this answer, but having found myself here in an effort to troubleshoot a similar problem, hopefully someone else might find this useful. As it turns out, Google has changed the way that they allow their SMTP server to be used. You will want to check a couple of things:</p> <ol> <li><p>That you are using the same address you used to authenticate as the 'from' address. If I am not mistaken it used to be the case that you could put pretty much whatever you wanted in the from field, but for security purposes many SMTP host sites (including google) now restrict this to the address that has authenticated with them.</p></li> <li><p>Allow your account to be accessed by 'less secure apps' (read: apps we do not generate revenue from). To do that log into your account and navigate here: <a href="https://www.google.com/settings/security/lesssecureapps" rel="nofollow">https://www.google.com/settings/security/lesssecureapps</a></p></li> <li><p>Use port 587 with tls. Not really sure why but I could never get port 465 to play nice.</p></li> </ol> <p>Hope this helps somebody else out.</p>
4
2015-03-11T15:28:33Z
[ "python", "smtp", "gmail", "smtplib" ]
smtplib and gmail - python script problems
778,202
<p>Here's my script:</p> <pre><code>#!/usr/bin/python import smtplib msg = 'Hello world.' server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587 server.ehlo() server.starttls() server.ehlo() server.login('myname@gmail.com','mypass') server.sendmail('myname@gmail.com','somename@somewhere.com',msg) server.close() </code></pre> <p>I'm just trying to send an email from my gmail account. The script uses starttls because of gmail's requirement. I've tried this on two web hosts, 1and1 and webfaction. 1and1 gives me a 'connection refused' error and webfaction reports no error but just doesn't send the email. I can't see anything wrong with the script, so I'm thinking it might be related to the web hosts. Any thoughts and comments would be much appreciated.</p> <p>EDIT: I turned on debug mode. From the output, it looks like it sent the message successfully...I just never receive it.</p> <pre><code>send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS send: 'ehlo web65.webfaction.com\r\n' reply: '250-mx.google.com at your service, [174.133.21.84]\r\n' reply: '250-SIZE 35651584\r\n' reply: '250-8BITMIME\r\n' reply: '250-AUTH LOGIN PLAIN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250 PIPELINING\r\n' reply: retcode (250); Msg: mx.google.com at your service, [174.133.21.84] SIZE 35651584 8BITMIME AUTH LOGIN PLAIN ENHANCEDSTATUSCODES PIPELINING send: 'AUTH PLAIN *****\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted send: 'mail FROM:&lt;myname@gmail.com&gt; size=12\r\n' reply: '250 2.1.0 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.0 OK 4sm652580yxq.48 send: 'rcpt TO:&lt;myname@gmail.com&gt;\r\n' reply: '250 2.1.5 OK 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.1.5 OK 4sm652580yxq.48 send: 'data\r\n' reply: '354 Go ahead 4sm652580yxq.48\r\n' reply: retcode (354); Msg: Go ahead 4sm652580yxq.48 data: (354, 'Go ahead 4sm652580yxq.48') send: 'Hello world.\r\n.\r\n' reply: '250 2.0.0 OK 1240421143 4sm652580yxq.48\r\n' reply: retcode (250); Msg: 2.0.0 OK 1240421143 4sm652580yxq.48 data: (250, '2.0.0 OK 1240421143 4sm652580yxq.48') </code></pre>
19
2009-04-22T16:52:17Z
29,720,420
<p>Some self-promotion here, but I feel on a valid ground.</p> <p>You would literally only need this code to do exactly what you wrote:</p> <pre><code>import yagmail yag = yagmail.SMTP('myname@gmail.com') yag.send('somename@somewhere.com', subject = None, contents = 'Hello') </code></pre> <p>Or a one liner:</p> <pre><code>yagmail.SMTP('myname@gmail.com').send('somename@somewhere.com', None, 'Hello world.') </code></pre> <p>What is nice is that I propose to use keyring to store your password, so you never have a risk of people seeing your password in your script.</p> <p>For the package/installation please look at <a href="https://github.com/kootenpv/yagmail" rel="nofollow">git</a> or <a href="https://pypi.python.org/pypi/yagmail/" rel="nofollow">pip</a>, available for both Python 2 and 3.</p>
4
2015-04-18T17:18:18Z
[ "python", "smtp", "gmail", "smtplib" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
778,399
<p>Here's what we do. It isn't a "complete" solution, but it does much of what you're looking for.</p> <pre><code>from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User exclude = ('email',) username = forms.EmailField(max_length=64, help_text="The person's email address.") def clean_email(self): email = self.cleaned_data['username'] return email class UserAdmin(UserAdmin): form = UserForm list_display = ('email', 'first_name', 'last_name', 'is_staff') list_filter = ('is_staff',) search_fields = ('email',) admin.site.unregister(User) admin.site.register(User, UserAdmin) </code></pre>
25
2009-04-22T17:46:39Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
781,259
<p>you can also find an interesting discussion on this topic at the below link :</p> <p><a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/c943ede66e6807c/2fbf2afeade397eb#2fbf2afeade397eb" rel="nofollow">http://groups.google.com/group/django-users/browse_thread/thread/c943ede66e6807c/2fbf2afeade397eb#2fbf2afeade397eb</a></p>
1
2009-04-23T11:09:40Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
9,134,982
<p>For anyone else wanting to do this, I'd recommend taking a look at <a href="https://github.com/dabapps/django-email-as-username">django-email-as-username</a> which is a pretty comprehensive solution, that includes patching up the admin and the <code>createsuperuser</code> management commands, amongst other bits and pieces.</p> <p><strong>Edit</strong>: As of Django 1.5 onwards you should consider using a <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#auth-custom-user">custom user model</a> instead of <a href="https://github.com/dabapps/django-email-as-username">django-email-as-username</a>.</p>
32
2012-02-03T20:20:55Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
11,459,439
<p>Latest version of django-registration allows some nice customisation and might do the job - docs here <a href="https://bitbucket.org/ubernostrum/django-registration/src/fad7080fe769/docs/backend-api.rst" rel="nofollow">https://bitbucket.org/ubernostrum/django-registration/src/fad7080fe769/docs/backend-api.rst</a></p>
1
2012-07-12T19:42:37Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
24,071,649
<p>The easiest way is to lookup the username based on the email in the login view. That way you can leave everything else alone:</p> <pre><code>from django.contrib.auth import authenticate, login as auth_login def _is_valid_email(email): from django.core.validators import validate_email from django.core.exceptions import ValidationError try: validate_email(email) return True except ValidationError: return False def login(request): next = request.GET.get('next', '/') if request.method == 'POST': username = request.POST['username'].lower() # case insensitivity password = request.POST['password'] if _is_valid_email(username): try: username = User.objects.filter(email=username).values_list('username', flat=True) except User.DoesNotExist: username = None kwargs = {'username': username, 'password': password} user = authenticate(**kwargs) if user is not None: if user.is_active: auth_login(request, user) return redirect(next or '/') else: messages.info(request, "&lt;stvrong&gt;Error&lt;/strong&gt; User account has not been activated..") else: messages.info(request, "&lt;strong&gt;Error&lt;/strong&gt; Username or password was incorrect.") return render_to_response('accounts/login.html', {}, context_instance=RequestContext(request)) </code></pre> <p>In your template set the next variable accordingly, i.e. </p> <pre><code>&lt;form method="post" class="form-login" action="{% url 'login' %}?next={{ request.GET.next }}" accept-charset="UTF-8"&gt; </code></pre> <p>And give your username / password inputs the right names, i.e. username, password.</p> <p><strong>UPDATE</strong>: </p> <p>Alternatively, the if _is_valid_email(email): call can be replaced with if '@' in username. That way you can drop the _is_valid_email function. This really depends on how you define your username. It will not work if you allow the '@' character in your usernames.</p>
0
2014-06-05T23:07:08Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
25,278,186
<p>Here is one way to do it so that both username and email are accepted:</p> <pre><code>from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.forms import ValidationError class EmailAuthenticationForm(AuthenticationForm): def clean_username(self): username = self.data['username'] if '@' in username: try: username = User.objects.get(email=username).username except ObjectDoesNotExist: raise ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username':self.username_field.verbose_name}, ) return username </code></pre> <p>Don't know if there is some setting to set the default Authentication form but you can also override the url in urls.py</p> <pre><code>url(r'^accounts/login/$', 'django.contrib.auth.views.login', { 'authentication_form': EmailAuthenticationForm }, name='login'), </code></pre> <p>Raising the ValidationError will prevent 500 errors when an invalid email is submitted. Using the super's definition for "invalid_login" keeps the error message ambiguous (vs a specific "no user by that email found") which would be required to prevent leaking whether an email address is signed up for an account on your service. If that information is not secure in your architecture it might be friendlier to have a more informative error message.</p>
15
2014-08-13T04:39:42Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
26,336,203
<p>Django now provides a full example of an extended authentication system with admin and form: <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#a-full-example">https://docs.djangoproject.com/en/dev/topics/auth/customizing/#a-full-example</a></p> <p>You can basically copy/paste it and adapt (I didn't need the <code>date_of_birth</code> in my case).</p> <p>It is actually available since Django 1.5 and is still available as of now (django 1.7).</p>
7
2014-10-13T08:57:09Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
27,433,341
<p>Other alternatives look too complex for me, so I wrote a snippet that allows to authenticate using username, email, or both, and also enable or disable case sensitive. I uploaded it to pip as <a href="https://github.com/Zeioth/django-dual-authentication" rel="nofollow">django-dual-authentication</a>.</p> <pre><code>from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django.conf import settings ################################### """ DEFAULT SETTINGS + ALIAS """ ################################### try: am = settings.AUTHENTICATION_METHOD except: am = 'both' try: cs = settings.AUTHENTICATION_CASE_SENSITIVE except: cs = 'both' ##################### """ EXCEPTIONS """ ##################### VALID_AM = ['username', 'email', 'both'] VALID_CS = ['username', 'email', 'both', 'none'] if (am not in VALID_AM): raise Exception("Invalid value for AUTHENTICATION_METHOD in project " "settings. Use 'username','email', or 'both'.") if (cs not in VALID_CS): raise Exception("Invalid value for AUTHENTICATION_CASE_SENSITIVE in project " "settings. Use 'username','email', 'both' or 'none'.") ############################ """ OVERRIDDEN METHODS """ ############################ class DualAuthentication(ModelBackend): """ This is a ModelBacked that allows authentication with either a username or an email address. """ def authenticate(self, username=None, password=None): UserModel = get_user_model() try: if ((am == 'email') or (am == 'both')): if ((cs == 'email') or cs == 'both'): kwargs = {'email': username} else: kwargs = {'email__iexact': username} user = UserModel.objects.get(**kwargs) else: raise except: if ((am == 'username') or (am == 'both')): if ((cs == 'username') or cs == 'both'): kwargs = {'username': username} else: kwargs = {'username__iexact': username} user = UserModel.objects.get(**kwargs) finally: try: if user.check_password(password): return user except: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user. UserModel().set_password(password) return None def get_user(self, username): UserModel = get_user_model() try: return UserModel.objects.get(pk=username) except UserModel.DoesNotExist: return None </code></pre>
0
2014-12-11T22:08:47Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
29,638,766
<p>If you're going to extend user model, you would have to implement custom user model anyway. </p> <p>Here is an example for Django 1.8. Django 1.7 would require a little bit more work, mostly changing default forms (just take a look at <code>UserChangeForm</code> &amp; <code>UserCreationForm</code> in <code>django.contrib.auth.forms</code> - that's what you need in 1.7).</p> <p>user_manager.py:</p> <pre><code>from django.contrib.auth.models import BaseUserManager from django.utils import timezone class SiteUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): today = timezone.now() if not email: raise ValueError('The given email address must be set') email = SiteUserManager.normalize_email(email) user = self.model(email=email, is_staff=False, is_active=True, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): u = self.create_user(email, password, **extra_fields) u.is_staff = True u.is_active = True u.is_superuser = True u.save(using=self._db) return u </code></pre> <p>models.py:</p> <pre><code>from mainsite.user_manager import SiteUserManager from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class SiteUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, blank=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = SiteUserManager() def get_full_name(self): return self.email def get_short_name(self): return self.email </code></pre> <p>forms.py:</p> <pre><code>from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from mainsite.models import SiteUser class MyUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = SiteUser fields = ("email",) class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = SiteUser class MyUserAdmin(UserAdmin): form = MyUserChangeForm add_form = MyUserCreationForm fieldsets = ( (None, {'fields': ('email', 'password',)}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser',)}), ('Groups', {'fields': ('groups', 'user_permissions',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2')} ), ) list_display = ('email', ) list_filter = ('is_active', ) search_fields = ('email',) ordering = ('email',) admin.site.register(SiteUser, MyUserAdmin) </code></pre> <p>settings.py:</p> <pre><code>AUTH_USER_MODEL = 'mainsite.SiteUser' </code></pre>
5
2015-04-14T22:54:45Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
33,623,706
<p>I think the most quickly way is to create a form inherit from <code>UserCreateForm</code>, and then override the <code>username</code> field with <code>forms.EmailField</code>. Then for every new registration user, they need to signon with their email address.</p> <p>For example:</p> <p><strong>urls.py</strong></p> <pre><code>... urlpatterns += url(r'^signon/$', SignonView.as_view(), name="signon") </code></pre> <p><strong>views.py</strong></p> <pre><code>from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django import forms class UserSignonForm(UserCreationForm): username = forms.EmailField() class SignonView(CreateView): template_name = "registration/signon.html" model = User form_class = UserSignonForm </code></pre> <p><strong>signon.html</strong></p> <pre><code>... &lt;form action="#" method="post"&gt; ... &lt;input type="email" name="username" /&gt; ... &lt;/form&gt; ... </code></pre>
0
2015-11-10T05:45:32Z
[ "python", "django", "authentication" ]
Accepting email address as username in Django
778,382
<p>Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user's email address instead of them creating a username.</p> <p>Please advise, thank you.</p>
68
2009-04-22T17:42:20Z
35,508,483
<p>Not sure if people are trying to accomplish this, but I found nice (and clean) way to only ask for the email and then set the username as the email in the view before saving.</p> <p>My UserForm only requires the email and password:</p> <pre><code>class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('email', 'password') </code></pre> <p>Then in my view I add the following logic:</p> <pre><code>if user_form.is_valid(): # Save the user's form data to a user object without committing. user = user_form.save(commit=False) user.set_password(user.password) #Set username of user as the email user.username = user.email #commit user.save() </code></pre>
0
2016-02-19T15:09:55Z
[ "python", "django", "authentication" ]
Identifying the types of all variables in a C project
778,468
<p>I am trying to write a program to check that some C source code conforms to a variable naming convention. In order to do this, I need to analyse the source code and identify the type of all the local and global variables.</p> <p>The end result will almost certainly be a python program, but the tool to analyse the code could either be a python module or an application that produces an easy-to-parse report. Alternatively (more on this below) it could be a way of extracting information from the compiler (by way of a report or similar). In case that's helpful, in all likelihood, it will be the <a href="http://www.keil.com">Keil</a> ARM compiler.</p> <p>I've been experimenting with <a href="http://ctags.sourceforge.net">ctags</a> and this is very useful for finding all of the typedefs and macro definitions etc, but it doesn't provide a direct way to find the type of variables, especially when the definition is spread over multiple lines (which I hope it won't be!).</p> <p>Examples might include:</p> <pre><code>static volatile u8 var1; // should be flagged as static and volatile and a u8 (typedef of unsigned 8-bit integer) volatile /* comments */ static /* inserted just to make life */ u8 /* difficult! */ var2 = (u8) 72 ; // likewise (nasty syntax, but technically valid C) const uint_16t *pointer1; // flagged as a pointer to a constant uint_16t int * const pointer2; // flagged as a constant pointer to an int const char * const pointer3; // flagged as a constant pointer to a constant char static MyTypedefTYPE var3; // flagged as a MyTypedefTYPE variable u8 var4, var5, var6 = 72; int *array1[SOME_LENGTH]; // flagged as an array of pointers to integers char array2[FIRST_DIM][72]; // flagged as an array of arrays of type char </code></pre> <p>etc etc etc</p> <p>It will also need to identify whether they're local or global/file-scope variables (which ctags can do) and if they're local, I'd ideally like the name of the function that they're declared within.</p> <p>Also, I'd like to do a similar thing with functions: identify the return type, whether they're static and the type and name of all of their arguments.</p> <p>Unfortunately, this is rather difficult with the C syntax since there is a certain amount of flexibility in parameter order and lots of flexibility in the amount of white space that is allowed between the parameters. I've toyed with using some fancy regular expressions to do the work, but it's far from ideal as there are so many different situations that can be applied, so the regular expressions quickly become unmanageable. I can't help but think that compilers must be able to do this (in order to work!), so I was wondering whether it was possible to extract this information. The Keil compiler seems to produce a ".crf" file for each source file that's compiled and this appears to contain all of the variables declared in that file, but it's a binary format and I can't find any information on how to parse this file. Alternatively a way of getting the information out of ctags would be perfect.</p> <p>Any help that anyone can offer with this would be gratefully appreciated.</p> <p>Thanks,</p> <p>Al</p>
7
2009-04-22T18:06:50Z
778,513
<p>There are a number of Python parser packages that can be used to describe a syntax and then it will generate Python code to parse that syntax.</p> <p>Ned Batchelder wrote a <strong><a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">very nice summary</a></strong></p> <p>Of those, Ply was used in a project called <strong><a href="http://code.google.com/p/pycparser/" rel="nofollow">pycparser</a></strong> that parses C source code. I would recommend starting with this.</p> <p>Some of those other parser projects might also have sample C parsers.</p> <p><strong>Edit</strong>: just noticed that pycparser even has a sample Python script to just <a href="http://code.google.com/p/pycparser/source/browse/examples/cdecl.py" rel="nofollow">parse C type declarations</a> like the old cdecl program.</p>
5
2009-04-22T18:17:02Z
[ "python", "c", "variables", "coding-style", "code-analysis" ]
Identifying the types of all variables in a C project
778,468
<p>I am trying to write a program to check that some C source code conforms to a variable naming convention. In order to do this, I need to analyse the source code and identify the type of all the local and global variables.</p> <p>The end result will almost certainly be a python program, but the tool to analyse the code could either be a python module or an application that produces an easy-to-parse report. Alternatively (more on this below) it could be a way of extracting information from the compiler (by way of a report or similar). In case that's helpful, in all likelihood, it will be the <a href="http://www.keil.com">Keil</a> ARM compiler.</p> <p>I've been experimenting with <a href="http://ctags.sourceforge.net">ctags</a> and this is very useful for finding all of the typedefs and macro definitions etc, but it doesn't provide a direct way to find the type of variables, especially when the definition is spread over multiple lines (which I hope it won't be!).</p> <p>Examples might include:</p> <pre><code>static volatile u8 var1; // should be flagged as static and volatile and a u8 (typedef of unsigned 8-bit integer) volatile /* comments */ static /* inserted just to make life */ u8 /* difficult! */ var2 = (u8) 72 ; // likewise (nasty syntax, but technically valid C) const uint_16t *pointer1; // flagged as a pointer to a constant uint_16t int * const pointer2; // flagged as a constant pointer to an int const char * const pointer3; // flagged as a constant pointer to a constant char static MyTypedefTYPE var3; // flagged as a MyTypedefTYPE variable u8 var4, var5, var6 = 72; int *array1[SOME_LENGTH]; // flagged as an array of pointers to integers char array2[FIRST_DIM][72]; // flagged as an array of arrays of type char </code></pre> <p>etc etc etc</p> <p>It will also need to identify whether they're local or global/file-scope variables (which ctags can do) and if they're local, I'd ideally like the name of the function that they're declared within.</p> <p>Also, I'd like to do a similar thing with functions: identify the return type, whether they're static and the type and name of all of their arguments.</p> <p>Unfortunately, this is rather difficult with the C syntax since there is a certain amount of flexibility in parameter order and lots of flexibility in the amount of white space that is allowed between the parameters. I've toyed with using some fancy regular expressions to do the work, but it's far from ideal as there are so many different situations that can be applied, so the regular expressions quickly become unmanageable. I can't help but think that compilers must be able to do this (in order to work!), so I was wondering whether it was possible to extract this information. The Keil compiler seems to produce a ".crf" file for each source file that's compiled and this appears to contain all of the variables declared in that file, but it's a binary format and I can't find any information on how to parse this file. Alternatively a way of getting the information out of ctags would be perfect.</p> <p>Any help that anyone can offer with this would be gratefully appreciated.</p> <p>Thanks,</p> <p>Al</p>
7
2009-04-22T18:06:50Z
778,529
<p>I did something similar for a project I was working on a few years ago. I ended up writing the first half of a C compiler. Don't be alarmed by that prospect. It is actually much easier than it sounds, especially if you are only looking for certain tokens (variable definitions, in this case).</p> <p>Look for documentation online about how to scan C source code, detect tokens of interest, and parse the results. A good place to start is <a href="http://en.wikipedia.org/wiki/Lexical_analysis#Scanner" rel="nofollow">Wikipedia's artricle on lexical analysis</a>.</p>
0
2009-04-22T18:21:51Z
[ "python", "c", "variables", "coding-style", "code-analysis" ]
Identifying the types of all variables in a C project
778,468
<p>I am trying to write a program to check that some C source code conforms to a variable naming convention. In order to do this, I need to analyse the source code and identify the type of all the local and global variables.</p> <p>The end result will almost certainly be a python program, but the tool to analyse the code could either be a python module or an application that produces an easy-to-parse report. Alternatively (more on this below) it could be a way of extracting information from the compiler (by way of a report or similar). In case that's helpful, in all likelihood, it will be the <a href="http://www.keil.com">Keil</a> ARM compiler.</p> <p>I've been experimenting with <a href="http://ctags.sourceforge.net">ctags</a> and this is very useful for finding all of the typedefs and macro definitions etc, but it doesn't provide a direct way to find the type of variables, especially when the definition is spread over multiple lines (which I hope it won't be!).</p> <p>Examples might include:</p> <pre><code>static volatile u8 var1; // should be flagged as static and volatile and a u8 (typedef of unsigned 8-bit integer) volatile /* comments */ static /* inserted just to make life */ u8 /* difficult! */ var2 = (u8) 72 ; // likewise (nasty syntax, but technically valid C) const uint_16t *pointer1; // flagged as a pointer to a constant uint_16t int * const pointer2; // flagged as a constant pointer to an int const char * const pointer3; // flagged as a constant pointer to a constant char static MyTypedefTYPE var3; // flagged as a MyTypedefTYPE variable u8 var4, var5, var6 = 72; int *array1[SOME_LENGTH]; // flagged as an array of pointers to integers char array2[FIRST_DIM][72]; // flagged as an array of arrays of type char </code></pre> <p>etc etc etc</p> <p>It will also need to identify whether they're local or global/file-scope variables (which ctags can do) and if they're local, I'd ideally like the name of the function that they're declared within.</p> <p>Also, I'd like to do a similar thing with functions: identify the return type, whether they're static and the type and name of all of their arguments.</p> <p>Unfortunately, this is rather difficult with the C syntax since there is a certain amount of flexibility in parameter order and lots of flexibility in the amount of white space that is allowed between the parameters. I've toyed with using some fancy regular expressions to do the work, but it's far from ideal as there are so many different situations that can be applied, so the regular expressions quickly become unmanageable. I can't help but think that compilers must be able to do this (in order to work!), so I was wondering whether it was possible to extract this information. The Keil compiler seems to produce a ".crf" file for each source file that's compiled and this appears to contain all of the variables declared in that file, but it's a binary format and I can't find any information on how to parse this file. Alternatively a way of getting the information out of ctags would be perfect.</p> <p>Any help that anyone can offer with this would be gratefully appreciated.</p> <p>Thanks,</p> <p>Al</p>
7
2009-04-22T18:06:50Z
778,532
<p>Check out ANTLR. It's a parser generator, with bindings for python. The ANTLR site provides a whole bunch of grammars for common languages, C included. You could download the grammar for C and add actions in appropriate places to collect the information you're interested in. There's even a neat graphical tool for creating and debugging the grammars. (I know that seems hokey, but it's actually quite handy and not obnoxious)</p> <ul> <li>ANTLR Main Page: <a href="http://www.antlr.org/" rel="nofollow">http://www.antlr.org</a></li> <li>Their Grammars Page: <a href="http://www.antlr.org/grammar/list" rel="nofollow">http://www.antlr.org/grammar/list</a></li> <li>ANSI C Grammar: <a href="http://www.antlr.org/grammar/1153358328744/C.g" rel="nofollow">http://www.antlr.org/grammar/1153358328744/C.g</a></li> <li>ANTLR Python Target Information: <a href="http://www.antlr.org/wiki/display/ANTLR3/Antlr3PythonTarget" rel="nofollow">http://www.antlr.org/wiki/display/ANTLR3/Antlr3PythonTarget</a></li> </ul> <p>I just did something sort of similar, except to get my symbol information I'm actually extracting it from GDB.</p>
2
2009-04-22T18:22:03Z
[ "python", "c", "variables", "coding-style", "code-analysis" ]
Identifying the types of all variables in a C project
778,468
<p>I am trying to write a program to check that some C source code conforms to a variable naming convention. In order to do this, I need to analyse the source code and identify the type of all the local and global variables.</p> <p>The end result will almost certainly be a python program, but the tool to analyse the code could either be a python module or an application that produces an easy-to-parse report. Alternatively (more on this below) it could be a way of extracting information from the compiler (by way of a report or similar). In case that's helpful, in all likelihood, it will be the <a href="http://www.keil.com">Keil</a> ARM compiler.</p> <p>I've been experimenting with <a href="http://ctags.sourceforge.net">ctags</a> and this is very useful for finding all of the typedefs and macro definitions etc, but it doesn't provide a direct way to find the type of variables, especially when the definition is spread over multiple lines (which I hope it won't be!).</p> <p>Examples might include:</p> <pre><code>static volatile u8 var1; // should be flagged as static and volatile and a u8 (typedef of unsigned 8-bit integer) volatile /* comments */ static /* inserted just to make life */ u8 /* difficult! */ var2 = (u8) 72 ; // likewise (nasty syntax, but technically valid C) const uint_16t *pointer1; // flagged as a pointer to a constant uint_16t int * const pointer2; // flagged as a constant pointer to an int const char * const pointer3; // flagged as a constant pointer to a constant char static MyTypedefTYPE var3; // flagged as a MyTypedefTYPE variable u8 var4, var5, var6 = 72; int *array1[SOME_LENGTH]; // flagged as an array of pointers to integers char array2[FIRST_DIM][72]; // flagged as an array of arrays of type char </code></pre> <p>etc etc etc</p> <p>It will also need to identify whether they're local or global/file-scope variables (which ctags can do) and if they're local, I'd ideally like the name of the function that they're declared within.</p> <p>Also, I'd like to do a similar thing with functions: identify the return type, whether they're static and the type and name of all of their arguments.</p> <p>Unfortunately, this is rather difficult with the C syntax since there is a certain amount of flexibility in parameter order and lots of flexibility in the amount of white space that is allowed between the parameters. I've toyed with using some fancy regular expressions to do the work, but it's far from ideal as there are so many different situations that can be applied, so the regular expressions quickly become unmanageable. I can't help but think that compilers must be able to do this (in order to work!), so I was wondering whether it was possible to extract this information. The Keil compiler seems to produce a ".crf" file for each source file that's compiled and this appears to contain all of the variables declared in that file, but it's a binary format and I can't find any information on how to parse this file. Alternatively a way of getting the information out of ctags would be perfect.</p> <p>Any help that anyone can offer with this would be gratefully appreciated.</p> <p>Thanks,</p> <p>Al</p>
7
2009-04-22T18:06:50Z
778,602
<p>What you're trying to do is a lightweight form of static analysis. You might have some luck looking at the tools pointed to by <a href="http://en.wikipedia.org/wiki/List%5Fof%5Ftools%5Ffor%5Fstatic%5Fcode%5Fanalysis#C" rel="nofollow">Wikipedia</a>.</p> <p>Parsing the C code yourself sounds like the wrong direction to me: therein lies madness. If you insist, then [f]lex and yacc (bison) are the tools likely used by your compiler-writers.</p> <p>Or, if ctags or cscope gets you 80% of the way, the source code to both is widely available. The last 20% is a Simple Matter of Programming. :)</p>
2
2009-04-22T18:41:45Z
[ "python", "c", "variables", "coding-style", "code-analysis" ]
Identifying the types of all variables in a C project
778,468
<p>I am trying to write a program to check that some C source code conforms to a variable naming convention. In order to do this, I need to analyse the source code and identify the type of all the local and global variables.</p> <p>The end result will almost certainly be a python program, but the tool to analyse the code could either be a python module or an application that produces an easy-to-parse report. Alternatively (more on this below) it could be a way of extracting information from the compiler (by way of a report or similar). In case that's helpful, in all likelihood, it will be the <a href="http://www.keil.com">Keil</a> ARM compiler.</p> <p>I've been experimenting with <a href="http://ctags.sourceforge.net">ctags</a> and this is very useful for finding all of the typedefs and macro definitions etc, but it doesn't provide a direct way to find the type of variables, especially when the definition is spread over multiple lines (which I hope it won't be!).</p> <p>Examples might include:</p> <pre><code>static volatile u8 var1; // should be flagged as static and volatile and a u8 (typedef of unsigned 8-bit integer) volatile /* comments */ static /* inserted just to make life */ u8 /* difficult! */ var2 = (u8) 72 ; // likewise (nasty syntax, but technically valid C) const uint_16t *pointer1; // flagged as a pointer to a constant uint_16t int * const pointer2; // flagged as a constant pointer to an int const char * const pointer3; // flagged as a constant pointer to a constant char static MyTypedefTYPE var3; // flagged as a MyTypedefTYPE variable u8 var4, var5, var6 = 72; int *array1[SOME_LENGTH]; // flagged as an array of pointers to integers char array2[FIRST_DIM][72]; // flagged as an array of arrays of type char </code></pre> <p>etc etc etc</p> <p>It will also need to identify whether they're local or global/file-scope variables (which ctags can do) and if they're local, I'd ideally like the name of the function that they're declared within.</p> <p>Also, I'd like to do a similar thing with functions: identify the return type, whether they're static and the type and name of all of their arguments.</p> <p>Unfortunately, this is rather difficult with the C syntax since there is a certain amount of flexibility in parameter order and lots of flexibility in the amount of white space that is allowed between the parameters. I've toyed with using some fancy regular expressions to do the work, but it's far from ideal as there are so many different situations that can be applied, so the regular expressions quickly become unmanageable. I can't help but think that compilers must be able to do this (in order to work!), so I was wondering whether it was possible to extract this information. The Keil compiler seems to produce a ".crf" file for each source file that's compiled and this appears to contain all of the variables declared in that file, but it's a binary format and I can't find any information on how to parse this file. Alternatively a way of getting the information out of ctags would be perfect.</p> <p>Any help that anyone can offer with this would be gratefully appreciated.</p> <p>Thanks,</p> <p>Al</p>
7
2009-04-22T18:06:50Z
779,504
<p>How about approaching it from the other side completely. You already have a parser that fully understands all of the nuances of the C type system: the compiler itself. So, compile the project with full debug support, and go spelunking in the debug data. </p> <p>For a system based on formats supported by <a href="http://www.gnu.org/software/binutils/" rel="nofollow">binutils</a>, most of the detail you need can be learned with the <a href="http://sourceware.org/binutils/docs/bfd/index.html" rel="nofollow">BFD</a> library.</p> <p>Microsoft's debug formats are (somewhat) supported by libraries and documents at MSDN, but my Google-fu is weak today and I'm not putting my hands on the articles I know exist to link here.</p> <p>The Keil 8051 compiler (I haven't used their ARM compiler here) uses Intel OMF or OMF2 format, and documents that the debug symbols are for their debugger or "any Intel-compatible emulators". Specs for <a href="http://www.keil.com/support/docs/163.htm" rel="nofollow">OMF</a> as used by Keil C51 are available from <a href="http://www.keil.com/" rel="nofollow">Keil</a>, so I would imagine that similar specs are available for their other compilers too.</p> <p>A quick scan of Keil's web site seems to indicate that they abandoned their proprietary ARM compiler in favor of licensing ARM's RealView Compiler, which appears to use ELF objects with DWARF format debug info. Dwarf should be supported by BFD, and should give you everything you need to know to verify that the types and names match.</p>
3
2009-04-22T22:20:22Z
[ "python", "c", "variables", "coding-style", "code-analysis" ]
How to center a GNOME pop-up notification?
778,660
<p>To display a GNOME pop-up notification at (200,400) on the screen (using Python):</p> <pre><code>import pynotify n = pynotify.Notification("This is my title", "This is my description") n.set_hint('x', 200) n.set_hint('y', 400) n.show() </code></pre> <p>I'm a gtk noob. How can I make this Notification show up centered on the screen, or at the bottom-center of the screen?</p> <p>Perhaps my question should be "what Python snippet gets me the Linux screen dimensions?", and I'll plug those into set_hint() as appropriate.</p>
4
2009-04-22T18:56:05Z
778,674
<p>on windows, </p> <pre><code> from win32api import GetSystemMetrics width = GetSystemMetrics (0) height = GetSystemMetrics (1) print "Screen resolution = %dx%d" % (width, height) </code></pre> <p>I cant seem to find the linux version for it tho. </p>
-4
2009-04-22T19:00:28Z
[ "python", "user-interface", "gtk", "pynotify" ]
How to center a GNOME pop-up notification?
778,660
<p>To display a GNOME pop-up notification at (200,400) on the screen (using Python):</p> <pre><code>import pynotify n = pynotify.Notification("This is my title", "This is my description") n.set_hint('x', 200) n.set_hint('y', 400) n.show() </code></pre> <p>I'm a gtk noob. How can I make this Notification show up centered on the screen, or at the bottom-center of the screen?</p> <p>Perhaps my question should be "what Python snippet gets me the Linux screen dimensions?", and I'll plug those into set_hint() as appropriate.</p>
4
2009-04-22T18:56:05Z
778,871
<p>A bit of a hack, but this works:</p> <pre><code>from Tkinter import * r = Tk() r.withdraw() width, height = r.winfo_screenwidth(), r.winfo_screenheight() </code></pre> <p>Another option is:</p> <pre><code>from commands import getstatusoutput status, output = getstatusoutput("xwininfo -root") width = re.compile(r"Width: (\d+)").findall(output)[0] height = re.compile(r"Height: (\d+)").findall(output)[0] </code></pre>
0
2009-04-22T19:43:02Z
[ "python", "user-interface", "gtk", "pynotify" ]
How to center a GNOME pop-up notification?
778,660
<p>To display a GNOME pop-up notification at (200,400) on the screen (using Python):</p> <pre><code>import pynotify n = pynotify.Notification("This is my title", "This is my description") n.set_hint('x', 200) n.set_hint('y', 400) n.show() </code></pre> <p>I'm a gtk noob. How can I make this Notification show up centered on the screen, or at the bottom-center of the screen?</p> <p>Perhaps my question should be "what Python snippet gets me the Linux screen dimensions?", and I'll plug those into set_hint() as appropriate.</p>
4
2009-04-22T18:56:05Z
779,669
<p>Since you're using GNOME, here's the GTK way of getting the screen resolution</p> <pre><code>import gtk.gdk import pynotify n = pynotify.Notification("This is my title", "This is my description") n.set_hint('x', gtk.gdk.screen_width()/2.) n.set_hint('y', gtk.gdk.screen_height()/2.) n.show() </code></pre>
4
2009-04-22T23:29:26Z
[ "python", "user-interface", "gtk", "pynotify" ]
Generating unique and opaque user IDs in Google App Engine
778,965
<p>I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows people to browse its users' pages.</p> <p>To do this, I need a way to identify the user in the anonymous HTTP GET request. A user should be able to type <code>http://myapplication.com/browse/&lt;userid&gt;/&lt;contentid&gt;</code> and get to the right page - should be unique, but mustn't be something like the user's email address, for privacy reasons. </p> <p>Through Google App Engine, I can get the email address associated with the user, but like I said, I don't want to use that. I can have users of my application pick a unique user name when they register, but I would like to make that optional if at all possible, so that the registration process is as short as possible. </p> <p>Another option is to generate some random cookie (a GUID?) during the registration process, and use that, I don't see an obvious way of guaranteeing uniqueness of such a cookie without a trip to the database.</p> <p>Is there a way, given an App Engine user object, of getting a unique identifier for that object that can be used in this way? </p> <p>I'm looking for a Python solution - I forgot that GAE also supports Java now. Still, I expect the techniques to be similar, regardless of the language.</p>
9
2009-04-22T20:06:21Z
779,023
<p>Do you mean <a href="http://en.wikipedia.org/wiki/HTTP%5Fcookie" rel="nofollow">session cookies</a>?</p> <p>Try <a href="http://code.google.com/p/gaeutilities/" rel="nofollow">http://code.google.com/p/gaeutilities/</a></p> <p><hr /></p> <p>What DzinX said. The only way to create an opaque key that can be authenticated without a database roundtrip is using encryption or a cryptographic hash.</p> <p>Give the user a random number and hash it or encrypt it with a private key. You still run the (tiny) risk of collisions, but you can avoid this by touching the database on key creation, changing the random number in case of a collision. Make sure the random number is cryptographic, and add a long server-side random number to prevent chosen plaintext attacks.</p> <p>You'll end up with a token like the Google Docs key, basically a signature proving the user is authenticated, which can be verified without touching the database.</p> <p>However, given the pricing of GAE and the speed of bigtable, you're probably better off using a session ID if you really can't use Google's own authentication.</p>
1
2009-04-22T20:21:23Z
[ "python", "google-app-engine", "guid", "uniqueidentifier" ]
Generating unique and opaque user IDs in Google App Engine
778,965
<p>I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows people to browse its users' pages.</p> <p>To do this, I need a way to identify the user in the anonymous HTTP GET request. A user should be able to type <code>http://myapplication.com/browse/&lt;userid&gt;/&lt;contentid&gt;</code> and get to the right page - should be unique, but mustn't be something like the user's email address, for privacy reasons. </p> <p>Through Google App Engine, I can get the email address associated with the user, but like I said, I don't want to use that. I can have users of my application pick a unique user name when they register, but I would like to make that optional if at all possible, so that the registration process is as short as possible. </p> <p>Another option is to generate some random cookie (a GUID?) during the registration process, and use that, I don't see an obvious way of guaranteeing uniqueness of such a cookie without a trip to the database.</p> <p>Is there a way, given an App Engine user object, of getting a unique identifier for that object that can be used in this way? </p> <p>I'm looking for a Python solution - I forgot that GAE also supports Java now. Still, I expect the techniques to be similar, regardless of the language.</p>
9
2009-04-22T20:06:21Z
779,600
<p>I think you should distinguish between two types of users:</p> <p>1) users that have logged in via Google Accounts or that have already registered on your site with a non-google e-mail address</p> <p>2) users that opened your site for the first time and are not logged in in any way</p> <p>For the second case, I can see no other way than to generate some random string (e.g. via <code>uuid.uuid4()</code> or from this user's session cookie key), as an anonymous user does not carry any unique information with himself.</p> <p>For users that are logged in, however, you already have a unique identifier -- their e-mail address. I agree with your privacy concerns -- you shouldn't use it as an identifier. Instead, how about generating a string that <em>seems</em> random, but is in fact generated from the e-mail address? Hashing functions are perfect for this purpose. Example:</p> <pre><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; email = 'user@host.com' &gt;&gt;&gt; salt = 'SomeLongStringThatWillBeAppendedToEachEmail' &gt;&gt;&gt; key = hashlib.sha1('%s$%s' % (email, salt)).hexdigest() &gt;&gt;&gt; print key f6cd3459f9a39c97635c652884b3e328f05be0f7 </code></pre> <p>As <code>hashlib.sha1</code> is not a random function, but for given data returns always the same result, but it is proven to be practically irreversible, you can safely present the hashed key on the website without compromising user's e-mail address. Also, you can safely assume that no two hashes of distinct e-mails will be the same (they can be, but probability of it happening is very, very small). For more information on hashing functions, consult <a href="http://en.wikipedia.org/wiki/Cryptographic%5Fhash%5Ffunction" rel="nofollow">the Wikipedia entry</a>.</p>
3
2009-04-22T22:56:35Z
[ "python", "google-app-engine", "guid", "uniqueidentifier" ]
Generating unique and opaque user IDs in Google App Engine
778,965
<p>I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows people to browse its users' pages.</p> <p>To do this, I need a way to identify the user in the anonymous HTTP GET request. A user should be able to type <code>http://myapplication.com/browse/&lt;userid&gt;/&lt;contentid&gt;</code> and get to the right page - should be unique, but mustn't be something like the user's email address, for privacy reasons. </p> <p>Through Google App Engine, I can get the email address associated with the user, but like I said, I don't want to use that. I can have users of my application pick a unique user name when they register, but I would like to make that optional if at all possible, so that the registration process is as short as possible. </p> <p>Another option is to generate some random cookie (a GUID?) during the registration process, and use that, I don't see an obvious way of guaranteeing uniqueness of such a cookie without a trip to the database.</p> <p>Is there a way, given an App Engine user object, of getting a unique identifier for that object that can be used in this way? </p> <p>I'm looking for a Python solution - I forgot that GAE also supports Java now. Still, I expect the techniques to be similar, regardless of the language.</p>
9
2009-04-22T20:06:21Z
780,623
<p>Your timing is impeccable: Just yesterday, a new release of the SDK came out, with support for <a href="http://code.google.com/appengine/docs/python/users/userclass.html#User%5Fuser%5Fid">unique, permanent user IDs</a>. They meet all the criteria you specified.</p>
7
2009-04-23T07:15:00Z
[ "python", "google-app-engine", "guid", "uniqueidentifier" ]
regex for parsing SQL statements
778,969
<p>I've got an IronPython script that executes a bunch of SQL statements against a SQL Server database. the statements are large strings that actually contain multiple statements, separated by the "GO" keyword. That works when they're run from sql management studio and some other tools, but not in ADO. So I split up the strings using the 2.5 "re" module like so:</p> <pre><code>splitter = re.compile(r'\bGO\b', re.IGNORECASE) for script in splitter.split(scriptBlob): if(script): [... execute the query ...] </code></pre> <p>This breaks in the rare case that there's the word "go" in a comment or a string. How in the heck would I work around that? i.e. correctly parse this string into two scripts:</p> <pre><code>-- this is a great database script! go team go! INSERT INTO myTable(stringColumn) VALUES ('go away!') /* here are some comments that go with this script. */ GO INSERT INTO myTable(stringColumn) VALUES ('this is the next script') </code></pre> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>I searched more and found this SQL documentation: <a href="http://msdn.microsoft.com/en-us/library/ms188037%28SQL.90%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms188037(SQL.90).aspx</a></p> <p>As it turns out, GO must be on its own line as some answers suggested. However it can be followed by a "count" integer which will actually execute the statement batch that many times (has anybody actually used that before??) and it can be followed by a single-line comments on the same line (but not a multi-line, I tested this.) So the magic regex would look something like:</p> <pre><code>"(?m)^\s*GO\s*\d*\s*$" </code></pre> <p>Except this doesn't account for:</p> <ul> <li>a possible single-line comment (<code>"--"</code> followed by any character except a line break) at the end.</li> <li>the whole line being inside a larger multi-line comment.</li> </ul> <p>I'm not concerned about capturing the "count" argument and using it. Now that I have some technical documentation i'm tantalizingly close to writing this "to spec" and never having to worry about it again.</p>
6
2009-04-22T20:07:38Z
779,048
<p>since you can have comments inside comments, nested comments, comments inside queries, etc, there is no sane way to do it with regexes.</p> <p>Just immagine the following script:</p> <pre><code>INSERT INTO table (name) VALUES ( -- GO NOW GO 'GO to GO /* GO */ GO' + /* some comment 'go go go' -- */ 'GO GO' /* GO */ ) </code></pre> <p>That without mentioning:</p> <pre><code>INSERT INTO table (go) values ('xxx') GO </code></pre> <p>The only way would be to build a stateful parser instead. One that reads a char at a time, and has a flag that will be set when it is inside a comment/quote-delimited string/etc and reset when it ends, so the code can ignore "GO" instances when inside those.</p>
5
2009-04-22T20:25:35Z
[ "python", "regex" ]
regex for parsing SQL statements
778,969
<p>I've got an IronPython script that executes a bunch of SQL statements against a SQL Server database. the statements are large strings that actually contain multiple statements, separated by the "GO" keyword. That works when they're run from sql management studio and some other tools, but not in ADO. So I split up the strings using the 2.5 "re" module like so:</p> <pre><code>splitter = re.compile(r'\bGO\b', re.IGNORECASE) for script in splitter.split(scriptBlob): if(script): [... execute the query ...] </code></pre> <p>This breaks in the rare case that there's the word "go" in a comment or a string. How in the heck would I work around that? i.e. correctly parse this string into two scripts:</p> <pre><code>-- this is a great database script! go team go! INSERT INTO myTable(stringColumn) VALUES ('go away!') /* here are some comments that go with this script. */ GO INSERT INTO myTable(stringColumn) VALUES ('this is the next script') </code></pre> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>I searched more and found this SQL documentation: <a href="http://msdn.microsoft.com/en-us/library/ms188037%28SQL.90%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms188037(SQL.90).aspx</a></p> <p>As it turns out, GO must be on its own line as some answers suggested. However it can be followed by a "count" integer which will actually execute the statement batch that many times (has anybody actually used that before??) and it can be followed by a single-line comments on the same line (but not a multi-line, I tested this.) So the magic regex would look something like:</p> <pre><code>"(?m)^\s*GO\s*\d*\s*$" </code></pre> <p>Except this doesn't account for:</p> <ul> <li>a possible single-line comment (<code>"--"</code> followed by any character except a line break) at the end.</li> <li>the whole line being inside a larger multi-line comment.</li> </ul> <p>I'm not concerned about capturing the "count" argument and using it. Now that I have some technical documentation i'm tantalizingly close to writing this "to spec" and never having to worry about it again.</p>
6
2009-04-22T20:07:38Z
779,083
<p>If GO is always on a line by itself you can use split like this:</p> <pre><code>#!/usr/bin/python import re sql = """-- this is a great database script! go team go! INSERT INTO myTable(stringColumn) VALUES ('go away!') /* here are some comments that go with this script. */ GO 5 --this is a test INSERT INTO myTable(stringColumn) VALUES ('this is the next script')""" statements = re.split("(?m)^\s*GO\s*(?:[0-9]+)?\s*(?:--.*)?$", sql) for statement in statements: print "the statement is\n%s\n" % (statement) </code></pre> <ul> <li><code>(?m)</code> turns on multiline matchings, that is <code>^</code> and <code>$</code> will match start and end of line (instead of start and end of string).</li> <li><code>^</code> matches at the start of a line</li> <li><code>\s*</code> matches zero or more whitespaces (space, tab, etc.)</li> <li><code>GO</code> matches a literal GO</li> <li><code>\s*</code> matches as before</li> <li><code>(?:[0-9]+)?</code> matches an optional integer number (with possible leading zeros)</li> <li><code>\s*</code> matches as before</li> <li><code>(?:--.*)?</code> matches an optional end-of-line comment </li> <li><code>$</code> matches at the end of a line</li> </ul> <p>The split will consume the GO line, so you won't have to worry about it. This will leave you with a list of statements.</p> <p>This modified split has a problem: it will not give you back the number after the GO, if that is important I would say it is time to move to a parser of some form.</p>
5
2009-04-22T20:31:28Z
[ "python", "regex" ]
regex for parsing SQL statements
778,969
<p>I've got an IronPython script that executes a bunch of SQL statements against a SQL Server database. the statements are large strings that actually contain multiple statements, separated by the "GO" keyword. That works when they're run from sql management studio and some other tools, but not in ADO. So I split up the strings using the 2.5 "re" module like so:</p> <pre><code>splitter = re.compile(r'\bGO\b', re.IGNORECASE) for script in splitter.split(scriptBlob): if(script): [... execute the query ...] </code></pre> <p>This breaks in the rare case that there's the word "go" in a comment or a string. How in the heck would I work around that? i.e. correctly parse this string into two scripts:</p> <pre><code>-- this is a great database script! go team go! INSERT INTO myTable(stringColumn) VALUES ('go away!') /* here are some comments that go with this script. */ GO INSERT INTO myTable(stringColumn) VALUES ('this is the next script') </code></pre> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>I searched more and found this SQL documentation: <a href="http://msdn.microsoft.com/en-us/library/ms188037%28SQL.90%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms188037(SQL.90).aspx</a></p> <p>As it turns out, GO must be on its own line as some answers suggested. However it can be followed by a "count" integer which will actually execute the statement batch that many times (has anybody actually used that before??) and it can be followed by a single-line comments on the same line (but not a multi-line, I tested this.) So the magic regex would look something like:</p> <pre><code>"(?m)^\s*GO\s*\d*\s*$" </code></pre> <p>Except this doesn't account for:</p> <ul> <li>a possible single-line comment (<code>"--"</code> followed by any character except a line break) at the end.</li> <li>the whole line being inside a larger multi-line comment.</li> </ul> <p>I'm not concerned about capturing the "count" argument and using it. Now that I have some technical documentation i'm tantalizingly close to writing this "to spec" and never having to worry about it again.</p>
6
2009-04-22T20:07:38Z
779,084
<p>Is "GO" always on a line by itself? You could just split on "^GO$".</p>
8
2009-04-22T20:31:40Z
[ "python", "regex" ]
regex for parsing SQL statements
778,969
<p>I've got an IronPython script that executes a bunch of SQL statements against a SQL Server database. the statements are large strings that actually contain multiple statements, separated by the "GO" keyword. That works when they're run from sql management studio and some other tools, but not in ADO. So I split up the strings using the 2.5 "re" module like so:</p> <pre><code>splitter = re.compile(r'\bGO\b', re.IGNORECASE) for script in splitter.split(scriptBlob): if(script): [... execute the query ...] </code></pre> <p>This breaks in the rare case that there's the word "go" in a comment or a string. How in the heck would I work around that? i.e. correctly parse this string into two scripts:</p> <pre><code>-- this is a great database script! go team go! INSERT INTO myTable(stringColumn) VALUES ('go away!') /* here are some comments that go with this script. */ GO INSERT INTO myTable(stringColumn) VALUES ('this is the next script') </code></pre> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>I searched more and found this SQL documentation: <a href="http://msdn.microsoft.com/en-us/library/ms188037%28SQL.90%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms188037(SQL.90).aspx</a></p> <p>As it turns out, GO must be on its own line as some answers suggested. However it can be followed by a "count" integer which will actually execute the statement batch that many times (has anybody actually used that before??) and it can be followed by a single-line comments on the same line (but not a multi-line, I tested this.) So the magic regex would look something like:</p> <pre><code>"(?m)^\s*GO\s*\d*\s*$" </code></pre> <p>Except this doesn't account for:</p> <ul> <li>a possible single-line comment (<code>"--"</code> followed by any character except a line break) at the end.</li> <li>the whole line being inside a larger multi-line comment.</li> </ul> <p>I'm not concerned about capturing the "count" argument and using it. Now that I have some technical documentation i'm tantalizingly close to writing this "to spec" and never having to worry about it again.</p>
6
2009-04-22T20:07:38Z
779,100
<p><s>This won't detect if <code>GO</code> ever is used as a variable name inside some statement, but should take care of those inside comments or strings.</s></p> <p><strong>EDIT:</strong> This now works if <code>GO</code> is part of the statement, as long as it is not in it's own line.</p> <pre><code>import re line_comment = r'(?:--|#).*$' block_comment = r'/\*[\S\s]*?\*/' singe_quote_string = r"'(?:\\.|[^'\\])*'" double_quote_string = r'"(?:\\.|[^"\\])*"' go_word = r'^[^\S\n]*(?P&lt;GO&gt;GO)[^\S\n]*\d*[^\S\n]*(?:(?:--|#).*)?$' full_pattern = re.compile(r'|'.join(( line_comment, block_comment, singe_quote_string, double_quote_string, go_word, )), re.IGNORECASE | re.MULTILINE) def split_sql_statements(statement_string): last_end = 0 for match in full_pattern.finditer(statement_string): if match.group('GO'): yield statement_string[last_end:match.start()] last_end = match.end() yield statement_string[last_end:] </code></pre> <p>Example usage:</p> <pre><code>statement_string = r""" -- this is a great database script! go team go! INSERT INTO go(go) VALUES ('go away!') go 7 -- foo INSERT INTO go(go) VALUES ( 'I have to GO " with a /* comment to GO inside a /* GO string /*' ) /* here are some comments that go with this script. */ GO INSERT INTO go(go) VALUES ('this is the next script') """ for statement in split_sql_statements(statement_string): print '=======' print statement </code></pre> <p>Output:</p> <pre><code>======= -- this is a great database script! go team go! INSERT INTO go(go) VALUES ('go away!') ======= INSERT INTO go(go) VALUES ( 'I have to GO " with a /* comment to GO inside a /* GO string /*' ) /* here are some comments that go with this script. */ ======= INSERT INTO go(go) VALUES ('this is the next script') </code></pre>
2
2009-04-22T20:33:41Z
[ "python", "regex" ]
How to upload a pristine Python package to PyPI?
778,980
<p>What's the magic "<code>python setup.py some_incantation_here</code>" command to upload a package to PyPI, in a form that can be downloaded to get the original package in its original form?</p> <p>I have a package with some source and a few image files (as package_data). If I do "<code>setup.py sdist register upload</code>", the .tar.gz has the image files excluded. If I do "<code>setup.py bdist_egg register upload</code>", the egg contains the images but excludes the setup.py file. I want to be able to get a file uploaded that is just the entirety of my project -- aka "<code>setup.py the_whole_freaking_thing register upload</code>".</p> <p>Perhaps the best way to do this is to manually tar.gz my project directory and upload it using the PyPI web interface?</p> <p>Caveat: I'm trying to avoid having to store a simple project I just created in my SVN repo as well as on PyPI -- it seems like a waste of work to keep track of its history and files in two places.</p>
10
2009-04-22T20:10:03Z
779,790
<p>When you perform an "sdist" command, then what controls the list of included files is your "MANIFEST.in" file sitting next to "setup.py", not whatever you have listed in "package_data". This has something to do with the schizophrenic nature of the Python packaging solutions today; "sdist" is powered by the <a href="http://docs.python.org/distutils/index.html#distutils-index">distutils</a> in the standard library, while "bdist_egg" is controlled by the <a href="http://peak.telecommunity.com/DevCenter/setuptools">setuptools</a> module.</p> <p>To solve the problem, try creating a MANIFEST.in next to your setup.py file, and give it contents like this:</p> <pre><code>include *.jpg </code></pre> <p>Of course, I'm imaging that your "image files" are actual pictures rather than disk images or ISO images or something; you might have to adjust the above line if I've guessed wrong! But check out the <a href="http://docs.python.org/distutils/sourcedist.html#specifying-the-files-to-distribute">Specifying which files to distribute</a> section of the distutils docs, and see whether you can't get those files appearing in your .tar.gz source distribution! Good luck.</p>
16
2009-04-23T00:15:17Z
[ "python", "packaging", "pypi" ]
Python Multiprocessing: Sending data to a process
779,384
<p>I have subclassed <code>Process</code> like so:</p> <pre><code>class EdgeRenderer(Process): def __init__(self,starter,*args,**kwargs): Process.__init__(self,*args,**kwargs) self.starter=starter </code></pre> <p>Then I define a <code>run</code> method which uses <code>self.starter</code>.</p> <p>That <code>starter</code> object is of a class <code>State</code> that I define.</p> <p>Is it okay that I do this? What happens to the object? Does it get serialized? Does that mean that I always have to ensure the <code>State</code> object is serializable? Does the new process get a duplicate copy of this object?</p>
2
2009-04-22T21:47:29Z
781,749
<p>On unix systems, multiprocessing uses os.fork() to create the children, on windows, it uses some subprocess trickery and serialization to share the data. So to be cross platform, yes - it must be serializable. The child will get a new copy.</p> <p>That being said, here's an example:</p> <pre><code>from multiprocessing import Process import time class Starter(object): def __init__(self): self.state = False x = Starter() class EdgeRenderer(Process): def __init__(self,starter,*args,**kwargs): Process.__init__(self,*args,**kwargs) self.starter=starter def run(self): self.starter.state = "HAM SANDWICH" time.sleep(1) print self.starter.state a = EdgeRenderer(x) a.start() x.state = True a.join() print x.state </code></pre> <p>When run, you will see:</p> <pre><code>HAM SANDWICH True </code></pre> <p>So the changes the parent makes don't get communicated after the fork() and the changes the child makes have the same issue. You have to adhere to fork limitations. </p>
8
2009-04-23T13:37:03Z
[ "python", "multiprocessing" ]
Python Access Data in Package Subdirectory
779,495
<p>I am writing a python package with modules that need to open data files in a <code>./data/</code> subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system. </p> <p>I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module. </p> <p>This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not <code>.py</code> files, so I can't use import functions and the like. </p> <p>Any suggestions? </p> <p>Right now my package directory looks like:</p> <pre><code>/ __init__.py module1.py module2.py data/ data.txt </code></pre> <p>I am trying to access <code>data.txt</code> from <code>module*.py</code></p> <p>Thanks!</p>
41
2009-04-22T22:17:52Z
779,548
<p>I think I hunted down an answer. </p> <p>I make a module data_path.py, which I import into my other modules containing:</p> <pre><code>data_path = os.path.join(os.path.dirname(__file__),'data') </code></pre> <p>And then I open all my files with </p> <pre><code>open(os.path.join(data_path,'filename'), &lt;param&gt;) </code></pre>
4
2009-04-22T22:35:52Z
[ "python", "packages" ]
Python Access Data in Package Subdirectory
779,495
<p>I am writing a python package with modules that need to open data files in a <code>./data/</code> subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system. </p> <p>I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module. </p> <p>This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not <code>.py</code> files, so I can't use import functions and the like. </p> <p>Any suggestions? </p> <p>Right now my package directory looks like:</p> <pre><code>/ __init__.py module1.py module2.py data/ data.txt </code></pre> <p>I am trying to access <code>data.txt</code> from <code>module*.py</code></p> <p>Thanks!</p>
41
2009-04-22T22:17:52Z
779,552
<p>You can use underscore-underscore-file-underscore-underscore (<code>__file__</code>) to get the path to the package, like this:</p> <pre><code>import os this_dir, this_filename = os.path.split(__file__) DATA_PATH = os.path.join(this_dir, "data", "data.txt") print open(DATA_PATH).read() </code></pre>
19
2009-04-22T22:37:04Z
[ "python", "packages" ]
Python Access Data in Package Subdirectory
779,495
<p>I am writing a python package with modules that need to open data files in a <code>./data/</code> subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system. </p> <p>I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module. </p> <p>This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not <code>.py</code> files, so I can't use import functions and the like. </p> <p>Any suggestions? </p> <p>Right now my package directory looks like:</p> <pre><code>/ __init__.py module1.py module2.py data/ data.txt </code></pre> <p>I am trying to access <code>data.txt</code> from <code>module*.py</code></p> <p>Thanks!</p>
41
2009-04-22T22:17:52Z
5,601,839
<p>The standard way to do this is with setuptools packages and pkg_resources.</p> <p>You can lay out your package according to the following hierarchy, and configure the package setup file to point it your data resources, as per this link:</p> <p><a href="http://docs.python.org/distutils/setupscript.html#installing-package-data">http://docs.python.org/distutils/setupscript.html#installing-package-data</a></p> <p>You can then re-find and use those files using pkg_resources, as per this link: </p> <p><a href="http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access">http://peak.telecommunity.com/DevCenter/PkgResources#basic-resource-access</a></p>
47
2011-04-08T23:42:39Z
[ "python", "packages" ]
Python Access Data in Package Subdirectory
779,495
<p>I am writing a python package with modules that need to open data files in a <code>./data/</code> subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system. </p> <p>I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module. </p> <p>This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not <code>.py</code> files, so I can't use import functions and the like. </p> <p>Any suggestions? </p> <p>Right now my package directory looks like:</p> <pre><code>/ __init__.py module1.py module2.py data/ data.txt </code></pre> <p>I am trying to access <code>data.txt</code> from <code>module*.py</code></p> <p>Thanks!</p>
41
2009-04-22T22:17:52Z
26,278,544
<p>To provide a solution working today. Definitely use this API to not reinvent all those wheels.</p> <p>A true filesystem filename is needed. Zipped eggs will be extracted to a cache directory:</p> <pre><code>from pkg_resources import resource_filename, Requirement path_to_vik_logo = resource_filename(Requirement.parse("enb.portals"), "enb/portals/reports/VIK_logo.png") </code></pre> <p>Return a readable file-like object for the specified resource; it may be an actual file, a StringIO, or some similar object. The stream is in “binary mode”, in the sense that whatever bytes are in the resource will be read as-is.</p> <pre><code>from pkg_resources import resource_stream, Requirement vik_logo_as_stream = resource_stream(Requirement.parse("enb.portals"), "enb/portals/reports/VIK_logo.png") </code></pre> <p>Package Discovery and Resource Access using pkg_resources</p> <ul> <li><a href="https://setuptools.readthedocs.io/en/latest/pkg_resources.html#resource-extraction" rel="nofollow">https://setuptools.readthedocs.io/en/latest/pkg_resources.html#resource-extraction</a></li> <li><a href="https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access" rel="nofollow">https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access</a></li> </ul>
9
2014-10-09T12:33:03Z
[ "python", "packages" ]
Python Access Data in Package Subdirectory
779,495
<p>I am writing a python package with modules that need to open data files in a <code>./data/</code> subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system. </p> <p>I've tried a variety of methods, but so far I have had no luck. It seems that most of the "current directory" commands return the directory of the system's python interpreter, and not the directory of the module. </p> <p>This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not <code>.py</code> files, so I can't use import functions and the like. </p> <p>Any suggestions? </p> <p>Right now my package directory looks like:</p> <pre><code>/ __init__.py module1.py module2.py data/ data.txt </code></pre> <p>I am trying to access <code>data.txt</code> from <code>module*.py</code></p> <p>Thanks!</p>
41
2009-04-22T22:17:52Z
34,198,757
<p>You need a name for your whole module, you're given directory tree doesn't list that detail, for me this worked:</p> <pre><code>import pkg_resources print( pkg_resources.resource_filename(__name__, 'data/data.txt') ) </code></pre> <p>Notibly setuptools does not appear to resolve files based on a name match with packed data files, soo you're gunna have to include the <code>data/</code> prefix pretty much no matter what. You can use <code>os.path.join('data', 'data.txt)</code> if you need alternate directory separators, Generally I find no compatibility problems with hard-coded unix style directory separators though.</p>
2
2015-12-10T09:59:33Z
[ "python", "packages" ]
Using Gecko/Firefox or Webkit got HTML parsing in python
779,538
<p>I am using BeautifulSoup and urllib2 for downloading HTML pages and parsing them. Problem is with mis formed HTML pages. Though BeautifulSoup is good at handling mis formed HTML still its not as good as Firefox.</p> <p>Considering that Firefox or Webkit are more updated and resilient at handling HTML I think its ideal to use them to construct and normalize DOM tree of a page and then manipulate it through Python.</p> <p>However I cant find any python binding for the same. Can anyone suggest a way ?</p> <p>I ran into some solutions of running a headless Firefox process and manipulating it through python but is there a more pythonic solution available.</p>
6
2009-04-22T22:33:15Z
779,984
<p>Perhaps <a href="http://code.google.com/p/pywebkitgtk/" rel="nofollow">pywebkitgtk</a> would do what you need.</p>
1
2009-04-23T01:37:41Z
[ "python", "html", "parsing" ]
Using Gecko/Firefox or Webkit got HTML parsing in python
779,538
<p>I am using BeautifulSoup and urllib2 for downloading HTML pages and parsing them. Problem is with mis formed HTML pages. Though BeautifulSoup is good at handling mis formed HTML still its not as good as Firefox.</p> <p>Considering that Firefox or Webkit are more updated and resilient at handling HTML I think its ideal to use them to construct and normalize DOM tree of a page and then manipulate it through Python.</p> <p>However I cant find any python binding for the same. Can anyone suggest a way ?</p> <p>I ran into some solutions of running a headless Firefox process and manipulating it through python but is there a more pythonic solution available.</p>
6
2009-04-22T22:33:15Z
3,897,478
<p>see <a href="http://wiki.python.org/moin/WebBrowserProgramming" rel="nofollow">http://wiki.python.org/moin/WebBrowserProgramming</a></p> <p>there are quite a lot of options - i'm maintaining the page above so that i don't keep repeating myself.</p> <p>you should look at pyjamas-desktop: see the examples/uitest example because we use exactly this trick to get copies of the HTML page "out", so that the python-to-javascript compiler can be tested by comparing the page results after each unit test.</p> <p>each of the runtimes supported and used by pyjamas-desktop is capable of allowing access to the "innerHTML" property of the document's body element (and a hell of a lot more).</p> <p>bottom line: it is trivial to do what you want to do, but you have to know where to look to find out how to do it.</p> <p>l.</p>
1
2010-10-09T19:07:53Z
[ "python", "html", "parsing" ]
Using Gecko/Firefox or Webkit got HTML parsing in python
779,538
<p>I am using BeautifulSoup and urllib2 for downloading HTML pages and parsing them. Problem is with mis formed HTML pages. Though BeautifulSoup is good at handling mis formed HTML still its not as good as Firefox.</p> <p>Considering that Firefox or Webkit are more updated and resilient at handling HTML I think its ideal to use them to construct and normalize DOM tree of a page and then manipulate it through Python.</p> <p>However I cant find any python binding for the same. Can anyone suggest a way ?</p> <p>I ran into some solutions of running a headless Firefox process and manipulating it through python but is there a more pythonic solution available.</p>
6
2009-04-22T22:33:15Z
17,502,814
<p>You might like PyWebkitDFB from <a href="http://www.gnu.org/software/pythonwebkit/" rel="nofollow">http://www.gnu.org/software/pythonwebkit/</a></p>
0
2013-07-06T12:09:29Z
[ "python", "html", "parsing" ]
Stop python from closing on error
779,675
<p>In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?</p>
10
2009-04-22T23:31:27Z
779,684
<p>Your question is not very clear, but I assume that the python interpreter exits (and therefore the calling console window closes) when an exception happens.</p> <p>You need to modify your python application to catch the exception and print it without exiting the interpreter. One way to do that is to print "press ENTER to exit" and then read some input from the console window, effectively waiting for the user to press Enter.</p>
0
2009-04-22T23:35:35Z
[ "python", "debugging" ]
Stop python from closing on error
779,675
<p>In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?</p>
10
2009-04-22T23:31:27Z
779,686
<pre><code>try: #do some stuff 1/0 #stuff that generated the exception except Exception as ex: print ex raw_input() </code></pre>
13
2009-04-22T23:37:20Z
[ "python", "debugging" ]
Stop python from closing on error
779,675
<p>In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?</p>
10
2009-04-22T23:31:27Z
779,691
<p>You could have a second script, which imports/runs your main code. This script would catch all exceptions, and print a traceback (then wait for user input before ending)</p> <p>Assuming your code is structured using the <code>if __name__ == "__main__": main()</code> idiom..</p> <pre><code>def myfunction(): pass class Myclass(): pass def main(): c = Myclass() myfunction(c) if __name__ == "__main__": main() </code></pre> <p>..and the file is named "myscriptname.py" (obviously that can be changed), the following will work</p> <pre><code>from myscriptname import main as myscript_main try: myscript_main() except Exception, errormsg: print "Script errored!" print "Error message: %s" % errormsg print "Traceback:" import traceback traceback.print_exc() print "Press return to exit.." raw_input() </code></pre> <p>(Note that <code>raw_input()</code> has been replaced by <code>input()</code> in <a href="https://docs.python.org/3/whatsnew/3.0.html" rel="nofollow">Python 3</a>)</p> <p>If you don't have a <code>main()</code> function, you would use put the import statement in the <code>try:</code> block:</p> <pre><code>try: import myscriptname except [...] </code></pre> <p>A better solution, one that requires no extra wrapper-scripts, is to run the script either from IDLE, or the command line..</p> <p>On Windows, go to Start > Run, enter <code>cmd</code> and enter. Then enter something like..</p> <pre><code>cd "\Path\To Your\ Script\" \Python\bin\python.exe myscriptname.py </code></pre> <p>(If you installed Python into <code>C:\Python\</code>)</p> <p>On Linux/Mac OS X it's a bit easier, you just run <code>cd /home/your/script/</code> then <code>python myscriptname.py</code></p> <p>The easiest way would be to use IDLE, launch IDLE, open the script and click the run button (<code>F5</code> or <code>Ctrl+F5</code> I think). When the script exits, the window will not close automatically, so you can see any errors</p> <p>Also, as <a href="http://stackoverflow.com/questions/779675/stop-python-from-closing-on-error/779693#779693">Chris Thornhill</a> suggested, on Windows, you can create a shortcut to your script, and in it's Properties prefix the target with..</p> <pre><code>C:\WINDOWS\system32\cmd.exe /K [existing command] </code></pre> <p>From <a href="http://www.computerhope.com/cmd.htm" rel="nofollow">http://www.computerhope.com/cmd.htm</a>:</p> <blockquote> <pre><code>/K command - Executes the specified command and continues running. </code></pre> </blockquote>
6
2009-04-22T23:38:52Z
[ "python", "debugging" ]
Stop python from closing on error
779,675
<p>In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?</p>
10
2009-04-22T23:31:27Z
779,693
<p>If you doing this on a Windows OS, you can prefix the target of your shortcut with:</p> <pre><code>C:\WINDOWS\system32\cmd.exe /K &lt;command&gt; </code></pre> <p>This will prevent the window from closing when the command exits.</p>
13
2009-04-22T23:39:11Z
[ "python", "debugging" ]
Stop python from closing on error
779,675
<p>In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?</p>
10
2009-04-22T23:31:27Z
780,509
<p>On UNIX systems (Windows has already been covered above...) you can change the interpreter argument to include the -i flag:</p> <p>#!/usr/bin/python -i</p> <p>From the man page:</p> <blockquote> <p>-i </p> <p>When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.</p> </blockquote>
2
2009-04-23T06:29:48Z
[ "python", "debugging" ]
Stop python from closing on error
779,675
<p>In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?</p>
10
2009-04-22T23:31:27Z
781,074
<p>You can register a top-level exception handler that keeps the application alive when an unhandled exception occurs:</p> <pre><code>def show_exception_and_exit(exc_type, exc_value, tb): import traceback traceback.print_exception(exc_type, exc_value, tb) raw_input("Press key to exit.") sys.exit(-1) import sys sys.excepthook = show_exception_and_exit </code></pre> <p>This is especially useful if you have exceptions occuring inside event handlers that are called from C code, which often do not propagate the errors.</p>
8
2009-04-23T10:03:04Z
[ "python", "debugging" ]
Stop python from closing on error
779,675
<p>In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?</p>
10
2009-04-22T23:31:27Z
14,227,240
<p>In windows instead of double clicking the py file you can drag it into an already open CMD window, and then hit enter. It stays open after an exception.</p> <p>Dan</p>
0
2013-01-09T02:08:06Z
[ "python", "debugging" ]
Stop python from closing on error
779,675
<p>In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?</p>
10
2009-04-22T23:31:27Z
40,098,403
<p>if you are using windows you could do this </p> <pre><code> import os #code here os.system('pause') </code></pre>
0
2016-10-18T02:05:15Z
[ "python", "debugging" ]
What to write into log file?
779,989
<p>My question is simple: what to write into a log. Are there any conventions? What do I have to put in?</p> <p>Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.</p> <p>I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings.</p> <p>Do you use some pre-formatted log resources?</p> <p>Thank you</p>
10
2009-04-23T01:41:25Z
779,995
<p><strong>Here are some suggestions for content:</strong></p> <ul> <li>timestamp</li> <li>message</li> <li>log message type (such as error, warning, trace, debug)</li> <li>thread id ( so you can make sense of the log file from a multi threaded application)</li> </ul> <p><strong>Best practices for implementation:</strong></p> <ul> <li>Put a mutex around the write method so that you can be sure that each write is thread safe and will make sense.</li> <li>Send 1 message at at a time to the log file, and specify the type of log message each time. Then you can set what type of logging you want to take on program startup.</li> <li>Use no buffering on the file, or flush often in case there is a program crash.</li> </ul> <p><strong>Edit:</strong> I just noticed the question was tagged with Python, so please see S. Lott's answer before mine. It may be enough for your needs.</p>
9
2009-04-23T01:44:15Z
[ "python", "logging", "methodology" ]
What to write into log file?
779,989
<p>My question is simple: what to write into a log. Are there any conventions? What do I have to put in?</p> <p>Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.</p> <p>I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings.</p> <p>Do you use some pre-formatted log resources?</p> <p>Thank you</p>
10
2009-04-23T01:41:25Z
780,005
<p>It's quite pleasant, and already implemented.</p> <p>Read this: <a href="http://docs.python.org/library/logging.html">http://docs.python.org/library/logging.html</a></p> <p><hr /></p> <p><strong>Edit</strong></p> <p>"easy to parse, read," are generally contradictory features. English -- easy to read, hard to parse. XML -- easy to parse, hard to read. There is no format that achieves easy-to-read and easy-to-parse. Some log formats are "not horrible to read and not impossible to parse".</p> <p>Some folks create multiple handlers so that one log has several formats: a summary for people to read and an XML version for automated parsing.</p>
18
2009-04-23T01:47:54Z
[ "python", "logging", "methodology" ]
What to write into log file?
779,989
<p>My question is simple: what to write into a log. Are there any conventions? What do I have to put in?</p> <p>Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.</p> <p>I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings.</p> <p>Do you use some pre-formatted log resources?</p> <p>Thank you</p>
10
2009-04-23T01:41:25Z
780,007
<p>Since you tagged your question python, I refer you to <a href="http://stackoverflow.com/questions/741063/reporting-information-during-code-execution-best-design">this question</a> as well. As for the content, Brian proposal is good. Remember however to add the program name if you are using a shared log.</p> <p>The important thing about a logfile is "greppability". Try to provide all your info in a single line, with proper string identifiers that are unique (also in radix) for a particular condition. As for the timestamp, use the ISO-8601 standard which sorts nicely.</p>
1
2009-04-23T01:48:47Z
[ "python", "logging", "methodology" ]
What to write into log file?
779,989
<p>My question is simple: what to write into a log. Are there any conventions? What do I have to put in?</p> <p>Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.</p> <p>I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings.</p> <p>Do you use some pre-formatted log resources?</p> <p>Thank you</p>
10
2009-04-23T01:41:25Z
780,025
<p>timeStamp i.e. DateTime YYYY/MM/DD:HH:mm:ss:ms User Thread ID Function Name Message/Error Message/Success Message/Function Trace</p> <p>Have this in XML format and you can then easily write a parser for it.</p> <pre><code>&lt;log&gt; &lt;logEntry DebugLevel="0|1|2|3|4|5...."&gt; &lt;TimeStamp format="YYYY/MM/DD:HH:mm:ss:ms" value="2009/04/22:14:12:33:120" /&gt; &lt;ThreadId value="" /&gt; &lt;FunctionName value="" /&gt; &lt;Message type="Error|Success|Failure|Status|Trace"&gt; Your message goes here &lt;/Message&gt; &lt;/logEntry&gt; &lt;/log&gt; </code></pre>
0
2009-04-23T01:57:03Z
[ "python", "logging", "methodology" ]
What to write into log file?
779,989
<p>My question is simple: what to write into a log. Are there any conventions? What do I have to put in?</p> <p>Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is.</p> <p>I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings.</p> <p>Do you use some pre-formatted log resources?</p> <p>Thank you</p>
10
2009-04-23T01:41:25Z
780,068
<p>A good idea is to look at log analysis software. Unless you plan to write your own, you will probably want to exploit an existing log analysis package such as Analog. If that is the case, you will probably want to generate a log output that is similar enough to the formats that it accepts. It will allow you to create nice charts and graphs with minimal effort!</p>
1
2009-04-23T02:17:39Z
[ "python", "logging", "methodology" ]