title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?
383,738
<p>We're developing a Python web service and a client web site in parallel. When we make an HTTP request from the client to the service, one call consistently raises a socket.error in socket.py, in read:</p> <pre>(104, 'Connection reset by peer')</pre> <p>When I listen in with wireshark, the "good" and "bad" responses look very similar:</p> <ul> <li>Because of the size of the OAuth header, the request is split into two packets. The service responds to both with ACK</li> <li>The service sends the response, one packet per header (HTTP/1.0 200 OK, then the Date header, etc.). The client responds to each with ACK.</li> <li>(Good request) the server sends a FIN, ACK. The client responds with a FIN, ACK. The server responds ACK.</li> <li>(Bad request) the server sends a RST, ACK, the client doesn't send a TCP response, the socket.error is raised on the client side.</li> </ul> <p>Both the web service and the client are running on a Gentoo Linux x86-64 box running glibc-2.6.1. We're using Python 2.5.2 inside the same virtual_env.</p> <p>The client is a Django 1.0.2 app that is calling httplib2 0.4.0 to make requests. We're signing requests with the OAuth signing algorithm, with the OAuth token always set to an empty string.</p> <p>The service is running Werkzeug 0.3.1, which is using Python's wsgiref.simple_server. I ran the WSGI app through wsgiref.validator with no issues.</p> <p>It seems like this should be easy to debug, but when I trace through a good request on the service side, it looks just like the bad request, in the socket._socketobject.close() function, turning delegate methods into dummy methods. When the send or sendto (can't remember which) method is switched off, the FIN or RST is sent, and the client starts processing.</p> <p>"Connection reset by peer" seems to place blame on the service, but I don't trust httplib2 either. Can the client be at fault?</p> <p>** Further debugging - Looks like server on Linux **</p> <p>I have a MacBook, so I tried running the service on one and the client website on the other. The Linux client calls the OS X server without the bug (FIN ACK). The OS X client calls the Linux service with the bug (RST ACK, and a (54, 'Connection reset by peer')). So, it looks like it's the service running on Linux. Is it x86_64? A bad glibc? wsgiref? Still looking...</p> <p>** Further testing - wsgiref looks flaky **</p> <p>We've gone to production with Apache and mod_wsgi, and the connection resets have gone away. See my answer below, but my advice is to log the connection reset and retry. This will let your server run OK in development mode, and solidly in production.</p>
20
2008-12-20T21:04:42Z
1,196,886
<p>I realize you are using python, but I found this Java article to be useful.</p> <p><a href="http://java.sun.com/javase/6/docs/technotes/guides/net/articles/connection_release.html">http://java.sun.com/javase/6/docs/technotes/guides/net/articles/connection_release.html</a></p>
5
2009-07-28T21:35:46Z
[ "python", "sockets", "wsgi", "httplib2", "werkzeug" ]
Django objects.filter, how "expensive" would this be?
383,760
<p>I am trying to make a search view in Django. It is a search form with freetext input + some options to select, so that you can filter on years and so on. This is some of the code I have in the view so far, the part that does the filtering. And I would like some input on how expensive this would be on the database server.</p> <p><code> soknad_list = Soknad.objects.all()</p> <pre><code>if var1: soknad_list = soknad_list.filter(pub_date__year=var1) if var2: soknad_list = soknad_list.filter(muncipality__name__exact=var2) if var3: soknad_list = soknad_list.filter(genre__name__exact=var3) # TEXT SEARCH stop_word_list = re.compile(STOP_WORDS, re.IGNORECASE) search_term = '%s' % request.GET['q'] cleaned_search_term = stop_word_list.sub('', search_term) cleaned_search_term = cleaned_search_term.strip() if len(cleaned_search_term) != 0: soknad_list = soknad_list.filter(Q(dream__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term) | Q(name__icontains=cleaned_search_term) | Q(school__name__icontains=cleaned_search_term)) </code></pre> <p></code></p> <p>So what I do is, first make a list of all objects, then I check which variables exists (I fetch these with GET on an earlier point) and then I filter the results if they exists. But this doesn't seem too elegant, it probably does a lot of queries to achieve the result, so is there a better way to this?</p> <p>It does exactly what I want, but I guess there is a better/smarter way to do this. Any ideas?</p>
1
2008-12-20T21:30:12Z
383,776
<p>filter itself doesn't execute a query, no query is executed until you explicitly fetch items from query (e.g. get), and list( query ) also executes it.</p>
4
2008-12-20T21:43:51Z
[ "python", "sql", "django", "search", "optimization" ]
Django objects.filter, how "expensive" would this be?
383,760
<p>I am trying to make a search view in Django. It is a search form with freetext input + some options to select, so that you can filter on years and so on. This is some of the code I have in the view so far, the part that does the filtering. And I would like some input on how expensive this would be on the database server.</p> <p><code> soknad_list = Soknad.objects.all()</p> <pre><code>if var1: soknad_list = soknad_list.filter(pub_date__year=var1) if var2: soknad_list = soknad_list.filter(muncipality__name__exact=var2) if var3: soknad_list = soknad_list.filter(genre__name__exact=var3) # TEXT SEARCH stop_word_list = re.compile(STOP_WORDS, re.IGNORECASE) search_term = '%s' % request.GET['q'] cleaned_search_term = stop_word_list.sub('', search_term) cleaned_search_term = cleaned_search_term.strip() if len(cleaned_search_term) != 0: soknad_list = soknad_list.filter(Q(dream__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term) | Q(name__icontains=cleaned_search_term) | Q(school__name__icontains=cleaned_search_term)) </code></pre> <p></code></p> <p>So what I do is, first make a list of all objects, then I check which variables exists (I fetch these with GET on an earlier point) and then I filter the results if they exists. But this doesn't seem too elegant, it probably does a lot of queries to achieve the result, so is there a better way to this?</p> <p>It does exactly what I want, but I guess there is a better/smarter way to do this. Any ideas?</p>
1
2008-12-20T21:30:12Z
383,797
<p>You can see the query that will be generated by using:</p> <pre><code>soknad_list.query.as_sql()[0] </code></pre> <p>You can then put that into your database shell to see how long the query takes, or use EXPLAIN (if your database backend supports it) to see how expensive it is.</p>
2
2008-12-20T22:02:29Z
[ "python", "sql", "django", "search", "optimization" ]
Django objects.filter, how "expensive" would this be?
383,760
<p>I am trying to make a search view in Django. It is a search form with freetext input + some options to select, so that you can filter on years and so on. This is some of the code I have in the view so far, the part that does the filtering. And I would like some input on how expensive this would be on the database server.</p> <p><code> soknad_list = Soknad.objects.all()</p> <pre><code>if var1: soknad_list = soknad_list.filter(pub_date__year=var1) if var2: soknad_list = soknad_list.filter(muncipality__name__exact=var2) if var3: soknad_list = soknad_list.filter(genre__name__exact=var3) # TEXT SEARCH stop_word_list = re.compile(STOP_WORDS, re.IGNORECASE) search_term = '%s' % request.GET['q'] cleaned_search_term = stop_word_list.sub('', search_term) cleaned_search_term = cleaned_search_term.strip() if len(cleaned_search_term) != 0: soknad_list = soknad_list.filter(Q(dream__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term) | Q(name__icontains=cleaned_search_term) | Q(school__name__icontains=cleaned_search_term)) </code></pre> <p></code></p> <p>So what I do is, first make a list of all objects, then I check which variables exists (I fetch these with GET on an earlier point) and then I filter the results if they exists. But this doesn't seem too elegant, it probably does a lot of queries to achieve the result, so is there a better way to this?</p> <p>It does exactly what I want, but I guess there is a better/smarter way to do this. Any ideas?</p>
1
2008-12-20T21:30:12Z
383,829
<p>As Aaron mentioned, you should get a hold of the query text that is going to be run against the database and use an EXPLAIN (or other some method) to view the query execution plan. Once you have a hold of the execution plan for the query you can see what is going on in the database itself. There are a lot of operations that see very expensive to run through procedural code that are very trivial for any database to run, especially if you provide indexes that the database can use for speeding up your query.</p> <p>If I read your question correctly, you're retrieving a result set of all rows in the Soknad table. Once you have these results back you use the filter() method to trim down your results meet your criteria. From looking at the Django documentation, it looks like this will do an in-memory filter rather than re-query the database (of course, this really depends on which data access layer you're using and not on Django itself).</p> <p>The most optimal solution would be to use a full-text search engine (Lucene, ferret, etc) to handle this for you. If that is not available or practical the next best option would be to to construct a query predicate (WHERE clause) before issuing your query to the database and let the database perform the filtering. </p> <p><strong>However,</strong> as with all things that involve the database, the real answer is 'it depends.' The best suggestion is to try out several different approaches using data that is close to production and benchmark them over at least 3 iterations before settling on a final solution to the problem. It may be just as fast, or even faster, to filter in memory rather than filter in the database.</p>
-1
2008-12-20T22:35:20Z
[ "python", "sql", "django", "search", "optimization" ]
Best way to return the language of a given string
383,966
<p>More specifically, I'm trying to check if given string (a sentence) is in Turkish. </p> <p>I can check if the string has Turkish characters such as Ç, Ş, Ü, Ö, Ğ etc. However that's not very reliable as those might be converted to C, S, U, O, G before I receive the string.</p> <p>Another method is to have the 100 most used words in Turkish and check if the sentence includes any/some of those words. I can combine these two methods and use a point system. </p> <p>What do you think is the most efficient way to solve my problem in Python?</p> <p>Related question: <a href="http://stackoverflow.com/questions/257125/human-language-of-a-document">(human) Language of a document</a> (Perl, Google Translation API)</p>
7
2008-12-21T01:12:56Z
383,988
<p>One option would be to use a Bayesian Classifier such as <a href="http://www.divmod.org/trac/wiki/DivmodReverend">Reverend</a>. The Reverend homepage gives this suggestion for a naive language detector:</p> <pre><code>from reverend.thomas import Bayes guesser = Bayes() guesser.train('french', 'le la les du un une je il elle de en') guesser.train('german', 'der die das ein eine') guesser.train('spanish', 'el uno una las de la en') guesser.train('english', 'the it she he they them are were to') guesser.guess('they went to el cantina') guesser.guess('they were flying planes') guesser.train('english', 'the rain in spain falls mainly on the plain') guesser.save('my_guesser.bay') </code></pre> <p>Training with more complex token sets would strengthen the results. For more information on Bayesian classification, <a href="http://en.wikipedia.org/wiki/Bayesian_analysis">see here</a> and <a href="http://en.wikipedia.org/wiki/Naive_Bayesian_classification">here</a>.</p>
14
2008-12-21T01:40:58Z
[ "python", "algorithm", "string" ]
Best way to return the language of a given string
383,966
<p>More specifically, I'm trying to check if given string (a sentence) is in Turkish. </p> <p>I can check if the string has Turkish characters such as Ç, Ş, Ü, Ö, Ğ etc. However that's not very reliable as those might be converted to C, S, U, O, G before I receive the string.</p> <p>Another method is to have the 100 most used words in Turkish and check if the sentence includes any/some of those words. I can combine these two methods and use a point system. </p> <p>What do you think is the most efficient way to solve my problem in Python?</p> <p>Related question: <a href="http://stackoverflow.com/questions/257125/human-language-of-a-document">(human) Language of a document</a> (Perl, Google Translation API)</p>
7
2008-12-21T01:12:56Z
384,062
<p>A simple statistical method that I've used before:</p> <p>Get a decent amount of sample training text in the language you want to detect. Split it up into trigrams, e.g.</p> <p>"Hello foobar" in trigrams is: 'Hel', 'ell', 'llo', 'lo ', 'o f', ' fo', 'foo', 'oob', 'oba', 'bar'</p> <p>For all of the source data, count up the frequency of occurrence of each trigram, presumably in a dict where key=trigram and value=frequency. You can limit this to the top 300 most frequent 3-letter combinations or something if you want. Pickle the dict away somewhere.</p> <p>To tell if a new sample of text is written in the same language, repeat the above steps for the sample text. Now, all you have to do is compute a correlation between the sample trigram frequencies and the training trigram frequencies. You'll need to play with it a bit to pick a threshold correlation above which you are willing to consider input to be turkish or not.</p> <p>This method has been shown to be highly accurate, beating out more sophisticated methods, see</p> <p><a href="http://lesfourmisrouges.com/bs/documentation/@%20work/sdair-94-bc.pdf">Cavnar &amp; Trenkle (1994): "N-Gram-Based Text Categorization"</a></p> <p>Using trigrams solves the problem of using word lists, as there is a vast number of words in any given language, especially given different grammatical permutations. I've tried looking for common words, the problem is they often give a false positive for some other language, or themselves have many permutations. The statistical method doesn't require a lot of storage space and does not require complex parsing. By the way this method only works for languages with a phonetic writing system, it works poorly if at all with languages that use an ideographic language (i.e. Chinese, Japanese, Korean).</p> <p>Alternatively wikipedia has a section on Turkish in <a href="http://en.wikipedia.org/wiki/Language_recognition_chart#Turkic_languages">its handy language recognition chart.</a></p>
10
2008-12-21T03:32:36Z
[ "python", "algorithm", "string" ]
Best way to return the language of a given string
383,966
<p>More specifically, I'm trying to check if given string (a sentence) is in Turkish. </p> <p>I can check if the string has Turkish characters such as Ç, Ş, Ü, Ö, Ğ etc. However that's not very reliable as those might be converted to C, S, U, O, G before I receive the string.</p> <p>Another method is to have the 100 most used words in Turkish and check if the sentence includes any/some of those words. I can combine these two methods and use a point system. </p> <p>What do you think is the most efficient way to solve my problem in Python?</p> <p>Related question: <a href="http://stackoverflow.com/questions/257125/human-language-of-a-document">(human) Language of a document</a> (Perl, Google Translation API)</p>
7
2008-12-21T01:12:56Z
384,515
<p>Why not just use an existing spell checking library? Spell check for several languages, choose language with lowest error count.</p>
-1
2008-12-21T14:26:36Z
[ "python", "algorithm", "string" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
384,125
<p>I already knew about the color escapes, I used them in my bash prompt a while ago. Thanks anyway.<br> What I wanted was to integrate it with the logging module, which I eventually did after a couple of tries and errors.<br> Here is what I end up with:</p> <pre><code>BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) #The background is set with 40 plus the number of the color, and the foreground with 30 #These are the sequences need to get colored ouput RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" def formatter_message(message, use_color = True): if use_color: message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) else: message = message.replace("$RESET", "").replace("$BOLD", "") return message COLORS = { 'WARNING': YELLOW, 'INFO': WHITE, 'DEBUG': BLUE, 'CRITICAL': YELLOW, 'ERROR': RED } class ColoredFormatter(logging.Formatter): def __init__(self, msg, use_color = True): logging.Formatter.__init__(self, msg) self.use_color = use_color def format(self, record): levelname = record.levelname if self.use_color and levelname in COLORS: levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ record.levelname = levelname_color return logging.Formatter.format(self, record) </code></pre> <p>And to use it, create your own Logger:</p> <pre><code># Custom logger class with multiple destinations class ColoredLogger(logging.Logger): FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s] %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)" COLOR_FORMAT = formatter_message(FORMAT, True) def __init__(self, name): logging.Logger.__init__(self, name, logging.DEBUG) color_formatter = ColoredFormatter(self.COLOR_FORMAT) console = logging.StreamHandler() console.setFormatter(color_formatter) self.addHandler(console) return logging.setLoggerClass(ColoredLogger) </code></pre> <p>Just in case anyone else needs it.</p> <p>Be careful if you're using more than one logger or handler: <code>ColoredFormatter</code> is changing the record object, which is passed further to other handlers or propagated to other loggers. If you have configured file loggers etc. you probably don't want to have the colors in the log files. To avoid that, it's probably best to simply create a copy of <code>record</code> with <code>copy.copy()</code> before manipulating the levelname attribute, or to reset the levelname to the previous value, before returning the formatted string (credit to <a href="https://stackoverflow.com/users/715042/michael">Michael</a> in the comments).</p>
119
2008-12-21T05:17:39Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
1,336,640
<p>Here is a solution that should work on any platform. If it doesn't just tell me and I will update it.</p> <p>How it works: on platform supporting ANSI escapes is using them (non-Windows) and on Windows it does use API calls to change the console colors.</p> <p>The script does hack the logging.StreamHandler.emit method from standard library adding a wrapper to it.</p> <p><strong>TestColorer.py</strong></p> <pre><code># Usage: add Colorer.py near you script and import it. import logging import Colorer logging.warn("a warning") logging.error("some error") logging.info("some info") </code></pre> <p><strong>Colorer.py</strong></p> <pre><code>#!/usr/bin/env python # encoding: utf-8 import logging # now we patch Python code to add color support to logging.StreamHandler def add_coloring_to_emit_windows(fn): # add methods we need to the class def _out_handle(self): import ctypes return ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE) out_handle = property(_out_handle) def _set_color(self, code): import ctypes # Constants from the Windows API self.STD_OUTPUT_HANDLE = -11 hdl = ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE) ctypes.windll.kernel32.SetConsoleTextAttribute(hdl, code) setattr(logging.StreamHandler, '_set_color', _set_color) def new(*args): FOREGROUND_BLUE = 0x0001 # text color contains blue. FOREGROUND_GREEN = 0x0002 # text color contains green. FOREGROUND_RED = 0x0004 # text color contains red. FOREGROUND_INTENSITY = 0x0008 # text color is intensified. FOREGROUND_WHITE = FOREGROUND_BLUE|FOREGROUND_GREEN |FOREGROUND_RED # winbase.h STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 # wincon.h FOREGROUND_BLACK = 0x0000 FOREGROUND_BLUE = 0x0001 FOREGROUND_GREEN = 0x0002 FOREGROUND_CYAN = 0x0003 FOREGROUND_RED = 0x0004 FOREGROUND_MAGENTA = 0x0005 FOREGROUND_YELLOW = 0x0006 FOREGROUND_GREY = 0x0007 FOREGROUND_INTENSITY = 0x0008 # foreground color is intensified. BACKGROUND_BLACK = 0x0000 BACKGROUND_BLUE = 0x0010 BACKGROUND_GREEN = 0x0020 BACKGROUND_CYAN = 0x0030 BACKGROUND_RED = 0x0040 BACKGROUND_MAGENTA = 0x0050 BACKGROUND_YELLOW = 0x0060 BACKGROUND_GREY = 0x0070 BACKGROUND_INTENSITY = 0x0080 # background color is intensified. levelno = args[1].levelno if(levelno&gt;=50): color = BACKGROUND_YELLOW | FOREGROUND_RED | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY elif(levelno&gt;=40): color = FOREGROUND_RED | FOREGROUND_INTENSITY elif(levelno&gt;=30): color = FOREGROUND_YELLOW | FOREGROUND_INTENSITY elif(levelno&gt;=20): color = FOREGROUND_GREEN elif(levelno&gt;=10): color = FOREGROUND_MAGENTA else: color = FOREGROUND_WHITE args[0]._set_color(color) ret = fn(*args) args[0]._set_color( FOREGROUND_WHITE ) #print "after" return ret return new def add_coloring_to_emit_ansi(fn): # add methods we need to the class def new(*args): levelno = args[1].levelno if(levelno&gt;=50): color = '\x1b[31m' # red elif(levelno&gt;=40): color = '\x1b[31m' # red elif(levelno&gt;=30): color = '\x1b[33m' # yellow elif(levelno&gt;=20): color = '\x1b[32m' # green elif(levelno&gt;=10): color = '\x1b[35m' # pink else: color = '\x1b[0m' # normal args[1].msg = color + args[1].msg + '\x1b[0m' # normal #print "after" return fn(*args) return new import platform if platform.system()=='Windows': # Windows does not support ANSI escapes and we are using API calls to set the console color logging.StreamHandler.emit = add_coloring_to_emit_windows(logging.StreamHandler.emit) else: # all non-Windows platforms are supporting ANSI escapes so we use them logging.StreamHandler.emit = add_coloring_to_emit_ansi(logging.StreamHandler.emit) #log = logging.getLogger() #log.addFilter(log_filter()) #//hdlr = logging.StreamHandler() #//hdlr.setFormatter(formatter()) </code></pre>
56
2009-08-26T18:29:35Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
2,205,909
<p>I modified the original example provided by Sorin and subclassed StreamHandler to a ColorizedConsoleHandler.</p> <p>The downside of their solution is that it modifies the message, and because that is modifying the actual logmessage any other handlers will get the modified message as well.</p> <p>This resulted in logfiles with colorcodes in them in our case because we use multiple loggers.</p> <p>The class below only works on platforms that support ansi, but it should be trivial to add the windows colorcodes to it.</p> <pre><code>import copy import logging class ColoredConsoleHandler(logging.StreamHandler): def emit(self, record): # Need to make a actual copy of the record # to prevent altering the message for other loggers myrecord = copy.copy(record) levelno = myrecord.levelno if(levelno &gt;= 50): # CRITICAL / FATAL color = '\x1b[31m' # red elif(levelno &gt;= 40): # ERROR color = '\x1b[31m' # red elif(levelno &gt;= 30): # WARNING color = '\x1b[33m' # yellow elif(levelno &gt;= 20): # INFO color = '\x1b[32m' # green elif(levelno &gt;= 10): # DEBUG color = '\x1b[35m' # pink else: # NOTSET and anything else color = '\x1b[0m' # normal myrecord.msg = color + str(myrecord.msg) + '\x1b[0m' # normal logging.StreamHandler.emit(self, myrecord) </code></pre>
8
2010-02-05T08:36:51Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
2,532,931
<p>I updated the example from airmind supporting tags for foreground and background. Just use the color variables $BLACK - $WHITE in your log formatter string. To set the background just use $BG-BLACK - $BG-WHITE.</p> <pre><code>import logging BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) COLORS = { 'WARNING' : YELLOW, 'INFO' : WHITE, 'DEBUG' : BLUE, 'CRITICAL' : YELLOW, 'ERROR' : RED, 'RED' : RED, 'GREEN' : GREEN, 'YELLOW' : YELLOW, 'BLUE' : BLUE, 'MAGENTA' : MAGENTA, 'CYAN' : CYAN, 'WHITE' : WHITE, } RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" class ColorFormatter(logging.Formatter): def __init__(self, *args, **kwargs): # can't do super(...) here because Formatter is an old school class logging.Formatter.__init__(self, *args, **kwargs) def format(self, record): levelname = record.levelname color = COLOR_SEQ % (30 + COLORS[levelname]) message = logging.Formatter.format(self, record) message = message.replace("$RESET", RESET_SEQ)\ .replace("$BOLD", BOLD_SEQ)\ .replace("$COLOR", color) for k,v in COLORS.items(): message = message.replace("$" + k, COLOR_SEQ % (v+30))\ .replace("$BG" + k, COLOR_SEQ % (v+40))\ .replace("$BG-" + k, COLOR_SEQ % (v+40)) return message + RESET_SEQ logging.ColorFormatter = ColorFormatter </code></pre> <p>So now you can simple do the following in your config file:</p> <pre><code>[formatter_colorFormatter] class=logging.ColorFormatter format= $COLOR%(levelname)s $RESET %(asctime)s $BOLD$COLOR%(name)s$RESET %(message)s </code></pre>
12
2010-03-28T12:49:40Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
2,666,796
<p>Another minor remix of airmind's approach that keeps everything in one class:</p> <pre><code>class ColorFormatter(logging.Formatter): FORMAT = ("[$BOLD%(name)-20s$RESET][%(levelname)-18s] " "%(message)s " "($BOLD%(filename)s$RESET:%(lineno)d)") BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" COLORS = { 'WARNING': YELLOW, 'INFO': WHITE, 'DEBUG': BLUE, 'CRITICAL': YELLOW, 'ERROR': RED } def formatter_msg(self, msg, use_color = True): if use_color: msg = msg.replace("$RESET", self.RESET_SEQ).replace("$BOLD", self.BOLD_SEQ) else: msg = msg.replace("$RESET", "").replace("$BOLD", "") return msg def __init__(self, use_color=True): msg = self.formatter_msg(self.FORMAT, use_color) logging.Formatter.__init__(self, msg) self.use_color = use_color def format(self, record): levelname = record.levelname if self.use_color and levelname in self.COLORS: fore_color = 30 + self.COLORS[levelname] levelname_color = self.COLOR_SEQ % fore_color + levelname + self.RESET_SEQ record.levelname = levelname_color return logging.Formatter.format(self, record) </code></pre> <p>To use attach the formatter to a handler, something like:</p> <pre><code>handler.setFormatter(ColorFormatter()) logger.addHandler(handler) </code></pre>
6
2010-04-19T11:01:26Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
4,672,282
<p>The bit I had trouble with was setting up the formatter properly:</p> <pre><code>class ColouredFormatter(logging.Formatter): def __init__(self, msg): logging.Formatter.__init__(self, msg) self._init_colour = _get_colour() def close(self): # restore the colour information to what it was _set_colour(self._init_colour) def format(self, record): # Add your own colourer based on the other examples _set_colour( LOG_LEVEL_COLOUR[record.levelno] ) return logging.Formatter.format(self, record) def init(): # Set up the formatter. Needs to be first thing done. rootLogger = logging.getLogger() hdlr = logging.StreamHandler() fmt = ColouredFormatter('%(message)s') hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) </code></pre> <p>And then to use:</p> <pre><code>import coloured_log import logging coloured_log.init() logging.info("info") logging.debug("debug") coloured_log.close() # restore colours </code></pre>
1
2011-01-12T18:07:31Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
4,691,726
<p>Look at the following solution. The stream handler should be the thing doing the colouring, then you have the option of colouring words rather than just the whole line (with the Formatter). </p> <p><a href="http://plumberjack.blogspot.com/2010/12/colorizing-logging-output-in-terminals.html">http://plumberjack.blogspot.com/2010/12/colorizing-logging-output-in-terminals.html</a></p>
10
2011-01-14T13:52:14Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
7,995,762
<p>Quick and dirty solution for predefined log levels and without defining a new class.</p> <pre><code>logging.addLevelName( logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING)) logging.addLevelName( logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR)) </code></pre>
39
2011-11-03T13:31:53Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
16,630,038
<p>Just answered the same on similar question: <a href="http://stackoverflow.com/questions/2330245/python-change-text-color-in-shell/16630004#16630004">Python | change text color in shell</a></p> <p>The idea is to use the <a href="https://github.com/kennethreitz/clint" rel="nofollow">clint</a> library. Which has support for MAC, Linux and Windows shells (CLI).</p>
-1
2013-05-18T23:34:28Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
16,847,935
<p>Years ago I wrote a colored stream handler for my own use. Then I came across this page and found a collection of code snippets that people are copy/pasting :-(. My stream handler currently only works on UNIX (Linux, Mac OS X) but the advantage is that it's <a href="https://pypi.python.org/pypi/coloredlogs">available on PyPI</a> (and <a href="https://github.com/xolox/python-coloredlogs">GitHub</a>) and it's dead simple to use. It also has a Vim syntax mode :-). In the future I might extend it to work on Windows.</p> <p><strong>To install the package:</strong></p> <pre><code>$ pip install coloredlogs </code></pre> <p><strong>To confirm that it works:</strong></p> <pre><code>$ python -m coloredlogs.demo </code></pre> <p><strong>To get started with your own code:</strong></p> <pre><code>$ python &gt; import coloredlogs, logging &gt; coloredlogs.install() &gt; logging.info("It works!") 2014-07-30 21:21:26 peter-macbook root[7471] INFO It works! </code></pre> <p>The default log format shown in the above example contains the date, time, hostname, the name of the logger, the PID, the log level and the log message. This is what it looks like in practice:</p> <p><img src="http://i.stack.imgur.com/AgqpA.png" alt="Screenshot of coloredlogs output"></p>
29
2013-05-31T00:16:27Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
20,698,959
<p>Now there is a released PyPi module for customizable colored logging output:</p> <p><a href="https://pypi.python.org/pypi/rainbow_logging_handler/">https://pypi.python.org/pypi/rainbow_logging_handler/</a></p> <p>and</p> <p><a href="https://github.com/laysakura/rainbow_logging_handler">https://github.com/laysakura/rainbow_logging_handler</a></p> <ul> <li><p>Supports Windows</p></li> <li><p>Supports Django</p></li> <li><p>Customizable colors</p></li> </ul> <p>As this is distributed as a Python egg, it is very easy to install for any Python application.</p>
6
2013-12-20T08:08:40Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
23,964,880
<p><strong>Update</strong>: Because this is an itch that I've been meaning to scratch for so long, I went ahead and wrote a library for lazy people like me who just want simple ways to do things: <a href="https://github.com/ManufacturaInd/zenlog">zenlog</a></p> <p>Colorlog is excellent for this. It's <a href="https://pypi.python.org/pypi/colorlog/2.2.0">available on PyPI</a> (and thus installable through <code>pip install colorlog</code>) and is <a href="https://github.com/borntyping/python-colorlog">actively maintained</a>. </p> <p>Here's a quick copy-and-pasteable snippet to set up logging and print decent-looking log messages:</p> <pre><code>import logging LOG_LEVEL = logging.DEBUG LOGFORMAT = " %(log_color)s%(levelname)-8s%(reset)s | %(log_color)s%(message)s%(reset)s" from colorlog import ColoredFormatter logging.root.setLevel(LOG_LEVEL) formatter = ColoredFormatter(LOGFORMAT) stream = logging.StreamHandler() stream.setLevel(LOG_LEVEL) stream.setFormatter(formatter) log = logging.getLogger('pythonConfig') log.setLevel(LOG_LEVEL) log.addHandler(stream) log.debug("A quirky message only developers care about") log.info("Curious users might want to know this") log.warn("Something is wrong and any user should be informed") log.error("Serious stuff, this is red for a reason") log.critical("OH NO everything is on fire") </code></pre> <p>Output:</p> <p><img src="http://manufacturaindependente.com/dump/colorlogs.png" alt="Colorlog output"></p>
16
2014-05-30T23:39:51Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
26,183,545
<p>Here's my solution:</p> <pre><code>class ColouredFormatter(logging.Formatter): RESET = '\x1B[0m' RED = '\x1B[31m' YELLOW = '\x1B[33m' BRGREEN = '\x1B[01;32m' # grey in solarized for terminals def format(self, record, colour=False): message = super().format(record) if not colour: return message level_no = record.levelno if level_no &gt;= logging.CRITICAL: colour = self.RED elif level_no &gt;= logging.ERROR: colour = self.RED elif level_no &gt;= logging.WARNING: colour = self.YELLOW elif level_no &gt;= logging.INFO: colour = self.RESET elif level_no &gt;= logging.DEBUG: colour = self.BRGREEN else: colour = self.RESET message = colour + message + self.RESET return message class ColouredHandler(logging.StreamHandler): def __init__(self, stream=sys.stdout): super().__init__(stream) def format(self, record, colour=False): if not isinstance(self.formatter, ColouredFormatter): self.formatter = ColouredFormatter() return self.formatter.format(record, colour) def emit(self, record): stream = self.stream try: msg = self.format(record, stream.isatty()) stream.write(msg) stream.write(self.terminator) self.flush() except Exception: self.handleError(record) h = ColouredHandler() h.formatter = ColouredFormatter('{asctime} {levelname:8} {message}', '%Y-%m-%d %H:%M:%S', '{') logging.basicConfig(level=logging.DEBUG, handlers=[h]) </code></pre>
2
2014-10-03T17:10:01Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
28,266,098
<p>Use <a href="https://github.com/ilovecode1/pyfancy" rel="nofollow">pyfancy</a>.</p> <p>Example:</p> <pre><code>print(pyfancy.RED + "Hello Red!" + pyfancy.END) </code></pre>
0
2015-02-01T18:16:55Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
29,948,976
<p>While the other solutions seem fine they have some issues. Some do colour the whole lines which some times is not wanted and some omit any configuration you might have all together. The solution below doesn't affect anything but the message itself.</p> <p><strong>Code</strong></p> <pre><code>class ColoredFormatter(logging.Formatter): def format(self, record): if record.levelno == logging.WARNING: record.msg = '\033[93m%s\033[0m' % record.msg elif record.levelno == logging.ERROR: record.msg = '\033[91m%s\033[0m' % record.msg return logging.Formatter.format(self, record) </code></pre> <p><strong>Example</strong></p> <pre><code>logger = logging.getLogger('mylogger') handler = logging.StreamHandler() log_format = '[%(asctime)s]:%(levelname)-7s:%(message)s' time_format = '%H:%M:%S' formatter = ColoredFormatter(log_format, datefmt=time_format) handler.setFormatter(formatter) logger.addHandler(handler) logger.warn('this should be yellow') logger.error('this should be red') </code></pre> <p><strong>Output</strong></p> <pre><code>[17:01:36]:WARNING:this should be yellow [17:01:37]:ERROR :this should be red </code></pre> <p>As you see, everything else still gets outputted and remain in their initial color. If you want to change anything else than the message you can simply pass the color codes to <code>log_format</code> in the example.</p>
0
2015-04-29T16:03:16Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
30,649,849
<p>I have two submissions to add, one of which colorizes just the message (ColoredFormatter), and one of which colorizes the entire line (ColorizingStreamHandler). These also include more ANSI color codes than previous solutions.</p> <p>Some content has been sourced (with modification) from: The post above, and <a href="http://plumberjack.blogspot.com/2010/12/colorizing-logging-output-in-terminals.html" rel="nofollow">http://plumberjack.blogspot.com/2010/12/colorizing-logging-output-in-terminals.html</a>.</p> <p>Colorizes the message only:</p> <pre><code>class ColoredFormatter(logging.Formatter): """Special custom formatter for colorizing log messages!""" BLACK = '\033[0;30m' RED = '\033[0;31m' GREEN = '\033[0;32m' BROWN = '\033[0;33m' BLUE = '\033[0;34m' PURPLE = '\033[0;35m' CYAN = '\033[0;36m' GREY = '\033[0;37m' DARK_GREY = '\033[1;30m' LIGHT_RED = '\033[1;31m' LIGHT_GREEN = '\033[1;32m' YELLOW = '\033[1;33m' LIGHT_BLUE = '\033[1;34m' LIGHT_PURPLE = '\033[1;35m' LIGHT_CYAN = '\033[1;36m' WHITE = '\033[1;37m' RESET = "\033[0m" def __init__(self, *args, **kwargs): self._colors = {logging.DEBUG: self.DARK_GREY, logging.INFO: self.RESET, logging.WARNING: self.BROWN, logging.ERROR: self.RED, logging.CRITICAL: self.LIGHT_RED} super(ColoredFormatter, self).__init__(*args, **kwargs) def format(self, record): """Applies the color formats""" record.msg = self._colors[record.levelno] + record.msg + self.RESET return logging.Formatter.format(self, record) def setLevelColor(self, logging_level, escaped_ansi_code): self._colors[logging_level] = escaped_ansi_code </code></pre> <p>Colorizes the whole line:</p> <pre><code>class ColorizingStreamHandler(logging.StreamHandler): BLACK = '\033[0;30m' RED = '\033[0;31m' GREEN = '\033[0;32m' BROWN = '\033[0;33m' BLUE = '\033[0;34m' PURPLE = '\033[0;35m' CYAN = '\033[0;36m' GREY = '\033[0;37m' DARK_GREY = '\033[1;30m' LIGHT_RED = '\033[1;31m' LIGHT_GREEN = '\033[1;32m' YELLOW = '\033[1;33m' LIGHT_BLUE = '\033[1;34m' LIGHT_PURPLE = '\033[1;35m' LIGHT_CYAN = '\033[1;36m' WHITE = '\033[1;37m' RESET = "\033[0m" def __init__(self, *args, **kwargs): self._colors = {logging.DEBUG: self.DARK_GREY, logging.INFO: self.RESET, logging.WARNING: self.BROWN, logging.ERROR: self.RED, logging.CRITICAL: self.LIGHT_RED} super(ColorizingStreamHandler, self).__init__(*args, **kwargs) @property def is_tty(self): isatty = getattr(self.stream, 'isatty', None) return isatty and isatty() def emit(self, record): try: message = self.format(record) stream = self.stream if not self.is_tty: stream.write(message) else: message = self._colors[record.levelno] + message + self.RESET stream.write(message) stream.write(getattr(self, 'terminator', '\n')) self.flush() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) def setLevelColor(self, logging_level, escaped_ansi_code): self._colors[logging_level] = escaped_ansi_code </code></pre>
1
2015-06-04T16:56:59Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
31,991,678
<pre><code>import logging import sys colors = {'pink': '\033[95m', 'blue': '\033[94m', 'green': '\033[92m', 'yellow': '\033[93m', 'red': '\033[91m', 'ENDC': '\033[0m', 'bold': '\033[1m', 'underline': '\033[4m'} logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) def str_color(color, data): return colors[color] + str(data) + colors['ENDC'] params = {'param1': id1, 'param2': id2} logging.info('\nParams:' + str_color("blue", str(params)))` </code></pre>
4
2015-08-13T14:52:25Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
32,093,299
<p>A simple but very flexible tool for coloring ANY terminal text is '<a href="http://nojhan.github.io/colout/" rel="nofollow">colout</a>'.</p> <pre><code>pip install colout myprocess | colout REGEX_WITH_GROUPS color1,color2... </code></pre> <p>Where any text in the output of 'myprocess' which matches group 1 of the regex will be colored with color1, group 2 with color2, etc.</p> <p>For example:</p> <pre><code>tail -f /var/log/mylogfile | colout '^(\w+ \d+ [\d:]+)|(\w+\.py:\d+ .+\(\)): (.+)$' white,black,cyan bold,bold,normal </code></pre> <p>i.e. the first regex group (parens) matches the initial date in the logfile, the second group matches a python filename, line number and function name, and the third group matches the log message that comes after that. I also use a parallel sequence of 'bold/normals' as well as the sequence of colors. This looks like:</p> <p><a href="http://i.stack.imgur.com/99ztB.png" rel="nofollow"><img src="http://i.stack.imgur.com/99ztB.png" alt="logfile with colored formatting"></a></p> <p>Note that lines or parts of lines which don't match any of my regex are still echoed, so this isn't like 'grep --color' - nothing is filtered out of the output.</p> <p>Obviously this is flexible enough that you can use it with any process, not just tailing logfiles. I usually just whip up a new regex on the fly any time I want to colorize something. For this reason, I prefer colout to any custom logfile-coloring tool, because I only need to learn one tool, regardless of what I'm coloring: logging, test output, syntax highlighting snippets of code in the terminal, etc.</p> <p>It also avoids actually dumping ANSI codes in the logfile itself, which IMHO is a bad idea, because it will break things like grepping for patterns in the logfile unless you always remember to match the ANSI codes in your grep regex.</p>
1
2015-08-19T10:45:15Z
[ "python", "logging", "colors" ]
How can I color Python logging output?
384,076
<p>Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). </p> <p>Now, Python has the <code>logging</code> module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. </p> <p>Is there any way to make the Python <code>logging</code> module output in color? </p> <p>What I want (for instance) errors in red, debug messages in blue or yellow, and so on. </p> <p>Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original <code>logging</code> output if color isn't supported.</p> <p>Any ideas how I can get colored output with the logging module?</p>
174
2008-12-21T03:57:45Z
37,895,226
<p>You can import the <a href="https://github.com/borntyping/python-colorlog" rel="nofollow">colorlog</a> module and use its <code>ColoredFormatter</code> for colorizing log messages.</p> <h2>Example</h2> <p>Boilerplate for main module:</p> <pre><code>import logging import os try: import colorlog have_colorlog = True except ImportError: have_colorlog = False def mk_logger(): log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) format = '%(asctime)s - %(levelname)-8s - %(message)s' cformat = '%(log_color)s' + format date_format = '%Y-%m-%d %H:%M:%S' f = logging.Formatter(format, date_format) if have_colorlog == True: cf = colorlog.ColoredFormatter(cformat, date_format, log_colors = { 'DEBUG': 'reset', 'INFO': 'reset', 'WARNING' : 'bold_yellow' , 'ERROR': 'bold_red', 'CRITICAL': 'bold_red'}) else: cf = f ch = logging.StreamHandler() if os.isatty(2): ch.setFormatter(cf) else: ch.setFormatter(f) log.addHandler(ch) return log log = mk_logger() </code></pre> <p>The code only enables colors in log messages, if the colorlog module is installed and if the output actually goes to a terminal. This avoids escape sequences being written to a file when the log output is redirected.</p> <p>Also, a custom color scheme is setup that is better suited for terminals with dark background.</p> <p>Some example logging calls:</p> <pre><code>log.debug ('Hello Debug') log.info ('Hello Info') log.warn ('Hello Warn') log.error ('Hello Error') log.critical('Hello Critical') </code></pre> <p>Output:</p> <p><a href="http://i.stack.imgur.com/lWWpI.png" rel="nofollow"><img src="http://i.stack.imgur.com/lWWpI.png" alt="enter image description here"></a></p>
1
2016-06-18T09:05:22Z
[ "python", "logging", "colors" ]
Database does not update automatically with MySQL and Python
384,228
<p>I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:</p> <pre><code>import MySQLdb conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname") cursor=conn.cursor() cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100") cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100") results = cursor.fetchall() for row in results: print row[0] print "Number of rows updated: %d" % cursor.rowcount cursor.close() conn.close() </code></pre> <p>The output I get when I run this program is:</p> <blockquote> <p>4<br>Number of rows updated: 1</p> </blockquote> <p>It seems like it's working but if I query the database from the MySQL command line interface (CLI) I find that it was not updated at all. However, if from the CLI I enter <code>UPDATE compinfo SET Co_num=4 WHERE ID=100;</code> the database is updated as expected.</p> <p>What is my problem? I'm running Python 2.5.2 with MySQL 5.1.30 on a Windows box.</p>
24
2008-12-21T07:57:04Z
384,240
<p>I am not certain, but I am going to guess you are using a INNODB table, and you haven't done a commit. I believe MySQLdb enable transactions automatically.</p> <p>Call <code>conn.commit()</code> before calling <code>close</code>.</p> <p>From the FAQ: <a href="http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away" rel="nofollow">Starting with 1.2.0, MySQLdb disables autocommit by default</a></p>
42
2008-12-21T08:08:32Z
[ "python", "mysql", "mysql-python" ]
Database does not update automatically with MySQL and Python
384,228
<p>I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:</p> <pre><code>import MySQLdb conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname") cursor=conn.cursor() cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100") cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100") results = cursor.fetchall() for row in results: print row[0] print "Number of rows updated: %d" % cursor.rowcount cursor.close() conn.close() </code></pre> <p>The output I get when I run this program is:</p> <blockquote> <p>4<br>Number of rows updated: 1</p> </blockquote> <p>It seems like it's working but if I query the database from the MySQL command line interface (CLI) I find that it was not updated at all. However, if from the CLI I enter <code>UPDATE compinfo SET Co_num=4 WHERE ID=100;</code> the database is updated as expected.</p> <p>What is my problem? I'm running Python 2.5.2 with MySQL 5.1.30 on a Windows box.</p>
24
2008-12-21T07:57:04Z
384,311
<p>You need to commit changes manually or turn auto-commit on.</p> <p>The reason SELECT returns the modified (but not persisted) data is because the connection is still in the same transaction.</p>
7
2008-12-21T10:11:28Z
[ "python", "mysql", "mysql-python" ]
Database does not update automatically with MySQL and Python
384,228
<p>I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:</p> <pre><code>import MySQLdb conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname") cursor=conn.cursor() cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100") cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100") results = cursor.fetchall() for row in results: print row[0] print "Number of rows updated: %d" % cursor.rowcount cursor.close() conn.close() </code></pre> <p>The output I get when I run this program is:</p> <blockquote> <p>4<br>Number of rows updated: 1</p> </blockquote> <p>It seems like it's working but if I query the database from the MySQL command line interface (CLI) I find that it was not updated at all. However, if from the CLI I enter <code>UPDATE compinfo SET Co_num=4 WHERE ID=100;</code> the database is updated as expected.</p> <p>What is my problem? I'm running Python 2.5.2 with MySQL 5.1.30 on a Windows box.</p>
24
2008-12-21T07:57:04Z
384,338
<p>I've found that Python's connector automatically turns autocommit off, and there doesn't appear to be any way to change this behaviour. Of course you can turn it back on, but then looking at the query logs, it stupidly does two pointless queries after connect to turn autocommit off then back on.</p>
1
2008-12-21T10:53:43Z
[ "python", "mysql", "mysql-python" ]
Database does not update automatically with MySQL and Python
384,228
<p>I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:</p> <pre><code>import MySQLdb conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname") cursor=conn.cursor() cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100") cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100") results = cursor.fetchall() for row in results: print row[0] print "Number of rows updated: %d" % cursor.rowcount cursor.close() conn.close() </code></pre> <p>The output I get when I run this program is:</p> <blockquote> <p>4<br>Number of rows updated: 1</p> </blockquote> <p>It seems like it's working but if I query the database from the MySQL command line interface (CLI) I find that it was not updated at all. However, if from the CLI I enter <code>UPDATE compinfo SET Co_num=4 WHERE ID=100;</code> the database is updated as expected.</p> <p>What is my problem? I'm running Python 2.5.2 with MySQL 5.1.30 on a Windows box.</p>
24
2008-12-21T07:57:04Z
384,452
<p>MySQLdb has autocommit off by default, which may be confusing at first. Your connection exists in its own transaction and you will not be able to see the changes you make from other connections until you commit that transaction.</p> <p>You can either do <code>conn.commit()</code> after the update statement as others have pointed out, or disable this functionality altogether by setting <code>conn.autocommit(True)</code> right after you create the connection object.</p>
22
2008-12-21T13:19:16Z
[ "python", "mysql", "mysql-python" ]
Database does not update automatically with MySQL and Python
384,228
<p>I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:</p> <pre><code>import MySQLdb conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname") cursor=conn.cursor() cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100") cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100") results = cursor.fetchall() for row in results: print row[0] print "Number of rows updated: %d" % cursor.rowcount cursor.close() conn.close() </code></pre> <p>The output I get when I run this program is:</p> <blockquote> <p>4<br>Number of rows updated: 1</p> </blockquote> <p>It seems like it's working but if I query the database from the MySQL command line interface (CLI) I find that it was not updated at all. However, if from the CLI I enter <code>UPDATE compinfo SET Co_num=4 WHERE ID=100;</code> the database is updated as expected.</p> <p>What is my problem? I'm running Python 2.5.2 with MySQL 5.1.30 on a Windows box.</p>
24
2008-12-21T07:57:04Z
588,076
<p>I did a lot of work with MySQL database in Python and I used to always forget to commit the query. SO Zoredashe is correct.</p>
0
2009-02-25T21:53:16Z
[ "python", "mysql", "mysql-python" ]
Code refactoring help - how to reorganize validations
384,291
<p>We have a web application that takes user inputs or database lookups to form some operations against some physical resources. The design can be simply presented as following diagram:</p> <p>user input &lt;=> model object &lt;=> database storage</p> <p>validations are needed with request coming from user input but NOT when coming from database lookup hits (since if a record exists, those attributes must have already been validated before). I am trying to refactoring the code so that the validations happen in the object constructor instead of the old way (a separate few validation routines)</p> <p>How would you decide which way is better? (The fundamental difference of method 1 (the old way) and 2 is that validations in 1 are not mandatory and decoupled from object instantiation but 2 binds them and makes them mandatory for all requests)</p> <p>Here are two example code snippets for design 1 and 2:</p> <p>Method 1:</p> <pre><code># For processing single request. # Steps: 1. Validate all incoming data. 2. instantiate the object. ValidateAttribures(request) # raise Exceptions if failed resource = Resource(**request) </code></pre> <p>Method 2:</p> <pre><code># Have to extract out this since it does not have anything to do with # the object. # raise Exceptions if some required params missing. # steps: 1. Check whether its a batching request. 2. instantiate the object. # (validations are performed inside the constructor) CheckIfBatchRequest(request) resource = Resource(**request) # raise Exceptions when validations failed </code></pre> <p>In a batch request: Method 1:</p> <pre><code># steps: 1. validate each request and return error to the client if any found. # 2. perform the object instantiate and creation process. Exceptions are # captured. # 3. when all finished, email out any errors. for request in batch_requests: try: ValidateAttribute(request) except SomeException, e: return ErrorPage(e) errors = [] for request in batch_requests: try: CreatResource(Resource(**request), request) except CreationError, e: errors.append('failed to create with error: %s', e) email(errors) </code></pre> <p>Method 2:</p> <pre><code># steps: 1. validate batch job related data from the request. # 2. If success, create objects for each request and do the validations. # 3. If exception, return error found, otherwise, # return a list of pairs with (object, request) # 4. Do the creation process and email out any errors if encountered. CheckIfBatchRequest(request) request_objects = [] for request in batch_requests: try: resource = Resource(**request) except SomeException, e: return ErrorPage(e) request_objects.append((resource, request)) email(CreateResource(request_objects)) # the CreateResource will also need to be refactored. </code></pre> <p>Pros and Cons as I can see here are:</p> <ol> <li>Method 1 follows more close to the business logic. No redundant validations check when objects come from db lookup. The validation routines are better maintainable and read.</li> <li>Method 2 makes easy and clean for the caller. Validations are mandatory even if from db lookup. Validations are less maintainable and read.</li> </ol>
0
2008-12-21T09:40:28Z
384,791
<p>Doing validation in the constructor really isn't the "Django way". Since the data you need to validate is coming from the client-side, using <a href="http://docs.djangoproject.com/en/dev/topics/forms/" rel="nofollow">new forms</a> (probably with a <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#topics-forms-modelforms" rel="nofollow">ModelForm</a>) is the most idiomatic method to validate because it wraps all of your concerns into one API: it provides sensible validation defaults (with the ability to easily customize), plus model forms integrates the data-entry side (the html form) with the data commit (model.save()).</p> <p>However, it sounds like you have what may be a mess of a legacy project; it may be outside the scope of your time to rewrite all your form handling to use new forms, at least initially. So here are my thoughts:</p> <p>First of all, it's not "non-Djangonic" to put some validation in the model itself - after all, html form submissions may not be the only source of new data. You can override the save() method or use <a href="http://docs.djangoproject.com/en/dev/ref/models/instances/#what-happens-when-you-save" rel="nofollow">signals</a> to either clean the data on save or throw an exception on invalid data. Long term, Django will have model validation, but it's not there yet; in the interim, you should consider this a "safety" to ensure you don't commit invalid data to your DB. In other words, you still need to validate field by field before committing so you know what error to display to your users on invalid input.</p> <p>What I would suggest is this. Create new forms classes for each item you need to validate, even if you're not using them initially. <a href="http://www.pointy-stick.com/blog/2008/10/15/django-tip-poor-mans-model-validation/" rel="nofollow">Malcolm Tredinnick</a> outlined a technique for doing model validation using the hooks provided in the forms system. Read up on that (it's really quite simple and elegant), and hook in into your models. Once you've got the newforms classes defined and working, you'll see that it's not very difficult - and will in fact greatly simplify your code - if you rip out your existing form templates and corresponding validation, and handle your form POSTs using the forms framework. There is a bit of a learning curve, but the forms API is extremely well thought out and you'll be grateful how much cleaner it will make your code.</p>
1
2008-12-21T18:46:17Z
[ "python", "django", "optimization", "refactoring", "web-applications" ]
Code refactoring help - how to reorganize validations
384,291
<p>We have a web application that takes user inputs or database lookups to form some operations against some physical resources. The design can be simply presented as following diagram:</p> <p>user input &lt;=> model object &lt;=> database storage</p> <p>validations are needed with request coming from user input but NOT when coming from database lookup hits (since if a record exists, those attributes must have already been validated before). I am trying to refactoring the code so that the validations happen in the object constructor instead of the old way (a separate few validation routines)</p> <p>How would you decide which way is better? (The fundamental difference of method 1 (the old way) and 2 is that validations in 1 are not mandatory and decoupled from object instantiation but 2 binds them and makes them mandatory for all requests)</p> <p>Here are two example code snippets for design 1 and 2:</p> <p>Method 1:</p> <pre><code># For processing single request. # Steps: 1. Validate all incoming data. 2. instantiate the object. ValidateAttribures(request) # raise Exceptions if failed resource = Resource(**request) </code></pre> <p>Method 2:</p> <pre><code># Have to extract out this since it does not have anything to do with # the object. # raise Exceptions if some required params missing. # steps: 1. Check whether its a batching request. 2. instantiate the object. # (validations are performed inside the constructor) CheckIfBatchRequest(request) resource = Resource(**request) # raise Exceptions when validations failed </code></pre> <p>In a batch request: Method 1:</p> <pre><code># steps: 1. validate each request and return error to the client if any found. # 2. perform the object instantiate and creation process. Exceptions are # captured. # 3. when all finished, email out any errors. for request in batch_requests: try: ValidateAttribute(request) except SomeException, e: return ErrorPage(e) errors = [] for request in batch_requests: try: CreatResource(Resource(**request), request) except CreationError, e: errors.append('failed to create with error: %s', e) email(errors) </code></pre> <p>Method 2:</p> <pre><code># steps: 1. validate batch job related data from the request. # 2. If success, create objects for each request and do the validations. # 3. If exception, return error found, otherwise, # return a list of pairs with (object, request) # 4. Do the creation process and email out any errors if encountered. CheckIfBatchRequest(request) request_objects = [] for request in batch_requests: try: resource = Resource(**request) except SomeException, e: return ErrorPage(e) request_objects.append((resource, request)) email(CreateResource(request_objects)) # the CreateResource will also need to be refactored. </code></pre> <p>Pros and Cons as I can see here are:</p> <ol> <li>Method 1 follows more close to the business logic. No redundant validations check when objects come from db lookup. The validation routines are better maintainable and read.</li> <li>Method 2 makes easy and clean for the caller. Validations are mandatory even if from db lookup. Validations are less maintainable and read.</li> </ol>
0
2008-12-21T09:40:28Z
384,904
<p>Thanks Daniel for your reply. Especially for the newforms API, I will definitely spend time digging into it and see if I can adopt it for the better long-term benefits. But just for the sake of getting my work done for this iteration (meet my deadline before EOY), I'd probably still have to stick with the current legacy structure, after all, either way will get me to what I want, just that I want to make it sane and clean as possible as I can without breaking too much.</p> <p>So sounds like doing validations in model isn't a too bad idea, but in another sense, my old way of doing validations in views against the request seems also close to the concept of encapsulating them inside the newforms API (data validation is decoupled from model creation). Do you think it is ok to just keep my old design? It make more sense to me to touch this with the newforms API instead of juggling them right now...</p> <p>(Well I got this refactoring suggestion from my code reviewer but I am really not so sure that my old way violates any mvc patterns or too complicated to maintain. I think my way makes more senses but my reviewer thought binding validation and model creation together makes more sense...)</p>
0
2008-12-21T20:28:35Z
[ "python", "django", "optimization", "refactoring", "web-applications" ]
How do you manage your Django applications?
384,333
<p>I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.</p> <p>Let's take a kind of SO as an example. Which applications would you use? I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes. How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?</p> <p>I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...</p>
7
2008-12-21T10:48:19Z
384,377
<p>I'll tell you how I am approaching such question: I usually sit with a sheet of paper and draw the boxes (functionalities) and arrows (interdependencies between functionalities). I am sure there are methodologies or other things that could help you, but my approach usually works for me (YMMV, of course).</p> <p>Knowing what a site is supposed to be is basic, though. ;)</p>
0
2008-12-21T12:07:27Z
[ "python", "django", "project", "structure" ]
How do you manage your Django applications?
384,333
<p>I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.</p> <p>Let's take a kind of SO as an example. Which applications would you use? I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes. How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?</p> <p>I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...</p>
7
2008-12-21T10:48:19Z
384,427
<p>You should try and separate the project in as much applications as possible. For most projects an application will not contain more than 5 models. For example a project like SO would have separate applications for UsersProfiles, Questions, Tags (there's a ready one in django for this), etc. If there was a system with static pages that'd be a separate application too (there are ready ones for this purpose). You should also try and make your applications as generic as possible, so you may reuse them in other projects. There's a good <a href="http://www.youtube.com/watch?v=A-S0tqpPga4&amp;feature=PlayList&amp;p=D415FAF806EC47A1&amp;index=14">presentation</a> on reusable apps.</p>
5
2008-12-21T12:56:59Z
[ "python", "django", "project", "structure" ]
How do you manage your Django applications?
384,333
<p>I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.</p> <p>Let's take a kind of SO as an example. Which applications would you use? I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes. How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?</p> <p>I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...</p>
7
2008-12-21T10:48:19Z
384,494
<p>Just like any set of dependencies... try to find the most useful stand-alone aspects of the project and make those stand-alone apps. Other Django Apps will have higher level functionality, and reuse the parts of the lowest level apps that you have set up.</p> <p>In my project, I have a calendar app with its own Event object in its models. I also have a carpool database set up, and for the departure time and the duration I use the calendar's Event object right in my RideShare tables. The carpooling database is calendar-aware, and gets all the nice .ics export and calendar views from the calendar app for 'free.'</p> <p>There are some tricks to getting the Apps reusable, like naming the templates directory: project/app2/templates/app2/index.html. This lets you refer to app2/index.html from any other app, and get the right template. I picked that one up looking at the built-in reusable apps in Django itself. Pinax is a bit of a monster size-wise but it also demonstrates a nice reusable App structure.</p> <p>If in doubt, forget about reusable apps for now. Put all your messages and polls in one app and get through one rev. You'll discover during the process what steps feel unnecessary, and could be broken out as something stand-alone in the future.</p>
3
2008-12-21T14:03:39Z
[ "python", "django", "project", "structure" ]
How do you manage your Django applications?
384,333
<p>I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.</p> <p>Let's take a kind of SO as an example. Which applications would you use? I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes. How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?</p> <p>I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...</p>
7
2008-12-21T10:48:19Z
384,497
<p>There aren't hard-and-fast rules, but I would say it's better to err on the side of more specialized applications. Ideally an application should handle just one functional concern: i.e. "tagging" or "commenting" or "auth/auth" or "posts." This type of design will also help you reuse available open source applications instead of reinventing the wheel (i.e. Django comes with <a href="http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth">auth</a> and <a href="http://docs.djangoproject.com/en/dev/ref/contrib/comments/#ref-contrib-comments-index">comments</a> apps, <a href="http://code.google.com/p/django-tagging/">django-tagging</a> or <a href="http://code.google.com/p/django-taggable/">django-taggable</a> can almost certainly do what you need, etc). </p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1">Generic foreign keys</a> can help you decouple applications such as tagging or commenting that might be applied to models from several other applications.</p>
6
2008-12-21T14:08:05Z
[ "python", "django", "project", "structure" ]
How do you manage your Django applications?
384,333
<p>I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications.</p> <p>Let's take a kind of SO as an example. Which applications would you use? I'd say there should be the applications "users" and "questions". But what if there was a topic system with static articles, too. Maybe they also could receive votes. How to build the apps structure then? One app for "questions", "votes" and "topics" or just one app "content"?</p> <p>I have no idea what to do. Maybe it's because I know not very much about Django yet, but I'm interested either...</p>
7
2008-12-21T10:48:19Z
388,021
<p>A good question to ask yourself when deciding whether or not to write an app is "could I use this in another project?". If you think you could, then consider what it would take to make the application as independent as possible; How can you reduce the dependancies so that the app doesn't rely on anything specific to a particular project.</p> <p>Some of the ways you can do this are:</p> <ul> <li>Giving each app its own urls.py</li> <li>Allowing model types to be passed in as parameters rather than explicitly declaring what models are used in your views. Generic views use this principle.</li> <li>Make your templates easily overridden by having some sort of template_name parameter passed in your urls.py</li> <li>Make sure you can do reverse url lookups with your objects and views. This means naming your views in the urls.py and creating get_absolute_url methods on your models.</li> <li>In some cases like Tagging, GenericForeignKeys can be used to associate a model in your app to any other model, regardless of whether it has ForeignKeys "looking back" at it.</li> </ul>
3
2008-12-23T02:34:09Z
[ "python", "django", "project", "structure" ]
Using Python Web GET data
384,336
<p>I'm trying to pass information to a python page via the url. I have the following link text:</p> <pre><code>"&lt;a href='complete?id=%s'&gt;" % (str(r[0])) </code></pre> <p>on the complete page, I have this:</p> <pre><code>import cgi def complete(): form = cgi.FieldStorage() db = MySQLdb.connect(user="", passwd="", db="todo") c = db.cursor() c.execute("delete from tasks where id =" + str(form["id"])) return "&lt;html&gt;&lt;center&gt;Task completed! Click &lt;a href='/chris'&gt;here&lt;/a&gt; to go back!&lt;/center&gt;&lt;/html&gt;" </code></pre> <p>The problem is that when i go to the complete page, i get a key error on "id". Does anyone know how to fix this?</p> <p><em>EDIT</em> when i run cgi.test() it gives me nothing</p> <p>I think something is wrong with the way i'm using the url because its not getting passed through.</p> <p>its basically localhost/chris/complete?id=1</p> <p>/chris/ is a folder and complete is a function within index.py</p> <p>Am i formatting the url the wrong way?</p>
0
2008-12-21T10:53:09Z
384,355
<p>The error means that <code>form["id"]</code> failed to find the key <code>"id"</code> in <code>cgi.FieldStorage()</code>.</p> <p>To test what keys are in the called URL, use <a href="http://docs.python.org/library/cgi.html#cgi.test" rel="nofollow">cgi.test()</a>:</p> <blockquote> <p>cgi.test()</p> <p>Robust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form.</p> </blockquote> <p>EDIT: a basic test script (using the python cgi module with Linux path) is only 3 lines. Make sure you know how to run it on your system, then call it from a browser to check arguments are seen on the CGI side. You may also want to add <a href="http://docs.python.org/library/cgitb.html#module-cgitb" rel="nofollow">traceback formatting</a> with <code> import cgitb; cgitb.enable()</code>.</p> <pre><code>#!/usr/bin/python import cgi cgi.test() </code></pre>
1
2008-12-21T11:26:32Z
[ "python", "form-data" ]
Using Python Web GET data
384,336
<p>I'm trying to pass information to a python page via the url. I have the following link text:</p> <pre><code>"&lt;a href='complete?id=%s'&gt;" % (str(r[0])) </code></pre> <p>on the complete page, I have this:</p> <pre><code>import cgi def complete(): form = cgi.FieldStorage() db = MySQLdb.connect(user="", passwd="", db="todo") c = db.cursor() c.execute("delete from tasks where id =" + str(form["id"])) return "&lt;html&gt;&lt;center&gt;Task completed! Click &lt;a href='/chris'&gt;here&lt;/a&gt; to go back!&lt;/center&gt;&lt;/html&gt;" </code></pre> <p>The problem is that when i go to the complete page, i get a key error on "id". Does anyone know how to fix this?</p> <p><em>EDIT</em> when i run cgi.test() it gives me nothing</p> <p>I think something is wrong with the way i'm using the url because its not getting passed through.</p> <p>its basically localhost/chris/complete?id=1</p> <p>/chris/ is a folder and complete is a function within index.py</p> <p>Am i formatting the url the wrong way?</p>
0
2008-12-21T10:53:09Z
384,359
<p>First off, you should make dictionary lookups via</p> <pre><code>possibly_none = my_dict.get( "key_name" ) </code></pre> <p>Because this assigns None to the variable, if the key is not in the dict. You can then use the </p> <pre><code>if key is not None: do_stuff </code></pre> <p>idiom (yes, I'm a fan of null checks and defensive programming in general...). The python documentation suggests something along these lines as well.</p> <p>Without digging into the code too much, I think you should reference </p> <pre><code>form.get( 'id' ).value </code></pre> <p>in order to extract the data you seem to be asking for.</p>
0
2008-12-21T11:32:46Z
[ "python", "form-data" ]
Using Python Web GET data
384,336
<p>I'm trying to pass information to a python page via the url. I have the following link text:</p> <pre><code>"&lt;a href='complete?id=%s'&gt;" % (str(r[0])) </code></pre> <p>on the complete page, I have this:</p> <pre><code>import cgi def complete(): form = cgi.FieldStorage() db = MySQLdb.connect(user="", passwd="", db="todo") c = db.cursor() c.execute("delete from tasks where id =" + str(form["id"])) return "&lt;html&gt;&lt;center&gt;Task completed! Click &lt;a href='/chris'&gt;here&lt;/a&gt; to go back!&lt;/center&gt;&lt;/html&gt;" </code></pre> <p>The problem is that when i go to the complete page, i get a key error on "id". Does anyone know how to fix this?</p> <p><em>EDIT</em> when i run cgi.test() it gives me nothing</p> <p>I think something is wrong with the way i'm using the url because its not getting passed through.</p> <p>its basically localhost/chris/complete?id=1</p> <p>/chris/ is a folder and complete is a function within index.py</p> <p>Am i formatting the url the wrong way?</p>
0
2008-12-21T10:53:09Z
390,735
<p>Have you tried printing out the value of form to make sure you're getting what you think you're getting? You do have a little problem with your code though... you should be doing form["id"].value to get the value of the item from FieldStorage. Another alternative is to just do it yourself, like so:</p> <pre><code>import os import cgi query_string = os.environ.get("QUERY_STRING", "") form = cgi.parse_qs(query_string) </code></pre> <p>This should result in something like this:</p> <pre><code>{'id': ['123']} </code></pre>
1
2008-12-24T04:24:29Z
[ "python", "form-data" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
384,540
<p>As for future plans of MySQLdb, you might want to ask the author (Andy Dustman).<br> His blog is here: <a href="http://mysql-python.blogspot.com/" rel="nofollow">http://mysql-python.blogspot.com/</a></p>
1
2008-12-21T14:54:44Z
[ "python", "mysql", "python-3.x" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
385,225
<p>You're probably better off using Python 2.x at the moment. It's going to be a while before all Python packages are ported to 3.x, and I expect writing a library or application with 3.x at the moment would be quite frustrating.</p>
0
2008-12-22T00:02:24Z
[ "python", "mysql", "python-3.x" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
1,448,215
<p>not sure if you're still looking, but you could try this: <a href="http://sourceforge.net/projects/mypysql/" rel="nofollow">http://sourceforge.net/projects/mypysql/</a></p>
1
2009-09-19T09:16:10Z
[ "python", "mysql", "python-3.x" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
3,611,517
<p>I was looking for it too, but also found nothing, so I ported MySQL-python-1.2.3 to py3k you can read it here <a href="http://sourceforge.net/p/mysql-python/discussion/70460/thread/61e3a3c9/" rel="nofollow">http://sourceforge.net/p/mysql-python/discussion/70460/thread/61e3a3c9/</a></p>
7
2010-08-31T17:19:17Z
[ "python", "mysql", "python-3.x" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
5,288,582
<p>It appears the MySQLdb is pretty much a dead project. However, <a href="https://github.com/PyMySQL/PyMySQL/">PyMySQL</a> is a dbapi compliant, pure-python implementation of a mysql client, and it has python 3 support.</p> <p>EDIT: There's also <a href="https://launchpad.net/myconnpy">MySQL Connector/Python</a>. Same idea.</p>
29
2011-03-13T09:42:27Z
[ "python", "mysql", "python-3.x" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
6,160,255
<p>You can download the mysql-connector-python module compatible with Python3: </p> <blockquote> <p><a href="http://rpm.pbone.net/index.php3/stat/4/idpl/15667200/dir/rawhide/com/mysql-connector-python3-0.3.2-2.fc16.noarch.rpm.html" rel="nofollow">http://rpm.pbone.net/index.php3/stat/4/idpl/15667200/dir/rawhide/com/mysql-connector-python3-0.3.2-2.fc16.noarch.rpm.html</a></p> </blockquote> <p>Get the "source RPM", unzip it and use it (e.g. put it in your PYTHONPATH, and look at the examples).</p>
1
2011-05-28T07:18:35Z
[ "python", "mysql", "python-3.x" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
12,905,382
<p>There is an official Python 2/3 library, downloadable from MySQL website. Oracle released version 1.0.7 to public on 29 September 2012.</p> <p>It's pure Python and works with MySQL 4.1+</p> <p>See more details here: <a href="http://dev.mysql.com/doc/connector-python/en/connector-python.html" rel="nofollow">http://dev.mysql.com/doc/connector-python/en/connector-python.html</a></p> <p>I'm currently using it with MySQL 5.5 and Python 3.2 with no problems thus far :)</p>
0
2012-10-15T23:22:43Z
[ "python", "mysql", "python-3.x" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
17,156,299
<p>Here is a working repository for Python 3: <a href="https://github.com/davispuh/MySQL-for-Python-3" rel="nofollow">https://github.com/davispuh/MySQL-for-Python-3</a></p>
2
2013-06-17T20:30:52Z
[ "python", "mysql", "python-3.x" ]
MySQL-db lib for Python 3.x?
384,471
<p>So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing.</p>
29
2008-12-21T13:37:38Z
39,008,521
<p>There are currently a few options for using Python 3 with mysql:</p> <p><a href="https://pypi.python.org/pypi/mysql-connector-python" rel="nofollow">https://pypi.python.org/pypi/mysql-connector-python</a></p> <ul> <li>Officially supported by Oracle</li> <li>Pure python</li> <li>A little slow</li> <li>Not compatible with MySQLdb</li> </ul> <p><a href="https://pypi.python.org/pypi/pymysql" rel="nofollow">https://pypi.python.org/pypi/pymysql</a></p> <ul> <li>Pure python</li> <li>Faster than mysql-connector</li> <li>Almost completely compatible with <code>MySQLdb</code>, after calling <code>pymysql.install_as_MySQLdb()</code></li> </ul> <p><a href="https://pypi.python.org/pypi/cymysql" rel="nofollow">https://pypi.python.org/pypi/cymysql</a></p> <ul> <li>fork of pymysql with optional C speedups</li> </ul> <p><a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">https://pypi.python.org/pypi/mysqlclient</a></p> <ul> <li>Django's recommended library.</li> <li>Friendly fork of the original MySQLdb, hopes to merge back some day</li> <li>The fastest implementation, as it is C based.</li> <li>The most compatible with MySQLdb, as it is a fork</li> <li>Debian and Ubuntu use it to provide both <code>python-mysqldb</code> and<code>python3-mysqldb</code> packages.</li> </ul> <p>benchmarks here: <a href="https://github.com/methane/mysql-driver-benchmarks" rel="nofollow">https://github.com/methane/mysql-driver-benchmarks</a></p>
0
2016-08-18T01:17:10Z
[ "python", "mysql", "python-3.x" ]
PIL and numpy
384,759
<p>Alright, I'm toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL's PixelAccess object would allow. I've figured out how to place the pixel information in a useful 3D numpy array by way of:</p> <pre><code>pic = Image.open("foo.jpg") pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3) </code></pre> <p>But I can't seem to figure out how to load it back into the PIL object after I've done all my awesome transforms. I'm aware of the <strong>putdata()</strong> method, but can't quite seem to get it to behave.</p> <p>Any thoughts?</p>
67
2008-12-21T18:21:32Z
384,926
<p>You're not saying how exactly <code>putdata()</code> is not behaving. I'm assuming you're doing </p> <pre><code>&gt;&gt;&gt; pic.putdata(a) Traceback (most recent call last): File "...blablabla.../PIL/Image.py", line 1185, in putdata self.im.putdata(data, scale, offset) SystemError: new style getargs format but argument is not a tuple </code></pre> <p>This is because <code>putdata</code> expects a sequence of tuples and you're giving it a numpy array. This</p> <pre><code>&gt;&gt;&gt; data = list(tuple(pixel) for pixel in pix) &gt;&gt;&gt; pic.putdata(data) </code></pre> <p>will work but it is very slow. </p> <p>As of PIL 1.1.6, the <a href="http://effbot.org/zone/pil-changes-116.htm">"proper" way to convert between images and numpy arrays</a> is simply</p> <pre><code>&gt;&gt;&gt; pix = numpy.array(pic) </code></pre> <p>although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).</p> <p>Then, after you make your changes to the array, you should be able to do either <code>pic.putdata(pix)</code> or create a new image with <code>Image.fromarray(pix)</code>. </p>
81
2008-12-21T20:46:21Z
[ "python", "image", "numpy", "python-imaging-library" ]
PIL and numpy
384,759
<p>Alright, I'm toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL's PixelAccess object would allow. I've figured out how to place the pixel information in a useful 3D numpy array by way of:</p> <pre><code>pic = Image.open("foo.jpg") pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3) </code></pre> <p>But I can't seem to figure out how to load it back into the PIL object after I've done all my awesome transforms. I'm aware of the <strong>putdata()</strong> method, but can't quite seem to get it to behave.</p> <p>Any thoughts?</p>
67
2008-12-21T18:21:32Z
1,095,878
<p>Open I as an array:</p> <pre><code>&gt;&gt;&gt; I = numpy.asarray(PIL.Image.open('test.jpg')) </code></pre> <p>Do some stuff to I, then, convert it back to an image:</p> <pre><code>&gt;&gt;&gt; im = PIL.Image.fromarray(numpy.uint8(I)) </code></pre> <p><a href="http://barnesc.blogspot.com/2007/09/filter-numpy-images-with-fft-python.html">Filter numpy images with FFT, Python</a></p> <p>If you want to do it explicitly for some reason, there are pil2array() and array2pil() functions using getdata() on <a href="http://bradmontgomery.blogspot.com/2007/12/computing-correlation-coefficients-in.html">this page</a> in correlation.zip.</p>
66
2009-07-08T02:33:17Z
[ "python", "image", "numpy", "python-imaging-library" ]
PIL and numpy
384,759
<p>Alright, I'm toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL's PixelAccess object would allow. I've figured out how to place the pixel information in a useful 3D numpy array by way of:</p> <pre><code>pic = Image.open("foo.jpg") pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3) </code></pre> <p>But I can't seem to figure out how to load it back into the PIL object after I've done all my awesome transforms. I'm aware of the <strong>putdata()</strong> method, but can't quite seem to get it to behave.</p> <p>Any thoughts?</p>
67
2008-12-21T18:21:32Z
37,675,266
<p>You need to convert your image to a numpy array this way:</p> <pre><code>import numpy import PIL img = PIL.Image.open("foo.jpg").convert("L") imgarr = numpy.array(img) </code></pre>
1
2016-06-07T09:18:59Z
[ "python", "image", "numpy", "python-imaging-library" ]
Checking 2-dimensional array (like eight queens puzzle)
384,874
<p>My problem is very similar to eight queens puzzle.</p> <p>I've got 2-dimensional array (N x N) that for example, looks like this:</p> <pre><code>0,0,0,0,1 y 0,0,0,0,0 | 0,0,0,0,0 V 0,0,0,1,0 0,0,0,0,0 x-&gt; </code></pre> <p>I'm checking horizontally, vertically and diagonally for occurrences of 1</p> <pre><code>\,0,|,0,/ 0,\,|,/,0 -,-,1,-,- 0,/,|,\,0 /,0,|,0,\ </code></pre> <p>I'm thinking about storing only the (x,y) postions of "1"'s in a list </p> <pre><code>[[4,0],[3,3]] </code></pre> <p>and solving it mathematically, check every position of "1" with another (x1,y1)&lt;->(x2,y2),</p> <p>if <code>x1 == x2</code> or <code>y1 == y2</code> <code>we have a collision!</code> if not check:</p> <pre><code>x2 == x1 + z; y2 == y1 + z; x2 == x1 - z; y2 == y1 - z; </code></pre> <p>(???)</p> <p>where z is +/- that <code>( x1+z in 0..N ) and ( y1+z in 0..N ) .......</code></p> <p><strong><em>My problem is checking for diagonal collision, is there a better way to do it???</em></strong></p>
5
2008-12-21T20:00:55Z
384,887
<p>One possible solution:</p> <pre><code>def collision(x1, y1, x2, y2): return x1 == x2 or y1 == y2 or abs(x1-x2) == abs(y1-y2) </code></pre> <p>i.e. there is a collision if the two points are on the same horizontal row, same vertical row or same diagonal (vertical distance == horizontal distance).</p>
19
2008-12-21T20:10:32Z
[ "python", "arrays", "puzzle" ]
Checking 2-dimensional array (like eight queens puzzle)
384,874
<p>My problem is very similar to eight queens puzzle.</p> <p>I've got 2-dimensional array (N x N) that for example, looks like this:</p> <pre><code>0,0,0,0,1 y 0,0,0,0,0 | 0,0,0,0,0 V 0,0,0,1,0 0,0,0,0,0 x-&gt; </code></pre> <p>I'm checking horizontally, vertically and diagonally for occurrences of 1</p> <pre><code>\,0,|,0,/ 0,\,|,/,0 -,-,1,-,- 0,/,|,\,0 /,0,|,0,\ </code></pre> <p>I'm thinking about storing only the (x,y) postions of "1"'s in a list </p> <pre><code>[[4,0],[3,3]] </code></pre> <p>and solving it mathematically, check every position of "1" with another (x1,y1)&lt;->(x2,y2),</p> <p>if <code>x1 == x2</code> or <code>y1 == y2</code> <code>we have a collision!</code> if not check:</p> <pre><code>x2 == x1 + z; y2 == y1 + z; x2 == x1 - z; y2 == y1 - z; </code></pre> <p>(???)</p> <p>where z is +/- that <code>( x1+z in 0..N ) and ( y1+z in 0..N ) .......</code></p> <p><strong><em>My problem is checking for diagonal collision, is there a better way to do it???</em></strong></p>
5
2008-12-21T20:00:55Z
384,908
<p>I think it would be much faster if you didn't solve it mathematically but first check all rows for multiple occurrences of 1s, then all columns and finally all diagonal lines.</p> <p>Here is some code to test the diagonal lines in a simple way. (It's JavaScript, sorry!)</p> <pre><code>var count = 0; for (column = -n; column &lt; n; column++) { for (row = 0; row &lt; n; row++) { // conditions for which there are no valid coordinates. if (column + row &gt; 6) { break; } if (column &lt; 0) { continue; if (field[row][column] == 1) { count++; if (count == 2) break; // collision } } } </code></pre> <p>This method would have a complexity of <code>O(n^2)</code>, whereas the one you suggested has a complexity of <code>O(n^2 + k^2)</code> (k being the number of 1s) If <code>k</code> is always small this should be no problem.</p>
0
2008-12-21T20:31:52Z
[ "python", "arrays", "puzzle" ]
Checking 2-dimensional array (like eight queens puzzle)
384,874
<p>My problem is very similar to eight queens puzzle.</p> <p>I've got 2-dimensional array (N x N) that for example, looks like this:</p> <pre><code>0,0,0,0,1 y 0,0,0,0,0 | 0,0,0,0,0 V 0,0,0,1,0 0,0,0,0,0 x-&gt; </code></pre> <p>I'm checking horizontally, vertically and diagonally for occurrences of 1</p> <pre><code>\,0,|,0,/ 0,\,|,/,0 -,-,1,-,- 0,/,|,\,0 /,0,|,0,\ </code></pre> <p>I'm thinking about storing only the (x,y) postions of "1"'s in a list </p> <pre><code>[[4,0],[3,3]] </code></pre> <p>and solving it mathematically, check every position of "1" with another (x1,y1)&lt;->(x2,y2),</p> <p>if <code>x1 == x2</code> or <code>y1 == y2</code> <code>we have a collision!</code> if not check:</p> <pre><code>x2 == x1 + z; y2 == y1 + z; x2 == x1 - z; y2 == y1 - z; </code></pre> <p>(???)</p> <p>where z is +/- that <code>( x1+z in 0..N ) and ( y1+z in 0..N ) .......</code></p> <p><strong><em>My problem is checking for diagonal collision, is there a better way to do it???</em></strong></p>
5
2008-12-21T20:00:55Z
384,953
<p>Your description sounds like an instance of an exact cover problem, which can be solved using an algorithm Knuth calls <a href="http://en.wikipedia.org/wiki/Algorithm_X" rel="nofollow">Algorithm X</a>. I have implemented a <a href="http://hewgill.com/sudoku/" rel="nofollow">Sudoku solver in Javascript</a> using this technique. You can probably find implementations in Python, too.</p>
2
2008-12-21T21:06:14Z
[ "python", "arrays", "puzzle" ]
Checking 2-dimensional array (like eight queens puzzle)
384,874
<p>My problem is very similar to eight queens puzzle.</p> <p>I've got 2-dimensional array (N x N) that for example, looks like this:</p> <pre><code>0,0,0,0,1 y 0,0,0,0,0 | 0,0,0,0,0 V 0,0,0,1,0 0,0,0,0,0 x-&gt; </code></pre> <p>I'm checking horizontally, vertically and diagonally for occurrences of 1</p> <pre><code>\,0,|,0,/ 0,\,|,/,0 -,-,1,-,- 0,/,|,\,0 /,0,|,0,\ </code></pre> <p>I'm thinking about storing only the (x,y) postions of "1"'s in a list </p> <pre><code>[[4,0],[3,3]] </code></pre> <p>and solving it mathematically, check every position of "1" with another (x1,y1)&lt;->(x2,y2),</p> <p>if <code>x1 == x2</code> or <code>y1 == y2</code> <code>we have a collision!</code> if not check:</p> <pre><code>x2 == x1 + z; y2 == y1 + z; x2 == x1 - z; y2 == y1 - z; </code></pre> <p>(???)</p> <p>where z is +/- that <code>( x1+z in 0..N ) and ( y1+z in 0..N ) .......</code></p> <p><strong><em>My problem is checking for diagonal collision, is there a better way to do it???</em></strong></p>
5
2008-12-21T20:00:55Z
385,515
<p>Assuming you actually do have an N-dimensional space, which you probably don't, you can use this collision detector:</p> <pre><code>def collision(t1, t2): return len(set([abs(a-b) for a,b in zip(t1, t2)] + [0])) &lt;= 2 </code></pre> <p>Pass it a pair of tuples with whatever arity you like, and it will return true if the two points lie on any N-dimensional diagonal.</p>
0
2008-12-22T04:01:08Z
[ "python", "arrays", "puzzle" ]
How do I send a custom header with urllib2 in a HTTP Request?
385,262
<p>I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that?</p>
42
2008-12-22T00:39:53Z
385,411
<p>Not quite. Creating a <code>Request</code> object does not actually send the request, and Request objects have no <code>Read()</code> method. (Also: <code>read()</code> is lowercase.) All you need to do is pass the <code>Request</code> as the first argument to <code>urlopen()</code> and that will give you your response.</p> <pre><code>import urllib2 request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"}) contents = urllib2.urlopen(request).read() </code></pre>
91
2008-12-22T02:29:01Z
[ "python", "header", "urllib2" ]
How do I send a custom header with urllib2 in a HTTP Request?
385,262
<p>I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that?</p>
42
2008-12-22T00:39:53Z
32,026,467
<pre><code>import urllib2 request_headers = { "Accept-Language": "en-US,en;q=0.5", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Referer": "http://thewebsite.com", "Connection": "keep-alive" } request = urllib2.Request("http://thewebsite.com", headers=request_headers) contents = urllib2.urlopen(request).read() print contents </code></pre>
8
2015-08-15T15:51:41Z
[ "python", "header", "urllib2" ]
How do I send a custom header with urllib2 in a HTTP Request?
385,262
<p>I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that?</p>
42
2008-12-22T00:39:53Z
37,414,162
<p>Beside the other solutions mentioned already, you could use <code>add_header</code> method.</p> <p>So the example provided py @pantsgolem will be: </p> <pre><code>import urllib2 request = urllib2.Request("http://www.google.com") request.add_header('Accept','text/html') ##Show the header having the key 'Accept' request.get_header('Accept') response = urllib2.urlopen(request) response.read() </code></pre>
1
2016-05-24T12:50:28Z
[ "python", "header", "urllib2" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
385,360
<p>Using Python's <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">string formatting</a> (use <a href="http://docs.python.org/library/stdtypes.html#str.format" rel="nofollow">str.format()</a> with Python 3.0):</p> <pre><code>from decimal import Decimal def format_number(i): return '%g' % (Decimal(str(i))) </code></pre>
0
2008-12-22T01:53:00Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
385,363
<pre><code>def floatstrip(x): if x == int(x): return str(int(x)) else: return str(x) </code></pre> <p>Be aware, though, that Python represents 0.1 as an imprecise float, on my system 0.10000000000000001 .</p>
5
2008-12-22T01:56:28Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
385,366
<pre><code>from decimal import Decimal '%g' % (Decimal(str(x))) </code></pre>
3
2008-12-22T01:59:23Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
385,392
<p><code>rstrip</code> doesn't do what you want it to do, it strips <em>any</em> of the characters you give it and not a suffix:</p> <pre><code>&gt;&gt;&gt; '30000.0'.rstrip('.0') '3' </code></pre> <p>Actually, just <code>'%g' % i</code> will do what you want. EDIT: as Robert pointed out in his comment this won't work for large numbers since it uses the default precision of %g which is 6 significant digits.</p> <p>Since <code>str(i)</code> uses 12 significant digits, I think this will work:</p> <pre><code>&gt;&gt;&gt; numbers = [ 0.0, 1.0, 0.1, 123456.7 ] &gt;&gt;&gt; ['%.12g' % n for n in numbers] ['1', '0', '0.1', '123456.7'] </code></pre>
14
2008-12-22T02:18:07Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
385,395
<pre><code>&gt;&gt;&gt; '%g' % 0 '0' &gt;&gt;&gt; '%g' % 0.0 '0' &gt;&gt;&gt; '%g' % 0.1 '0.1' &gt;&gt;&gt; '%g' % 1.0 '1' </code></pre>
0
2008-12-22T02:21:37Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
385,398
<p>Us the 0 prcision and add a period if you want one. EG "%.0f."</p> <pre><code>&gt;&gt;&gt; print "%.0f."%1.0 1. &gt;&gt;&gt; </code></pre>
-1
2008-12-22T02:23:35Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
385,406
<pre><code>(str(i)[-2:] == '.0' and str(i)[:-2] or str(i) for i in ...) </code></pre>
5
2008-12-22T02:25:58Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
385,487
<p>If you only care about 1 decimal place of precision (as in your examples), you can just do:</p> <pre><code>("%.1f" % i).replace(".0", "") </code></pre> <p>This will convert the number to a string with 1 decimal place and then remove it if it is a zero:</p> <pre><code>&gt;&gt;&gt; ("%.1f" % 0).replace(".0", "") '0' &gt;&gt;&gt; ("%.1f" % 0.0).replace(".0", "") '0' &gt;&gt;&gt; ("%.1f" % 0.1).replace(".0", "") '0.1' &gt;&gt;&gt; ("%.1f" % 1.0).replace(".0", "") '1' &gt;&gt;&gt; ("%.1f" % 3000.0).replace(".0", "") '3000' &gt;&gt;&gt; ("%.1f" % 1.0000001).replace(".0", "") '1' </code></pre>
2
2008-12-22T03:37:18Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
399,925
<pre><code>&gt;&gt;&gt; x = '1.0' &gt;&gt;&gt; int(float(x)) 1 &gt;&gt;&gt; x = 1 &gt;&gt;&gt; int(float(x)) 1 </code></pre>
3
2008-12-30T10:16:19Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
1,616,837
<pre><code>str(x)[-2:] == '.0' and int(x) or x </code></pre>
1
2009-10-24T03:23:32Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
12,080,042
<p>See <a href="http://www.python.org/dev/peps/pep-3101/">PEP 3101</a>:</p> <pre> 'g' - General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to 'e' exponent notation. </pre> <p>Old style:</p> <pre><code>&gt;&gt;&gt; "%g" % float(10) '10' </code></pre> <p>New style (recommended):</p> <pre><code>&gt;&gt;&gt; '{0:g}'.format(float(21)) '21' </code></pre>
28
2012-08-22T19:23:16Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
16,953,234
<p>To print a <code>float</code> that has an integer value as an <code>int</code>:</p> <pre><code>format = "%d" if f.is_integer() else "%s" print(format % f) </code></pre> <p><a href="http://ideone.com/eaUpLj" rel="nofollow">Example</a></p> <pre><code> 0.0 -&gt; 0 0.1 -&gt; 0.1 10.0 -&gt; 10 12345678.9 -&gt; 12345678.9 123456789.0 -&gt; 123456789 12345678912345.0 -&gt; 12345678912345 12345678912345.6 -&gt; 1.23456789123e+13 1.000000000001 -&gt; 1.0 </code></pre>
2
2013-06-06T03:24:24Z
[ "python" ]
dropping trailing '.0' from floats
385,325
<p>I'm looking for a way to convert numbers to string format, dropping any redundant '.0' </p> <p>The input data is a mix of floats and strings. Desired output:</p> <p>0 --> '0'</p> <p>0.0 --> '0'</p> <p>0.1 --> '0.1'</p> <p>1.0 --> '1'</p> <p>I've come up with the following generator expression, but I wonder if there's a faster way:</p> <pre><code>(str(i).rstrip('.0') if i else '0' for i in lst) </code></pre> <p>The truth check is there to prevent 0 from becoming an empty string.</p> <p>EDIT: The more or less acceptable solution I have for now is this:</p> <pre><code>('%d'%i if i == int(i) else '%s'%i for i in lst) </code></pre> <p>It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.</p>
22
2008-12-22T01:33:33Z
18,383,452
<p>So much ugliness out there…</p> <p>My personal favorite is to convert <code>float</code>s that don't require to be a <code>float</code> (= when they actually are integers) to <code>int</code>, thus removing the, now useless, trailing <code>0</code></p> <p><code>(int(i) if i.is_integer() else i for i in lst)</code></p> <p>Then you can print them normally.</p>
3
2013-08-22T14:34:28Z
[ "python" ]
Python 3 porting workflow?
385,394
<p>I have a small project I want to try porting to Python 3 - how do I go about this?</p> <p>I have made made the code run without warnings using <code>python2.6 -3</code> (mostly removing <code>.has_key()</code> calls), but I am not sure of the best way to use the 2to3 tool.</p> <blockquote> <p>Use the 2to3 tool to convert this source code to 3.0 syntax. Do not manually edit the output!</p> </blockquote> <p>Running <code>2to3 something.py</code> outputs a diff, which isn't useful on it's own. Using the <code>--write</code> flag overwrites something.py and creates a backup.. It seems like I have to do..</p> <pre><code>2to3 something.py python3.0 something.py mv something.py.bak something.py vim something.py # repeat </code></pre> <p>..which is a bit round-a-bout - ideally I could do something like..</p> <pre><code>mv something.py py2.6_something.py # once 2to3 py2.6_something.py --write-file something.py vim py2.6_something.py # repeat </code></pre>
5
2008-12-22T02:18:22Z
385,397
<p>Aha, you can pipe the 2to3 output to the <code>patch</code> command, which can write the modified file to a new file:</p> <pre><code>mv something.py py2.6_something.py 2to3 py2.6_something.py | patch -o something.py </code></pre>
5
2008-12-22T02:22:23Z
[ "python", "python-3.x", "porting" ]
Python 3 porting workflow?
385,394
<p>I have a small project I want to try porting to Python 3 - how do I go about this?</p> <p>I have made made the code run without warnings using <code>python2.6 -3</code> (mostly removing <code>.has_key()</code> calls), but I am not sure of the best way to use the 2to3 tool.</p> <blockquote> <p>Use the 2to3 tool to convert this source code to 3.0 syntax. Do not manually edit the output!</p> </blockquote> <p>Running <code>2to3 something.py</code> outputs a diff, which isn't useful on it's own. Using the <code>--write</code> flag overwrites something.py and creates a backup.. It seems like I have to do..</p> <pre><code>2to3 something.py python3.0 something.py mv something.py.bak something.py vim something.py # repeat </code></pre> <p>..which is a bit round-a-bout - ideally I could do something like..</p> <pre><code>mv something.py py2.6_something.py # once 2to3 py2.6_something.py --write-file something.py vim py2.6_something.py # repeat </code></pre>
5
2008-12-22T02:18:22Z
386,897
<p>2.x should be your codebase of active development, so 2to3 should really be run in a branch or temporary directory. I'm not sure why you'd want to have the 2.x and 3.x versions lying around in the same directory. distutils has a build_2to3 script that will run 2to3 on a 3.0 install.</p>
0
2008-12-22T17:55:55Z
[ "python", "python-3.x", "porting" ]
Prototype based object orientation. The good, the bad and the ugly?
385,403
<p>I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.</p> <p>The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.</p> <p>In summary, what is the good, the bad and the ugly parts of such approach?</p>
10
2008-12-22T02:25:02Z
385,417
<p>Okay, first of all, the prototype model isn't all that different in reality; Smalltalk uses a similar sort of scheme; the class is an object with the classes methods.</p> <p>Looked at from the class POV, a class is really the equivalence class of objects with the same data, and all the same methods; you can look at adding a method to a prototype as creating a new subclass.</p> <p>The implementation is simple, but makes it very difficult to do effective typechecking.</p>
0
2008-12-22T02:31:15Z
[ "javascript", "python", "language-agnostic", "lua", "oop" ]
Prototype based object orientation. The good, the bad and the ugly?
385,403
<p>I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.</p> <p>The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.</p> <p>In summary, what is the good, the bad and the ugly parts of such approach?</p>
10
2008-12-22T02:25:02Z
385,467
<p>To conserve the bandwidth here is the link to <a href="http://stackoverflow.com/questions/355848/what-is-the-best-way-to-emulate-classes-in-javascript-with-or-without-a-framewo#356343">my answer on "How can I emulate “classes” in JavaScript? (with or without a third-party library)"</a>. It contains further references as well as examples.</p> <p>The short answer: the heart of JavaScript's prototypal <a href="http://en.wikipedia.org/wiki/Object-orientation" rel="nofollow">OO</a> is delegation. In this style of OOP different objects of the same "class" can delegate the handling of methods and properties to the same prototype (usually some third object):</p> <pre><code>var foo = { property: 42, inc: function(){ ++this.counter; }, dec: function(){ --this.counter; } }; // Note: foo does not define `counter`. </code></pre> <p>Let's create a constructor for objects with foo as a prototype. Effectively, everything unhandled will be delegated to foo.</p> <pre><code>var Bar = function(){ this.counter = 0; }; Bar.prototype = foo; // This is how we set up the delegation. // Some people refer to Bar (a constructor function) as "class". var bar = new Bar(); console.log(bar.counter); // 0 --- Comes from bar itself console.log(bar.property); // 42 --- Not defined in bar, comes from foo bar.inc(); // Not defined in bar =&gt; delegated to foo bar.inc(); bar.dec(); // Not defined in bar =&gt; delegated to foo // Note: foo.inc() and foo.dec() are called but this === bar // that is why bar is modified, not foo. console.log(bar.counter); // 1 --- Comes from bar itself </code></pre> <p>Let's define <code>inc()</code> directly on bar:</p> <pre><code>bar.inc = function(){ this.counter = 42; }; bar.inc(); // Defined in bar =&gt; calling it directly. // foo.inc() is not even called. console.log(bar.counter); // 42 --- Comes from bar </code></pre> <p>Setting up the single inheritance chain:</p> <pre><code>var Baz = function(){ this.counter = 99; }; Baz.protype = new Bar(); var baz = new Baz(); console.log(baz.counter); // 99 baz.inc(); console.log(baz.counter); // 100 console.log(baz instanceof Baz); // true console.log(baz instanceof Bar); // true console.log(baz instanceof Object); // true </code></pre> <p>Neat, eh?</p>
7
2008-12-22T03:15:34Z
[ "javascript", "python", "language-agnostic", "lua", "oop" ]
Prototype based object orientation. The good, the bad and the ugly?
385,403
<p>I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.</p> <p>The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.</p> <p>In summary, what is the good, the bad and the ugly parts of such approach?</p>
10
2008-12-22T02:25:02Z
385,571
<p>Prototype-based OO lends itself poorly to static type checking, which some might consider a bad or ugly thing. Prototype-based OO <em>does</em> have a standard way of creating new objects, you <strong>clone and modify existing objects</strong>. You can also build factories, etc.</p> <p>I think what people like most (the "good") is that prototype-based OO is very <strong>lightweight and flexible</strong>, offering a <strong>very high power-to-weight ratio</strong>.</p> <p>For <strong>tips on how to use prototype-based OO</strong>, a great place to start is the original Self paper on <a href="http://research.sun.com/self/papers/self-power.html">The Power of Simplicity</a>.</p>
13
2008-12-22T04:34:49Z
[ "javascript", "python", "language-agnostic", "lua", "oop" ]
Prototype based object orientation. The good, the bad and the ugly?
385,403
<p>I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.</p> <p>The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.</p> <p>In summary, what is the good, the bad and the ugly parts of such approach?</p>
10
2008-12-22T02:25:02Z
408,410
<p>Before worrying about how to emulate class-based inheritance in JavaScript, have a quick read of <em><a href="http://javascript.crockford.com/prototypal.html" rel="nofollow">Prototypal Inheritance in JavaScript</a></em>.</p>
2
2009-01-03T00:50:41Z
[ "javascript", "python", "language-agnostic", "lua", "oop" ]
Prototype based object orientation. The good, the bad and the ugly?
385,403
<p>I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.</p> <p>The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.</p> <p>In summary, what is the good, the bad and the ugly parts of such approach?</p>
10
2008-12-22T02:25:02Z
3,958,261
<p>Classical inheritance is inherently flawed in terms of flexibility, in that we are saying "this object is of this type and no other". Some languages introduce multiple inheritance to alleviate this, but multiple inheritance has its own pitfalls, and so the benefits of pure composition over inheritance (which, in a statically typed language, is a runtime rather than a compile time mechanism) become clear. </p> <p>Taking the concept of composition to this "pure" level, we can eliminate classical inheritance altogether along with static typing. By composing objects at runtime and using them as blueprints (the prototypal approach), we need never concern ourselves with boxing objects too tightly through inheritance, nor burden ourselves with the issues inherent in multiple inheritance approaches.</p> <p>So prototypal means much more flexible development of modules.</p> <p>Of course, it's quite another thing to say it's EASY to develop without static typing. IMO, it is not.</p>
1
2010-10-18T10:31:26Z
[ "javascript", "python", "language-agnostic", "lua", "oop" ]
Extract float/double value
385,558
<p>How do I extract a double value from a string using regex.</p> <pre><code>import re pattr = re.compile(???) x = pattr.match("4.5") </code></pre>
17
2008-12-22T04:28:01Z
385,597
<p>A regexp from the <a href="http://perldoc.perl.org/perlretut.html#Building-a-regexp" rel="nofollow"><code>perldoc perlretut</code></a>:</p> <pre><code>import re re_float = re.compile("""(?x) ^ [+-]?\ * # first, match an optional sign *and space* ( # then match integers or f.p. mantissas: \d+ # start out with a ... ( \.\d* # mantissa of the form a.b or a. )? # ? takes care of integers of the form a |\.\d+ # mantissa of the form .b ) ([eE][+-]?\d+)? # finally, optionally match an exponent $""") m = re_float.match("4.5") print m.group(0) # -&gt; 4.5 </code></pre> <p>To extract numbers from a bigger string:</p> <pre><code>s = """4.5 abc -4.5 abc - 4.5 abc + .1e10 abc . abc 1.01e-2 abc 1.01e-.2 abc 123 abc .123""" print re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s) # -&gt; ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2', # ' 1.01', '-.2', ' 123', ' .123'] </code></pre>
38
2008-12-22T04:56:22Z
[ "python", "regex" ]
Extract float/double value
385,558
<p>How do I extract a double value from a string using regex.</p> <pre><code>import re pattr = re.compile(???) x = pattr.match("4.5") </code></pre>
17
2008-12-22T04:28:01Z
386,177
<p>Here's the easy way. Don't use regex's for built-in types.</p> <pre><code>try: x = float( someString ) except ValueError, e: # someString was NOT floating-point, what now? </code></pre>
16
2008-12-22T12:41:31Z
[ "python", "regex" ]
Extract float/double value
385,558
<p>How do I extract a double value from a string using regex.</p> <pre><code>import re pattr = re.compile(???) x = pattr.match("4.5") </code></pre>
17
2008-12-22T04:28:01Z
6,278,082
<p>a float as regular expression in brute force. there are smaller differences to the version of J.F. Sebastian:</p> <pre><code>import re if __name__ == '__main__': x = str(1.000e-123) reFloat = r'(^[+-]?\d+(?:\.\d+)?(?:[eE][+-]\d+)?$)' print re.match(reFloat,x) &gt;&gt;&gt; &lt;_sre.SRE_Match object at 0x0054D3E0&gt; </code></pre>
1
2011-06-08T11:33:59Z
[ "python", "regex" ]
Extract float/double value
385,558
<p>How do I extract a double value from a string using regex.</p> <pre><code>import re pattr = re.compile(???) x = pattr.match("4.5") </code></pre>
17
2008-12-22T04:28:01Z
28,832,504
<p>For parse int and float (point separator) values:</p> <pre><code>re.findall( r'\d+\.*\d*', 'some 12 12.3 0 any text 0.8' ) </code></pre> <p>result:</p> <pre><code>['12', '12.3', '0', '0.8'] </code></pre>
3
2015-03-03T13:01:36Z
[ "python", "regex" ]
Typecasting in Python
385,572
<p>I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.</p> <p>How can I do this?</p>
12
2008-12-22T04:35:18Z
385,580
<p>Python only has a single <code>int</code> type. To convert a string to an <code>int</code>, use <code>int()</code> like this:</p> <pre><code>&gt;&gt;&gt; str = '123' &gt;&gt;&gt; num = int(str) &gt;&gt;&gt; num 123 </code></pre> <p><strong>Edit:</strong> Also to convert to float, use <code>float()</code> in the exact same way.</p>
3
2008-12-22T04:42:51Z
[ "python", "string", "int", "bit", "casting" ]
Typecasting in Python
385,572
<p>I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.</p> <p>How can I do this?</p>
12
2008-12-22T04:35:18Z
385,583
<p>You can convert a string to a 32-bit signed integer with the <code>int</code> function:</p> <pre><code>str = "1234" i = int(str) // i is a 32-bit integer </code></pre> <p>If the string does not represent an integer, you'll get a <code>ValueError</code> exception. Note, however, that if the string does represent an integer, but that integer does not fit into a 32-bit signed int, then you'll actually get an object of type <code>long</code> instead.</p> <p>You can then convert it to other widths and signednesses with some simple math:</p> <pre><code>s8 = (i + 2**7) % 2**8 - 2**7 // convert to signed 8-bit u8 = i % 2**8 // convert to unsigned 8-bit s16 = (i + 2**15) % 2**16 - 2**15 // convert to signed 16-bit u16 = i % 2**16 // convert to unsigned 16-bit s32 = (i + 2**31) % 2**32 - 2**31 // convert to signed 32-bit u32 = i % 2**32 // convert to unsigned 32-bit s64 = (i + 2**63) % 2**64 - 2**63 // convert to signed 64-bit u64 = i % 2**64 // convert to unsigned 64-bit </code></pre> <p>You can convert strings to floating point with the <code>float</code> function:</p> <pre><code>f = float("3.14159") </code></pre> <p>Python floats are what other languages refer to as <code>double</code>, i.e. they are 64-bits. There are no 32-bit floats in Python.</p>
26
2008-12-22T04:44:48Z
[ "python", "string", "int", "bit", "casting" ]
Typecasting in Python
385,572
<p>I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.</p> <p>How can I do this?</p>
12
2008-12-22T04:35:18Z
386,116
<p>The following types -- for the most part -- don't exist in Python in the first place. In Python, strings are converted to ints, longs or floats, because that's all there is.</p> <p>You're asking for conversions that aren't relevant to Python in the first place. Here's the list of types you asked for and their Python equivalent.</p> <ul> <li>unsigned and signed int 8 bits, <strong>int</strong></li> <li>unsigned and signed int 16 bits, <strong>int</strong></li> <li>unsigned and signed int 32 bits, unsigned: <strong>long</strong>, signed <strong>int</strong></li> <li><p>unsigned and signed int 64 bits, <strong>long</strong></p></li> <li><p>double, <strong>float</strong></p></li> <li>float, <strong>float</strong></li> <li>string, <strong>this is what you had to begin with</strong></li> </ul> <p>I don't know what the following are, so I don't know a Python equivalent.</p> <ul> <li>unsigned and signed 8 bit, </li> <li>unsigned and signed 16 bit, </li> <li>unsigned and signed 32 bit,</li> <li>unsigned and signed 64 bit.</li> </ul> <p>You already have all the conversions that matter: <code>int()</code>, <code>long()</code> and <code>float()</code>.</p>
3
2008-12-22T12:15:11Z
[ "python", "string", "int", "bit", "casting" ]
Typecasting in Python
385,572
<p>I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.</p> <p>How can I do this?</p>
12
2008-12-22T04:35:18Z
386,651
<p>I don't think this can necessarily be answered well without more information. As others have said, there are only int and long for integers in python -- the language doesn't adhere to the bit-width and signedness archetypes of lower-level programming languages.</p> <p>If you're operating completely within python, then you're probably asking the wrong question. There's likely a better way to do what you need.</p> <p>If you are interoperating with, for instance, C code, or over the network, then there <strong>are</strong> ways to do this, and it looks like the answer to your previous posting covered that avenue pretty handily.</p>
0
2008-12-22T16:22:34Z
[ "python", "string", "int", "bit", "casting" ]
Phone numbers to links in Python
385,632
<p>I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty.</p> <pre><code>import re from string import digits PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') def numbers2links(s): result = "" last_match_index = 0 for match in PHONE_RE.finditer(s): raw_number = match.group() number = ''.join(d for d in raw_number if d in digits) call = '&lt;a href="tel:%s"&gt;%s&lt;/a&gt;' % (number, raw_number) result += s[last_match_index:match.start()] + call last_match_index = match.end() result += s[last_match_index:] return result &gt;&gt;&gt; numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.") 'Ghost Busters at &lt;a href="tel:5554232368"&gt;(555) 423-2368&lt;/a&gt;! How about this one: &lt;a href="tel:5554567890"&gt;555 456 7890&lt;/a&gt;! &lt;a href="tel:5554567893"&gt;555-456-7893&lt;/a&gt; is where its at.' </code></pre> <p>Is there anyway I could restructure the regex or the the regex method I'm using to make this cleaner?</p> <p><strong>Update</strong></p> <p>To clarify, my question is not about the correctness of my regex - I realize that it's limited. Instead I'm wondering if anyone had any comments on the method of substiting in links for the phone numbers - is there anyway I could use <code>re.replace</code> or something like that instead of the string hackery that I have?</p>
2
2008-12-22T05:44:41Z
385,647
<p>A few things that will clean up your existing regex without really changing the functionality:</p> <p>Replace {0,1} with ?, [(] with (, [)] with ). You also might as well just make your [2-9] b e a \d as well, so you can make those patterns be \d{3} and \d{4} for the last part. I doubt it will really increase the rate of false positives.</p>
0
2008-12-22T05:57:05Z
[ "python", "regex", "mobile-website", "phone-number" ]
Phone numbers to links in Python
385,632
<p>I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty.</p> <pre><code>import re from string import digits PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') def numbers2links(s): result = "" last_match_index = 0 for match in PHONE_RE.finditer(s): raw_number = match.group() number = ''.join(d for d in raw_number if d in digits) call = '&lt;a href="tel:%s"&gt;%s&lt;/a&gt;' % (number, raw_number) result += s[last_match_index:match.start()] + call last_match_index = match.end() result += s[last_match_index:] return result &gt;&gt;&gt; numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.") 'Ghost Busters at &lt;a href="tel:5554232368"&gt;(555) 423-2368&lt;/a&gt;! How about this one: &lt;a href="tel:5554567890"&gt;555 456 7890&lt;/a&gt;! &lt;a href="tel:5554567893"&gt;555-456-7893&lt;/a&gt; is where its at.' </code></pre> <p>Is there anyway I could restructure the regex or the the regex method I'm using to make this cleaner?</p> <p><strong>Update</strong></p> <p>To clarify, my question is not about the correctness of my regex - I realize that it's limited. Instead I'm wondering if anyone had any comments on the method of substiting in links for the phone numbers - is there anyway I could use <code>re.replace</code> or something like that instead of the string hackery that I have?</p>
2
2008-12-22T05:44:41Z
385,674
<p>Why not re-use the work of others - for example, from <a href="http://regexlib.com/REDetails.aspx?regexp_id=458" rel="nofollow">RegExpLib.com</a>?</p> <p>My second suggestion is to remember there are other countries besides the USA, and quite a few of them have telephones ;-) Please don't forget us during your software development.</p> <p>Also, there is a standard for the formatting of telephone numbers; the ITU's <a href="http://en.wikipedia.org/wiki/E.123" rel="nofollow">E.123</a>. My recollection of the standard was that what it describes doesn't match well with popular usage.</p> <p>Edit: I mixed up G.123 and E.123. Oops. Props <a href="http://stackoverflow.com/users/15625/bortzmeyer">Bortzmeyer</a></p>
0
2008-12-22T06:37:28Z
[ "python", "regex", "mobile-website", "phone-number" ]
Phone numbers to links in Python
385,632
<p>I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty.</p> <pre><code>import re from string import digits PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') def numbers2links(s): result = "" last_match_index = 0 for match in PHONE_RE.finditer(s): raw_number = match.group() number = ''.join(d for d in raw_number if d in digits) call = '&lt;a href="tel:%s"&gt;%s&lt;/a&gt;' % (number, raw_number) result += s[last_match_index:match.start()] + call last_match_index = match.end() result += s[last_match_index:] return result &gt;&gt;&gt; numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.") 'Ghost Busters at &lt;a href="tel:5554232368"&gt;(555) 423-2368&lt;/a&gt;! How about this one: &lt;a href="tel:5554567890"&gt;555 456 7890&lt;/a&gt;! &lt;a href="tel:5554567893"&gt;555-456-7893&lt;/a&gt; is where its at.' </code></pre> <p>Is there anyway I could restructure the regex or the the regex method I'm using to make this cleaner?</p> <p><strong>Update</strong></p> <p>To clarify, my question is not about the correctness of my regex - I realize that it's limited. Instead I'm wondering if anyone had any comments on the method of substiting in links for the phone numbers - is there anyway I could use <code>re.replace</code> or something like that instead of the string hackery that I have?</p>
2
2008-12-22T05:44:41Z
385,813
<p>Your regexp only parses a specific format, which is not the international standard. If you limit yourself to one country, it may work.</p> <p>Otherwise, the international standard is <a href="http://www.itu.int/rec/T-REC-E.123/en" rel="nofollow">ITU E.123</a> : "Notation for national and international telephone numbers, e-mail addresses and Web addresses"</p>
1
2008-12-22T08:55:16Z
[ "python", "regex", "mobile-website", "phone-number" ]
Phone numbers to links in Python
385,632
<p>I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty.</p> <pre><code>import re from string import digits PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') def numbers2links(s): result = "" last_match_index = 0 for match in PHONE_RE.finditer(s): raw_number = match.group() number = ''.join(d for d in raw_number if d in digits) call = '&lt;a href="tel:%s"&gt;%s&lt;/a&gt;' % (number, raw_number) result += s[last_match_index:match.start()] + call last_match_index = match.end() result += s[last_match_index:] return result &gt;&gt;&gt; numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.") 'Ghost Busters at &lt;a href="tel:5554232368"&gt;(555) 423-2368&lt;/a&gt;! How about this one: &lt;a href="tel:5554567890"&gt;555 456 7890&lt;/a&gt;! &lt;a href="tel:5554567893"&gt;555-456-7893&lt;/a&gt; is where its at.' </code></pre> <p>Is there anyway I could restructure the regex or the the regex method I'm using to make this cleaner?</p> <p><strong>Update</strong></p> <p>To clarify, my question is not about the correctness of my regex - I realize that it's limited. Instead I'm wondering if anyone had any comments on the method of substiting in links for the phone numbers - is there anyway I could use <code>re.replace</code> or something like that instead of the string hackery that I have?</p>
2
2008-12-22T05:44:41Z
385,869
<p>First off, reliably capturing phone numbers with a single regular expression is notoriously difficult with a strong tendency to being impossible. Not every country has a definition of a "phone number" that is as narrow as it is in the U.S. Even in the U.S., things are more complicated than they seem (from the <a href="http://en.wikipedia.org/wiki/North_American_Numbering_Plan" rel="nofollow">Wikipedia article on the North American Numbering Plan</a>):</p> <ul> <li>A) Country code: optional prefix ("1" or "+1" or "001") <ul> <li><code>((00|\+)?1)?</code></li> </ul></li> <li>B) Numbering Plan Area code (NPA): cannot begin with 1, digit 2 cannot be 9 <ul> <li><code>[2-9][0-8][0-9]</code></li> </ul></li> <li>C) Exchange code (NXX): cannot begin with 1, cannot end with "11", optional parentheses <ul> <li><code>\(?[2-9](00|[2-9]{2})\)?</code></li> </ul></li> <li>D) Station Code: four digits, cannot all be 0 (I suppose) <ul> <li><code>(?!0{4})\d{4}</code></li> </ul></li> <li>E) an optional extension may follow <ul> <li><code>([x#-]\d+)?</code></li> </ul></li> <li>S) parts of the number are separated by spaces, dashes, dots (or not) <ul> <li><code>[. -]?</code></li> </ul></li> </ul> <p>So, the basic regex for the U.S. would be:</p> <pre><code>((00|\+)?1[. -]?)?\(?[2-9][0-8][0-9]\)?[. -]?[2-9](00|[2-9]{2})[. -]?(?!0{4})\d{4}([. -]?[x#-]\d+)? | A |S | | B | S | C | S | D | S | E | </code></pre> <p>And that's just for the relatively trivial numbering plan of the U.S., and even there it certainly is not covering all subtleties. If you want to make it reliable you have to develop a similar beast for all expected input languages.</p>
1
2008-12-22T09:41:01Z
[ "python", "regex", "mobile-website", "phone-number" ]
Phone numbers to links in Python
385,632
<p>I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty.</p> <pre><code>import re from string import digits PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') def numbers2links(s): result = "" last_match_index = 0 for match in PHONE_RE.finditer(s): raw_number = match.group() number = ''.join(d for d in raw_number if d in digits) call = '&lt;a href="tel:%s"&gt;%s&lt;/a&gt;' % (number, raw_number) result += s[last_match_index:match.start()] + call last_match_index = match.end() result += s[last_match_index:] return result &gt;&gt;&gt; numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.") 'Ghost Busters at &lt;a href="tel:5554232368"&gt;(555) 423-2368&lt;/a&gt;! How about this one: &lt;a href="tel:5554567890"&gt;555 456 7890&lt;/a&gt;! &lt;a href="tel:5554567893"&gt;555-456-7893&lt;/a&gt; is where its at.' </code></pre> <p>Is there anyway I could restructure the regex or the the regex method I'm using to make this cleaner?</p> <p><strong>Update</strong></p> <p>To clarify, my question is not about the correctness of my regex - I realize that it's limited. Instead I'm wondering if anyone had any comments on the method of substiting in links for the phone numbers - is there anyway I could use <code>re.replace</code> or something like that instead of the string hackery that I have?</p>
2
2008-12-22T05:44:41Z
387,101
<p>Nice first take :) I think this version is a bit more readable (and probably a teensy bit faster). The key thing to note here is the use of <a href="http://docs.python.org/library/re.html#module-contents" rel="nofollow">re.sub</a>. Keeps us away from the nasty match indexes...</p> <pre><code>import re PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') NON_NUMERIC = re.compile('\D') def numbers2links(s): def makelink(mo): raw_number = mo.group() number = NON_NUMERIC.sub("", raw_number) return '&lt;a href="tel:%s"&gt;%s&lt;/a&gt;' % (number, raw_number) return PHONE_RE.sub(makelink, s) print numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.") </code></pre> <p>A note: In my practice, I've not noticed much of a speedup pre-compiling simple regular expressions like the two I'm using, even if you're using them thousands of times. The re module may have some sort of internal caching - didn't bother to read the source and check.</p> <p>Also, I replaced your method of checking each character to see if it's in <code>string.digits</code> with another <code>re.sub()</code> because I think my version is more readable, not because I'm certain it performs better (although it might).</p>
5
2008-12-22T19:26:03Z
[ "python", "regex", "mobile-website", "phone-number" ]
need help - bit-field conversion
386,151
<p>I want to convert strings to bit-fields.Also,convert them to binary and then use. Need help with this..help me ..</p>
-3
2008-12-22T12:29:23Z
386,161
<p>they're all binary already... Which language are we talking about?</p> <p>I'd start by looking at the string as an array of characters and working with each character individually.</p>
0
2008-12-22T12:33:30Z
[ "python", "string", "bits", "bit-fields" ]
need help - bit-field conversion
386,151
<p>I want to convert strings to bit-fields.Also,convert them to binary and then use. Need help with this..help me ..</p>
-3
2008-12-22T12:29:23Z
386,188
<p>I think the <a href="http://www.python.org/doc/2.5.2/lib/module-struct.html" rel="nofollow">struct module</a> is what you're after.</p> <p>Example of usage: </p> <pre><code>&gt;&gt;&gt; from struct import * &gt;&gt;&gt; pack('hhl', 1, 2, 3) '\x00\x01\x00\x02\x00\x00\x00\x03' &gt;&gt;&gt; unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) &gt;&gt;&gt; calcsize('hhl') 8 </code></pre>
2
2008-12-22T12:49:44Z
[ "python", "string", "bits", "bit-fields" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
386,674
<p>Yes, I have. I wrote a row-count program for a binary (length-prefixed rather than delimited) bcp output file once and ended up having to redo it in C because the python one was too slow. This program was quite small (it only took a couple of days to re-write it in C), so I didn't bother to try and build a hybrid application (python glue with central routines written in C) but this would also have been a viable route.</p> <p>A larger application with performance critical bits can be written in a combination of C and a higher level language. You can write the performance-critical parts in C with an interface to Python for the rest of the system. <a href="http://www.swig.org/">SWIG</a>, <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/">Pyrex</a> or <a href="http://www.boost.org/doc/libs/1_37_0/libs/python/doc/index.html">Boost.Python</a> (if you're using C++) all provide good mechanisms to do the plumbing for your Python interface. The <a href="http://docs.python.org/c-api/">C API for python</a> is more complex than that for <a href="http://www.tcl.tk">Tcl</a> or <a href="http://www.lua.org/pil/24.html">Lua</a>, but isn't infeasible to build by hand. For an example of a hand-built Python/C API, check out <a href="http://cx-oracle.sourceforge.net/">cx_Oracle</a>.</p> <p>This approach has been used on quite a number of successful applications going back as far as the 1970s (that I am aware of). <a href="http://en.wikipedia.org/wiki/SeaMonkey">Mozilla</a> was substantially written in Javascript around a core engine written in C. <a href="http://en.wikipedia.org/wiki/IntelliCAD_Technology_Consortium">Several</a> <a href="http://www.fourmilab.ch/autofile/www/chapter2_35.html">CAD packages</a>, <a href="http://en.wikipedia.org/wiki/Interleaf">Interleaf</a> (a technical document publishing system) and of course <a href="http://www.gnu.org/software/emacs/">EMACS</a> are substantially written in LISP with a central C, assembly language or other core. Quite a few commercial and open-source applications (e.g. <a href="http://en.wikipedia.org/wiki/Chandler_(PIM)">Chandler</a> or <a href="http://www.sungard.com/FrontArena">Sungard Front Arena</a>) use embedded Python interpreters and implement substantial parts of the application in Python.</p> <p><strong>EDIT:</strong> In rsponse to Dutch Masters' comment, keeping someone with C or C++ programming skills on the team for a Python project gives you the option of writing some of the application for speed. The areas where you can expect to get a significant performance gain are where the application does something highly iterative over a large data structure or large volume of data. In the case of the row-counter above it had to inhale a series of files totalling several gigabytes and go through a process where it read a varying length prefix and used that to determine the length of the data field. Most of the fields were short (just a few bytes long). This was somewhat bit-twiddly and very low level and iterative, which made it a natural fit for C.</p> <p>Many of the python libraries such as <a href="http://numpy.scipy.org/">numpy</a>, <a href="http://effbot.org/zone/celementtree.htm">cElementTree</a> or <a href="http://effbot.org/librarybook/cstringio.htm">cStringIO</a> make use of an optimised C core with a python API that facilitates working with data in aggregate. For example, numpy has matrix data structures and operations written in C which do all the hard work and a Python API that provides services at the aggregate level.</p>
33
2008-12-22T16:28:08Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
386,689
<p>I used to prototype lots of things in python for doing things like log processing. When they didn't run fast enough, I'd rewrite them in ocaml.</p> <p>In many cases, the python was fine and I was happy with it. In some cases, as it started approaching 23 hours to do a days' logs, I'd get to rewriting. :)</p> <p>I would like to point out that even in those cases, I may have been better off just profiling the python code and finding a happier python implementation.</p>
2
2008-12-22T16:34:44Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
386,702
<p>This is a much more difficult question to answer than people are willing to admit. </p> <p>For example, it may be that I am able to write a program that performs better in Python than it does in C. The fallacious conclusion from that statement is "Python is therefore faster than C". In reality, it may be because I have much more recent experience in Python and its best practices and standard libraries. </p> <p>In fact no one can really answer your question unless they are certain that they can create an optimal solution in both languages, which is unlikely. In other words "My C solution was faster than my Python solution" is not the same as "C is faster than Python"</p> <p>I'm willing to bet that Guido Van Rossum could have written Python solutions for adam and Dustin's problems that performed quite well.</p> <p>My rule of thumb is that unless you are writing the sort of application that requires you to count clock cycles, you can probably achieve acceptable performance in Python.</p>
18
2008-12-22T16:40:55Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
386,706
<p>You can always write parts of your application in Python. Not every component is equally important for performance. Python integrates easily with C++ natively, or with Java via Jython, or with .NET via IronPython.</p> <p>By the way, IronPython is more efficient than the C implementation of Python on some benchmarks. </p>
2
2008-12-22T16:42:26Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
386,752
<p>I've been working for a while now, developing an application that operate on large structured data, stored in several-gigabytes-thick-database and well, Python is good enough for that. The application has GUI client with a multitude of controls (lists, trees, notebooks, virtual lists and more), and a console server. </p> <p>We had some performance issues, but those were mostly related more to poor algorithm design or database engine limitations (we use Oracle, MS-SQL, MySQL and had short romance with BerkeleyDB used for speed optimizations) than to Python itself. Once you know how to use standard libraries (written in C) properly you can make your code really quick. </p> <p>As others say - any computation intensive algorithm, code that depends on bit-stuffing, some memory constrained computation - can be done in raw C/C++ for CPU/memory saving (or any other tricks), but the whole user interaction, logging, database handling, error handling - all that makes the application actually run, can be written in Python and it will maintain responsiveness and decent overall performance.</p>
2
2008-12-22T17:05:58Z
[ "python", "performance", "optimization", "rewrite" ]