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
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
13,641,398
<p>Beautiful soup does convert html entities. It's probably your best bet considering HTML is often buggy and filled with unicode and html encoding issues. This is the code I use to convert html to raw text:</p> <pre><code>import BeautifulSoup def getsoup(data, to_unicode=False): data = data.replace("&amp;nbsp;", " ") # Fixes for bad markup I've seen in the wild. Remove if not applicable. masssage_bad_comments = [ (re.compile('&lt;!-([^-])'), lambda match: '&lt;!--' + match.group(1)), (re.compile('&lt;!WWWAnswer T[=\w\d\s]*&gt;'), lambda match: '&lt;!--' + match.group(0) + '--&gt;'), ] myNewMassage = copy.copy(BeautifulSoup.BeautifulSoup.MARKUP_MASSAGE) myNewMassage.extend(masssage_bad_comments) return BeautifulSoup.BeautifulSoup(data, markupMassage=myNewMassage, convertEntities=BeautifulSoup.BeautifulSoup.ALL_ENTITIES if to_unicode else None) remove_html = lambda c: getsoup(c, to_unicode=True).getText(separator=u' ') if c else "" </code></pre>
3
2012-11-30T08:23:23Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
16,423,634
<p>Here is a version of xperroni's answer which is a bit more complete. It skips script and style sections and translates charrefs (e.g., &amp;#39;) and HTML entities (e.g., &amp;amp;).</p> <p>It also includes a trivial plain-text-to-html inverse converter.</p> <pre><code>""" HTML &lt;-&gt; text conversions. """ from HTMLParser import HTMLParser, HTMLParseError from htmlentitydefs import name2codepoint import re class _HTMLToText(HTMLParser): def __init__(self): HTMLParser.__init__(self) self._buf = [] self.hide_output = False def handle_starttag(self, tag, attrs): if tag in ('p', 'br') and not self.hide_output: self._buf.append('\n') elif tag in ('script', 'style'): self.hide_output = True def handle_startendtag(self, tag, attrs): if tag == 'br': self._buf.append('\n') def handle_endtag(self, tag): if tag == 'p': self._buf.append('\n') elif tag in ('script', 'style'): self.hide_output = False def handle_data(self, text): if text and not self.hide_output: self._buf.append(re.sub(r'\s+', ' ', text)) def handle_entityref(self, name): if name in name2codepoint and not self.hide_output: c = unichr(name2codepoint[name]) self._buf.append(c) def handle_charref(self, name): if not self.hide_output: n = int(name[1:], 16) if name.startswith('x') else int(name) self._buf.append(unichr(n)) def get_text(self): return re.sub(r' +', ' ', ''.join(self._buf)) def html_to_text(html): """ Given a piece of HTML, return the plain text it contains. This handles entities and char refs, but not javascript and stylesheets. """ parser = _HTMLToText() try: parser.feed(html) parser.close() except HTMLParseError: pass return parser.get_text() def text_to_html(text): """ Convert the given text to html, wrapping what looks like URLs with &lt;a&gt; tags, converting newlines to &lt;br&gt; tags and converting confusing chars into html entities. """ def f(mo): t = mo.group() if len(t) == 1: return {'&amp;':'&amp;amp;', "'":'&amp;#39;', '"':'&amp;quot;', '&lt;':'&amp;lt;', '&gt;':'&amp;gt;'}.get(t) return '&lt;a href="%s"&gt;%s&lt;/a&gt;' % (t, t) return re.sub(r'https?://[^] ()"\';]+|[&amp;\'"&lt;&gt;]', f, text) </code></pre>
10
2013-05-07T16:04:21Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
21,505,430
<p>In Python 3.x you can do it in a very easy way by importing 'imaplib' and 'email' packages. Although this is an older post but maybe my answer can help new comers on this post.</p> <pre><code>status, data = self.imap.fetch(num, '(RFC822)') email_msg = email.message_from_bytes(data[0][1]) #email.message_from_string(data[0][1]) #If message is multi part we only want the text version of the body, this walks the message and gets the body. if email_msg.is_multipart(): for part in email_msg.walk(): if part.get_content_type() == "text/plain": body = part.get_payload(decode=True) #to control automatic email-style MIME decoding (e.g., Base64, uuencode, quoted-printable) body = body.decode() elif part.get_content_type() == "text/html": continue </code></pre> <p>Now you can print body variable and it will be in plaintext format :) If it is good enough for you then it would be nice to select it as accepted answer.</p>
3
2014-02-02T00:13:03Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
24,618,186
<p>The best piece of code I found for extracting text without getting javascript or not wanted things :</p> <pre><code>import urllib from bs4 import BeautifulSoup url = "http://news.bbc.co.uk/2/hi/health/2284783.stm" html = urllib.urlopen(url).read() soup = BeautifulSoup(html) # kill all script and style elements for script in soup(["script", "style"]): script.extract() # rip it out # get text text = soup.get_text() # break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) print(text) </code></pre> <p>You just have to install BeautifulSoup before :</p> <pre><code>pip install beautifulsoup4 </code></pre>
44
2014-07-07T19:18:20Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
25,195,237
<p>Another option is to run the html through a text based web browser and dump it. For example (using Lynx):</p> <pre><code>lynx -dump html_to_convert.html &gt; converted_html.txt </code></pre> <p>This can be done within a python script as follows:</p> <pre><code>import subprocess with open('converted_html.txt', 'w') as outputFile: subprocess.call(['lynx', '-dump', 'html_to_convert.html'], stdout=testFile) </code></pre> <p>It won't give you exactly just the text from the HTML file, but depending on your use case it may be preferable to the output of html2text. </p>
2
2014-08-08T02:29:50Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
33,917,274
<p>I recommend a Python Package called goose-extractor Goose will try to extract the following information:</p> <p>Main text of an article Main image of article Any Youtube/Vimeo movies embedded in article Meta Description Meta tags</p> <p>More :<a href="https://pypi.python.org/pypi/goose-extractor/" rel="nofollow">https://pypi.python.org/pypi/goose-extractor/</a></p>
3
2015-11-25T13:05:59Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
34,215,991
<p>Another non-python solution: Libre Office:</p> <pre><code>soffice --headless --invisible --convert-to txt input1.html </code></pre> <p>The reason I prefer this one over other alternatives is that every HTML paragraph gets converted into a single text line (no line breaks), which is what I was looking for. Other methods require post-processing. Lynx does produce nice output, but not exactly what I was looking for. Besides, Libre Office can be used to convert from all sorts of formats...</p>
2
2015-12-11T04:11:45Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
37,595,562
<p>in a simple way</p> <pre><code>import re html_text = open('html_file.html').read() text_filtered = re.sub(r'&lt;(.*?)&gt;', '', html_text) </code></pre> <p>this code finds all parts of the html_text started with '&lt;' and ending with '>' and replace all found by an empty string</p>
0
2016-06-02T15:04:54Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
38,816,725
<p>I am achieving it something like this. </p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; url = "http://news.bbc.co.uk/2/hi/health/2284783.stm" &gt;&gt;&gt; res = requests.get(url) &gt;&gt;&gt; text = res.text </code></pre>
-1
2016-08-07T17:27:43Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
39,226,132
<p>if you need more speed and less accuracy then you could use raw lxml.</p> <pre><code>import lxml.html as lh from lxml.html.clean import clean_html def lxml_to_text(html): doc = lh.fromstring(html) doc = clean_html(doc) return doc.text_content() </code></pre>
0
2016-08-30T11:21:42Z
[ "python", "html", "text", "html-content-extraction" ]
Extracting text from HTML file using Python
328,356
<p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p> <p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &amp;#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p> <p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p> <hr> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li> <li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
128
2008-11-30T02:28:04Z
39,899,612
<p>I know there are a lot of answers already, but the most <strong>elegent</strong> and <strong>pythonic</strong> solution I have found is described, in part, <a href="https://stackoverflow.com/questions/761824/python-how-to-convert-markdown-formatted-text-to-text">here</a>.</p> <pre><code>from bs4 import BeautifulSoup text = ''.join(BeautifulSoup(some_html_string).findAll(text=True)) </code></pre>
0
2016-10-06T15:08:54Z
[ "python", "html", "text", "html-content-extraction" ]
Monitoring a displays state in python?
328,490
<p>How can I tell when Windows is changing a monitors power state?</p>
2
2008-11-30T05:32:54Z
328,947
<p>It seems that, when Windows wants to start the screen saver or turn the monitor off, it will send a <code>WM_SYSCOMMAND</code> to the topmost window with a <code>wParam</code> of <code>SC_SCREENSAVE</code> (to start the screen saver) or a <code>wParam</code> of <code>SC_MONITORPOWER</code> and a <code>lParam</code> of 1 or 2 (to turn the monitor off). This message will then be passed to <code>DefWindowProc</code>, which will actually do the action. So, if your window happens to be the topmost one, you can intercept these events and ignore them (or do anything else you want before passing them to <code>DefWindowProc</code>).</p> <p>On Windows Vista, there seems to be a more intuitive, and more reliable, way to know the monitor power state. You call <code>RegisterPowerSettingNotification</code> to tell the system to send your window a <code>WM_POWERBROADCAST</code> message with a <code>wParam</code> of <code>PBT_POWERSETTINGCHANGE</code> and a <code>lParam</code> pointing to a <code>POWERBROADCAST_SETTING</code> structure.</p> <p>I cannot test either of them since I currently do not have any computer with Windows nearby. I hope, however, they point you in the right direction.</p> <p>References:</p> <ul> <li><a href="http://blogs.msdn.com/oldnewthing/archive/2006/06/13/629451.aspx" rel="nofollow">The Old New Thing : Fumbling around in the dark and stumbling across the wrong solution</a></li> <li><a href="http://groups.google.com/group/borland.public.delphi.nativeapi.win32/browse_thread/thread/81afbb4aff7503d4" rel="nofollow">Recursive hook ... - borland.public.delphi.nativeapi.win32 | Google Groups</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/aa373195(VS.85).aspx" rel="nofollow">Registering for Power Events (Windows)</a></li> </ul>
5
2008-11-30T15:21:13Z
[ "python", "winapi" ]
Setting monitor power state in python?
328,492
<p>How can I send a monitor into/out-of a different power state (like sleep)?</p>
0
2008-11-30T05:34:32Z
328,567
<p>After looking at this article:</p> <p><a href="http://vbnet.mvps.org/index.html?code/screen/scmonitorpower.htm" rel="nofollow">http://vbnet.mvps.org/index.html?code/screen/scmonitorpower.htm</a></p> <p>It appears you need to send a SendMessage call similar to:</p> <p>SendMessage(Me.hWnd, WM_SYSCOMMAND, SC_MONITORPOWER, ByVal MONITOR_OFF)</p> <p>Although, that is a VB version. What you're really after is the WinAPI call, I'm sure you can convert this bit to however you invoke WinAPI calls in Python. I hope this helps.</p>
1
2008-11-30T07:00:50Z
[ "python", "winapi" ]
Setting monitor power state in python?
328,492
<p>How can I send a monitor into/out-of a different power state (like sleep)?</p>
0
2008-11-30T05:34:32Z
18,998,350
<pre><code>import win32gui import win32con if argument == "on": win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, -1) if argument == "off": win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, 2) if argument == "sleep": win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, 1) </code></pre>
0
2013-09-25T07:04:24Z
[ "python", "winapi" ]
Deploying a python application with shared package
328,568
<p>I'm thinking how to arrange a deployed python application which will have a </p> <ol> <li>Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in</li> <li>A library installed to wherever the current site-packages directory is.</li> </ol> <p>Now, currently, I have the following directory structure in my sources:</p> <pre><code>foo.py foo/ __init__.py ... </code></pre> <p>which I guess is not the best way to do things. During development, everything works as expected, however when deployed, the "from foo import FooObject" code in foo.py seemingly attempts to import foo.py itself, which is not the behaviour I'm looking for.</p> <p>So the question is what is the standard practice of orchestrating situations like this? One of the things I could think of is, when installing, rename foo.py to just foo, which stops it from importing itself, but that seems rather awkward...</p> <p>Another part of the problem, I suppose, is that it's a naming challenge. Perhaps call the executable script foo-bin.py?</p>
2
2008-11-30T07:02:14Z
328,579
<p>You should call the executable just <code>foo</code>, not <code>foo.py</code>, then attempts to import foo will not use it.</p> <p>As for naming it properly: this is difficult to answer in the abstract; we would need to know what specifically it does. For example, if it configures and controls, calling it -config or ctl might be appropriate. If it is a shell API for the library, it should have the same name as the library.</p>
0
2008-11-30T07:18:10Z
[ "python", "naming", "package", "conventions", "deploying" ]
Deploying a python application with shared package
328,568
<p>I'm thinking how to arrange a deployed python application which will have a </p> <ol> <li>Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in</li> <li>A library installed to wherever the current site-packages directory is.</li> </ol> <p>Now, currently, I have the following directory structure in my sources:</p> <pre><code>foo.py foo/ __init__.py ... </code></pre> <p>which I guess is not the best way to do things. During development, everything works as expected, however when deployed, the "from foo import FooObject" code in foo.py seemingly attempts to import foo.py itself, which is not the behaviour I'm looking for.</p> <p>So the question is what is the standard practice of orchestrating situations like this? One of the things I could think of is, when installing, rename foo.py to just foo, which stops it from importing itself, but that seems rather awkward...</p> <p>Another part of the problem, I suppose, is that it's a naming challenge. Perhaps call the executable script foo-bin.py?</p>
2
2008-11-30T07:02:14Z
328,589
<p><a href="http://www.python.org/doc/2.5.2/dist/dist.html" rel="nofollow">Distutils</a> supports installing modules, packages, and scripts. If you create a distutils <code>setup.py</code> which refers to <code>foo</code> as a package and <code>foo.py</code> as a script, then <code>foo.py</code> should get installed to <code>/usr/local/bin</code> or whatever the appropriate script install path is on the target OS, and the <code>foo</code> package should get installed to the <code>site_packages</code> directory.</p>
2
2008-11-30T07:30:01Z
[ "python", "naming", "package", "conventions", "deploying" ]
Deploying a python application with shared package
328,568
<p>I'm thinking how to arrange a deployed python application which will have a </p> <ol> <li>Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in</li> <li>A library installed to wherever the current site-packages directory is.</li> </ol> <p>Now, currently, I have the following directory structure in my sources:</p> <pre><code>foo.py foo/ __init__.py ... </code></pre> <p>which I guess is not the best way to do things. During development, everything works as expected, however when deployed, the "from foo import FooObject" code in foo.py seemingly attempts to import foo.py itself, which is not the behaviour I'm looking for.</p> <p>So the question is what is the standard practice of orchestrating situations like this? One of the things I could think of is, when installing, rename foo.py to just foo, which stops it from importing itself, but that seems rather awkward...</p> <p>Another part of the problem, I suppose, is that it's a naming challenge. Perhaps call the executable script foo-bin.py?</p>
2
2008-11-30T07:02:14Z
328,826
<p>Your CLI module is one thing, the package that supports it is another thing. Don't confuse the names withe module <code>foo</code> (in a file <code>foo.py</code>) and the package <code>foo</code> (in a directory <code>foo</code> with a file <code>__init__.py</code>).</p> <p>You have two things named <code>foo</code>: a module and a package. What else do you want to name <code>foo</code>? A class? A function? A variable?</p> <p>Pick a distinctive name for the foo module or the foo package. <code>foolib</code>, for example, is a popular package name.</p>
0
2008-11-30T12:47:16Z
[ "python", "naming", "package", "conventions", "deploying" ]
Deploying a python application with shared package
328,568
<p>I'm thinking how to arrange a deployed python application which will have a </p> <ol> <li>Executable script located in /usr/bin/ which will provide a CLI to functionality implemented in</li> <li>A library installed to wherever the current site-packages directory is.</li> </ol> <p>Now, currently, I have the following directory structure in my sources:</p> <pre><code>foo.py foo/ __init__.py ... </code></pre> <p>which I guess is not the best way to do things. During development, everything works as expected, however when deployed, the "from foo import FooObject" code in foo.py seemingly attempts to import foo.py itself, which is not the behaviour I'm looking for.</p> <p>So the question is what is the standard practice of orchestrating situations like this? One of the things I could think of is, when installing, rename foo.py to just foo, which stops it from importing itself, but that seems rather awkward...</p> <p>Another part of the problem, I suppose, is that it's a naming challenge. Perhaps call the executable script foo-bin.py?</p>
2
2008-11-30T07:02:14Z
333,621
<p><a href="http://jcalderone.livejournal.com/39794.html" rel="nofollow">This article</a> is pretty good, and shows you a good way to do it. The second item from the <em>Do</em> list answers your question.</p> <p><em>shameless copy paste:</em></p> <blockquote> <h1>Filesystem structure of a Python project</h1> <p><em>by <a href="http://jcalderone.livejournal.com/profile" rel="nofollow">Jp Calderone</a></em></p> <p><strong>Do:</strong></p> <ul> <li>name the directory something related to your project. For example, if your project is named "Twisted", name the top-level directory for its source files <code>Twisted</code>. When you do releases, you should include a version number suffix: <code>Twisted-2.5</code>.</li> <li>create a directory <code>Twisted/bin</code> and put your executables there, if you have any. Don't give them a <code>.py</code> extension, even if they are Python source files. Don't put any code in them except an import of and call to a main function defined somewhere else in your projects.</li> <li>If your project is expressable as a single Python source file, then put it into the directory and name it something related to your project. For example, <code>Twisted/twisted.py</code>. If you need multiple source files, create a package instead (<code>Twisted/twisted/</code>, with an empty <code>Twisted/twisted/__init__.py</code>) and place your source files in it. For example, <code>Twisted/twisted/internet.py</code>.</li> <li>put your unit tests in a sub-package of your package (note - this means that the single Python source file option above was a trick - you always need at least one other file for your unit tests). For example, <code>Twisted/twisted/test/</code>. Of course, make it a package with <code>Twisted/twisted/test/__init__.py</code>. Place tests in files like <code>Twisted/twisted/test/test_internet.py</code>.</li> <li>add <code>Twisted/README</code> and <code>Twisted/setup.py</code> to explain and install your software, respectively, if you're feeling nice.</li> </ul> <p><strong>Don't:</strong></p> <ul> <li>put your source in a directory called <code>src</code> or <code>lib</code>. This makes it hard to run without installing.</li> <li>put your tests outside of your Python package. This makes it hard to run the tests against an installed version.</li> <li>create a package that only has a <code>__init__.py</code> and then put all your code into <code>__init__.py</code>. Just make a module instead of a package, it's simpler.</li> <li>try to come up with magical hacks to make Python able to import your module or package without having the user add the directory containing it to their import path (either via <code>PYTHONPATH</code> or some other mechanism). You will not correctly handle all cases and users will get angry at you when your software doesn't work in their environment.</li> </ul> </blockquote>
5
2008-12-02T10:57:19Z
[ "python", "naming", "package", "conventions", "deploying" ]
python curses.ascii depending on locale?
328,793
<p>The <code>curses.ascii</code> module has some nice functions defined, that allow for example to recognize which characters are printable (<code>curses.ascii.isprint(ch)</code>).</p> <p>But, diffrent character codes can be printable depending on which locale setting is being used. For example, there are certain polish characters:</p> <pre><code>&gt;&gt;&gt; ord('a') 97 &gt;&gt;&gt; ord('ą') 177 &gt;&gt;&gt; </code></pre> <p>I'm wondering, is there a better way to tell if a number represents printable character then the one used in <code>curses.ascii</code> module:</p> <pre><code>def isprint(c): return _ctoi(c) &gt;= 32 and _ctoi(c) &lt;= 126 </code></pre> <p>which is kind of locale-unfriendly.</p>
0
2008-11-30T12:18:18Z
328,807
<p>If you convert the character to a unicode then you can use unicodedata:</p> <pre><code>&gt;&gt;&gt; unicodedata.category(u'ą')[0] in 'LNPS' True </code></pre>
4
2008-11-30T12:31:09Z
[ "python", "locale", "ncurses" ]
python curses.ascii depending on locale?
328,793
<p>The <code>curses.ascii</code> module has some nice functions defined, that allow for example to recognize which characters are printable (<code>curses.ascii.isprint(ch)</code>).</p> <p>But, diffrent character codes can be printable depending on which locale setting is being used. For example, there are certain polish characters:</p> <pre><code>&gt;&gt;&gt; ord('a') 97 &gt;&gt;&gt; ord('ą') 177 &gt;&gt;&gt; </code></pre> <p>I'm wondering, is there a better way to tell if a number represents printable character then the one used in <code>curses.ascii</code> module:</p> <pre><code>def isprint(c): return _ctoi(c) &gt;= 32 and _ctoi(c) &lt;= 126 </code></pre> <p>which is kind of locale-unfriendly.</p>
0
2008-11-30T12:18:18Z
330,086
<p>Well, it is called curses.ascii, so using ASCII rules for what's printable should not be a surprise. If you are using an ISO 8-bit code, or you are operating from a known code page, you will need rules that correspond to what the actual codes and their displays are.</p> <p>I think using unicode characters and standard Unicode classifications is fine. That just might not deal with what the curses and console arrangement are actually going to display properly. </p> <p>There also needs to be some consideration for what is acceptable and unacceptable for the application, even if displayable.</p>
2
2008-12-01T05:11:46Z
[ "python", "locale", "ncurses" ]
Printing all instances of a class
328,851
<p>With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?</p>
31
2008-11-30T13:23:48Z
328,856
<p>Same as almost all other OO languages, keep all instances of the class in a collection of some kind.</p> <p>You can try this kind of thing.</p> <pre><code>class MyClassFactory( object ): theWholeList= [] def __call__( self, *args, **kw ): x= MyClass( *args, **kw ) self.theWholeList.append( x ) return x </code></pre> <p>Now you can do this.</p> <pre><code>object= MyClassFactory( args, ... ) print MyClassFactory.theWholeList </code></pre>
3
2008-11-30T13:29:49Z
[ "python", "class" ]
Printing all instances of a class
328,851
<p>With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?</p>
31
2008-11-30T13:23:48Z
328,863
<p>Maybe you mean something like <a href="http://docs.python.org/reference/datamodel.html?highlight=__str__#object.__str__" rel="nofollow"><code>__str__</code></a>:</p> <pre><code>object.__str__(self) </code></pre> <blockquote> <p>Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from <strong>repr</strong>() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.</p> </blockquote> <p>A trivial example:</p> <pre><code>&gt;&gt;&gt; class dummy(object): ... def __init__(self): ... pass ... def __str__(self): ... return "I am a dummy" ... &gt;&gt;&gt; d1=dummy() &gt;&gt;&gt; d2=dummy() &gt;&gt;&gt; print d1,d2 I am a dummy I am a dummy &gt;&gt;&gt; </code></pre>
1
2008-11-30T13:34:13Z
[ "python", "class" ]
Printing all instances of a class
328,851
<p>With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?</p>
31
2008-11-30T13:23:48Z
328,882
<p>I see two options in this case:</p> <h2>Garbage collector</h2> <pre><code>import gc for obj in gc.get_objects(): if isinstance(obj, some_class): dome_something(obj) </code></pre> <p>This has the disadvantage of being very slow when you have a lot of objects, but works with types over which you have no control.</p> <h2>Use a mixin and weakrefs</h2> <pre><code>from collections import defaultdict import weakref class KeepRefs(object): __refs__ = defaultdict(list) def __init__(self): self.__refs__[self.__class__].append(weakref.ref(self)) @classmethod def get_instances(cls): for inst_ref in cls.__refs__[cls]: inst = inst_ref() if inst is not None: yield inst class X(KeepRefs): def __init__(self, name): super(X, self).__init__() self.name = name x = X("x") y = X("y") for r in X.get_instances(): print r.name del y for r in X.get_instances(): print r.name </code></pre> <p>In this case, all the references get stored as a weak reference in a list. If you create and delete a lot of instances frequently, you should clean up the list of weakrefs after iteration, otherwise there's going to be a lot of cruft. </p> <p>Another problem in this case is that you have to make sure to call the base class constructor. You could also override <code>__new__</code>, but only the <code>__new__</code> method of the first base class is used on instantiation. This also works only on types that are under your control.</p> <p><strong>Edit</strong>: The method for printing all instances according to a specific format is left as an exercise, but it's basically just a variation on the <code>for</code>-loops.</p>
53
2008-11-30T13:56:48Z
[ "python", "class" ]
Printing all instances of a class
328,851
<p>With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?</p>
31
2008-11-30T13:23:48Z
328,883
<p>Python doesn't have an equivalent to Smallktalk's #allInstances as the architecture doesn't have this type of central object table (although modern smalltalks don't really work like that either).</p> <p>As the other poster says, you have to explicitly manage a collection. His suggestion of a factory method that maintains a registry is a perfectly reasonable way to do it. You may wish to do something with <a href="http://www.python.org/doc/2.5.2/lib/module-weakref.html" rel="nofollow">weak references</a> so you don't have to explicitly keep track of object disposal.</p>
2
2008-11-30T13:57:28Z
[ "python", "class" ]
Printing all instances of a class
328,851
<p>With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?</p>
31
2008-11-30T13:23:48Z
329,351
<p>It's not clear if you need to print all class instances at once or when they're initialized, nor if you're talking about a class you have control over vs a class in a 3rd party library.</p> <p>In any case, I would solve this by writing a class factory using Python metaclass support. If you don't have control over the class, manually update the <code>__metaclass__</code> for the class or module you're tracking.</p> <p>See <a href="http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html" rel="nofollow">http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html</a> for more information.</p>
1
2008-11-30T20:55:27Z
[ "python", "class" ]
Printing all instances of a class
328,851
<p>With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?</p>
31
2008-11-30T13:23:48Z
9,460,070
<p>You'll want to create a static list on your class, and add a <code>weakref</code> to each instance so the garbage collector can clean up your instances when they're no longer needed.</p> <pre><code>import weakref class A: instances = [] def __init__(self, name=None): self.__class__.instances.append(weakref.proxy(self)) self.name = name a1 = A('a1') a2 = A('a2') a3 = A('a3') a4 = A('a4') for instance in A.instances: print(instance.name) </code></pre>
10
2012-02-27T04:26:56Z
[ "python", "class" ]
long <-> str binary conversion
328,964
<p>Is there any lib that convert very long numbers to string just copying the data?</p> <p>These one-liners are too slow:</p> <pre><code>def xlong(s): return sum([ord(c) &lt;&lt; e*8 for e,c in enumerate(s)]) def xstr(x): return chr(x&amp;255) + xstr(x &gt;&gt; 8) if x else '' print xlong('abcd'*1024) % 666 print xstr(13**666) </code></pre>
6
2008-11-30T15:40:58Z
328,967
<p>You want the struct module.</p> <pre><code>packed = struct.pack('l', 123456) assert struct.unpack('l', packed)[0] == 123456 </code></pre>
4
2008-11-30T15:45:53Z
[ "python", "string", "bignum" ]
long <-> str binary conversion
328,964
<p>Is there any lib that convert very long numbers to string just copying the data?</p> <p>These one-liners are too slow:</p> <pre><code>def xlong(s): return sum([ord(c) &lt;&lt; e*8 for e,c in enumerate(s)]) def xstr(x): return chr(x&amp;255) + xstr(x &gt;&gt; 8) if x else '' print xlong('abcd'*1024) % 666 print xstr(13**666) </code></pre>
6
2008-11-30T15:40:58Z
329,011
<p>How about</p> <pre><code>from binascii import hexlify, unhexlify def xstr(x): hex = '%x' % x return unhexlify('0'*(len(hex)%2) + hex)[::-1] def xlong(s): return int(hexlify(s[::-1]), 16) </code></pre> <p>I didn't time it but it should be faster and also work on larger numbers, since it doesn't use recursion.</p>
2
2008-11-30T16:13:23Z
[ "python", "string", "bignum" ]
long <-> str binary conversion
328,964
<p>Is there any lib that convert very long numbers to string just copying the data?</p> <p>These one-liners are too slow:</p> <pre><code>def xlong(s): return sum([ord(c) &lt;&lt; e*8 for e,c in enumerate(s)]) def xstr(x): return chr(x&amp;255) + xstr(x &gt;&gt; 8) if x else '' print xlong('abcd'*1024) % 666 print xstr(13**666) </code></pre>
6
2008-11-30T15:40:58Z
329,079
<p>I'm guessing you don't care about the string format, you just want a serialization? If so, why not use Python's built-in serializer, the <a href="http://www.python.org/doc/2.5.2/lib/module-cPickle.html" rel="nofollow">cPickle</a> module? The <code>dumps</code> function will convert any python object including a long integer to a string, and the <code>loads</code> function is its inverse. If you're doing this for saving out to a file, check out the <code>dump</code> and <code>load</code> functions, too.</p> <pre><code>&gt;&gt;&gt; import cPickle &gt;&gt;&gt; print cPickle.loads(cPickle.dumps(13**666)) % 666 73 &gt;&gt;&gt; print (13**666) % 666 73 </code></pre>
0
2008-11-30T17:11:41Z
[ "python", "string", "bignum" ]
long <-> str binary conversion
328,964
<p>Is there any lib that convert very long numbers to string just copying the data?</p> <p>These one-liners are too slow:</p> <pre><code>def xlong(s): return sum([ord(c) &lt;&lt; e*8 for e,c in enumerate(s)]) def xstr(x): return chr(x&amp;255) + xstr(x &gt;&gt; 8) if x else '' print xlong('abcd'*1024) % 666 print xstr(13**666) </code></pre>
6
2008-11-30T15:40:58Z
329,085
<p>If you need fast serialization use <a href="http://www.python.org/doc/2.5.2/lib/module-marshal.html" rel="nofollow">marshal</a> module. It's around 400x faster than your methods.</p>
1
2008-11-30T17:21:12Z
[ "python", "string", "bignum" ]
long <-> str binary conversion
328,964
<p>Is there any lib that convert very long numbers to string just copying the data?</p> <p>These one-liners are too slow:</p> <pre><code>def xlong(s): return sum([ord(c) &lt;&lt; e*8 for e,c in enumerate(s)]) def xstr(x): return chr(x&amp;255) + xstr(x &gt;&gt; 8) if x else '' print xlong('abcd'*1024) % 666 print xstr(13**666) </code></pre>
6
2008-11-30T15:40:58Z
329,127
<p>Performance of <code>cPickle</code> vs. <code>marshal</code> (Python 2.5.2, Windows):</p> <pre><code>python -mtimeit -s"from cPickle import loads,dumps;d=13**666" "loads(dumps(d))" 1000 loops, best of 3: 600 usec per loop python -mtimeit -s"from marshal import loads,dumps;d=13**666" "loads(dumps(d))" 100000 loops, best of 3: 7.79 usec per loop python -mtimeit -s"from pickle import loads,dumps;d= 13**666" "loads(dumps(d))" 1000 loops, best of 3: 644 usec per loop </code></pre> <p><code>marshal</code> is much faster.</p>
-1
2008-11-30T18:01:58Z
[ "python", "string", "bignum" ]
long <-> str binary conversion
328,964
<p>Is there any lib that convert very long numbers to string just copying the data?</p> <p>These one-liners are too slow:</p> <pre><code>def xlong(s): return sum([ord(c) &lt;&lt; e*8 for e,c in enumerate(s)]) def xstr(x): return chr(x&amp;255) + xstr(x &gt;&gt; 8) if x else '' print xlong('abcd'*1024) % 666 print xstr(13**666) </code></pre>
6
2008-11-30T15:40:58Z
366,576
<p>In fact, I have a lack of long(s,256) . I lurk more and see that there are 2 function in Python CAPI file "longobject.h":</p> <pre><code>PyObject * _PyLong_FromByteArray( const unsigned char* bytes, size_t n, int little_endian, int is_signed); int _PyLong_AsByteArray(PyLongObject* v, unsigned char* bytes, size_t n, int little_endian, int is_signed); </code></pre> <p>They do the job. I don't know why there are not included in some python module, or correct me if I'am wrong.</p>
2
2008-12-14T14:13:38Z
[ "python", "string", "bignum" ]
Pure Python rational numbers module for 2.5
329,333
<p>Has anybody seen such a thing? Small self-sufficient modules are preferred.</p>
6
2008-11-30T20:42:50Z
329,338
<p><a href="http://code.google.com/p/sympy/" rel="nofollow">SymPy</a> is a symbolic maths library written entirely in Python and has full support for rational numbers. From the <a href="http://docs.sympy.org/tutorial.html" rel="nofollow">tutorial</a>:</p> <pre><code>&gt;&gt;&gt; from sympy import * &gt;&gt;&gt; a = Rational(1,2) &gt;&gt;&gt; a 1/2 &gt;&gt;&gt; a*2 1 &gt;&gt;&gt; Rational(2)**50/Rational(10)**50 1/88817841970012523233890533447265625 </code></pre> <p>There is also GMP for Python (<a href="http://gmpy.sourceforge.net/" rel="nofollow">GMPY</a>) which, while not pure Python, is probably more efficient.</p>
8
2008-11-30T20:47:25Z
[ "python", "rational-numbers" ]
Pure Python rational numbers module for 2.5
329,333
<p>Has anybody seen such a thing? Small self-sufficient modules are preferred.</p>
6
2008-11-30T20:42:50Z
329,453
<p>The <a href="http://docs.python.org/library/fractions.html" rel="nofollow">fractions module</a> from 2.6 can be ripped out if necessary. Grab fractions.py, numbers.py, and abc.py; all pure python modules. </p> <p>You can get the single files from here (2.6 branch, 2.7 does not work): <a href="http://hg.python.org/cpython/branches" rel="nofollow">http://hg.python.org/cpython/branches</a></p>
9
2008-11-30T21:57:16Z
[ "python", "rational-numbers" ]
Pure Python rational numbers module for 2.5
329,333
<p>Has anybody seen such a thing? Small self-sufficient modules are preferred.</p>
6
2008-11-30T20:42:50Z
330,691
<p>One more thing to try is <a href="http://svn.python.org/view/python/branches/release25-maint/Demo/classes/Rat.py?rev=51333&amp;view=markup" rel="nofollow">Rat.py</a> from demo folder in Python 2.5 maintenance branch. If i understand correctly, it is the daddy of 2.6 <code>fractions</code>. It's a single module without dependencies.</p> <pre><code>&gt;&gt;&gt; from Rat import rat &gt;&gt;&gt; rat(1) / rat(3) Rat(1,3) &gt;&gt;&gt; rat(1, 3) ** 2 Rat(1,9) </code></pre> <p><strong>UPDATE</strong>: Nah, <code>fractions.py</code> is about 2.5 times faster for my task.</p>
2
2008-12-01T12:33:28Z
[ "python", "rational-numbers" ]
How to find all built in libraries in Python
329,498
<p>I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.</p> <p>What's included, and where can I get other good quality libraries from?</p>
5
2008-11-30T22:21:34Z
329,509
<p>The Python Global Module Index (<a href="http://docs.python.org/modindex.html" rel="nofollow">http://docs.python.org/modindex.html</a>) lists out every module included in Python 2.6. </p> <p>Sourceforge has all sorts of good Python modules - one that came in handy for me recently was PyExcelerator, a module for writing straight to MS Excel workbooks. The Python Package Index, (<a href="http://pypi.python.org/" rel="nofollow">http://pypi.python.org/</a>) is also a good source of Python modules.</p>
3
2008-11-30T22:26:42Z
[ "python" ]
How to find all built in libraries in Python
329,498
<p>I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.</p> <p>What's included, and where can I get other good quality libraries from?</p>
5
2008-11-30T22:21:34Z
329,510
<p>Firstly, the <a href="http://www.python.org/doc/2.5.2/lib/lib.html">python libary reference</a> gives a blow by blow of what's actually included. And the <a href="http://docs.python.org/modindex.html">global module index</a> contains a neat, alphabetized summary of those same modules. If you have dependencies on a library, you can trivially test for the presence with a construct like:</p> <pre><code>try: import foobar except: print 'No foobar module' </code></pre> <p>If you do this on startup for modules not necessarily present in the distribution you can bail with a sensible diagnostic.</p> <p>The <a href="http://pypi.python.org/pypi">Python Package Index</a> plays a role similar to that of CPAN in the perl world and has a list of many third party modules of one sort or another. Browsing and searching this should give you a feel for what's about. There are also utilities such as <a href="http://pypi.python.org/pypi/yolk">Yolk</a> which allow you to query the Python Package Index and the installed packages on Python.</p> <p>Other good online Python resources are:</p> <ul> <li><p><a href="http://www.python.org">www.python.org</a></p></li> <li><p>The <a href="http://groups.google.com/group/comp.lang.python">comp.lang.python</a> newsgroup - this is still very active.</p></li> <li><p>Various of the <a href="http://www.python.org/links/">items linked off</a> the Python home page.</p></li> <li><p>Various home pages and blogs by python luminaries such as <a href="http://www.pythonware.com/daily/">The Daily Python URL</a>, <a href="http://www.effbot.org/">effbot.org</a>, <a href="http://code.activestate.com/recipes/langs/python/">The Python Cookbook</a>, <a href="http://blog.ianbicking.org/">Ian Bicking's blog</a> (the guy responsible for SQLObject), and the <a href="http://planet.python.org/">Many blogs and sites off planet.python.org.</a></p></li> </ul>
16
2008-11-30T22:26:58Z
[ "python" ]
How to find all built in libraries in Python
329,498
<p>I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.</p> <p>What's included, and where can I get other good quality libraries from?</p>
5
2008-11-30T22:21:34Z
329,518
<p>run</p> <pre><code>pydoc -p 8080 </code></pre> <p>and point your browser to <a href="http://localhost:8080/">http://localhost:8080/</a></p> <p>You'll see everything that's installed and can spend lots of time discovering new things. :)</p>
11
2008-11-30T22:34:52Z
[ "python" ]
How to find all built in libraries in Python
329,498
<p>I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.</p> <p>What's included, and where can I get other good quality libraries from?</p>
5
2008-11-30T22:21:34Z
329,519
<p>This is not directly related to your question, but when you're in the python console, you can call help() on any function and it will print its documentation.</p> <p>also, you can call dir() on any module or object and it will list all of its attributes, including functions.</p> <p>This useful for inspecting contents of a module after you've imported it.</p> <pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; dir(math) ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] &gt;&gt;&gt; help( math.log ) Help on built-in function log in module math: log(...) log(x[, base]) -&gt; the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x. </code></pre>
0
2008-11-30T22:35:11Z
[ "python" ]
How to find all built in libraries in Python
329,498
<p>I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.</p> <p>What's included, and where can I get other good quality libraries from?</p>
5
2008-11-30T22:21:34Z
769,569
<p><a href="http://blog.doughellmann.com/" rel="nofollow">Doug Hellman's blog</a> covers lots of built-in libraries in depth. If you want to learn more about the standard library you should definitely read through his articles.</p>
1
2009-04-20T18:42:23Z
[ "python" ]
Python CMS for my own website?
329,706
<p>I'm an accomplished web and database developer, and I'm interested in redesigning my own website. </p> <p>I have the following content goals:</p> <ul> <li>Support a book I'm writing</li> <li>Move my blog to my own site (from blogger.com)</li> <li>Publish my articles (more persistent content than a blog)</li> <li>Host a forum with light use</li> <li>Embed slide sharing and screencasts</li> </ul> <p>I have the following technology goals for implementing my site:</p> <ul> <li>Learn more Python and Django</li> <li>Leverage a CMS solution such as Pinax or Django-CMS</li> <li>Utilize a CSS framework, such as Blueprint or YUI</li> <li>I develop on a Mac OS X platform</li> <li>I'm comfortable developing in a CLI, but I'd like to practice Eclipse or NetBeans</li> <li>I'd like to employ testing during development</li> <li>Please, no Microsoft languages or tools</li> </ul> <p>Any suggestions for technology choices that support these goals?</p> <p><strong>Edit:</strong> Apologies if the question above was too unclear or general. What I'm asking for is if folks have had experience doing a similar modest website, what would be recommendations for tools, frameworks, or techniques outside of those I listed?</p> <ul> <li>Is there another Python CMS that I should consider besides the two I listed? E.g. there may be a great Python solution, but it isn't built on top of Django.</li> <li>Perhaps all current Python CMS packages are too "alpha," and I'd be better off writing my own from scratch? Although I am up to it, I'd rather leverage an existing package.</li> <li>Given this kind of project, would you deploy a CMS with built-in (or plug-in) support for blogs, forums, etc. or would you rather design a simpler website and embed the more complex content management using other services, relying on your own website only as a dumb proxy or portal. E.g. one can re-publish Blogger.com content using the Google Gdata API. One can embed re-branded Nabble.com archives into any website, which may provide forum/mailinglist functionality more easily than running the forum itself.</li> <li>Sometimes a CMS package has its own CSS integrated, and using another CSS framework would be redundant or otherwise make no sense. Yes? No?</li> <li>Are there plugins for Django in Eclipse or Netbeans? I understand there's a pretty nice environment for Rails development in NetBeans, and I've read some people wish longingly for something similar for Django, but I don't know if these wishes have since been realized.</li> <li>What are some current preferred tools for unit and functional testing a Django application? Are these integrated with Eclipse or Netbeans?</li> </ul>
5
2008-12-01T00:53:21Z
329,718
<ol> <li><p><strong>Is there another Python CMS?</strong> Yes, there is. Are they better than Django? From some perspective, yes. Should you change? No. Learn Django, it's as good as or better than most.</p></li> <li><p><strong>Perhaps all current Python CMS packages are too "alpha."</strong> A shocking statement, IMO. However, if you think you can do better, by all means, jump in. However, it's a huge amount of work, and your goal does not say "do a huge amount of work to invent Yet Another CMS Framework."</p></li> <li><p><strong>Would you deploy a CMS with built-in (or plug-in) support for blogs, forums, etc.</strong> I don't completely get this. There's content (i.e., blog postings, forum postings) and there's a web application (i.e., a blog site with forum comments). They're different beasts, web applications depend on CMS. A CMS can (generally) handle any kind of content; therefore, blogs aren't usually described as "plug-ins", they're just content. Maybe you want a pre-built content model for blogs or something? Not sure what your question really is.</p> <ul> <li><strong>relying on your own website [to] re-publish Blogger.com content</strong>. Hard to know what to say here. It matches your goals to simply proxy or rebrand nabble. But it doesn't match your other goals because You won't learn very much Django, CMS, or any other technology. Since your first goal and your technology list don't match up well, I have no idea what you're planning to do: learn Django or work on your book and move your blog. Not sure what your question really is.</li> </ul></li> <li><p><strong>Sometimes a CMS package has its own CSS integrated, and using another CSS framework would be redundant or otherwise make no sense.</strong> Correct. Not sure what your question really is.</p></li> <li><p><strong>Are there plugins for Django in Eclipse or Netbeans?</strong> Is this a "let me google that for you" question? <a href="http://pydev.sourceforge.net/" rel="nofollow">http://pydev.sourceforge.net/</a> is the Eclipse plug-in for Python. <a href="http://wiki.netbeans.org/Python" rel="nofollow">http://wiki.netbeans.org/Python</a> is information on the Python plug-in for Net Beans. Django is just Python, so a Django-specific plug-in doesn't really mean much. <a href="http://www.activestate.com/store/download.aspx?prdGUID=20f4ed15-6684-4118-a78b-d37ff4058c5f" rel="nofollow">Komodo Edit</a> knows Django template syntax and can do some syntax highlighting. That's cool.</p></li> <li><p><strong>What are some current preferred tools for unit and functional testing a Django application?</strong> Python has unittest tools. They're part of Python. Not part of an IDE. Django has unit testing tools. They're part of Django -- which is just Python -- not part of an IDE. You simply run them and they produce a text log of what happened.</p></li> </ol>
9
2008-12-01T01:01:11Z
[ "python", "django", "content-management-system", "web-testing" ]
Python CMS for my own website?
329,706
<p>I'm an accomplished web and database developer, and I'm interested in redesigning my own website. </p> <p>I have the following content goals:</p> <ul> <li>Support a book I'm writing</li> <li>Move my blog to my own site (from blogger.com)</li> <li>Publish my articles (more persistent content than a blog)</li> <li>Host a forum with light use</li> <li>Embed slide sharing and screencasts</li> </ul> <p>I have the following technology goals for implementing my site:</p> <ul> <li>Learn more Python and Django</li> <li>Leverage a CMS solution such as Pinax or Django-CMS</li> <li>Utilize a CSS framework, such as Blueprint or YUI</li> <li>I develop on a Mac OS X platform</li> <li>I'm comfortable developing in a CLI, but I'd like to practice Eclipse or NetBeans</li> <li>I'd like to employ testing during development</li> <li>Please, no Microsoft languages or tools</li> </ul> <p>Any suggestions for technology choices that support these goals?</p> <p><strong>Edit:</strong> Apologies if the question above was too unclear or general. What I'm asking for is if folks have had experience doing a similar modest website, what would be recommendations for tools, frameworks, or techniques outside of those I listed?</p> <ul> <li>Is there another Python CMS that I should consider besides the two I listed? E.g. there may be a great Python solution, but it isn't built on top of Django.</li> <li>Perhaps all current Python CMS packages are too "alpha," and I'd be better off writing my own from scratch? Although I am up to it, I'd rather leverage an existing package.</li> <li>Given this kind of project, would you deploy a CMS with built-in (or plug-in) support for blogs, forums, etc. or would you rather design a simpler website and embed the more complex content management using other services, relying on your own website only as a dumb proxy or portal. E.g. one can re-publish Blogger.com content using the Google Gdata API. One can embed re-branded Nabble.com archives into any website, which may provide forum/mailinglist functionality more easily than running the forum itself.</li> <li>Sometimes a CMS package has its own CSS integrated, and using another CSS framework would be redundant or otherwise make no sense. Yes? No?</li> <li>Are there plugins for Django in Eclipse or Netbeans? I understand there's a pretty nice environment for Rails development in NetBeans, and I've read some people wish longingly for something similar for Django, but I don't know if these wishes have since been realized.</li> <li>What are some current preferred tools for unit and functional testing a Django application? Are these integrated with Eclipse or Netbeans?</li> </ul>
5
2008-12-01T00:53:21Z
329,742
<p>It depends what kind of tools you're looking for.</p> <p>As for an editor, if you like CLI stuff, then emacs or vim is the way to go (I prefer emacs). If you choose emacs, then you may also want to use <a href="http://pymacs.progiciels-bpi.ca/" rel="nofollow">pymacs</a> for customizing it (since you'll already be familiar with python). If you want some intellisense-like features, then eclipse is a good way to go, but I should warn you: python can be a tricky language to do that kind of stuff for. Thus, it may not be what you're used to with some other languages. All the same, you may give <a href="http://pydev.sourceforge.net/" rel="nofollow">pydev</a> a shot.</p> <p>I'd also recommend going with <a href="http://trac.edgewall.org/" rel="nofollow">trac</a> for tickets, source viewing, and for using your <a href="http://buildbot.net/trac" rel="nofollow">buildbot</a> continuous integration server.</p> <p>And tools like <a href="http://www.logilab.org/857" rel="nofollow">pylint</a> and <a href="http://bicyclerepair.sourceforge.net/" rel="nofollow">bicycle repair man</a> are always helpful as well.</p>
2
2008-12-01T01:14:29Z
[ "python", "django", "content-management-system", "web-testing" ]
Python CMS for my own website?
329,706
<p>I'm an accomplished web and database developer, and I'm interested in redesigning my own website. </p> <p>I have the following content goals:</p> <ul> <li>Support a book I'm writing</li> <li>Move my blog to my own site (from blogger.com)</li> <li>Publish my articles (more persistent content than a blog)</li> <li>Host a forum with light use</li> <li>Embed slide sharing and screencasts</li> </ul> <p>I have the following technology goals for implementing my site:</p> <ul> <li>Learn more Python and Django</li> <li>Leverage a CMS solution such as Pinax or Django-CMS</li> <li>Utilize a CSS framework, such as Blueprint or YUI</li> <li>I develop on a Mac OS X platform</li> <li>I'm comfortable developing in a CLI, but I'd like to practice Eclipse or NetBeans</li> <li>I'd like to employ testing during development</li> <li>Please, no Microsoft languages or tools</li> </ul> <p>Any suggestions for technology choices that support these goals?</p> <p><strong>Edit:</strong> Apologies if the question above was too unclear or general. What I'm asking for is if folks have had experience doing a similar modest website, what would be recommendations for tools, frameworks, or techniques outside of those I listed?</p> <ul> <li>Is there another Python CMS that I should consider besides the two I listed? E.g. there may be a great Python solution, but it isn't built on top of Django.</li> <li>Perhaps all current Python CMS packages are too "alpha," and I'd be better off writing my own from scratch? Although I am up to it, I'd rather leverage an existing package.</li> <li>Given this kind of project, would you deploy a CMS with built-in (or plug-in) support for blogs, forums, etc. or would you rather design a simpler website and embed the more complex content management using other services, relying on your own website only as a dumb proxy or portal. E.g. one can re-publish Blogger.com content using the Google Gdata API. One can embed re-branded Nabble.com archives into any website, which may provide forum/mailinglist functionality more easily than running the forum itself.</li> <li>Sometimes a CMS package has its own CSS integrated, and using another CSS framework would be redundant or otherwise make no sense. Yes? No?</li> <li>Are there plugins for Django in Eclipse or Netbeans? I understand there's a pretty nice environment for Rails development in NetBeans, and I've read some people wish longingly for something similar for Django, but I don't know if these wishes have since been realized.</li> <li>What are some current preferred tools for unit and functional testing a Django application? Are these integrated with Eclipse or Netbeans?</li> </ul>
5
2008-12-01T00:53:21Z
329,744
<p>You're all set, just do it :)<br /> Read the django tutorial to get started (if you haven't already).<br /> I don't know everything about django or python, I just keep the references by my side.</p>
1
2008-12-01T01:15:41Z
[ "python", "django", "content-management-system", "web-testing" ]
Python CMS for my own website?
329,706
<p>I'm an accomplished web and database developer, and I'm interested in redesigning my own website. </p> <p>I have the following content goals:</p> <ul> <li>Support a book I'm writing</li> <li>Move my blog to my own site (from blogger.com)</li> <li>Publish my articles (more persistent content than a blog)</li> <li>Host a forum with light use</li> <li>Embed slide sharing and screencasts</li> </ul> <p>I have the following technology goals for implementing my site:</p> <ul> <li>Learn more Python and Django</li> <li>Leverage a CMS solution such as Pinax or Django-CMS</li> <li>Utilize a CSS framework, such as Blueprint or YUI</li> <li>I develop on a Mac OS X platform</li> <li>I'm comfortable developing in a CLI, but I'd like to practice Eclipse or NetBeans</li> <li>I'd like to employ testing during development</li> <li>Please, no Microsoft languages or tools</li> </ul> <p>Any suggestions for technology choices that support these goals?</p> <p><strong>Edit:</strong> Apologies if the question above was too unclear or general. What I'm asking for is if folks have had experience doing a similar modest website, what would be recommendations for tools, frameworks, or techniques outside of those I listed?</p> <ul> <li>Is there another Python CMS that I should consider besides the two I listed? E.g. there may be a great Python solution, but it isn't built on top of Django.</li> <li>Perhaps all current Python CMS packages are too "alpha," and I'd be better off writing my own from scratch? Although I am up to it, I'd rather leverage an existing package.</li> <li>Given this kind of project, would you deploy a CMS with built-in (or plug-in) support for blogs, forums, etc. or would you rather design a simpler website and embed the more complex content management using other services, relying on your own website only as a dumb proxy or portal. E.g. one can re-publish Blogger.com content using the Google Gdata API. One can embed re-branded Nabble.com archives into any website, which may provide forum/mailinglist functionality more easily than running the forum itself.</li> <li>Sometimes a CMS package has its own CSS integrated, and using another CSS framework would be redundant or otherwise make no sense. Yes? No?</li> <li>Are there plugins for Django in Eclipse or Netbeans? I understand there's a pretty nice environment for Rails development in NetBeans, and I've read some people wish longingly for something similar for Django, but I don't know if these wishes have since been realized.</li> <li>What are some current preferred tools for unit and functional testing a Django application? Are these integrated with Eclipse or Netbeans?</li> </ul>
5
2008-12-01T00:53:21Z
330,278
<p>No one here seems to mention older CMS frameworks, like <a href="http://plone.org/" rel="nofollow">Plone</a>.</p> <p>Quoting <a href="http://en.wikipedia.org/wiki/Plone%5F%28software%29" rel="nofollow">Wikipedia</a>:</p> <blockquote> <p>Plone is a free and open source content management system built on top of the Zope application server. It is suited for an internal website or may be used as a server on the Internet, playing such roles as a document publishing system and groupware collaboration tool.</p> </blockquote> <p>Started at 1999, the latest release is Plone 3.1.7, dated November 2008. Plone is doing fine - the site is <a href="http://plone.net/sites" rel="nofollow">currently listing</a> 1420 sites powered by Plone.</p> <p>Status update December 2009: Version 3.3.2 (November 2009) is current. <a href="http://plone.net/sites" rel="nofollow">1904 sites are listed</a> as powered by Plone.</p>
5
2008-12-01T08:24:31Z
[ "python", "django", "content-management-system", "web-testing" ]
Python CMS for my own website?
329,706
<p>I'm an accomplished web and database developer, and I'm interested in redesigning my own website. </p> <p>I have the following content goals:</p> <ul> <li>Support a book I'm writing</li> <li>Move my blog to my own site (from blogger.com)</li> <li>Publish my articles (more persistent content than a blog)</li> <li>Host a forum with light use</li> <li>Embed slide sharing and screencasts</li> </ul> <p>I have the following technology goals for implementing my site:</p> <ul> <li>Learn more Python and Django</li> <li>Leverage a CMS solution such as Pinax or Django-CMS</li> <li>Utilize a CSS framework, such as Blueprint or YUI</li> <li>I develop on a Mac OS X platform</li> <li>I'm comfortable developing in a CLI, but I'd like to practice Eclipse or NetBeans</li> <li>I'd like to employ testing during development</li> <li>Please, no Microsoft languages or tools</li> </ul> <p>Any suggestions for technology choices that support these goals?</p> <p><strong>Edit:</strong> Apologies if the question above was too unclear or general. What I'm asking for is if folks have had experience doing a similar modest website, what would be recommendations for tools, frameworks, or techniques outside of those I listed?</p> <ul> <li>Is there another Python CMS that I should consider besides the two I listed? E.g. there may be a great Python solution, but it isn't built on top of Django.</li> <li>Perhaps all current Python CMS packages are too "alpha," and I'd be better off writing my own from scratch? Although I am up to it, I'd rather leverage an existing package.</li> <li>Given this kind of project, would you deploy a CMS with built-in (or plug-in) support for blogs, forums, etc. or would you rather design a simpler website and embed the more complex content management using other services, relying on your own website only as a dumb proxy or portal. E.g. one can re-publish Blogger.com content using the Google Gdata API. One can embed re-branded Nabble.com archives into any website, which may provide forum/mailinglist functionality more easily than running the forum itself.</li> <li>Sometimes a CMS package has its own CSS integrated, and using another CSS framework would be redundant or otherwise make no sense. Yes? No?</li> <li>Are there plugins for Django in Eclipse or Netbeans? I understand there's a pretty nice environment for Rails development in NetBeans, and I've read some people wish longingly for something similar for Django, but I don't know if these wishes have since been realized.</li> <li>What are some current preferred tools for unit and functional testing a Django application? Are these integrated with Eclipse or Netbeans?</li> </ul>
5
2008-12-01T00:53:21Z
455,141
<p>If you want to stick with Python than I'd say Django is your best bet. The out-of-the-box admin UI will save you a <em>lot</em> of time. I'd avoid Plone unless you plan on using it as is, which does not seem to be the case. If we're to make serious modifications you're probably better off building something in Zope2. From your description it sounds like really the best platform would be Wordpress. It's open source but PHP based.Even though its not build in Python You may want to give it a look though since it's an excellent publishing platform, blogging tool. You can always mix the 2 anyway. I have a blog that runs on Wordpress and custom poker site build in Zope2. I have the Zope stuff on a subdomain and run a cron job that grabs the header and footer files from Wordpress every few minutes.</p>
2
2009-01-18T13:41:08Z
[ "python", "django", "content-management-system", "web-testing" ]
Python CMS for my own website?
329,706
<p>I'm an accomplished web and database developer, and I'm interested in redesigning my own website. </p> <p>I have the following content goals:</p> <ul> <li>Support a book I'm writing</li> <li>Move my blog to my own site (from blogger.com)</li> <li>Publish my articles (more persistent content than a blog)</li> <li>Host a forum with light use</li> <li>Embed slide sharing and screencasts</li> </ul> <p>I have the following technology goals for implementing my site:</p> <ul> <li>Learn more Python and Django</li> <li>Leverage a CMS solution such as Pinax or Django-CMS</li> <li>Utilize a CSS framework, such as Blueprint or YUI</li> <li>I develop on a Mac OS X platform</li> <li>I'm comfortable developing in a CLI, but I'd like to practice Eclipse or NetBeans</li> <li>I'd like to employ testing during development</li> <li>Please, no Microsoft languages or tools</li> </ul> <p>Any suggestions for technology choices that support these goals?</p> <p><strong>Edit:</strong> Apologies if the question above was too unclear or general. What I'm asking for is if folks have had experience doing a similar modest website, what would be recommendations for tools, frameworks, or techniques outside of those I listed?</p> <ul> <li>Is there another Python CMS that I should consider besides the two I listed? E.g. there may be a great Python solution, but it isn't built on top of Django.</li> <li>Perhaps all current Python CMS packages are too "alpha," and I'd be better off writing my own from scratch? Although I am up to it, I'd rather leverage an existing package.</li> <li>Given this kind of project, would you deploy a CMS with built-in (or plug-in) support for blogs, forums, etc. or would you rather design a simpler website and embed the more complex content management using other services, relying on your own website only as a dumb proxy or portal. E.g. one can re-publish Blogger.com content using the Google Gdata API. One can embed re-branded Nabble.com archives into any website, which may provide forum/mailinglist functionality more easily than running the forum itself.</li> <li>Sometimes a CMS package has its own CSS integrated, and using another CSS framework would be redundant or otherwise make no sense. Yes? No?</li> <li>Are there plugins for Django in Eclipse or Netbeans? I understand there's a pretty nice environment for Rails development in NetBeans, and I've read some people wish longingly for something similar for Django, but I don't know if these wishes have since been realized.</li> <li>What are some current preferred tools for unit and functional testing a Django application? Are these integrated with Eclipse or Netbeans?</li> </ul>
5
2008-12-01T00:53:21Z
1,393,071
<p>Checkout <a href="http://code.google.com/p/django-blocks/" rel="nofollow">django-blocks</a>. Has multi-language Menu, Flatpages and even has a simple Shopping Cart!!</p>
1
2009-09-08T09:56:56Z
[ "python", "django", "content-management-system", "web-testing" ]
Python CMS for my own website?
329,706
<p>I'm an accomplished web and database developer, and I'm interested in redesigning my own website. </p> <p>I have the following content goals:</p> <ul> <li>Support a book I'm writing</li> <li>Move my blog to my own site (from blogger.com)</li> <li>Publish my articles (more persistent content than a blog)</li> <li>Host a forum with light use</li> <li>Embed slide sharing and screencasts</li> </ul> <p>I have the following technology goals for implementing my site:</p> <ul> <li>Learn more Python and Django</li> <li>Leverage a CMS solution such as Pinax or Django-CMS</li> <li>Utilize a CSS framework, such as Blueprint or YUI</li> <li>I develop on a Mac OS X platform</li> <li>I'm comfortable developing in a CLI, but I'd like to practice Eclipse or NetBeans</li> <li>I'd like to employ testing during development</li> <li>Please, no Microsoft languages or tools</li> </ul> <p>Any suggestions for technology choices that support these goals?</p> <p><strong>Edit:</strong> Apologies if the question above was too unclear or general. What I'm asking for is if folks have had experience doing a similar modest website, what would be recommendations for tools, frameworks, or techniques outside of those I listed?</p> <ul> <li>Is there another Python CMS that I should consider besides the two I listed? E.g. there may be a great Python solution, but it isn't built on top of Django.</li> <li>Perhaps all current Python CMS packages are too "alpha," and I'd be better off writing my own from scratch? Although I am up to it, I'd rather leverage an existing package.</li> <li>Given this kind of project, would you deploy a CMS with built-in (or plug-in) support for blogs, forums, etc. or would you rather design a simpler website and embed the more complex content management using other services, relying on your own website only as a dumb proxy or portal. E.g. one can re-publish Blogger.com content using the Google Gdata API. One can embed re-branded Nabble.com archives into any website, which may provide forum/mailinglist functionality more easily than running the forum itself.</li> <li>Sometimes a CMS package has its own CSS integrated, and using another CSS framework would be redundant or otherwise make no sense. Yes? No?</li> <li>Are there plugins for Django in Eclipse or Netbeans? I understand there's a pretty nice environment for Rails development in NetBeans, and I've read some people wish longingly for something similar for Django, but I don't know if these wishes have since been realized.</li> <li>What are some current preferred tools for unit and functional testing a Django application? Are these integrated with Eclipse or Netbeans?</li> </ul>
5
2008-12-01T00:53:21Z
2,134,293
<p><a href="http://www.web2py.com/" rel="nofollow">Web2Py</a> looks good, but I don't have any experience with it.</p>
1
2010-01-25T17:43:05Z
[ "python", "django", "content-management-system", "web-testing" ]
In Python, is there a concise way to use a list comprehension with multiple iterators?
329,886
<p>Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following <a href="http://www.haskell.org/haskellwiki/List_comprehension" rel="nofollow">Haskell code</a>:</p> <pre><code>[(i,j) | i &lt;- [1,2], j &lt;- [1..4]] </code></pre> <p>which yields</p> <pre><code>[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] </code></pre> <p>Can I obtain a similar behavior in Python in a concise way?</p>
6
2008-12-01T02:44:03Z
329,904
<p>Are you asking about this?</p> <pre><code>[ (i,j) for i in range(1,3) for j in range(1,5) ] </code></pre>
14
2008-12-01T02:58:14Z
[ "python", "iterator", "list-comprehension" ]
In Python, is there a concise way to use a list comprehension with multiple iterators?
329,886
<p>Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following <a href="http://www.haskell.org/haskellwiki/List_comprehension" rel="nofollow">Haskell code</a>:</p> <pre><code>[(i,j) | i &lt;- [1,2], j &lt;- [1..4]] </code></pre> <p>which yields</p> <pre><code>[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] </code></pre> <p>Can I obtain a similar behavior in Python in a concise way?</p>
6
2008-12-01T02:44:03Z
329,913
<p>This seems to do what you describe:</p> <p>[[a,b] for a in range(1,3) for b in range(1,5)]</p> <p>UPDATE: Drat! Should have reloaded the page to see S.Lott's answer before posting. Hmmm... what to do for a little value-add? Perhaps a short testimony to the usefulness of interactive mode with Python. </p> <p>I come most recently from a background with Perl so with issues like this I find it very helpful to type "python" at the command line and drop into interactive mode and just a)start trying things, and b)refine the niceties by hitting up-arrow and adjusting my previous attempt until I get what I want. Any time I'm hazy on some keyword, help is at hand. Just type: help("some_keyword"), read the brief summary, then hit "Q" and I'm back on line in direct conversation with the python interpreter. </p> <p>Recommended if you are a beginner and not using it.</p>
2
2008-12-01T03:03:33Z
[ "python", "iterator", "list-comprehension" ]
In Python, is there a concise way to use a list comprehension with multiple iterators?
329,886
<p>Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following <a href="http://www.haskell.org/haskellwiki/List_comprehension" rel="nofollow">Haskell code</a>:</p> <pre><code>[(i,j) | i &lt;- [1,2], j &lt;- [1..4]] </code></pre> <p>which yields</p> <pre><code>[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] </code></pre> <p>Can I obtain a similar behavior in Python in a concise way?</p>
6
2008-12-01T02:44:03Z
329,978
<p>Cartesian product is in the <a href="http://docs.python.org/library/itertools.html#itertools.product" rel="nofollow">itertools module</a> (in 2.6).</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; list(itertools.product(range(1, 3), range(1, 5))) [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)] </code></pre>
7
2008-12-01T03:40:28Z
[ "python", "iterator", "list-comprehension" ]
In Python, is there a concise way to use a list comprehension with multiple iterators?
329,886
<p>Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following <a href="http://www.haskell.org/haskellwiki/List_comprehension" rel="nofollow">Haskell code</a>:</p> <pre><code>[(i,j) | i &lt;- [1,2], j &lt;- [1..4]] </code></pre> <p>which yields</p> <pre><code>[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] </code></pre> <p>Can I obtain a similar behavior in Python in a concise way?</p>
6
2008-12-01T02:44:03Z
330,335
<p>Fun fact about the nested comprehension: it mimics nested "for" loops, so the inner ones can use values from outer ones. This isn't useful in the cartesian product case, but good to know. For example:</p> <pre><code>[ (i,j) for i in range(10) for j in range(i) ] </code></pre> <p>generates all pairs <code>(i,j)</code> where <code>0&gt;=i&gt;j&gt;10</code>.</p>
4
2008-12-01T09:12:21Z
[ "python", "iterator", "list-comprehension" ]
Python crypt module -- what's the correct use of salts?
329,956
<p>First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd.</p> <p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p> <p>Despite not using the system-level password files, using crypt seemed to be a good practice to use, as opposed to storing passwords in cleartext. (While crypt is certainly better than storing passwords in cleartext, I'm open to other ways of doing this.)</p> <p>My crypt knowledge is based on this: <a href="https://docs.python.org/2/library/crypt.html" rel="nofollow">https://docs.python.org/2/library/crypt.html</a></p> <p>The documentation seems to ask for something that isn't possible: "it is recommended to use the full crypted password as salt when checking for a password."</p> <p>Huh? If I'm creating the crypted password (as in, when creating a user record) how can I use the crypted password as a salt? It doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p> <p>I've tried using the plaintext password as a salt. This does work, but has two problems; one easily overcome, and one serious:</p> <p>1) The first two letters of the plaintext password are included in the crypted password. You can fix this by not writing the first two characters to the file:</p> <pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type) </code></pre> <p>2) By using the plaintext password as the salt, you would seem to be reducing the amount of entropy in the system. Possibly I'm misunderstanding the purpose of the salt.</p> <p>The best practice I've been able to derive is to use the first two characters from the username as the salt. Would this be appropriate, or is there something I've missed that makes that a bad move?</p> <p>My understanding of a salt is that it prevents pre-computing password hashes from a dictionary. I could use a standard salt for all passwords (such as my initials, "JS,") but that seems to be less of a burden for an attacker than using two characters from each user's username.</p>
9
2008-12-01T03:31:45Z
329,995
<p>You're misunderstanding the documentation; it says that since the length of the salt may vary depending on the underlying crypt() implementation, you should provide the entire crypted password as the salt value <em>when checking passwords</em>. That is, instead of pulling the first two chars off to be the salt, just toss in the whole thing.</p> <p>Your idea of having the initial salt be based on the username seems okay. </p>
3
2008-12-01T03:51:59Z
[ "python", "linux", "cryptography", "crypt" ]
Python crypt module -- what's the correct use of salts?
329,956
<p>First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd.</p> <p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p> <p>Despite not using the system-level password files, using crypt seemed to be a good practice to use, as opposed to storing passwords in cleartext. (While crypt is certainly better than storing passwords in cleartext, I'm open to other ways of doing this.)</p> <p>My crypt knowledge is based on this: <a href="https://docs.python.org/2/library/crypt.html" rel="nofollow">https://docs.python.org/2/library/crypt.html</a></p> <p>The documentation seems to ask for something that isn't possible: "it is recommended to use the full crypted password as salt when checking for a password."</p> <p>Huh? If I'm creating the crypted password (as in, when creating a user record) how can I use the crypted password as a salt? It doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p> <p>I've tried using the plaintext password as a salt. This does work, but has two problems; one easily overcome, and one serious:</p> <p>1) The first two letters of the plaintext password are included in the crypted password. You can fix this by not writing the first two characters to the file:</p> <pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type) </code></pre> <p>2) By using the plaintext password as the salt, you would seem to be reducing the amount of entropy in the system. Possibly I'm misunderstanding the purpose of the salt.</p> <p>The best practice I've been able to derive is to use the first two characters from the username as the salt. Would this be appropriate, or is there something I've missed that makes that a bad move?</p> <p>My understanding of a salt is that it prevents pre-computing password hashes from a dictionary. I could use a standard salt for all passwords (such as my initials, "JS,") but that seems to be less of a burden for an attacker than using two characters from each user's username.</p>
9
2008-12-01T03:31:45Z
330,000
<p>For the use of the crypt module:</p> <p>When GENERATING the crypted password, you provide the salt. It might as well be random to increase resistance to brute-forcing, as long as it meets the listed conditions. When CHECKING a password, you should provide the value from getpwname, in case you are on a system that supports larger salt sizes and didn't generate it yourself.</p> <p>General comments:</p> <p>If this has nothing to do w/ actual system logins, there is nothing preventing you from using a stronger method than crypt. You could randomly generate N characters of per-user salt, to be combined with the user's password in a SHA-1 hash.</p> <pre><code>string_to_hash = user.stored_salt + entered_password successful_login = (sha1(string_to_hash) == user.stored_password_hash) </code></pre> <p>UPDATE: While this is far more secure against rainbow tables, the method above still has cryptographic weaknesses. Correct application of an HMAC algorithm can yet further increase your security, but is beyond my realm of expertise.</p>
3
2008-12-01T03:54:55Z
[ "python", "linux", "cryptography", "crypt" ]
Python crypt module -- what's the correct use of salts?
329,956
<p>First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd.</p> <p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p> <p>Despite not using the system-level password files, using crypt seemed to be a good practice to use, as opposed to storing passwords in cleartext. (While crypt is certainly better than storing passwords in cleartext, I'm open to other ways of doing this.)</p> <p>My crypt knowledge is based on this: <a href="https://docs.python.org/2/library/crypt.html" rel="nofollow">https://docs.python.org/2/library/crypt.html</a></p> <p>The documentation seems to ask for something that isn't possible: "it is recommended to use the full crypted password as salt when checking for a password."</p> <p>Huh? If I'm creating the crypted password (as in, when creating a user record) how can I use the crypted password as a salt? It doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p> <p>I've tried using the plaintext password as a salt. This does work, but has two problems; one easily overcome, and one serious:</p> <p>1) The first two letters of the plaintext password are included in the crypted password. You can fix this by not writing the first two characters to the file:</p> <pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type) </code></pre> <p>2) By using the plaintext password as the salt, you would seem to be reducing the amount of entropy in the system. Possibly I'm misunderstanding the purpose of the salt.</p> <p>The best practice I've been able to derive is to use the first two characters from the username as the salt. Would this be appropriate, or is there something I've missed that makes that a bad move?</p> <p>My understanding of a salt is that it prevents pre-computing password hashes from a dictionary. I could use a standard salt for all passwords (such as my initials, "JS,") but that seems to be less of a burden for an attacker than using two characters from each user's username.</p>
9
2008-12-01T03:31:45Z
330,016
<p>Here's some general advice on salting passwords:</p> <ol> <li>In general, salts are used to make <a href="http://en.wikipedia.org/wiki/Rainbow_table" rel="nofollow">ranbow tables</a> too costly to compute. So, you should add a little randomized salt to all your password hashes, and just store it in plaintext next to the hashed password value.</li> <li>Use <a href="http://en.wikipedia.org/wiki/HMAC" rel="nofollow">HMAC</a> - it's a good standard, and it's more secure than concatenating the password and salt.</li> <li>Use SHA1: MD5 is broken. No offense intended if you knew this, just being thorough. ;)</li> </ol> <p>I <strong>would not</strong> have the salt be a function of the password. An attacker would have to generate a rainbow table to have an instant-lookup database of passwords, but they'd only have to do that once. If you choose a random 32-bit integer, they'd have to generate 2^32 tables, which (unlike a deterministic salt) costs way, way too much memory (and time).</p>
3
2008-12-01T04:01:13Z
[ "python", "linux", "cryptography", "crypt" ]
Python crypt module -- what's the correct use of salts?
329,956
<p>First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd.</p> <p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p> <p>Despite not using the system-level password files, using crypt seemed to be a good practice to use, as opposed to storing passwords in cleartext. (While crypt is certainly better than storing passwords in cleartext, I'm open to other ways of doing this.)</p> <p>My crypt knowledge is based on this: <a href="https://docs.python.org/2/library/crypt.html" rel="nofollow">https://docs.python.org/2/library/crypt.html</a></p> <p>The documentation seems to ask for something that isn't possible: "it is recommended to use the full crypted password as salt when checking for a password."</p> <p>Huh? If I'm creating the crypted password (as in, when creating a user record) how can I use the crypted password as a salt? It doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p> <p>I've tried using the plaintext password as a salt. This does work, but has two problems; one easily overcome, and one serious:</p> <p>1) The first two letters of the plaintext password are included in the crypted password. You can fix this by not writing the first two characters to the file:</p> <pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type) </code></pre> <p>2) By using the plaintext password as the salt, you would seem to be reducing the amount of entropy in the system. Possibly I'm misunderstanding the purpose of the salt.</p> <p>The best practice I've been able to derive is to use the first two characters from the username as the salt. Would this be appropriate, or is there something I've missed that makes that a bad move?</p> <p>My understanding of a salt is that it prevents pre-computing password hashes from a dictionary. I could use a standard salt for all passwords (such as my initials, "JS,") but that seems to be less of a burden for an attacker than using two characters from each user's username.</p>
9
2008-12-01T03:31:45Z
330,039
<p>Python's crypt() is a wrapper for the system's crypt() function. From the Linux crypt() man page:</p> <pre> char *crypt(const char *key, const char *salt); key is a user’s typed password. salt is a two-character string chosen from the set [a–zA–Z0–9./]. This string is used to perturb the algorithm in one of 4096 different ways. </pre> <p>Emphasis is on "<em>two-character</em> string". Now, if you look at crypt()'s behavior in Python:</p> <pre><code>&gt;&gt;&gt; crypt.crypt("Hello", "World") 'Wo5pEi/H5/mxU' &gt;&gt;&gt; crypt.crypt("Hello", "ABCDE") 'AB/uOsC7P93EI' </code></pre> <p>you discover that the first two characters of the result always coincide with the first two characters of the original salt, which indeed form the true two-character-salt itself. That is, the result of crypt() has the form 2char-salt + encrypted-pass. Hence, there is no difference in the result if instead of passing the two-character-salt or the original many-characters-salt you pass the whole encrypted password.</p> <p>Note: the set [a–zA–Z0–9./] contains 64 characters, and 64&#42;64=4096. Here's how <em>two</em> characters relate to "<em>4096</em> different ways".</p>
7
2008-12-01T04:20:23Z
[ "python", "linux", "cryptography", "crypt" ]
Python crypt module -- what's the correct use of salts?
329,956
<p>First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd.</p> <p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p> <p>Despite not using the system-level password files, using crypt seemed to be a good practice to use, as opposed to storing passwords in cleartext. (While crypt is certainly better than storing passwords in cleartext, I'm open to other ways of doing this.)</p> <p>My crypt knowledge is based on this: <a href="https://docs.python.org/2/library/crypt.html" rel="nofollow">https://docs.python.org/2/library/crypt.html</a></p> <p>The documentation seems to ask for something that isn't possible: "it is recommended to use the full crypted password as salt when checking for a password."</p> <p>Huh? If I'm creating the crypted password (as in, when creating a user record) how can I use the crypted password as a salt? It doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p> <p>I've tried using the plaintext password as a salt. This does work, but has two problems; one easily overcome, and one serious:</p> <p>1) The first two letters of the plaintext password are included in the crypted password. You can fix this by not writing the first two characters to the file:</p> <pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type) </code></pre> <p>2) By using the plaintext password as the salt, you would seem to be reducing the amount of entropy in the system. Possibly I'm misunderstanding the purpose of the salt.</p> <p>The best practice I've been able to derive is to use the first two characters from the username as the salt. Would this be appropriate, or is there something I've missed that makes that a bad move?</p> <p>My understanding of a salt is that it prevents pre-computing password hashes from a dictionary. I could use a standard salt for all passwords (such as my initials, "JS,") but that seems to be less of a burden for an attacker than using two characters from each user's username.</p>
9
2008-12-01T03:31:45Z
330,058
<p>The password, or anything derived from the password, should never be used as salt. The salt for a particular password should be unpredictable.</p> <p>A username or part of the user name is tolerable, but even better would be random bytes from a cryptographic RNG.</p>
1
2008-12-01T04:40:02Z
[ "python", "linux", "cryptography", "crypt" ]
Python crypt module -- what's the correct use of salts?
329,956
<p>First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd.</p> <p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p> <p>Despite not using the system-level password files, using crypt seemed to be a good practice to use, as opposed to storing passwords in cleartext. (While crypt is certainly better than storing passwords in cleartext, I'm open to other ways of doing this.)</p> <p>My crypt knowledge is based on this: <a href="https://docs.python.org/2/library/crypt.html" rel="nofollow">https://docs.python.org/2/library/crypt.html</a></p> <p>The documentation seems to ask for something that isn't possible: "it is recommended to use the full crypted password as salt when checking for a password."</p> <p>Huh? If I'm creating the crypted password (as in, when creating a user record) how can I use the crypted password as a salt? It doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p> <p>I've tried using the plaintext password as a salt. This does work, but has two problems; one easily overcome, and one serious:</p> <p>1) The first two letters of the plaintext password are included in the crypted password. You can fix this by not writing the first two characters to the file:</p> <pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type) </code></pre> <p>2) By using the plaintext password as the salt, you would seem to be reducing the amount of entropy in the system. Possibly I'm misunderstanding the purpose of the salt.</p> <p>The best practice I've been able to derive is to use the first two characters from the username as the salt. Would this be appropriate, or is there something I've missed that makes that a bad move?</p> <p>My understanding of a salt is that it prevents pre-computing password hashes from a dictionary. I could use a standard salt for all passwords (such as my initials, "JS,") but that seems to be less of a burden for an attacker than using two characters from each user's username.</p>
9
2008-12-01T03:31:45Z
331,283
<p>For some added strength, you can get the crypt module to use md5 by using a salt in the format.</p> <pre><code>$1$ABCDEFGH$ </code></pre> <p>where ABCDEFGH is your salt string. </p> <pre><code>&gt;&gt;&gt; p = crypt.crypt('password', '$1$s8Ty3/f$') &gt;&gt;&gt; p Out: '$1$s8Ty3/f$0H/M0JswK9pl3X/e.n55G1' &gt;&gt;&gt; p == crypt.crypt('password', p) Out: True </code></pre> <p>(note that this is a gnu extension to crypt, see "man crypt" on a linux system). MD5 (and now even SHA1) may be "broken", but they are still relatively good for password hashes, and md5 is still the standard for linux local passwords.</p>
2
2008-12-01T16:09:13Z
[ "python", "linux", "cryptography", "crypt" ]
Python crypt module -- what's the correct use of salts?
329,956
<p>First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd.</p> <p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p> <p>Despite not using the system-level password files, using crypt seemed to be a good practice to use, as opposed to storing passwords in cleartext. (While crypt is certainly better than storing passwords in cleartext, I'm open to other ways of doing this.)</p> <p>My crypt knowledge is based on this: <a href="https://docs.python.org/2/library/crypt.html" rel="nofollow">https://docs.python.org/2/library/crypt.html</a></p> <p>The documentation seems to ask for something that isn't possible: "it is recommended to use the full crypted password as salt when checking for a password."</p> <p>Huh? If I'm creating the crypted password (as in, when creating a user record) how can I use the crypted password as a salt? It doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p> <p>I've tried using the plaintext password as a salt. This does work, but has two problems; one easily overcome, and one serious:</p> <p>1) The first two letters of the plaintext password are included in the crypted password. You can fix this by not writing the first two characters to the file:</p> <pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type) </code></pre> <p>2) By using the plaintext password as the salt, you would seem to be reducing the amount of entropy in the system. Possibly I'm misunderstanding the purpose of the salt.</p> <p>The best practice I've been able to derive is to use the first two characters from the username as the salt. Would this be appropriate, or is there something I've missed that makes that a bad move?</p> <p>My understanding of a salt is that it prevents pre-computing password hashes from a dictionary. I could use a standard salt for all passwords (such as my initials, "JS,") but that seems to be less of a burden for an attacker than using two characters from each user's username.</p>
9
2008-12-01T03:31:45Z
331,861
<p>Use PBKDF2, see <a href="http://stackoverflow.com/questions/287517/encryptinghashing-plain-text-passwords-in-database#287883">this comment</a> on a different thread (includes Python implementation).</p>
1
2008-12-01T19:12:07Z
[ "python", "linux", "cryptography", "crypt" ]
Python crypt module -- what's the correct use of salts?
329,956
<p>First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd.</p> <p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p> <p>Despite not using the system-level password files, using crypt seemed to be a good practice to use, as opposed to storing passwords in cleartext. (While crypt is certainly better than storing passwords in cleartext, I'm open to other ways of doing this.)</p> <p>My crypt knowledge is based on this: <a href="https://docs.python.org/2/library/crypt.html" rel="nofollow">https://docs.python.org/2/library/crypt.html</a></p> <p>The documentation seems to ask for something that isn't possible: "it is recommended to use the full crypted password as salt when checking for a password."</p> <p>Huh? If I'm creating the crypted password (as in, when creating a user record) how can I use the crypted password as a salt? It doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p> <p>I've tried using the plaintext password as a salt. This does work, but has two problems; one easily overcome, and one serious:</p> <p>1) The first two letters of the plaintext password are included in the crypted password. You can fix this by not writing the first two characters to the file:</p> <pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type) </code></pre> <p>2) By using the plaintext password as the salt, you would seem to be reducing the amount of entropy in the system. Possibly I'm misunderstanding the purpose of the salt.</p> <p>The best practice I've been able to derive is to use the first two characters from the username as the salt. Would this be appropriate, or is there something I've missed that makes that a bad move?</p> <p>My understanding of a salt is that it prevents pre-computing password hashes from a dictionary. I could use a standard salt for all passwords (such as my initials, "JS,") but that seems to be less of a burden for an attacker than using two characters from each user's username.</p>
9
2008-12-01T03:31:45Z
347,070
<p>Take a look at the article <a href="http://blog.bjrn.se/2008/01/truecrypt-explained.html" rel="nofollow">TrueCrypt explained</a> by Björn Edström. It contains easy to understand explanation of how truecrypt works and a simple Python implementation of some of truecrypt's functionality <strong>including password management</strong>.</p> <blockquote> <p>He's talking about the Python crypt() module, not about TrueCrypt in Python</p> </blockquote> <p>Default <code>crypt.crypt()</code> in Python 2 is not very secure and <a href="http://blog.bjrn.se/2008/01/truecrypt-explained.html" rel="nofollow">the article</a> explains how more secure alternatives might work.</p>
-1
2008-12-07T01:01:21Z
[ "python", "linux", "cryptography", "crypt" ]
Replace textarea with rich text editor in Django Admin?
329,963
<p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
33
2008-12-01T03:32:46Z
330,087
<p>There's an <a href="http://pypi.python.org/pypi/django-tinymce/">add-on Django application</a> to provide <a href="http://tinymce.moxiecode.com/">TinyMCE</a> support for Django admin forms without having to muck around with admin templates or Django newform internals.</p>
19
2008-12-01T05:12:28Z
[ "python", "django", "admin" ]
Replace textarea with rich text editor in Django Admin?
329,963
<p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
33
2008-12-01T03:32:46Z
337,114
<p>Take a look on this <a href="http://www.djangosnippets.org/snippets/1035/">snippet</a> - basic idea is to include custom JS in your admin definitions which will replace standard text areas with rich-text editor.</p> <p>For jQuery/FCKEditor such JS could look like that:</p> <pre><code>$(document).ready(function() { $("textarea").each(function(n, obj) { fck = new FCKeditor(obj.id) ; fck.BasePath = "/admin-media/fckeditor/" ; fck.ReplaceTextarea() ; }); }); </code></pre>
12
2008-12-03T13:34:31Z
[ "python", "django", "admin" ]
Replace textarea with rich text editor in Django Admin?
329,963
<p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
33
2008-12-01T03:32:46Z
346,257
<p>I'd say: define your own ModelAdmin class and overwrite the widget used for particular field, like:</p> <pre><code>class ArticleAdminModelForm(forms.ModelForm): description = forms.CharField(widget=widgets.AdminWYMEditor) class Meta: model = models.Article </code></pre> <p>(AdminWYMEditor is a <code>forms.Textarea</code> subclass that adds WYMEditor with configuration specific to Django admin app).</p> <p>See <a href="http://web.archive.org/web/20101123194618/http://jannisleidel.com/2008/11/wysiwym-editor-widget-django-admin-interface/" rel="nofollow">this blog post by Jannis Leidel</a> to see how this widget can be implemented.</p>
9
2008-12-06T13:14:21Z
[ "python", "django", "admin" ]
Replace textarea with rich text editor in Django Admin?
329,963
<p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
33
2008-12-01T03:32:46Z
2,412,324
<p>Currently the most straight forward way to use tinymce in django admin is to use Grappelli.</p> <p><a href="http://code.google.com/p/django-grappelli/" rel="nofollow">http://code.google.com/p/django-grappelli/</a></p> <p>Grappelli is also a requirement for <a href="http://code.google.com/p/django-filebrowser/" rel="nofollow">django-filebrowser</a> so if you want the whole shebang you will gotta need it anyways.</p>
2
2010-03-09T20:31:53Z
[ "python", "django", "admin" ]
Replace textarea with rich text editor in Django Admin?
329,963
<p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
33
2008-12-01T03:32:46Z
2,695,859
<p>Ok, to update a little this post, I would say that the easiest way to implement TinyMCE is to use the <a href="http://code.google.com/p/django-tinymce/" rel="nofollow">django-tinymce</a> app. You must also download the JS files from the <a href="http://tinymce.moxiecode.com/index.php" rel="nofollow">TinyMCE page</a>. I got some errors with the django intenationalization, but downloading the laguage packs from the TinyMCE must be enough.</p>
1
2010-04-23T02:42:53Z
[ "python", "django", "admin" ]
Replace textarea with rich text editor in Django Admin?
329,963
<p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
33
2008-12-01T03:32:46Z
7,762,362
<pre><code>class KindEditor(forms.Textarea): class Media: css ={ 'all':(settings.STATIC_ROOT + 'editor/themes/default/default.css',) } js = (settings.STATIC_ROOT + 'editor/kindeditor-min.js',settings.STATIC_ROOT + 'editor/lang/zh_CN.js',) def __init__(self): attrs = {} attrs['rel'] = 'kind' super(KindEditor, self).__init__(attrs) class NewsAdminForm(forms.ModelForm): pass class Meta: model = News widgets = { 'body':KindEditor() } class NewsAdmin(admin.ModelAdmin): form = NewsAdminForm admin.site.register(News, NewsAdmin) </code></pre>
1
2011-10-14T02:01:27Z
[ "python", "django", "admin" ]
Replace textarea with rich text editor in Django Admin?
329,963
<p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
33
2008-12-01T03:32:46Z
29,077,663
<p>At the date of the post and the answers TinyMCE was quite popular (as it probably remains today). But after some time ckeditor has appeared and many consider that a better alternative, including many SO users:</p> <p><a href="http://stackoverflow.com/questions/1470067/compare-tinymce-and-ckeditor-for-a-wiki">Compare TinyMCE and CKeditor for a Wiki</a></p> <p><a href="http://www.turnkeylinux.org/blog/tinymce-vs-ckeditor" rel="nofollow">http://www.turnkeylinux.org/blog/tinymce-vs-ckeditor</a></p> <p>There is also a 2013 review of WISIWYG editors with Django in Russian:</p> <p><a href="http://habrahabr.ru/company/htdt/blog/202782/" rel="nofollow">http://habrahabr.ru/company/htdt/blog/202782/</a></p>
2
2015-03-16T13:09:13Z
[ "python", "django", "admin" ]
Parsing a string for nested patterns
330,334
<p>What would be the best way to do this.</p> <p>The input string is </p> <pre><code>&lt;133_3&gt;&lt;135_3&gt;&lt;116_2&gt;The other system worked for about 1 month&lt;/116_2&gt; got some good images &lt;137_3&gt;on it then it started doing the same thing as the first one&lt;/137_3&gt; so then I quit using either camera now they are just sitting and collecting dust.&lt;/135_3&gt;&lt;/133_3&gt; </code></pre> <p>the expected output is </p> <pre><code>{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \ using either camera now they are just sitting and collecting dust.':[133, 135], 'The other system worked for about 1 month': [116], 'on it then it started doing the same thing as the first one':[137] } </code></pre> <p>that seems like a recursive regexp search but I can't figure out how exactly.</p> <p>I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.</p> <p>Related question: <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">Can regular expressions be used to match nested patterns?</a></p>
3
2008-12-01T09:12:05Z
330,356
<p>I think a grammar would be the best option here. I found a link with some information: <a href="http://www.onlamp.com/pub/a/python/2006/01/26/pyparsing.html" rel="nofollow">http://www.onlamp.com/pub/a/python/2006/01/26/pyparsing.html</a></p>
1
2008-12-01T09:20:58Z
[ "python", "regex" ]
Parsing a string for nested patterns
330,334
<p>What would be the best way to do this.</p> <p>The input string is </p> <pre><code>&lt;133_3&gt;&lt;135_3&gt;&lt;116_2&gt;The other system worked for about 1 month&lt;/116_2&gt; got some good images &lt;137_3&gt;on it then it started doing the same thing as the first one&lt;/137_3&gt; so then I quit using either camera now they are just sitting and collecting dust.&lt;/135_3&gt;&lt;/133_3&gt; </code></pre> <p>the expected output is </p> <pre><code>{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \ using either camera now they are just sitting and collecting dust.':[133, 135], 'The other system worked for about 1 month': [116], 'on it then it started doing the same thing as the first one':[137] } </code></pre> <p>that seems like a recursive regexp search but I can't figure out how exactly.</p> <p>I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.</p> <p>Related question: <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">Can regular expressions be used to match nested patterns?</a></p>
3
2008-12-01T09:12:05Z
330,433
<p>Take an XML parser, make it generate a DOM (Document Object Model) and then build a recursive algorithm that traverses all the nodes, calls "text()" in each node (that should give you the text in the current node and all children) and puts that as a key in the dictionary.</p>
4
2008-12-01T10:15:25Z
[ "python", "regex" ]
Parsing a string for nested patterns
330,334
<p>What would be the best way to do this.</p> <p>The input string is </p> <pre><code>&lt;133_3&gt;&lt;135_3&gt;&lt;116_2&gt;The other system worked for about 1 month&lt;/116_2&gt; got some good images &lt;137_3&gt;on it then it started doing the same thing as the first one&lt;/137_3&gt; so then I quit using either camera now they are just sitting and collecting dust.&lt;/135_3&gt;&lt;/133_3&gt; </code></pre> <p>the expected output is </p> <pre><code>{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \ using either camera now they are just sitting and collecting dust.':[133, 135], 'The other system worked for about 1 month': [116], 'on it then it started doing the same thing as the first one':[137] } </code></pre> <p>that seems like a recursive regexp search but I can't figure out how exactly.</p> <p>I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.</p> <p>Related question: <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">Can regular expressions be used to match nested patterns?</a></p>
3
2008-12-01T09:12:05Z
330,463
<p>Use expat or another XML parser; it's more explicit than anything else, considering you're dealing with XML data anyway.</p> <p>However, note that XML element names can't start with a number as your example has them.</p> <p>Here's a parser that will do what you need, although you'll need to tweak it to combine duplicate elements into one dict key:</p> <pre><code>from xml.parsers.expat import ParserCreate open_elements = {} result_dict = {} def start_element(name, attrs): open_elements[name] = True def end_element(name): del open_elements[name] def char_data(data): for element in open_elements: cur = result_dict.setdefault(element, '') result_dict[element] = cur + data if __name__ == '__main__': p = ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data p.Parse(u'&lt;_133_3&gt;&lt;_135_3&gt;&lt;_116_2&gt;The other system worked for about 1 month&lt;/_116_2&gt; got some good images &lt;_137_3&gt;on it then it started doing the same thing as the first one&lt;/_137_3&gt; so then I quit using either camera now they are just sitting and collecting dust.&lt;/_135_3&gt;&lt;/_133_3&gt;', 1) print result_dict </code></pre>
4
2008-12-01T10:31:44Z
[ "python", "regex" ]
Parsing a string for nested patterns
330,334
<p>What would be the best way to do this.</p> <p>The input string is </p> <pre><code>&lt;133_3&gt;&lt;135_3&gt;&lt;116_2&gt;The other system worked for about 1 month&lt;/116_2&gt; got some good images &lt;137_3&gt;on it then it started doing the same thing as the first one&lt;/137_3&gt; so then I quit using either camera now they are just sitting and collecting dust.&lt;/135_3&gt;&lt;/133_3&gt; </code></pre> <p>the expected output is </p> <pre><code>{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \ using either camera now they are just sitting and collecting dust.':[133, 135], 'The other system worked for about 1 month': [116], 'on it then it started doing the same thing as the first one':[137] } </code></pre> <p>that seems like a recursive regexp search but I can't figure out how exactly.</p> <p>I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.</p> <p>Related question: <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">Can regular expressions be used to match nested patterns?</a></p>
3
2008-12-01T09:12:05Z
330,494
<p>Note that you can't actually solve this by a regular expression, since they don't have the expressive power to enforce proper nesting.</p> <p>Take the following mini-language:</p> <blockquote> <p><em>A certain number of "(" followed by the same number of ")", no matter what the number.</em></p> </blockquote> <p>You could make a regular expression very easily to represent a super-language of this mini-language (where you don't enforce the equality of the number of starts parentheses and end parentheses). You could also make a regular expression very easilty to represent any finite sub-language (where you limit yourself to some max depth of nesting). But you can never represent this exact language in a regular expression.</p> <p>So you'd have to use a grammar, yes.</p>
1
2008-12-01T10:45:42Z
[ "python", "regex" ]
Parsing a string for nested patterns
330,334
<p>What would be the best way to do this.</p> <p>The input string is </p> <pre><code>&lt;133_3&gt;&lt;135_3&gt;&lt;116_2&gt;The other system worked for about 1 month&lt;/116_2&gt; got some good images &lt;137_3&gt;on it then it started doing the same thing as the first one&lt;/137_3&gt; so then I quit using either camera now they are just sitting and collecting dust.&lt;/135_3&gt;&lt;/133_3&gt; </code></pre> <p>the expected output is </p> <pre><code>{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \ using either camera now they are just sitting and collecting dust.':[133, 135], 'The other system worked for about 1 month': [116], 'on it then it started doing the same thing as the first one':[137] } </code></pre> <p>that seems like a recursive regexp search but I can't figure out how exactly.</p> <p>I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.</p> <p>Related question: <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">Can regular expressions be used to match nested patterns?</a></p>
3
2008-12-01T09:12:05Z
330,591
<pre><code>from cStringIO import StringIO from collections import defaultdict ####from xml.etree import cElementTree as etree from lxml import etree xml = "&lt;e133_3&gt;&lt;e135_3&gt;&lt;e116_2&gt;The other system worked for about 1 month&lt;/e116_2&gt; got some good images &lt;e137_3&gt;on it then it started doing the same thing as the first one&lt;/e137_3&gt; so then I quit using either camera now they are just sitting and collecting dust. &lt;/e135_3&gt;&lt;/e133_3&gt;" d = defaultdict(list) for event, elem in etree.iterparse(StringIO(xml)): d[''.join(elem.itertext())].append(int(elem.tag[1:-2])) print(dict(d.items())) </code></pre> <p>Output:</p> <pre><code>{'on it then it started doing the same thing as the first one': [137], 'The other system worked for about 1 month': [116], 'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit using \ either camera now they are just sitting and collecting dust. ': [133, 135]} </code></pre>
2
2008-12-01T11:40:54Z
[ "python", "regex" ]
Parsing a string for nested patterns
330,334
<p>What would be the best way to do this.</p> <p>The input string is </p> <pre><code>&lt;133_3&gt;&lt;135_3&gt;&lt;116_2&gt;The other system worked for about 1 month&lt;/116_2&gt; got some good images &lt;137_3&gt;on it then it started doing the same thing as the first one&lt;/137_3&gt; so then I quit using either camera now they are just sitting and collecting dust.&lt;/135_3&gt;&lt;/133_3&gt; </code></pre> <p>the expected output is </p> <pre><code>{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \ using either camera now they are just sitting and collecting dust.':[133, 135], 'The other system worked for about 1 month': [116], 'on it then it started doing the same thing as the first one':[137] } </code></pre> <p>that seems like a recursive regexp search but I can't figure out how exactly.</p> <p>I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.</p> <p>Related question: <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">Can regular expressions be used to match nested patterns?</a></p>
3
2008-12-01T09:12:05Z
330,931
<p>Here's an unreliable inefficient recursive regexp solution:</p> <pre><code>import re re_tag = re.compile(r'&lt;(?P&lt;tag&gt;[^&gt;]+)&gt;(?P&lt;content&gt;.*?)&lt;/(?P=tag)&gt;', re.S) def iterparse(text, tag=None): if tag is not None: yield tag, text for m in re_tag.finditer(text): for tag, text in iterparse(m.group('content'), m.group('tag')): yield tag, text def strip_tags(content): nested = lambda m: re_tag.sub(nested, m.group('content')) return re_tag.sub(nested, content) txt = "&lt;133_3&gt;&lt;135_3&gt;&lt;116_2&gt;The other system worked for about 1 month&lt;/116_2&gt; got some good images &lt;137_3&gt;on it then it started doing the same thing as the first one&lt;/137_3&gt; so then I quit using either camera now they are just sitting and collecting dust. &lt;/135_3&gt;&lt;/133_3&gt;" d = {} for tag, text in iterparse(txt): d.setdefault(strip_tags(text), []).append(int(tag[:-2])) print(d) </code></pre> <p>Output:</p> <pre><code>{'on it then it started doing the same thing as the first one': [137], 'The other system worked for about 1 month': [116], 'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit using \ either camera now they are just sitting and collecting dust. ': [133, 135]} </code></pre>
0
2008-12-01T14:02:02Z
[ "python", "regex" ]
How would one make Python objects persistent in a web-app?
330,367
<p>I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with the application. This algorithm is used often during each user's work to make certain important decisions.</p> <p>For performance reasons, re-initializing the state on every request from the (semi-normalized) database data quickly becomes non-feasible. It would be highly preferable, for example, to cache the state's Python object in some way so that it can simply be used and/or updated whenever necessary. However, since this is a web application, there several processes serving requests, so using a global variable is out of the question.</p> <p>I've tried serializing the relevant object (via pickle) and saving the serialized data to the DB, and am now experimenting with caching the serialized data via memcached. However, this still has the significant overhead of serializing and deserializing the object often.</p> <p>I've looked at shared memory solutions but the only relevant thing I've found is <a href="http://poshmodule.sourceforge.net/" rel="nofollow">POSH</a>. However POSH doesn't seem to be widely used and I don't feel easy integrating such an experimental component into my application.</p> <p>I need some advice! This is my first shot at developing a web application, so I'm hoping this is a common enough issue that there are well-known solutions to such problems. At this point solutions which assume the Python back-end is running on a single server would be sufficient, but extra points for solutions which scale to multiple servers as well :)</p> <p>Notes:</p> <ul> <li>I have this application working, currently live and with active users. I started out without doing any premature optimization, and then optimized as needed. I've done the measuring and testing to make sure the above mentioned issue is the actual bottleneck. I'm sure pretty sure I could squeeze more performance out of the current setup, but I wanted to ask if there's a better way.</li> <li>The setup itself is still a work in progress; assume that the system's architecture can be whatever suites your solution.</li> </ul>
6
2008-12-01T09:26:07Z
330,537
<p>I think you can give ZODB a shot.</p> <p>"A major feature of ZODB is transparency. You do not need to write any code to explicitly read or write your objects to or from a database. You just put your persistent objects into a container that works just like a Python dictionary. Everything inside this dictionary is saved in the database. This dictionary is said to be the "root" of the database. It's like a magic bag; any Python object that you put inside it becomes persistent."</p> <p>Initailly it was a integral part of Zope, but lately a standalone package is also available.</p> <p>It has the following limitation:</p> <p>"Actually there are a few restrictions on what you can store in the ZODB. You can store any objects that can be "pickled" into a standard, cross-platform serial format. Objects like lists, dictionaries, and numbers can be pickled. Objects like files, sockets, and Python code objects, cannot be stored in the database because they cannot be pickled."</p> <p>I have read it but haven't given it a shot myself though.</p> <p>Other possible thing could be a in-memory sqlite db, that may speed up the process a bit - being an in-memory db, but still you would have to do the serialization stuff and all. Note: In memory db is expensive on resources.</p> <p>Here is a link: <a href="http://www.zope.org/Documentation/Articles/ZODB1" rel="nofollow">http://www.zope.org/Documentation/Articles/ZODB1</a></p>
2
2008-12-01T11:07:00Z
[ "python", "web-applications", "concurrency", "persistence" ]
How would one make Python objects persistent in a web-app?
330,367
<p>I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with the application. This algorithm is used often during each user's work to make certain important decisions.</p> <p>For performance reasons, re-initializing the state on every request from the (semi-normalized) database data quickly becomes non-feasible. It would be highly preferable, for example, to cache the state's Python object in some way so that it can simply be used and/or updated whenever necessary. However, since this is a web application, there several processes serving requests, so using a global variable is out of the question.</p> <p>I've tried serializing the relevant object (via pickle) and saving the serialized data to the DB, and am now experimenting with caching the serialized data via memcached. However, this still has the significant overhead of serializing and deserializing the object often.</p> <p>I've looked at shared memory solutions but the only relevant thing I've found is <a href="http://poshmodule.sourceforge.net/" rel="nofollow">POSH</a>. However POSH doesn't seem to be widely used and I don't feel easy integrating such an experimental component into my application.</p> <p>I need some advice! This is my first shot at developing a web application, so I'm hoping this is a common enough issue that there are well-known solutions to such problems. At this point solutions which assume the Python back-end is running on a single server would be sufficient, but extra points for solutions which scale to multiple servers as well :)</p> <p>Notes:</p> <ul> <li>I have this application working, currently live and with active users. I started out without doing any premature optimization, and then optimized as needed. I've done the measuring and testing to make sure the above mentioned issue is the actual bottleneck. I'm sure pretty sure I could squeeze more performance out of the current setup, but I wanted to ask if there's a better way.</li> <li>The setup itself is still a work in progress; assume that the system's architecture can be whatever suites your solution.</li> </ul>
6
2008-12-01T09:26:07Z
330,574
<p>Be cautious of premature optimization.</p> <p>Addition: The "Python backend runs an algorithm whose state..." is the session in the web framework. That's it. Let the Django framework maintain session state in cache. Period. </p> <p>"The algorithm's per-user state undergoes many small changes as a user works with the application." Most web frameworks offer a cached session object. Often it is very high performance. See Django's <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#topics-http-sessions" rel="nofollow">session documentation</a> for this. </p> <p>Advice. [Revised]</p> <p>It appears you have something that works. Leverage to learn your framework, learn the tools, and learn what knobs you can turn without breaking a sweat. Specifically, using session state.</p> <p>Second, fiddle with caching, session management, and things that are easy to adjust, and see if you have enough speed. Find out whether MySQL socket or named pipe is faster by trying them out. These are the no-programming optimizations.</p> <p>Third, measure performance to find your actual bottleneck. Be prepared to provide (and defend) the measurements as fine-grained enough to be useful and stable enough to providing meaningful comparison of alternatives. </p> <p>For example, show the performance difference between persistent sessions and cached sessions.</p>
8
2008-12-01T11:29:48Z
[ "python", "web-applications", "concurrency", "persistence" ]
How would one make Python objects persistent in a web-app?
330,367
<p>I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with the application. This algorithm is used often during each user's work to make certain important decisions.</p> <p>For performance reasons, re-initializing the state on every request from the (semi-normalized) database data quickly becomes non-feasible. It would be highly preferable, for example, to cache the state's Python object in some way so that it can simply be used and/or updated whenever necessary. However, since this is a web application, there several processes serving requests, so using a global variable is out of the question.</p> <p>I've tried serializing the relevant object (via pickle) and saving the serialized data to the DB, and am now experimenting with caching the serialized data via memcached. However, this still has the significant overhead of serializing and deserializing the object often.</p> <p>I've looked at shared memory solutions but the only relevant thing I've found is <a href="http://poshmodule.sourceforge.net/" rel="nofollow">POSH</a>. However POSH doesn't seem to be widely used and I don't feel easy integrating such an experimental component into my application.</p> <p>I need some advice! This is my first shot at developing a web application, so I'm hoping this is a common enough issue that there are well-known solutions to such problems. At this point solutions which assume the Python back-end is running on a single server would be sufficient, but extra points for solutions which scale to multiple servers as well :)</p> <p>Notes:</p> <ul> <li>I have this application working, currently live and with active users. I started out without doing any premature optimization, and then optimized as needed. I've done the measuring and testing to make sure the above mentioned issue is the actual bottleneck. I'm sure pretty sure I could squeeze more performance out of the current setup, but I wanted to ask if there's a better way.</li> <li>The setup itself is still a work in progress; assume that the system's architecture can be whatever suites your solution.</li> </ul>
6
2008-12-01T09:26:07Z
330,577
<p>Another option is to review the requirement for state, it sounds like if the serialisation is the bottle neck then the object is very large. Do you really need an object that large?</p> <p>I know in the Stackoverflow podcast 27 the reddit guys discuss what they use for state, so that maybe useful to listen to. </p>
1
2008-12-01T11:30:39Z
[ "python", "web-applications", "concurrency", "persistence" ]
How would one make Python objects persistent in a web-app?
330,367
<p>I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with the application. This algorithm is used often during each user's work to make certain important decisions.</p> <p>For performance reasons, re-initializing the state on every request from the (semi-normalized) database data quickly becomes non-feasible. It would be highly preferable, for example, to cache the state's Python object in some way so that it can simply be used and/or updated whenever necessary. However, since this is a web application, there several processes serving requests, so using a global variable is out of the question.</p> <p>I've tried serializing the relevant object (via pickle) and saving the serialized data to the DB, and am now experimenting with caching the serialized data via memcached. However, this still has the significant overhead of serializing and deserializing the object often.</p> <p>I've looked at shared memory solutions but the only relevant thing I've found is <a href="http://poshmodule.sourceforge.net/" rel="nofollow">POSH</a>. However POSH doesn't seem to be widely used and I don't feel easy integrating such an experimental component into my application.</p> <p>I need some advice! This is my first shot at developing a web application, so I'm hoping this is a common enough issue that there are well-known solutions to such problems. At this point solutions which assume the Python back-end is running on a single server would be sufficient, but extra points for solutions which scale to multiple servers as well :)</p> <p>Notes:</p> <ul> <li>I have this application working, currently live and with active users. I started out without doing any premature optimization, and then optimized as needed. I've done the measuring and testing to make sure the above mentioned issue is the actual bottleneck. I'm sure pretty sure I could squeeze more performance out of the current setup, but I wanted to ask if there's a better way.</li> <li>The setup itself is still a work in progress; assume that the system's architecture can be whatever suites your solution.</li> </ul>
6
2008-12-01T09:26:07Z
330,580
<p>I think that the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> framework has what might be applicable here - namely the shared ctypes module. </p> <p>Multiprocessing is fairly new to Python, so it might have some oddities. I am not quite sure whether the solution works with processes not spawned via <code>multiprocessing</code>.</p>
3
2008-12-01T11:32:43Z
[ "python", "web-applications", "concurrency", "persistence" ]
How would one make Python objects persistent in a web-app?
330,367
<p>I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with the application. This algorithm is used often during each user's work to make certain important decisions.</p> <p>For performance reasons, re-initializing the state on every request from the (semi-normalized) database data quickly becomes non-feasible. It would be highly preferable, for example, to cache the state's Python object in some way so that it can simply be used and/or updated whenever necessary. However, since this is a web application, there several processes serving requests, so using a global variable is out of the question.</p> <p>I've tried serializing the relevant object (via pickle) and saving the serialized data to the DB, and am now experimenting with caching the serialized data via memcached. However, this still has the significant overhead of serializing and deserializing the object often.</p> <p>I've looked at shared memory solutions but the only relevant thing I've found is <a href="http://poshmodule.sourceforge.net/" rel="nofollow">POSH</a>. However POSH doesn't seem to be widely used and I don't feel easy integrating such an experimental component into my application.</p> <p>I need some advice! This is my first shot at developing a web application, so I'm hoping this is a common enough issue that there are well-known solutions to such problems. At this point solutions which assume the Python back-end is running on a single server would be sufficient, but extra points for solutions which scale to multiple servers as well :)</p> <p>Notes:</p> <ul> <li>I have this application working, currently live and with active users. I started out without doing any premature optimization, and then optimized as needed. I've done the measuring and testing to make sure the above mentioned issue is the actual bottleneck. I'm sure pretty sure I could squeeze more performance out of the current setup, but I wanted to ask if there's a better way.</li> <li>The setup itself is still a work in progress; assume that the system's architecture can be whatever suites your solution.</li> </ul>
6
2008-12-01T09:26:07Z
330,887
<p>First of all your approach is not a common web development practice. Even multi threading is being used, web applications are designed to be able to run multi-processing environments, for both scalability and easier deployment .</p> <p>If you need to just initialize a large object, and do not need to change later, you can do it easily by using a global variable that is initialized while your WSGI application is being created, or the module contains the object is being loaded etc, multi processing will do fine for you.</p> <p>If you need to change the object and access it from every thread, you need to be sure your object is thread safe, use locks to ensure that. And use a single server context, a process. Any multi threading python server will serve you well, also FCGI is a good choice for this kind of design.</p> <p>But, if multiple threads are accessing and changing your object the locks may have a really bad effect on your performance gain, which is likely to make all the benefits go away.</p>
2
2008-12-01T13:47:51Z
[ "python", "web-applications", "concurrency", "persistence" ]
How would one make Python objects persistent in a web-app?
330,367
<p>I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with the application. This algorithm is used often during each user's work to make certain important decisions.</p> <p>For performance reasons, re-initializing the state on every request from the (semi-normalized) database data quickly becomes non-feasible. It would be highly preferable, for example, to cache the state's Python object in some way so that it can simply be used and/or updated whenever necessary. However, since this is a web application, there several processes serving requests, so using a global variable is out of the question.</p> <p>I've tried serializing the relevant object (via pickle) and saving the serialized data to the DB, and am now experimenting with caching the serialized data via memcached. However, this still has the significant overhead of serializing and deserializing the object often.</p> <p>I've looked at shared memory solutions but the only relevant thing I've found is <a href="http://poshmodule.sourceforge.net/" rel="nofollow">POSH</a>. However POSH doesn't seem to be widely used and I don't feel easy integrating such an experimental component into my application.</p> <p>I need some advice! This is my first shot at developing a web application, so I'm hoping this is a common enough issue that there are well-known solutions to such problems. At this point solutions which assume the Python back-end is running on a single server would be sufficient, but extra points for solutions which scale to multiple servers as well :)</p> <p>Notes:</p> <ul> <li>I have this application working, currently live and with active users. I started out without doing any premature optimization, and then optimized as needed. I've done the measuring and testing to make sure the above mentioned issue is the actual bottleneck. I'm sure pretty sure I could squeeze more performance out of the current setup, but I wanted to ask if there's a better way.</li> <li>The setup itself is still a work in progress; assume that the system's architecture can be whatever suites your solution.</li> </ul>
6
2008-12-01T09:26:07Z
873,784
<blockquote> <p>This is Durus, a persistent object system for applications written in the Python programming language. Durus offers an easy way to use and maintain a consistent collection of object instances used by one or more processes. Access and change of a persistent instances is managed through a cached Connection instance which includes commit() and abort() methods so that changes are transactional. </p> </blockquote> <p><a href="http://www.mems-exchange.org/software/durus/" rel="nofollow">http://www.mems-exchange.org/software/durus/</a></p> <p>I've used it before in some research code, where I wanted to persist the results of certain computations. I eventually switched to <a href="http://www.pytables.org" rel="nofollow">pytables</a> as it met my needs better.</p>
2
2009-05-17T02:31:06Z
[ "python", "web-applications", "concurrency", "persistence" ]
jython date conversion
330,383
<p>Given a string as below, I need to convert:</p> <p>1 Dec 2008 06:43:00 +0100</p> <p>to</p> <p>MM/DD/YYYY HH:MM:SSAM</p> <p>using jython what is the best way to do this?</p>
2
2008-12-01T09:40:18Z
330,466
<p>I don't have jython handy, but I'd expect something like this to work:</p> <pre><code>import java sdf = java.text.SimpleDateFormat fmt_in = sdf('d MMM yyyy HH:mm:ss Z') fmt_out = sdf('MM/dd/yyyy HH:mm:ssaa') fmt_out.format(fmt_in.parse(time_str)) </code></pre>
2
2008-12-01T10:32:57Z
[ "python", "jython", "date-conversion" ]
jython date conversion
330,383
<p>Given a string as below, I need to convert:</p> <p>1 Dec 2008 06:43:00 +0100</p> <p>to</p> <p>MM/DD/YYYY HH:MM:SSAM</p> <p>using jython what is the best way to do this?</p>
2
2008-12-01T09:40:18Z
330,596
<p><a href="http://www.jython.org/" rel="nofollow">Jython</a> 2.5b0 (beta) has an implementation of the <a href="http://www.python.org/doc/2.5.2/lib/module-time.html" rel="nofollow">time module</a> that includes </p> <blockquote> <p><code>strptime(string[, format])</code>.</p> <p>Parse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime(). </p> </blockquote> <p>(<code>strptime</code> is missing in Jython2.2.1).</p> <p>A python version of the conversion formats will look like (not sure of the zone component):</p> <pre><code>import time mytime = time.strptime("1 Dec 2008 06:43:00 +0100", "%d %b %Y %H:%M:%S %Z") new_time_string = time.strftime("%m/%d/%Y %I:%M:%S%p", mytime) </code></pre>
1
2008-12-01T11:47:02Z
[ "python", "jython", "date-conversion" ]
CherryPy for a webhosting control panel application
330,573
<p>For quite a long time I've wanted to start a pet project that will aim in time to become a web hosting control panel, but mainly focused on Python hosting -- meaning I would like to make a way for users to generate/start Django/ other frameworks projects right from the panel. I seemed to have found the perfect tool to build my app with it: CherryPy. </p> <p>This would allow me to do it the way I want, building the app with its own HTTP/ HTTPS server and also all in my favorite programming language.</p> <p>But now a new question arises: As CherryPy is a threaded server, will it be the right for this kind of task?</p> <p>There will be lots of time consuming tasks so if one of the tasks blocks, the rest of the users trying to access other pages will be left waiting and eventually get timed out.</p> <p>I imagine that this kind of problem wouldn't happen on a fork based server.</p> <p>What would you advise? </p>
1
2008-12-01T11:29:47Z
330,606
<p>"Threaded" and "Fork based" servers are equivalent. A "threaded" server has multiple threads of execution, and if one blocks then the others will continue. A "Fork based" server has multiple processes executing, and if one blocks then the others will continue. The only difference is that threaded servers by default will share memory between the threads, "fork based" ones by default will not share memory.</p> <p>One other point - the "subprocess" module is not thread safe, so if you try to use it from CherryPy you will get wierd errors. (This is <a href="http://bugs.python.org/issue1731717" rel="nofollow">Python Bug 1731717</a>)</p>
1
2008-12-01T11:54:45Z
[ "python", "multithreading", "fork", "cherrypy" ]
How to quickly parse a list of strings
330,900
<p>If I want to split a list of words separated by a delimiter character, I can use</p> <pre><code>&gt;&gt;&gt; 'abc,foo,bar'.split(',') ['abc', 'foo', 'bar'] </code></pre> <p>But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ?</p> <pre><code>In: 'abc,"a string, with a comma","another, one"' Out: ['abc', 'a string, with a comma', 'another, one'] </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">How can i parse a comma delimited string into a list (caveat)?</a></p>
14
2008-12-01T13:51:42Z
330,908
<p>The <a href="http://www.python.org/doc/2.5.2/lib/module-csv.html" rel="nofollow">CSV module</a> should be able to do that for you</p>
7
2008-12-01T13:53:57Z
[ "python" ]
How to quickly parse a list of strings
330,900
<p>If I want to split a list of words separated by a delimiter character, I can use</p> <pre><code>&gt;&gt;&gt; 'abc,foo,bar'.split(',') ['abc', 'foo', 'bar'] </code></pre> <p>But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ?</p> <pre><code>In: 'abc,"a string, with a comma","another, one"' Out: ['abc', 'a string, with a comma', 'another, one'] </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">How can i parse a comma delimited string into a list (caveat)?</a></p>
14
2008-12-01T13:51:42Z
330,924
<pre><code>import csv input = ['abc,"a string, with a comma","another, one"'] parser = csv.reader(input) for fields in parser: for i,f in enumerate(fields): print i,f # in Python 3 and up, print is a function; use: print(i,f) </code></pre> <p>Result:</p> <pre> 0 abc 1 a string, with a comma 2 another, one </pre>
32
2008-12-01T13:59:22Z
[ "python" ]
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible
331,377
<p>How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible and also not to conflict with different lib/version that is already on my system.</p> <p>L.E.: Sorry i forgot to specify. I will be doing this on linux. And I'm not referring in making my app a installable file like deb/rpm, etc but how to organize my files so like for example I'll be using cherrypy and sqlalchemy I'll ship those with my app and not put the user through the pain of installing all the dependencies by himself.</p>
4
2008-12-01T16:40:10Z
331,410
<p>Try <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>.</p>
3
2008-12-01T16:49:49Z
[ "python", "linux", "deployment" ]
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible
331,377
<p>How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible and also not to conflict with different lib/version that is already on my system.</p> <p>L.E.: Sorry i forgot to specify. I will be doing this on linux. And I'm not referring in making my app a installable file like deb/rpm, etc but how to organize my files so like for example I'll be using cherrypy and sqlalchemy I'll ship those with my app and not put the user through the pain of installing all the dependencies by himself.</p>
4
2008-12-01T16:40:10Z
331,489
<p>You could try <code>freeze.py</code>, see <a href="http://wiki.python.org/moin/Freeze" rel="nofollow">http://wiki.python.org/moin/Freeze</a> for more details.</p>
4
2008-12-01T17:09:38Z
[ "python", "linux", "deployment" ]
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible
331,377
<p>How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible and also not to conflict with different lib/version that is already on my system.</p> <p>L.E.: Sorry i forgot to specify. I will be doing this on linux. And I'm not referring in making my app a installable file like deb/rpm, etc but how to organize my files so like for example I'll be using cherrypy and sqlalchemy I'll ship those with my app and not put the user through the pain of installing all the dependencies by himself.</p>
4
2008-12-01T16:40:10Z
331,703
<p>But if you make a deb with the correct dependencies listed the installer will download them for the user. That's the best way, as it's non redundant. </p> <p>Maybe you could make a tar or zip with your deb and all the third-party deb's and an install script that just install all the debs in the correct order. This way, if the user already has some package it wouldn't be installed again.</p>
2
2008-12-01T18:17:26Z
[ "python", "linux", "deployment" ]
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible
331,377
<p>How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible and also not to conflict with different lib/version that is already on my system.</p> <p>L.E.: Sorry i forgot to specify. I will be doing this on linux. And I'm not referring in making my app a installable file like deb/rpm, etc but how to organize my files so like for example I'll be using cherrypy and sqlalchemy I'll ship those with my app and not put the user through the pain of installing all the dependencies by himself.</p>
4
2008-12-01T16:40:10Z
331,846
<p>You can have your users run the system from a startup script, and that script can fix the pythonpath ahead of time to put your versions first. For example if you put CherryPy, SQLAlchemy, etc. in an "external" subdirectory, you could try:</p> <pre><code># startproj.sh script_path=`dirname $0` export PYTHONPATH=${script_path}/external;${PYTHONPATH} exec ${script_path}/projstartup.py </code></pre>
2
2008-12-01T19:08:29Z
[ "python", "linux", "deployment" ]
Python style
331,767
<p>Simple beginner question:</p> <p>I've created a small python script to toggle between two files I'm using for testing.</p> <p>My question is, what is a good python format style for the following code:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) </code></pre> <p>Or what?</p> <p>Also, what is the preffered way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"</p> <p>Thanks.</p>
3
2008-12-01T18:40:32Z
331,775
<p>The most common naming I've seen is underscode separated words, to_copy.</p> <p>As for the format style, I've seen no such agreement. I find </p> <pre><code>source = remote if filecmp.cmp(local, config_file) else local shutil.copyfile(source, config_file) </code></pre> <p>to be the clearest among your options.</p> <p>And seeing that everyone prefers to split the if I'd, at the very least, encapsulate the copyfile call in case you someday wish to change it:</p> <pre><code>def copy_to(source, destination): shutil.copyfile(source,destination) if filecmp.cmp(local, config_file): copy_to(remote, config_file) else: copy_to(local, config_file) </code></pre>
4
2008-12-01T18:44:06Z
[ "python", "coding-style" ]
Python style
331,767
<p>Simple beginner question:</p> <p>I've created a small python script to toggle between two files I'm using for testing.</p> <p>My question is, what is a good python format style for the following code:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) </code></pre> <p>Or what?</p> <p>Also, what is the preffered way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"</p> <p>Thanks.</p>
3
2008-12-01T18:40:32Z
331,776
<p>For the conditional statement, I would probably go with:</p> <pre><code>if filecmp.cmp(local, config_file): shutil.copyfile(remote, config_file) else: shutil.copyfile(local, config_file) </code></pre> <p>There's little need to use the inline <code>y if x else z</code> in this case, since the surrounding code is simple enough.</p>
17
2008-12-01T18:44:39Z
[ "python", "coding-style" ]
Python style
331,767
<p>Simple beginner question:</p> <p>I've created a small python script to toggle between two files I'm using for testing.</p> <p>My question is, what is a good python format style for the following code:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) </code></pre> <p>Or what?</p> <p>Also, what is the preffered way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"</p> <p>Thanks.</p>
3
2008-12-01T18:40:32Z
331,788
<p>From the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">Python Style Guide</a>:</p> <p><strong>With regard to listing out a compound expression:</strong></p> <p>Compound statements (multiple statements on the same line) are generally discouraged.</p> <p>Yes:</p> <pre><code>if foo == 'blah': do_blah_thing() do_one() do_two() do_three() </code></pre> <p>Or for the code you supplied, Greg's example is a good one:</p> <pre><code>if filecmp.cmp(local, config_file): shutil.copyfile(remote, config_file) else: shutil.copyfile(local, config_file) </code></pre> <p>Rather not:</p> <pre><code>if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three() </code></pre> <p><strong>Method Names and Instance Variables</strong></p> <p>Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.</p> <p><strong>Update:</strong> Per Oscar's request, also listed how his code would look in this fashion.</p>
6
2008-12-01T18:47:23Z
[ "python", "coding-style" ]
Python style
331,767
<p>Simple beginner question:</p> <p>I've created a small python script to toggle between two files I'm using for testing.</p> <p>My question is, what is a good python format style for the following code:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) </code></pre> <p>Or what?</p> <p>Also, what is the preffered way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"</p> <p>Thanks.</p>
3
2008-12-01T18:40:32Z
331,906
<p>The third option looks the most natural to me, although your use of spaces in side parentheses and superfluous parentheses contradict the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">Python style guide</a>.</p> <p>That guide also answers the to_copy question, but I would probably use clearer names altogether.</p> <p>I would write it as:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" destination = r"C:\some\path\file.txt" source = remote if filecmp.cmp(local, destination) else local shutil.copyfile(source, destination) </code></pre>
4
2008-12-01T19:27:54Z
[ "python", "coding-style" ]
Python style
331,767
<p>Simple beginner question:</p> <p>I've created a small python script to toggle between two files I'm using for testing.</p> <p>My question is, what is a good python format style for the following code:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) </code></pre> <p>Or what?</p> <p>Also, what is the preffered way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"</p> <p>Thanks.</p>
3
2008-12-01T18:40:32Z
331,923
<p>What about:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" if filecmp.cmp( local, config_file): to_copy = remote else: to_copy = local shutil.copyfile( to_copy, config_file ) </code></pre> <p>yikes, this open id screen name looks terrible.</p>
0
2008-12-01T19:33:13Z
[ "python", "coding-style" ]
Python style
331,767
<p>Simple beginner question:</p> <p>I've created a small python script to toggle between two files I'm using for testing.</p> <p>My question is, what is a good python format style for the following code:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) </code></pre> <p>Or what?</p> <p>Also, what is the preffered way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"</p> <p>Thanks.</p>
3
2008-12-01T18:40:32Z
332,555
<p>You might find this useful; <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8 -- Style Guide for Python Code</a></p>
1
2008-12-01T23:08:07Z
[ "python", "coding-style" ]
How to determine if a page is being redirected
331,855
<p>I need to check whether a page is being redirected or not without actually downloading the content. I just need the final URL. What's the best way of doing this is Python? Thanks!</p>
4
2008-12-01T19:10:57Z
331,871
<p>When you open the URL with <code>urllib2</code>, and you're redirected, you get a status 30x for redirection. Check the info to see the location to which you're redirected. You don't need to read the page to read the <code>info()</code> that's part of the response.</p>
1
2008-12-01T19:15:49Z
[ "python", "http", "http-headers" ]
How to determine if a page is being redirected
331,855
<p>I need to check whether a page is being redirected or not without actually downloading the content. I just need the final URL. What's the best way of doing this is Python? Thanks!</p>
4
2008-12-01T19:10:57Z
331,890
<p>If you specifically want to avoid downloading the content, you'll need to use the HEAD request method. I believe the <code>urllib</code> and <code>urllib2</code> libraries do not support HEAD requests, so you'll have to use the lower-level <code>httplib</code> library:</p> <pre><code>import httplib h = httplib.HTTPConnection('www.example.com') h.request('HEAD', '/') response = h.getresponse() // Check for 30x status code if 300 &lt;= response.status &lt; 400: // It's a redirect location = response.getheader('Location') </code></pre>
9
2008-12-01T19:23:33Z
[ "python", "http", "http-headers" ]
Converting a PDF to a series of images with Python
331,918
<p>I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images.</p> <p>PIL does not work, as it can't read PDFs. The two options I've found are using either GhostScript or ImageMagick through the shell. This is not a viable option for me, since this program needs to be cross-platform, and I can't be sure either of those programs will be available on the machines it will be installed and used on.</p> <p>Are there any Python libraries out there that can do this?</p>
32
2008-12-01T19:31:07Z
331,924
<p>ImageMagick has <a href="http://www.imagemagick.org/download/python/">Python bindings</a>.</p>
16
2008-12-01T19:33:44Z
[ "python", "pdf", "imagemagick", "jpeg", "python-imaging-library" ]
Converting a PDF to a series of images with Python
331,918
<p>I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images.</p> <p>PIL does not work, as it can't read PDFs. The two options I've found are using either GhostScript or ImageMagick through the shell. This is not a viable option for me, since this program needs to be cross-platform, and I can't be sure either of those programs will be available on the machines it will be installed and used on.</p> <p>Are there any Python libraries out there that can do this?</p>
32
2008-12-01T19:31:07Z
657,704
<p>You can't avoid the Ghostscript dependency. Even Imagemagick relies on Ghostscript for its PDF reading functions. The reason for this is the complexity of the PDF format: a PDF doesn't just contain bitmap information, but mostly vector shapes, transparencies etc. Furthermore it is quite complex to figure out which of these objects appear on which page.</p> <p>So the correct rendering of a PDF Page is clearly out of scope for a pure Python library.</p> <p>The good news is that Ghostscript is pre-installed on many windows and Linux systems, because it is also needed by all those PDF Printers (except Adobe Acrobat).</p>
4
2009-03-18T10:27:39Z
[ "python", "pdf", "imagemagick", "jpeg", "python-imaging-library" ]
Converting a PDF to a series of images with Python
331,918
<p>I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images.</p> <p>PIL does not work, as it can't read PDFs. The two options I've found are using either GhostScript or ImageMagick through the shell. This is not a viable option for me, since this program needs to be cross-platform, and I can't be sure either of those programs will be available on the machines it will be installed and used on.</p> <p>Are there any Python libraries out there that can do this?</p>
32
2008-12-01T19:31:07Z
2,002,186
<p>If you're using linux some versions come with a command line utility called 'pdftopbm' out of the box. Check out <a href="http://en.wikipedia.org/wiki/Netpbm_format" rel="nofollow">netpbm</a></p>
2
2010-01-04T20:58:05Z
[ "python", "pdf", "imagemagick", "jpeg", "python-imaging-library" ]
Converting a PDF to a series of images with Python
331,918
<p>I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images.</p> <p>PIL does not work, as it can't read PDFs. The two options I've found are using either GhostScript or ImageMagick through the shell. This is not a viable option for me, since this program needs to be cross-platform, and I can't be sure either of those programs will be available on the machines it will be installed and used on.</p> <p>Are there any Python libraries out there that can do this?</p>
32
2008-12-01T19:31:07Z
8,497,532
<p>Perhaps relevant: <a href="http://www.swftools.org/gfx_tutorial.html" rel="nofollow">http://www.swftools.org/gfx_tutorial.html</a></p>
2
2011-12-13T23:09:55Z
[ "python", "pdf", "imagemagick", "jpeg", "python-imaging-library" ]
Converting a PDF to a series of images with Python
331,918
<p>I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images.</p> <p>PIL does not work, as it can't read PDFs. The two options I've found are using either GhostScript or ImageMagick through the shell. This is not a viable option for me, since this program needs to be cross-platform, and I can't be sure either of those programs will be available on the machines it will be installed and used on.</p> <p>Are there any Python libraries out there that can do this?</p>
32
2008-12-01T19:31:07Z
36,113,000
<p>Here's whats worked for me using the python ghostscript module (installed by '$ pip install ghostscript'):</p> <pre><code>import ghostscript def pdf2jpeg(pdf_input_path, jpeg_output_path): args = ["pdf2jpeg", # actual value doesn't matter "-dNOPAUSE", "-sDEVICE=jpeg", "-r144", "-sOutputFile=" + jpeg_output_path, pdf_input_path] ghostscript.Ghostscript(*args) </code></pre> <p>I also installed Ghostscript 9.18 on my computer and it probably wouldn't have worked otherwise.</p>
2
2016-03-20T11:13:40Z
[ "python", "pdf", "imagemagick", "jpeg", "python-imaging-library" ]