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
list
Why does setuptools sometimes delete and then re-install the exact same egg?
685,874
<p>I'm trying to install an egg on a computer where an identical egg already exists. Why does it remove the egg and then re-install it? I'm calling easy_install from a script with the options:</p> <pre><code>['-v', '-m', '-f', 'R:/OPTIONS/Stephen/python_eggs', 'mypkg==1.0_r2009_03_12'] </code></pre> <p>While running the easy_install command this was observed:</p> <pre><code>Searching for mypkg==1.0-r2009-03-12 Best match: calyon 1.0-r2009-03-12 Processing calyon-1.0_r2009_03_12-py2.4-win32.egg Removing d:\devtools\python24\lib\site-packages\mypkg-1.0_r2009_03_12-py2.4-win32.egg Copying mypkg-1.0_r2009_03_12-py2.4-win32.egg to d:\devtools\python24\lib\site-packages </code></pre> <p>What causes this? Why is it that some times the egg is removed and re-installed, and on other occasions the egg is preserved? I've seen it happen a few times on my own PC but I'm not sure how to consistently re-produce the behavior.</p> <p>I'm using setuptools 0.6c9</p>
3
2009-03-26T13:47:05Z
691,007
<p>It may show up on the <a href="http://bugs.python.org/setuptools/" rel="nofollow">bug list</a>, otherwise it'd be best to report it.</p>
0
2009-03-27T18:41:41Z
[ "python", "setuptools" ]
Why does setuptools sometimes delete and then re-install the exact same egg?
685,874
<p>I'm trying to install an egg on a computer where an identical egg already exists. Why does it remove the egg and then re-install it? I'm calling easy_install from a script with the options:</p> <pre><code>['-v', '-m', '-f', 'R:/OPTIONS/Stephen/python_eggs', 'mypkg==1.0_r2009_03_12'] </code></pre> <p>While running the easy_install command this was observed:</p> <pre><code>Searching for mypkg==1.0-r2009-03-12 Best match: calyon 1.0-r2009-03-12 Processing calyon-1.0_r2009_03_12-py2.4-win32.egg Removing d:\devtools\python24\lib\site-packages\mypkg-1.0_r2009_03_12-py2.4-win32.egg Copying mypkg-1.0_r2009_03_12-py2.4-win32.egg to d:\devtools\python24\lib\site-packages </code></pre> <p>What causes this? Why is it that some times the egg is removed and re-installed, and on other occasions the egg is preserved? I've seen it happen a few times on my own PC but I'm not sure how to consistently re-produce the behavior.</p> <p>I'm using setuptools 0.6c9</p>
3
2009-03-26T13:47:05Z
703,460
<p>Here is what I am guessing is happening... This is a guess based on your description of the symptoms.</p> <p>Assuming in your example mypkg and calyon are the same, the use of -r2009-03-12 on the end of your is not an expected format for setuptools (the standard format for post release tags is without hyphens YYYYMMDD) so it cannot ensure that the current version is up to date. Check out the links below and make sure you are versioning correctly.</p> <p>Additionally, I believe easy_install manages its version info in the easy-install.pth file. What does your easy-install.pth file say about your package?</p> <p><a href="http://peak.telecommunity.com/DevCenter/setuptools#specifying-your-project-s-version" rel="nofollow">http://peak.telecommunity.com/DevCenter/setuptools#specifying-your-project-s-version</a> <a href="http://peak.telecommunity.com/DevCenter/setuptools#tagging-and-daily-build-or-snapshot-releases" rel="nofollow">http://peak.telecommunity.com/DevCenter/setuptools#tagging-and-daily-build-or-snapshot-releases</a></p>
2
2009-03-31T23:19:16Z
[ "python", "setuptools" ]
URL tree walker in Python?
686,147
<p>For URLs that show file trees, such as <a href="http://pypi.python.org/packages/2.5" rel="nofollow">Pypi packages</a>, is there a small solid module to walk the URL tree and list it like <code>ls -lR</code>?<br /> I gather (correct me) that there's no standard encoding of file attributes, link types, size, date ... in html <code>&lt;A</code> attributes<br /> so building a solid URLtree module on shifting sands is tough.<br /> But surely this wheel (<code>Unix file tree -&gt; html -&gt; treewalk API -&gt; ls -lR or find</code>) has been done?<br /> (There seem to be several spiders / web crawlers / scrapers out there, but they look ugly and ad hoc so far, despite BeautifulSoup for parsing).</p>
3
2009-03-26T14:57:13Z
687,180
<p>Apache servers are very common, and they have a relatively standard way of listing file directories.</p> <p>Here's a simple enough script that does what you want, you should be able to make it do what you want.</p> <p>Usage: python list_apache_dir.py </p> <pre><code>import sys import urllib import re parse_re = re.compile('href="([^"]*)".*(..-...-.... ..:..).*?(\d+[^\s&lt;]*|-)') # look for a link + a timestamp + a size ('-' for dir) def list_apache_dir(url): try: html = urllib.urlopen(url).read() except IOError, e: print 'error fetching %s: %s' % (url, e) return if not url.endswith('/'): url += '/' files = parse_re.findall(html) dirs = [] print url + ' :' print '%4d file' % len(files) + 's' * (len(files) != 1) for name, date, size in files: if size.strip() == '-': size = 'dir' if name.endswith('/'): dirs += [name] print '%5s %s %s' % (size, date, name) for dir in dirs: print list_apache_dir(url + dir) for url in sys.argv[1:]: print list_apache_dir(url) </code></pre>
2
2009-03-26T19:21:33Z
[ "python", "tree", "beautifulsoup", "directory-walk" ]
URL tree walker in Python?
686,147
<p>For URLs that show file trees, such as <a href="http://pypi.python.org/packages/2.5" rel="nofollow">Pypi packages</a>, is there a small solid module to walk the URL tree and list it like <code>ls -lR</code>?<br /> I gather (correct me) that there's no standard encoding of file attributes, link types, size, date ... in html <code>&lt;A</code> attributes<br /> so building a solid URLtree module on shifting sands is tough.<br /> But surely this wheel (<code>Unix file tree -&gt; html -&gt; treewalk API -&gt; ls -lR or find</code>) has been done?<br /> (There seem to be several spiders / web crawlers / scrapers out there, but they look ugly and ad hoc so far, despite BeautifulSoup for parsing).</p>
3
2009-03-26T14:57:13Z
713,088
<p>Turns out that BeautifulSoup one-liners like these can turn &lt;table> rows into Python --</p> <pre><code>from BeautifulSoup import BeautifulSoup def trow_cols( trow ): """ soup.table( "tr" ) -&gt; &lt;td&gt; strings like [None, u'Name', u'Last modified', u'Size', u'Description'] """ return [td.next.string for td in trow( "td" )] def trow_headers( trow ): """ soup.table( "tr" ) -&gt; &lt;th&gt; table header strings like [None, u'Achoo-1.0-py2.5.egg', u'11-Aug-2008 07:40 ', u'8.9K'] """ return [th.next.string for th in trow( "th" )] if __name__ == "__main__": ... soup = BeautifulSoup( html ) if soup.table: trows = soup.table( "tr" ) print "headers:", trow_headers( trows[0] ) for row in trows[1:]: print trow_cols( row ) </code></pre> <p>Compared to sysrqb's one-line regexp above, this is ... longer; who said</p> <blockquote> <p>"You can parse some of the html all of the time, or all of the html some of the time, but not ..."</p> </blockquote>
0
2009-04-03T08:49:42Z
[ "python", "tree", "beautifulsoup", "directory-walk" ]
URL tree walker in Python?
686,147
<p>For URLs that show file trees, such as <a href="http://pypi.python.org/packages/2.5" rel="nofollow">Pypi packages</a>, is there a small solid module to walk the URL tree and list it like <code>ls -lR</code>?<br /> I gather (correct me) that there's no standard encoding of file attributes, link types, size, date ... in html <code>&lt;A</code> attributes<br /> so building a solid URLtree module on shifting sands is tough.<br /> But surely this wheel (<code>Unix file tree -&gt; html -&gt; treewalk API -&gt; ls -lR or find</code>) has been done?<br /> (There seem to be several spiders / web crawlers / scrapers out there, but they look ugly and ad hoc so far, despite BeautifulSoup for parsing).</p>
3
2009-03-26T14:57:13Z
1,223,026
<p>Others have recommended BeautifulSoup, but it's much better to use <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p> <p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/" rel="nofollow">Ian Blicking agrees</a>.</p> <p>There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.</p> <p>It has CSS selectors as well so this sort of thing is trivial.</p>
1
2009-08-03T15:37:12Z
[ "python", "tree", "beautifulsoup", "directory-walk" ]
Writing binary data to a socket (or file) with Python
686,296
<p>Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer that denotes the length of message, then another unsigned byte which is really a bit field with some flags set or unset and etc...</p> <p>How would I do this in python? I'm just wondering how to reliably generate this data and make sure I'm sending it correctly (i.e. that I'm really sending an unsigned byte rather than say a signed integer or worse, a string).</p>
9
2009-03-26T15:33:57Z
686,314
<p>Use the <a href="http://docs.python.org/library/struct.html">struct</a> module to build a buffer and write that.</p>
11
2009-03-26T15:38:37Z
[ "python" ]
Writing binary data to a socket (or file) with Python
686,296
<p>Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer that denotes the length of message, then another unsigned byte which is really a bit field with some flags set or unset and etc...</p> <p>How would I do this in python? I'm just wondering how to reliably generate this data and make sure I'm sending it correctly (i.e. that I'm really sending an unsigned byte rather than say a signed integer or worse, a string).</p>
9
2009-03-26T15:33:57Z
686,366
<p>At the lowest level, socket I/O consists of reading or writing a string of byte values to a socket. To do this, I encode the information to be written as a string of characters containing the byte values, and write it to the socket. I do this by creating a superstring, and then appending one character at a time. for example, to create a Modbus/Ethernet read request:</p> <pre><code> readRequest = """""" readRequest += chr(self.transactionID / 0x100) # Transaction ID MSB (0) readRequest += chr(self.transactionID % 0x100) # Transaction ID LSB (1) readRequest += chr(0) # Protocol ID MSB (Always 0) (2) readRequest += chr(0) # Protocol ID LSB (Always 0) (3) readRequest += chr(0) # Length MSB (Always 0) (4) readRequest += chr(6) # Length LSB (Always 6) (5) readRequest += chr(0) # Unit ID (Always 0) (6) readRequest += chr(0x04) # Function code 4 (0) readRequest += chr(startOffset / 0x100) # Starting offset MSB (1) readRequest += chr(startOffset % 0x100) # Starting offset LSB (2) readRequest += chr(0) # Word count MSB (3) readRequest += chr(2 * nToRead) # Word count LSB (4) sockOutfile.write(readRequest) </code></pre> <p>To convert multibyte values into character strings so they can be appended onto the I/O string, use the 'Pack()' function in the struct module. This function converts one or more single or multiple byte values into a string of individual byte values.</p> <p>Of course, this method is about as simple as a hammer. It will need to be fixed when the default character encoding in a string is Unicode instead of ASCII.</p>
0
2009-03-26T15:52:26Z
[ "python" ]
Writing binary data to a socket (or file) with Python
686,296
<p>Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer that denotes the length of message, then another unsigned byte which is really a bit field with some flags set or unset and etc...</p> <p>How would I do this in python? I'm just wondering how to reliably generate this data and make sure I'm sending it correctly (i.e. that I'm really sending an unsigned byte rather than say a signed integer or worse, a string).</p>
9
2009-03-26T15:33:57Z
686,460
<p>A very elegant way to handle theses transitions between Python objects and a binary representation (both directions) is using the <a href="http://construct.wikispaces.com/" rel="nofollow">Construct library</a>.</p> <p>In their documentation you'll find many nice examples of using it. I've been using it myself for several years now for serial communications protocols and decoding binary data.</p>
4
2009-03-26T16:16:57Z
[ "python" ]
Embed Python script
686,690
<p>I have some Python Scripts which I would like to use from my VB.NET class library however instead of increasing the amount of files that I distribute is it possible to embed the script into my project/dll in Visual Studio and then run the script from the dll during my program runtime?</p> <p>Thanks for any help.</p> <p>Rob</p>
1
2009-03-26T17:01:42Z
686,705
<p><a href="http://docs.python.org/extending/embedding.html" rel="nofollow">Yes, it is possible</a>.</p>
2
2009-03-26T17:06:51Z
[ ".net", "python", "vb.net", "visual-studio", "deployment" ]
Embed Python script
686,690
<p>I have some Python Scripts which I would like to use from my VB.NET class library however instead of increasing the amount of files that I distribute is it possible to embed the script into my project/dll in Visual Studio and then run the script from the dll during my program runtime?</p> <p>Thanks for any help.</p> <p>Rob</p>
1
2009-03-26T17:01:42Z
686,781
<p>I believe you may be <a href="http://www.vb-helper.com/howto%5Fnet%5Fembedded%5Fresources.html" rel="nofollow">looking for this</a>, but I am not sure. This is possible, however.</p> <p>The link above shows you how to add the file/script as an embedded resource. If that isn't what you are after, <a href="http://stackoverflow.com/questions/686690/embed-python-script/686705#686705">vartec's post</a> describes how to embed the python runtime directly.</p>
0
2009-03-26T17:28:15Z
[ ".net", "python", "vb.net", "visual-studio", "deployment" ]
Python: Why can't I modify the current scope within a function using locals()?
686,715
<p>Why does creating/modifying a member of locals() not work within a function?</p> <pre><code>Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; # Here's an example of what I expect to be possible in a function: &gt;&gt;&gt; a = 1 &gt;&gt;&gt; locals()["a"] = 2 &gt;&gt;&gt; print a 2 &gt;&gt;&gt; # ...and here's what actually happens: &gt;&gt;&gt; def foo(): ... b = 3 ... locals()["b"] = 4 ... print b ... &gt;&gt;&gt; foo() 3 </code></pre>
2
2009-03-26T17:10:21Z
686,730
<p>Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the <a href="http://docs.python.org/library/functions.html#locals" rel="nofollow">documentation</a> warns.</p>
7
2009-03-26T17:15:32Z
[ "python", "scope", "introspection" ]
Python: Why can't I modify the current scope within a function using locals()?
686,715
<p>Why does creating/modifying a member of locals() not work within a function?</p> <pre><code>Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; # Here's an example of what I expect to be possible in a function: &gt;&gt;&gt; a = 1 &gt;&gt;&gt; locals()["a"] = 2 &gt;&gt;&gt; print a 2 &gt;&gt;&gt; # ...and here's what actually happens: &gt;&gt;&gt; def foo(): ... b = 3 ... locals()["b"] = 4 ... print b ... &gt;&gt;&gt; foo() 3 </code></pre>
2
2009-03-26T17:10:21Z
686,827
<p>locals() return a copy of the namespace (which is the opposite of what globals() does). This means that any change you perform on the dictionary returned by locals() will have no effect. Check in <a href="http://www.faqs.org/docs/diveintopython/dialect%5Flocals.html" rel="nofollow">dive into python</a> at example 4.12.</p>
3
2009-03-26T17:40:19Z
[ "python", "scope", "introspection" ]
Python, Convert 9 tuple UTC date to MySQL datetime format
686,717
<p>I am parsing RSS feeds with the format as specified here: <a href="http://www.feedparser.org/docs/date-parsing.html">http://www.feedparser.org/docs/date-parsing.html</a></p> <p>date tuple (2009, 3, 23, 13, 6, 34, 0, 82, 0)</p> <p>I am a bit stumped at how to get this into the MySQL datetime format (Y-m-d H:M:S)?</p>
10
2009-03-26T17:10:34Z
686,728
<pre><code>tup = (2009, 3, 23, 13, 6, 34, 0, 82, 0) import datetime d = datetime.datetime(*(tup[0:6])) #two equivalent ways to format it: dStr = d.isoformat(' ') #or dStr = d.strftime('%Y-%m-%d %H:%M:%S') </code></pre>
20
2009-03-26T17:14:59Z
[ "python", "sql", "mysql", "datetime", "tuples" ]
pygame is screwing up ctypes
686,798
<pre><code>import mymodule, ctypes #import pygame foo = ctypes.cdll.MyDll.foo print 'success' </code></pre> <p>if i uncomment the <code>import pygame</code> this fails with <code>WindowsError: [Errno 182] The operating system cannot load %1</code>. the stack frame is in ctypes python code, trying to load MyDll. win32 error code 182 is <code>ERROR_INVALID_ORDINAL</code>. if the pygame import is not there, the script runs successfully.</p> <p>Update: If I run it outside the debugger, the %1 is filled with 'libpng13.dll', which is in the working directory and referenced by MyDll, and pygame is certainly loading some version of libpng. I have no idea how I would resolve this.</p>
1
2009-03-26T17:31:25Z
686,880
<p>This sounds like a dll conflict. It seems that <code>import pygame</code> loads some dll that is not compatible with a dll that <code>MyDll</code> needs. You should try to debug this with sysinternals ProcessExplorer, it can show which dlls a process has loaded; look for different dlls in both cases.</p> <p>Another usefull tool to debug dll problems is the dependencywalker, from <a href="http://www.dependencywalker.com" rel="nofollow">www.dependencywalker.com</a></p>
2
2009-03-26T17:56:51Z
[ "python", "winapi", "pygame", "ctypes" ]
pygame is screwing up ctypes
686,798
<pre><code>import mymodule, ctypes #import pygame foo = ctypes.cdll.MyDll.foo print 'success' </code></pre> <p>if i uncomment the <code>import pygame</code> this fails with <code>WindowsError: [Errno 182] The operating system cannot load %1</code>. the stack frame is in ctypes python code, trying to load MyDll. win32 error code 182 is <code>ERROR_INVALID_ORDINAL</code>. if the pygame import is not there, the script runs successfully.</p> <p>Update: If I run it outside the debugger, the %1 is filled with 'libpng13.dll', which is in the working directory and referenced by MyDll, and pygame is certainly loading some version of libpng. I have no idea how I would resolve this.</p>
1
2009-03-26T17:31:25Z
1,200,582
<p>Update for the record: I believe there were multiple versions of libpng being loaded by different modules (pygame, and mydll). I used multiprocessing to separate the two modules and everything's dandy.</p>
2
2009-07-29T14:17:07Z
[ "python", "winapi", "pygame", "ctypes" ]
Redirecting function definitions in python
686,899
<p>Pointing the class method at the instance method is clearly causing problems: </p> <pre><code>class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() B.__getitem__ = self.a.__getitem__ b1 = B() b1.a['a'] = 5 b2 = B() b2.a['b'] = 10 c = b1['a'] d = b2['b'] </code></pre> <p>Gives this error:</p> <pre><code> File ... in __getitem__ return dict.__getitem__(self, name) KeyError: 'a' </code></pre> <p>What should I be doing here instead?</p>
1
2009-03-26T18:03:08Z
686,961
<p><code>__getitem__</code> only works in the class. You can't override it in a instance basis.</p> <p>This works:</p> <pre><code>class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() def __getitem__(self, item): return self.a[item] b1 = B() b1.a['a'] = 5 b2 = B() b2.a['b'] = 10 c = b1['a'] d = b2['b'] </code></pre> <p>If you want to define it in <code>__init__</code> for some strange reason, you must create a descriptor:</p> <pre><code>def __init__(self): self.a = A() def mygetitem(self, item): return self.a[item] B.__getitem__ = types.MethodType(mygetitem, None, B) </code></pre>
7
2009-03-26T18:13:06Z
[ "python", "class-attributes" ]
How to get the root node of an xml file in Python?
687,177
<p>Basically I am using:</p> <p>from xml.etree import ElementTree as ET</p> <pre><code>path = 'C:\cool.xml' et = ET.parse ( path ) </code></pre> <p>But I am not sure how to get the root from et?</p>
3
2009-03-26T19:19:53Z
687,184
<p>You probably want:</p> <pre><code>et.getroot() </code></pre> <p>Have a look at the official docs for ElementTree from the <a href="http://effbot.org/zone/element-index.htm" rel="nofollow">effbot site</a>. Note that Python 2.5 (the first version of Python to include ElementTree out of the box) uses ElementTree 1.2, not the more recent 1.3. There aren't many differences, but just FYI in case.</p>
10
2009-03-26T19:23:18Z
[ "python", "xml" ]
How to get the root node of an xml file in Python?
687,177
<p>Basically I am using:</p> <p>from xml.etree import ElementTree as ET</p> <pre><code>path = 'C:\cool.xml' et = ET.parse ( path ) </code></pre> <p>But I am not sure how to get the root from et?</p>
3
2009-03-26T19:19:53Z
687,188
<pre><code>root = et.getroot() </code></pre>
2
2009-03-26T19:23:54Z
[ "python", "xml" ]
How to get the root node of an xml file in Python?
687,177
<p>Basically I am using:</p> <p>from xml.etree import ElementTree as ET</p> <pre><code>path = 'C:\cool.xml' et = ET.parse ( path ) </code></pre> <p>But I am not sure how to get the root from et?</p>
3
2009-03-26T19:19:53Z
687,190
<pre><code>root = et.getroot() </code></pre> <p>I would recommend using lxml.etree instead of xml.etree.ElementTree, as lxml is faster and the interface is the same.</p>
4
2009-03-26T19:23:58Z
[ "python", "xml" ]
Is there a function in Python to list the attributes and methods of a particular object?
687,239
<p>Is there a function in Python to list the attributes and methods of a particular object?</p> <p>Something like:</p> <pre><code>ShowAttributes ( myObject ) -&gt; .count -&gt; .size ShowMethods ( myObject ) -&gt; len -&gt; parse </code></pre>
15
2009-03-26T19:34:05Z
687,251
<p>Don't dir() and vars() suit you?</p>
9
2009-03-26T19:35:53Z
[ "python" ]
Is there a function in Python to list the attributes and methods of a particular object?
687,239
<p>Is there a function in Python to list the attributes and methods of a particular object?</p> <p>Something like:</p> <pre><code>ShowAttributes ( myObject ) -&gt; .count -&gt; .size ShowMethods ( myObject ) -&gt; len -&gt; parse </code></pre>
15
2009-03-26T19:34:05Z
687,252
<p>You want to look at the <a href="http://diveintopython.net/power_of_introspection/built_in_functions.html" rel="nofollow"><code>dir()</code></a> function:</p> <pre><code>&gt;&gt;&gt; li = [] &gt;&gt;&gt; dir(li) ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] </code></pre> <blockquote> <p><code>li</code> is a list, so <code>dir(li)</code> returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves. </p> </blockquote> <hr> <p><strong>Edit in response to comment:</strong> </p> <p>No this will show all inherited methods as well. Consider this example:</p> <p><strong>test.py:</strong></p> <pre><code>class Foo: def foo(): pass class Bar(Foo): def bar(): pass </code></pre> <p><strong>Python interpreter:</strong></p> <pre><code>&gt;&gt;&gt; from test import Foo, Bar &gt;&gt;&gt; dir(Foo) ['__doc__', '__module__', 'foo'] &gt;&gt;&gt; dir(Bar) ['__doc__', '__module__', 'bar', 'foo'] </code></pre> <hr> <p><strong>You should note that</strong> <a href="http://docs.python.org/library/functions.html" rel="nofollow">Python's documentation</a> states:</p> <blockquote> <p><strong>Note:</strong> Because <code>dir()</code> is supplied <em>primarily as a convenience for use at an interactive prompt</em>, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, <em>and its detailed behavior may change across releases</em>. For example, metaclass attributes are not in the result list when the argument is a class.</p> </blockquote> <p>Therefore it's not safe to use in your code. Use <code>vars()</code> instead. <code>Vars()</code> doesn't include information about the superclasses, you'd have to collect them yourself.</p> <hr> <p>If you're using <code>dir()</code> to find information in an interactive interpreter, consider the use of <code>help()</code>.</p>
33
2009-03-26T19:36:33Z
[ "python" ]
Is there a function in Python to list the attributes and methods of a particular object?
687,239
<p>Is there a function in Python to list the attributes and methods of a particular object?</p> <p>Something like:</p> <pre><code>ShowAttributes ( myObject ) -&gt; .count -&gt; .size ShowMethods ( myObject ) -&gt; len -&gt; parse </code></pre>
15
2009-03-26T19:34:05Z
687,312
<p>Another way to do this is with the nifty <a href="http://ipython.scipy.org/moin/" rel="nofollow">IPython</a> environment. It lets you tab complete to find all the methods and fields of an object. </p>
1
2009-03-26T19:53:12Z
[ "python" ]
Is there a function in Python to list the attributes and methods of a particular object?
687,239
<p>Is there a function in Python to list the attributes and methods of a particular object?</p> <p>Something like:</p> <pre><code>ShowAttributes ( myObject ) -&gt; .count -&gt; .size ShowMethods ( myObject ) -&gt; len -&gt; parse </code></pre>
15
2009-03-26T19:34:05Z
687,442
<p>and for a more human-readable way, you can use <a href="http://github.com/inky/see/tree/master">see</a>:</p> <pre><code>In [1]: from see import see In [2]: x = "hello world!" In [3]: see(x) Out[3]: [] in + * % &lt; &lt;= == != &gt; &gt;= hash() help() len() repr() str() .capitalize() .center() .count() .decode() .encode() .endswith() .expandtabs() .find() .format() .index() .isalnum() .isalpha() .isdigit() .islower() .isspace() .istitle() .isupper() .join() .ljust() .lower() .lstrip() .partition() .replace() .rfind() .rindex() .rjust() .rpartition() .rsplit() .rstrip() .split() .splitlines() .startswith() .strip() .swapcase() .title() .translate() .upper() .zfill() </code></pre>
7
2009-03-26T20:25:25Z
[ "python" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
687,316
<p>The last bit of code will exclude all objects where x!=5 and a is True. Try this:</p> <pre><code>results = Model.objects.filter(a=False, x=5) </code></pre> <p>Remember, the = sign in the above line is assigning False to the parameter a and the number 5 to the parameter x. It's not checking for equality. Thus, there isn't really any way to use the != symbol in a query call.</p>
6
2009-03-26T19:54:05Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
1,154,977
<p>Maybe <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects">Q objects</a> could be of help for this problem. I've never used them but it seems they can be negated and combined much like normal python expressions.</p> <p>Update: I Just tried it out, it seems to work pretty well:</p> <pre><code>&gt;&gt;&gt; from myapp.models import Entry &gt;&gt;&gt; from django.db.models import Q &gt;&gt;&gt; Entry.objects.filter(~Q(id = 3)) [&lt;Entry: Entry object&gt;, &lt;Entry: Entry object&gt;, &lt;Entry: Entry object&gt;, ...] </code></pre>
372
2009-07-20T17:58:38Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
1,155,013
<p>the <code>field=value</code> syntax in queries is a shorthand for <code>field__exact=value</code>. That is to say that <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id7">Django puts query operators on query fields in the identifiers</a>. Django supports the following operators:</p> <pre><code>exact iexact contains icontains in gt gte lt lte startswith istartswith endswith iendswith range year month day week_day isnull search regex iregex </code></pre> <p>I'm sure by combining these with the Q objects as <a href="http://stackoverflow.com/questions/687295/how-do-i-do-a-not-equal-in-django-queryset-filtering/1154977#1154977">Dave Vogt suggests</a> and using <code>filter()</code> or <code>exclude()</code> as <a href="http://stackoverflow.com/questions/687295/how-do-i-do-a-not-equal-in-django-queryset-filtering/687316#687316">Jason Baker suggests</a> you'll get exactly what you need for just about any possible query.</p>
77
2009-07-20T18:07:02Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
4,139,956
<p>Your query appears to have a double negative, you want to exclude all rows where x is not 5, so in other words you want to include all rows where x IS 5. I believe this will do the trick. </p> <pre><code>results = Model.objects.filter(x=5).exclude(a=true) </code></pre> <p>To answer your specific question, there is no "not equal to" but that's probably because django has both "filter" and "exclude" methods available so you can always just switch the logic round to get the desired result.</p>
342
2010-11-09T23:56:13Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
4,725,256
<p>While with the Models, you can filter with <code>=</code>, <code>__gt</code>, <code>__gte</code>, <code>__lt</code>, <code>__lte</code>, you cannot use <code>ne</code>, <code>!=</code> or <code>&lt;&gt;</code>. However, you can achieve better filtering on using the Q object.</p> <p>You can avoid chaining <code>QuerySet.filter()</code> and <code>QuerySet.exlude()</code>, and use this:</p> <pre><code>from django.db.models import Q object_list = QuerySet.filter(~Q(field='not wanted'), field='wanted') </code></pre>
33
2011-01-18T14:34:16Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
29,227,603
<p>It's easy to create a custom lookup with Django 1.7. There's an <code>__ne</code> lookup example in <a href="https://docs.djangoproject.com/en/1.7/howto/custom-lookups/#a-simple-lookup-example">Django official documentation</a>.</p> <p>You need to create the lookup itself first:</p> <pre><code>from django.db.models import Lookup class NotEqual(Lookup): lookup_name = 'ne' def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return '%s &lt;&gt; %s' % (lhs, rhs), params </code></pre> <p>Then you need to register it:</p> <pre><code>from django.db.models.fields import Field Field.register_lookup(NotEqual) </code></pre> <p>And now you can use the <code>__ne</code> lookup in your queries like this:</p> <pre><code>results = Model.objects.exclude(a=True, x__ne=5) </code></pre>
27
2015-03-24T08:07:27Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
32,778,343
<p>You should use <code>filter</code> and <code>exclude</code> like this</p> <pre><code>results = Model.objects.exclude(a=true).filter(x=5) </code></pre>
9
2015-09-25T08:52:02Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
35,603,223
<p>In <strong>django1.9</strong> you basically have three options.</p> <ol> <li><p>Chain <code>exclude</code> and <code>filter</code> (<a href="https://docs.djangoproject.com/es/1.9/topics/db/queries/#retrieving-specific-objects-with-filters" rel="nofollow">exclude docs</a></p> <pre><code>results = Model.objects.exclude(a=true).filter(x=5) </code></pre></li> <li><p>Use <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#q-objects" rel="nofollow"><code>Q() objects</code></a></p> <pre><code>from django.db.models import Q object_list = QuerySet.filter(~Q(a=True), x=5) </code></pre></li> <li><p>You can write a <a href="https://docs.djangoproject.com/en/1.9/howto/custom-lookups/#a-simple-lookup-example" rel="nofollow">Custom Lookup</a></p> <pre><code>from django.db.models import Lookup from django.db.models.fields import Field @Field.register_lookup class NotEqual(Lookup): lookup_name = 'ne' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return '%s &lt;&gt; %s' % (lhs, rhs), params </code></pre> <p>The <code>register_lookup</code> decorator was added in <code>django1.8</code> Now you can use the custom lookup like any normal lookup:</p> <pre><code>results = Model.objects.exclude(a=True, x__ne=5) </code></pre></li> </ol>
8
2016-02-24T13:12:47Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
36,764,306
<h1>Pending design decision. Meanwhile, use <code>exclude()</code></h1> <p>The Django issue tracker has the remarkable <a href="https://code.djangoproject.com/ticket/5763">entry #5763</a>, titled <em>"Queryset doesn't have a "not equal" filter operator"</em>. It is remarkable because (as of April 2016) it was "opened 9 years ago" (in the Django stone age), "closed 4 years ago", and "last changed 5 months ago".</p> <p>Read through the discussion, it is interesting. Basically, some people argue <code>__ne</code> should be added while others say <code>exclude()</code> is clearer and hence <code>__ne</code> should <em>not</em> be added.</p> <p>(I agree with the former, because the latter argument is roughly equivalent to saying Python should not have <code>!=</code> because it has <code>==</code> and <code>not</code> already...)</p>
5
2016-04-21T08:44:38Z
[ "python", "django", "django-models", "django-queryset" ]
How do I do a not equal in Django queryset filtering?
687,295
<p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparitive values, but is there a <code>__ne</code>/<code>!=</code>/<code>&lt;&gt;</code> (<strong>not equals</strong>?)</p> <p>I want to filter out using a not equals:</p> <p>Example:</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want</p> <pre><code>results = Model.objects.exclude(a=true, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I tried <code>__ne</code>, <code>&lt;&gt;</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) </code></pre>
348
2009-03-26T19:47:45Z
38,054,461
<p>What you are looking for are all objects that have either <code>a=false</code> <strong>or</strong> <code>x=5</code>. In Django, <code>|</code> serves as <code>OR</code> operator between querysets:</p> <pre><code>results = Model.objects.filter(a=false)|Model.objects.filter(x=5) </code></pre>
1
2016-06-27T12:50:58Z
[ "python", "django", "django-models", "django-queryset" ]
How to set up Python for .NET with Python 2.6.1?
687,487
<p>The "final" release of Python for .NET (<a href="http://sourceforge.net/project/showfiles.php?group%5Fid=162464&amp;package%5Fid=183296&amp;release%5Fid=537499" rel="nofollow" title="link">link</a>) isn't pre-compiled for Python 2.6. I don't have a problem changing the compilation symbol to PYTHON26 as specified in the docs, the solution rebuilds just fine, but when attempting to import the CLR, I get an error indicating that python26.dll is missing. Anyone know how to build this file? It doesn't seem to be part of the solution, but I might be missing something obvious.</p>
0
2009-03-26T20:39:57Z
687,738
<p>I managed it by following <a href="http://feihonghsu.blogspot.com/2008/02/installing-pythonnet-20-alpha-2-on.html" rel="nofollow">these instructions</a> by one Feihong Hsu.</p> <p>I notice now that the author has made a <a href="http://feihonghsu.blogspot.com/search/label/python.net" rel="nofollow">follow-up post</a> that may be important too if you're using SP1.</p>
3
2009-03-26T22:01:32Z
[ "python" ]
Python game programming: is my IO object a legitimate candidate for being a global variable?
687,703
<p>I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating the position of the player, showing a special effect caused by an in-game action), so my question is this:</p> <p>Does it make sense for a reference to the IO object to be available globally?</p> <p>The alternative is passing a reference to the IO object into the <code>__init__()</code> of every object that needs to use it. I understand that this is good from a testing point of view, but is this worth the resulting "function signature pollution"?</p> <p>Thanks.</p>
5
2009-03-26T21:52:07Z
687,777
<p>Yes, this is a legitimate use of a global variable. If you'd rather not, passing around a context object that is equivalent to this global is another option, as you mentioned.</p> <p>Since I assume you're using multiple files (modules), why not do something like:</p> <pre><code>import io io.print('hello, world') io.clear() </code></pre> <p>This is a common way programs that have more complex I/O needs than simple printing do things like logging.</p>
9
2009-03-26T22:20:35Z
[ "python", "io", "global-variables" ]
Python game programming: is my IO object a legitimate candidate for being a global variable?
687,703
<p>I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating the position of the player, showing a special effect caused by an in-game action), so my question is this:</p> <p>Does it make sense for a reference to the IO object to be available globally?</p> <p>The alternative is passing a reference to the IO object into the <code>__init__()</code> of every object that needs to use it. I understand that this is good from a testing point of view, but is this worth the resulting "function signature pollution"?</p> <p>Thanks.</p>
5
2009-03-26T21:52:07Z
687,782
<p>Yes, I think so.</p> <p>Another possibility would be to create a module <code>loggerModule</code> that has functions like <code>print()</code> and <code>write()</code>, but this would only marginally be better.</p>
1
2009-03-26T22:22:16Z
[ "python", "io", "global-variables" ]
Python game programming: is my IO object a legitimate candidate for being a global variable?
687,703
<p>I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating the position of the player, showing a special effect caused by an in-game action), so my question is this:</p> <p>Does it make sense for a reference to the IO object to be available globally?</p> <p>The alternative is passing a reference to the IO object into the <code>__init__()</code> of every object that needs to use it. I understand that this is good from a testing point of view, but is this worth the resulting "function signature pollution"?</p> <p>Thanks.</p>
5
2009-03-26T21:52:07Z
687,855
<p>Nope.</p> <p>Variables are too specific to be passed around in the global namespace. Hide them inside static functions/classes instead that can do magic things to them at run time (or call other ones entirely).</p> <p>Consider what happens if the IO can periodically change state or if it needs to block for a while (like many sockets do). </p> <p>Consider what happens if the same block of code is included multiple times. Does the variable instance get duplicated as well?</p> <p>Consider what happens if you want to have a version 2 of the same variable. What if you want to change its interface? Do you have to modify all the code that references it?</p> <p>Does it really make sense to infect all the code that uses the variable with knowledge of all the ways it can go bad? </p>
0
2009-03-26T22:50:02Z
[ "python", "io", "global-variables" ]
How to get upper paths from a single path?
687,863
<p>How to get upper paths from a single path?</p> <p>So say you have a path like:</p> <pre><code>'C:\a\b\c\d\' </code></pre> <p>How do I get to <code>'C:\a\b'</code> or <code>'C:\a\b\c'</code></p> <p>Is there a pythonic way to do this?</p>
1
2009-03-26T22:52:38Z
687,871
<p>See <a href="http://docs.python.org/library/os.path.html" rel="nofollow"><code>os.path</code></a></p> <pre><code>from os import path path.dirname("C:\\a\\b\\c\\d\\") </code></pre>
10
2009-03-26T22:56:15Z
[ "python", "directory" ]
How to get upper paths from a single path?
687,863
<p>How to get upper paths from a single path?</p> <p>So say you have a path like:</p> <pre><code>'C:\a\b\c\d\' </code></pre> <p>How do I get to <code>'C:\a\b'</code> or <code>'C:\a\b\c'</code></p> <p>Is there a pythonic way to do this?</p>
1
2009-03-26T22:52:38Z
687,873
<p>Theres basic stuff like <a href="http://docs.python.org/library/os.path.html" rel="nofollow">os.path</a> methods. </p> <p>If you want a list of the full path names of each successive parent in the directory tree, heres a one liner:</p> <pre><code>from os.path import dirname def f1(n): return [n] if n == dirname(n) else [n] + f1(dirname(n)) print f1("/a/b/c/d/e/f/g") </code></pre>
4
2009-03-26T22:56:45Z
[ "python", "directory" ]
How to get upper paths from a single path?
687,863
<p>How to get upper paths from a single path?</p> <p>So say you have a path like:</p> <pre><code>'C:\a\b\c\d\' </code></pre> <p>How do I get to <code>'C:\a\b'</code> or <code>'C:\a\b\c'</code></p> <p>Is there a pythonic way to do this?</p>
1
2009-03-26T22:52:38Z
687,886
<p><code>os.path.split("C:\\a\\b\\c")</code> will return a tuple:</p> <pre><code>('C:\a\b', 'c') </code></pre> <p>You can continue to call split on the first element of the tuple.</p>
2
2009-03-26T23:03:06Z
[ "python", "directory" ]
How to get upper paths from a single path?
687,863
<p>How to get upper paths from a single path?</p> <p>So say you have a path like:</p> <pre><code>'C:\a\b\c\d\' </code></pre> <p>How do I get to <code>'C:\a\b'</code> or <code>'C:\a\b\c'</code></p> <p>Is there a pythonic way to do this?</p>
1
2009-03-26T22:52:38Z
687,888
<pre><code>&gt;&gt;&gt; def go_up(path, n): ... return os.path.abspath(os.path.join(*([path] + ['..']*n))) &gt;&gt;&gt; path = 'C:\\a\\b\\c\\d\\' &gt;&gt;&gt; go_up(path, 2) 'C:\\a\\b' &gt;&gt;&gt; go_up(path, 1) 'C:\\a\\b\\c' &gt;&gt;&gt; go_up(path, 0) 'C:\\a\\b\\c\\d' </code></pre> <p>Not being a regular user of <a href="http://docs.python.org/library/os.path.html" rel="nofollow">os.path</a>, I don't know if this is an appropriate/pythonic solution. I compared it to an alternate function, define as follows:</p> <pre><code>def go_up_2(path, n): for i in xrange(n): path = os.path.split(path)[0] return path </code></pre> <p>The first thing to note is that <code>go_up_2('C:\\a\\b\\', 1) != go_up_2('c:\\a\\b', 1)</code>, where it does with the original <code>go_up</code>. However, performance is significantly better, if that is an issue (probably not, but I was looking for some definitive way to say my own algorithm was better):</p> <pre><code>import timeit g1 = """import os.path import ntpath os.path = ntpath def go_up(path, n): return os.path.abspath(os.path.join(*([path] + ['..']*n)))""" g2 = """import os.path import ntpath os.path = ntpath def go_up(path, n): for i in xrange(n-1): path = os.path.split(path)[0] return path""" t1 = timeit.Timer("go_up('C:\\a\\b\\c\\d', 3)", setup=g1).timeit() t2 = timeit.Timer("go_up('C:\\a\\b\\c\\d', 3)", setup=g2).timeit() print t1 print t2 </code></pre> <p>This outputs (on my machine):</p> <pre><code>133.364659071 30.101334095 </code></pre> <p>Not very useful information, but I was playing around, and figured it should be posted here anyway.</p>
2
2009-03-26T23:04:59Z
[ "python", "directory" ]
Is there a better Python bundle for textmate than the one in the bundle repository?
688,245
<p>At this time Textmate's official Python bundle is really bare bones, especially in comparison to the Ruby bundle. Does anyone know of a Python bundle that is more complete?</p> <p>EDIT:</p> <p>I am fully aware that there are editors and environments that are better suited to Python development, but I am really just interested to see if there is a third party Textmate bundle available.</p>
17
2009-03-27T01:57:33Z
688,266
<p>I use <a href="http://www.activestate.com/komodo%5Fedit/" rel="nofollow">Komodo Edit</a> and <a href="http://www.barebones.com/" rel="nofollow">BBEdit</a> for MacOS development.</p> <ol> <li><p>They handle Python whitespace perfectly.</p></li> <li><p>It's easy to roll my own snippets and components in either tool.</p></li> <li><p>They are really good editors for Python.</p></li> </ol> <p>But I don't want to discuss these things.</p>
-17
2009-03-27T02:02:51Z
[ "python", "textmate", "textmatebundles" ]
Is there a better Python bundle for textmate than the one in the bundle repository?
688,245
<p>At this time Textmate's official Python bundle is really bare bones, especially in comparison to the Ruby bundle. Does anyone know of a Python bundle that is more complete?</p> <p>EDIT:</p> <p>I am fully aware that there are editors and environments that are better suited to Python development, but I am really just interested to see if there is a third party Textmate bundle available.</p>
17
2009-03-27T01:57:33Z
2,353,554
<p>I took a look and noticed that there has been a lot of work on Python-related bundles recently. Also, it seems I missed the memo on the best <a href="http://al3x.net/2008/12/03/how-i-use-textmate.html">new way</a> to get bundles:</p> <p><a href="http://solutions.treypiepmeier.com/2009/02/25/installing-getbundles-on-a-fresh-copy-of-textmate/">Install GetBundles</a></p>
8
2010-03-01T02:20:14Z
[ "python", "textmate", "textmatebundles" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
688,311
<p>try python <a href="http://docs.python.org/howto/curses.html">curses</a> module , it is a command-line graphic operation library.</p>
18
2009-03-27T02:28:44Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
688,312
<p>Take a look at <a href="http://docs.python.org/howto/curses.html" rel="nofollow">Curses Programming in Python</a> and <a href="http://docs.python.org/library/curses.html" rel="nofollow">this</a> as well. </p>
9
2009-03-27T02:29:02Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
688,313
<p>Well, what do you mean by a GUI? If you just want to create something that can be used on a console, look into the <code>curses</code> module in the Python standard library, which allows you to simulate a primitive GUI of sorts on a console.</p>
1
2009-03-27T02:29:11Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
688,315
<p>Curses type libraries and resources will get you into the textual user interfaces, and provide very nice, relatively easy to use windows, menus, editors, etc.</p> <p>Then you'll want to look into code highlighting modules for python.</p> <p>It's a fun process dealing with the limitations of textual interfaces, and you can learn a lot by going down this road. Good luck!</p>
5
2009-03-27T02:30:29Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
688,348
<p>I would recommend the excellent urwid toolkit (<a href="http://excess.org/article/2009/03/urwid-0984-released" rel="nofollow">http://excess.org/article/2009/03/urwid-0984-released</a>) - it's much easier to use than straight curses.</p>
3
2009-03-27T02:47:34Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
688,353
<p>Another option if you want to write a TUI (Text User Interface) without having to descend to curses is <a href="http://www.wanware.com/tsgdocs/snack.html">Snack</a>, which comes with <a href="https://fedorahosted.org/newt/">Newt</a>.</p>
5
2009-03-27T02:48:04Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
688,382
<p>A not very serious suggestions: a <a href="http://en.wikipedia.org/wiki/Line_editor" rel="nofollow">line editor</a> can be implemented without curses.</p> <p>These things are pretty primitive, of course, and not a lot of fun to work in. But they can be implemented with very little code, and would give you a chance to fool around with various schemes for maintaining the file state in memory pretty quickly.</p> <p>And they would put you in touch with the programmers of the early seventies (when they had teletypes and the first glass teletypes, but after punched cards were a bit passe...).</p>
2
2009-03-27T03:00:06Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
688,502
<p>Not quite a reference to a Python library, but <a href="http://www.finseth.com/craft/" rel="nofollow">The Craft of Text Editing</a> by Craig A. Finseth might be of interest you.</p>
2
2009-03-27T03:59:25Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
689,366
<p>Kids today! Sheesh! When I was starting out, curses was not in widespread use!</p> <p>My first text editors worked on actual mechanical Teletype devices with actual paper (not a philosophical "TTY" device with a scrolling screen!)</p> <p>This still works nicely as a way to edit. </p> <p>Use the <code>cmd</code> module to implement a bunch of commands. Use the 'ex' man page for hints as to what you need. Do not read about the vi commands; avoid reading about vim. </p> <p>Look at older man pages for just the "EX COMMANDS" section. For example, here: <a href="http://www.manpagez.com/man/1/ex/" rel="nofollow">http://www.manpagez.com/man/1/ex/</a>.</p> <p>Implement the append, add, change, delete, global, insert, join, list, move, print, quit, substitute and write commands and you'll be happy.</p>
6
2009-03-27T11:20:17Z
[ "python", "text-editor", "tui" ]
How do I make a command line text editor?
688,302
<p>I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?</p>
15
2009-03-27T02:19:14Z
918,786
<p>Another option without curses is <a href="http://code.google.com/p/python-slang/" rel="nofollow">Python Slang</a></p> <p><a href="http://en.wikipedia.org/wiki/Newt%5F%28programming%5Flibrary)" rel="nofollow">Newt</a> is written on top of slang.</p>
0
2009-05-28T01:26:35Z
[ "python", "text-editor", "tui" ]
Reading and Grouping a List of Data in Python
688,461
<p>I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following</p> <pre><code>&lt;1x&gt;begins &lt;2x&gt;value-1 &lt;3x&gt;value-2 &lt;4x&gt;value-3 some indeterminate number of other values &lt;1y&gt;next observation begins &lt;2y&gt;value-1 &lt;3y&gt;value-2 &lt;4y&gt;value-3 some indeterminate number of other values </code></pre> <p>this continues for an indeterminate number of times in each sublist</p> <p>EDIT I need to get all the occurrences of &lt;2,&lt;3 &amp; &lt;4 separated out and grouped together I am creating a new list of lists [[&lt;2x>value-1,&lt;3x>value-2, &lt;4x>value-3], [&lt;2y>value-1, &lt;3y>value-2, &lt;4y>value-3]]</p> <p>EDIT all of the lines that follow &lt;4x> and &lt;4y> (and for that matter &lt;4anyalpha> have the same type of coding and I don't know a-priori how high the numbers can go-just think of these as sgml tags that are not closed I used numbers because my fingers were hurting from all the coding I have been doing today. </p> <p>The solution I have come up with finally is not very pretty</p> <pre><code> listINeed=[] for sublist in biglist: for line in sublist: if '&lt;2' in line: var2=line if '&lt;3' in line: var3=line if '&lt;4' in line: var4=line templist=[] templist.append(var2) templist.append(var3) templist.append(var4) listIneed.append(templist) templist=[] var4=var2=var3='' </code></pre> <p>I have looked at ways to try to clean this up but have not been successful. This works fine I just saw this as another opportunity to learn more about python because I would think that this should be processable by a one line function. </p>
0
2009-03-27T03:45:46Z
688,474
<p>You're off to a good start by noticing that your original solution may work but lacks elegance. </p> <p>You should parse the string in a loop, creating a new variable for each line. Here's some sample code: </p> <pre><code>import re s = """&lt;1x&gt;begins &lt;2x&gt;value-1 &lt;3x&gt;value-2 &lt;4x&gt;value-3 some indeterminate number of other values &lt;1y&gt;next observation begins &lt;2y&gt;value-1 &lt;3y&gt;value-2 &lt;4y&gt;value-3""" firstMatch = re.compile('^\&lt;1x') numMatch = re.compile('^\&lt;(\d+)') listIneed = [] templist = None for line in s.split(): if firstMatch.match(line): if templist is not None: listIneed.append(templist) templist = [line] elif numMatch.match(line): #print 'The matching number is %s' % numMatch.match(line).groups(1) templist.append(line) if templist is not None: listIneed.append(templist) print listIneed </code></pre>
1
2009-03-27T03:49:53Z
[ "python", "list" ]
Reading and Grouping a List of Data in Python
688,461
<p>I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following</p> <pre><code>&lt;1x&gt;begins &lt;2x&gt;value-1 &lt;3x&gt;value-2 &lt;4x&gt;value-3 some indeterminate number of other values &lt;1y&gt;next observation begins &lt;2y&gt;value-1 &lt;3y&gt;value-2 &lt;4y&gt;value-3 some indeterminate number of other values </code></pre> <p>this continues for an indeterminate number of times in each sublist</p> <p>EDIT I need to get all the occurrences of &lt;2,&lt;3 &amp; &lt;4 separated out and grouped together I am creating a new list of lists [[&lt;2x>value-1,&lt;3x>value-2, &lt;4x>value-3], [&lt;2y>value-1, &lt;3y>value-2, &lt;4y>value-3]]</p> <p>EDIT all of the lines that follow &lt;4x> and &lt;4y> (and for that matter &lt;4anyalpha> have the same type of coding and I don't know a-priori how high the numbers can go-just think of these as sgml tags that are not closed I used numbers because my fingers were hurting from all the coding I have been doing today. </p> <p>The solution I have come up with finally is not very pretty</p> <pre><code> listINeed=[] for sublist in biglist: for line in sublist: if '&lt;2' in line: var2=line if '&lt;3' in line: var3=line if '&lt;4' in line: var4=line templist=[] templist.append(var2) templist.append(var3) templist.append(var4) listIneed.append(templist) templist=[] var4=var2=var3='' </code></pre> <p>I have looked at ways to try to clean this up but have not been successful. This works fine I just saw this as another opportunity to learn more about python because I would think that this should be processable by a one line function. </p>
0
2009-03-27T03:45:46Z
688,478
<p>If you want to pick out the second, third, and fourth elements of each sublist, this should work:</p> <pre><code>listINeed = [sublist[1:4] for sublist in biglist] </code></pre>
1
2009-03-27T03:50:57Z
[ "python", "list" ]
Reading and Grouping a List of Data in Python
688,461
<p>I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following</p> <pre><code>&lt;1x&gt;begins &lt;2x&gt;value-1 &lt;3x&gt;value-2 &lt;4x&gt;value-3 some indeterminate number of other values &lt;1y&gt;next observation begins &lt;2y&gt;value-1 &lt;3y&gt;value-2 &lt;4y&gt;value-3 some indeterminate number of other values </code></pre> <p>this continues for an indeterminate number of times in each sublist</p> <p>EDIT I need to get all the occurrences of &lt;2,&lt;3 &amp; &lt;4 separated out and grouped together I am creating a new list of lists [[&lt;2x>value-1,&lt;3x>value-2, &lt;4x>value-3], [&lt;2y>value-1, &lt;3y>value-2, &lt;4y>value-3]]</p> <p>EDIT all of the lines that follow &lt;4x> and &lt;4y> (and for that matter &lt;4anyalpha> have the same type of coding and I don't know a-priori how high the numbers can go-just think of these as sgml tags that are not closed I used numbers because my fingers were hurting from all the coding I have been doing today. </p> <p>The solution I have come up with finally is not very pretty</p> <pre><code> listINeed=[] for sublist in biglist: for line in sublist: if '&lt;2' in line: var2=line if '&lt;3' in line: var3=line if '&lt;4' in line: var4=line templist=[] templist.append(var2) templist.append(var3) templist.append(var4) listIneed.append(templist) templist=[] var4=var2=var3='' </code></pre> <p>I have looked at ways to try to clean this up but have not been successful. This works fine I just saw this as another opportunity to learn more about python because I would think that this should be processable by a one line function. </p>
0
2009-03-27T03:45:46Z
688,492
<p><a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow">itertools.groupby()</a> can get you by.</p> <pre><code>itertools.groupby(biglist, operator.itemgetter(2)) </code></pre>
1
2009-03-27T03:56:19Z
[ "python", "list" ]
Reading and Grouping a List of Data in Python
688,461
<p>I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following</p> <pre><code>&lt;1x&gt;begins &lt;2x&gt;value-1 &lt;3x&gt;value-2 &lt;4x&gt;value-3 some indeterminate number of other values &lt;1y&gt;next observation begins &lt;2y&gt;value-1 &lt;3y&gt;value-2 &lt;4y&gt;value-3 some indeterminate number of other values </code></pre> <p>this continues for an indeterminate number of times in each sublist</p> <p>EDIT I need to get all the occurrences of &lt;2,&lt;3 &amp; &lt;4 separated out and grouped together I am creating a new list of lists [[&lt;2x>value-1,&lt;3x>value-2, &lt;4x>value-3], [&lt;2y>value-1, &lt;3y>value-2, &lt;4y>value-3]]</p> <p>EDIT all of the lines that follow &lt;4x> and &lt;4y> (and for that matter &lt;4anyalpha> have the same type of coding and I don't know a-priori how high the numbers can go-just think of these as sgml tags that are not closed I used numbers because my fingers were hurting from all the coding I have been doing today. </p> <p>The solution I have come up with finally is not very pretty</p> <pre><code> listINeed=[] for sublist in biglist: for line in sublist: if '&lt;2' in line: var2=line if '&lt;3' in line: var3=line if '&lt;4' in line: var4=line templist=[] templist.append(var2) templist.append(var3) templist.append(var4) listIneed.append(templist) templist=[] var4=var2=var3='' </code></pre> <p>I have looked at ways to try to clean this up but have not been successful. This works fine I just saw this as another opportunity to learn more about python because I would think that this should be processable by a one line function. </p>
0
2009-03-27T03:45:46Z
689,779
<p>If I've understood your question correctly:</p> <pre><code>import re def getlines(ori): matches = re.finditer(r'(&lt;([1-4])[a-zA-Z]&gt;.*)', ori) mainlist = [] sublist = [] for sr in matches: if int(sr.groups()[1]) == 1: if sublist != []: mainlist.append(sublist) sublist = [] else: sublist.append(sr.groups()[0]) else: mainlist.append(sublist) return mainlist </code></pre> <p>...would do the job for you, if you felt like using regular expressions.</p> <p>The version below would break all of the data down into sublists (not just the first four in each grouping) which might be more useful depending what else you need to do to the data. Use David's listINeed = [sublist[1:4] for sublist in biglist] to get the first four results from each list for the specific task above.</p> <pre><code>import re def getlines(ori): matches = re.finditer(r'(&lt;(\d*)[a-zA-Z]&gt;.*)', ori) mainlist = [] sublist = [] for sr in matches: if int(sr.groups()[1]) == 1: print "1 found!" if sublist != []: mainlist.append(sublist) sublist = [] else: sublist.append(sr.groups()[0]) else: mainlist.append(sublist) return mainlist </code></pre>
0
2009-03-27T13:33:48Z
[ "python", "list" ]
How to Make sure the code is still working after refactoring ( Dynamic language)
688,740
<p>How to make sure that code is still working after refactoring ( i.e, after variable name change)?</p> <p>In static language, if a class is renamed but other referring class is not, then I will get a compilation error. </p> <p>But in dynamic language there is no such safety net, and your code can break during refactoring <strong>if you are not careful enough</strong>. You can use unit test, but when you are using mocks it's pretty hard to know the name changes and as a consequence, it may not help.</p> <p>How to solve this problem?</p>
7
2009-03-27T06:36:30Z
688,756
<p>Before you start refactoring you should create tests that will be able to test what you're going to change - if you say unit tests will not be enought, or they will be hard to create, then by all means create higher level tests possibly even excersising the whole of your product. </p> <p>If you have code coverage tools for your language use them to measure the quality of the tests that you've created - after it's reached a reasonably high value and if the tests are kept up to date and extended you'll be able to do anything with your code very efficiently and be rather sure things are not going in the wrong direction.</p>
17
2009-03-27T06:46:53Z
[ "php", "python", "dynamic-languages" ]
How to Make sure the code is still working after refactoring ( Dynamic language)
688,740
<p>How to make sure that code is still working after refactoring ( i.e, after variable name change)?</p> <p>In static language, if a class is renamed but other referring class is not, then I will get a compilation error. </p> <p>But in dynamic language there is no such safety net, and your code can break during refactoring <strong>if you are not careful enough</strong>. You can use unit test, but when you are using mocks it's pretty hard to know the name changes and as a consequence, it may not help.</p> <p>How to solve this problem?</p>
7
2009-03-27T06:36:30Z
688,770
<p>Your code can break during refactoring even with a compiled language. Relying on that alone will get you into trouble. Automated testing is the best way to be sure that the program works as it should.</p> <p>If you say what dynamic language you are using we can maybe offer some advice on tools that can help you with testing. Everything can be tested.</p> <p><strong>EDIT:</strong></p> <p>You responded and said you use PHP and Python.</p> <p>If this is a web app use <a href="http://seleniumhq.org/" rel="nofollow">selenium</a> to create the tests in the browser. At first you just need Selenium IDE. Put all your tests in a single Test Suite so that you can easily execute them all. As the list grows you can start looking into Selenium RC and Selenium Grid.</p>
1
2009-03-27T06:54:25Z
[ "php", "python", "dynamic-languages" ]
How to Make sure the code is still working after refactoring ( Dynamic language)
688,740
<p>How to make sure that code is still working after refactoring ( i.e, after variable name change)?</p> <p>In static language, if a class is renamed but other referring class is not, then I will get a compilation error. </p> <p>But in dynamic language there is no such safety net, and your code can break during refactoring <strong>if you are not careful enough</strong>. You can use unit test, but when you are using mocks it's pretty hard to know the name changes and as a consequence, it may not help.</p> <p>How to solve this problem?</p>
7
2009-03-27T06:36:30Z
688,771
<p>I've been teaching a class on unit tests, refactoring and so forth, and this is probably the thing that most people get wrong. Refactoring is <em>not</em> just changing the code. It is changing the code without changing the external functional behavior. That is a very important point. </p> <p>In other words, you need to have some way to verify that the external functional behavior is intact after the refactoring. Lacking divine insight I find unit tests very useful for that. In his book on Refactoring, Martin Fowler stresses the use of automated tests for this verification.</p> <p>If your code was developed using TDD you will have the necessary test suite as it is developed during the development of the code itself. If you need to refactor code for which no tests are available, your best approach would be to set up automated tests before you make any changes to the code. I realize that setting up tests for existing code can be hard, but you will learn a lot about the code while doing so.</p> <p>You may also want to check <a href="http://www.mindview.net/WebLog/log-0025" rel="nofollow">Bruce Eckel's essay on strong typing versus strong testing</a> as it discusses the feedback you get from the compiler versus the feedback you get from your test suite. </p>
10
2009-03-27T06:55:07Z
[ "php", "python", "dynamic-languages" ]
How to Make sure the code is still working after refactoring ( Dynamic language)
688,740
<p>How to make sure that code is still working after refactoring ( i.e, after variable name change)?</p> <p>In static language, if a class is renamed but other referring class is not, then I will get a compilation error. </p> <p>But in dynamic language there is no such safety net, and your code can break during refactoring <strong>if you are not careful enough</strong>. You can use unit test, but when you are using mocks it's pretty hard to know the name changes and as a consequence, it may not help.</p> <p>How to solve this problem?</p>
7
2009-03-27T06:36:30Z
1,813,232
<p>1) For Python use PyUnit for PHP phpunit. 2) TDD approach is good but also making tests after writing code is acceptable. 3) Also use refactoring tools that are available for Your IDE they do only safe refactorings. In Python You have rope (this is library but have plugins for most IDEs). 4) Good books are: 'Test-Driven Development by example' Best 'Expert Python Programing' Tarek Ziade (explain both TDD and refactoring)</p> <p>google tdd and database to find a good book about TDD approach for developing databases.</p> <p>Add info for mocks you are using. AFAIK mocks are needed only when database or network is involved. But normally unit test should cover small pice of code (one class only) sometimes two classes so no mockup needed !!</p>
0
2009-11-28T18:02:38Z
[ "php", "python", "dynamic-languages" ]
Getting 401 on Twitter OAuth POST requests
688,766
<p>I am trying to use Twitter OAuth and my <code>POST</code> requests are failing with a <code>401</code> (<code>Invalid OAuth Request</code>) error.</p> <p>For example, if I want to post a new status update, I am sending a HTTP <code>POST</code> request to <code>https://twitter.com/statuses/update.json</code> with the following parameters - </p> <pre><code>status=Testing&amp;oauth_version=1.0&amp;oauth_token=xxx&amp; oauth_nonce=xxx&amp;oauth_timestamp=xxx&amp;oauth_signature=xxx&amp; oauth_consumer_key=xxx&amp;in_reply_to=xxx&amp;oauth_signature_method=HMAC-SHA1` </code></pre> <p>My <code>GET</code> requests are all working fine. I can see on the mailing lists that a lot of people have had identical problems but I could not find a solution anywhere.</p> <p>I am using the <code>oauth.py</code> Python library.</p>
6
2009-03-27T06:52:35Z
753,343
<p>Most likely, the signature is invalid. You must follow the OAuth spec on how to generate the signature( normalized parameters, URLencoding, and cosumerSecret&amp;oauthScret. More on this later ......</p>
-7
2009-04-15T19:34:02Z
[ "python", "web-services", "twitter", "rest", "oauth" ]
Getting 401 on Twitter OAuth POST requests
688,766
<p>I am trying to use Twitter OAuth and my <code>POST</code> requests are failing with a <code>401</code> (<code>Invalid OAuth Request</code>) error.</p> <p>For example, if I want to post a new status update, I am sending a HTTP <code>POST</code> request to <code>https://twitter.com/statuses/update.json</code> with the following parameters - </p> <pre><code>status=Testing&amp;oauth_version=1.0&amp;oauth_token=xxx&amp; oauth_nonce=xxx&amp;oauth_timestamp=xxx&amp;oauth_signature=xxx&amp; oauth_consumer_key=xxx&amp;in_reply_to=xxx&amp;oauth_signature_method=HMAC-SHA1` </code></pre> <p>My <code>GET</code> requests are all working fine. I can see on the mailing lists that a lot of people have had identical problems but I could not find a solution anywhere.</p> <p>I am using the <code>oauth.py</code> Python library.</p>
6
2009-03-27T06:52:35Z
759,111
<p>I just finished implementing twitter OAuth API from scratch using Java. Get and post requests work OK. You can use this page <a href="http://www.hueniverse.com/hueniverse/2008/10/beginners-gui-1.html" rel="nofollow">http://www.hueniverse.com/hueniverse/2008/10/beginners-gui-1.html</a> to check signature and HTTP headers. Just enter your keys and tokens and check output. It seems twitter works exactly as described on this post. Be careful with spaces and UTF-8 symbols, for example Java encodes space as "+" but OAuth requires %20</p>
4
2009-04-17T05:14:54Z
[ "python", "web-services", "twitter", "rest", "oauth" ]
Getting 401 on Twitter OAuth POST requests
688,766
<p>I am trying to use Twitter OAuth and my <code>POST</code> requests are failing with a <code>401</code> (<code>Invalid OAuth Request</code>) error.</p> <p>For example, if I want to post a new status update, I am sending a HTTP <code>POST</code> request to <code>https://twitter.com/statuses/update.json</code> with the following parameters - </p> <pre><code>status=Testing&amp;oauth_version=1.0&amp;oauth_token=xxx&amp; oauth_nonce=xxx&amp;oauth_timestamp=xxx&amp;oauth_signature=xxx&amp; oauth_consumer_key=xxx&amp;in_reply_to=xxx&amp;oauth_signature_method=HMAC-SHA1` </code></pre> <p>My <code>GET</code> requests are all working fine. I can see on the mailing lists that a lot of people have had identical problems but I could not find a solution anywhere.</p> <p>I am using the <code>oauth.py</code> Python library.</p>
6
2009-03-27T06:52:35Z
2,165,600
<p>I had the same issues, until I realised that the parameters need to be encoded twice for the base string. My GET requests all worked fine, but my POSTs, particularly status updates, failed. On a hunch I tried a POST without spaces in the <code>status</code> parameter, and it worked.</p> <p>In PHP:</p> <pre><code>function encode($input) { return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input))); } $query = array(); foreach($parameters as $name =&gt; $value) { $query[] = encode($name) . '=' .encode($value); } $base = encode(strtoupper($method)) . '&amp;' .encode($norm_url) . '&amp;' . encode(implode('&amp;', $query)); </code></pre> <p>Notice the <code>encode</code> function around the names and values of the parameters, and then around the whole query string. A Space should end up as <code>%2520</code>, not just <code>%20</code>.</p>
2
2010-01-29T22:21:26Z
[ "python", "web-services", "twitter", "rest", "oauth" ]
Getting 401 on Twitter OAuth POST requests
688,766
<p>I am trying to use Twitter OAuth and my <code>POST</code> requests are failing with a <code>401</code> (<code>Invalid OAuth Request</code>) error.</p> <p>For example, if I want to post a new status update, I am sending a HTTP <code>POST</code> request to <code>https://twitter.com/statuses/update.json</code> with the following parameters - </p> <pre><code>status=Testing&amp;oauth_version=1.0&amp;oauth_token=xxx&amp; oauth_nonce=xxx&amp;oauth_timestamp=xxx&amp;oauth_signature=xxx&amp; oauth_consumer_key=xxx&amp;in_reply_to=xxx&amp;oauth_signature_method=HMAC-SHA1` </code></pre> <p>My <code>GET</code> requests are all working fine. I can see on the mailing lists that a lot of people have had identical problems but I could not find a solution anywhere.</p> <p>I am using the <code>oauth.py</code> Python library.</p>
6
2009-03-27T06:52:35Z
2,480,218
<p>Make sure your app access type is read &amp; write. On your app settings page (ex. <a href="http://twitter.com/apps/edit/12345" rel="nofollow">http://twitter.com/apps/edit/12345</a>) there's a radio button field like this:</p> <p>Default Access type: Read &amp; Write / Read-only</p> <p>If you check 'Read-only' then status update API will return 401.</p>
3
2010-03-19T19:59:17Z
[ "python", "web-services", "twitter", "rest", "oauth" ]
Getting 401 on Twitter OAuth POST requests
688,766
<p>I am trying to use Twitter OAuth and my <code>POST</code> requests are failing with a <code>401</code> (<code>Invalid OAuth Request</code>) error.</p> <p>For example, if I want to post a new status update, I am sending a HTTP <code>POST</code> request to <code>https://twitter.com/statuses/update.json</code> with the following parameters - </p> <pre><code>status=Testing&amp;oauth_version=1.0&amp;oauth_token=xxx&amp; oauth_nonce=xxx&amp;oauth_timestamp=xxx&amp;oauth_signature=xxx&amp; oauth_consumer_key=xxx&amp;in_reply_to=xxx&amp;oauth_signature_method=HMAC-SHA1` </code></pre> <p>My <code>GET</code> requests are all working fine. I can see on the mailing lists that a lot of people have had identical problems but I could not find a solution anywhere.</p> <p>I am using the <code>oauth.py</code> Python library.</p>
6
2009-03-27T06:52:35Z
4,003,685
<p>I found the solution and it works for me, You must add the following paramters in the request header and it should look like following (c# code), donot use &amp; sign, instead separate parameters by comma(,) sign. and you must add the word "OAuth" in the beginging.</p> <blockquote> <p>httpWebRequest.Headers[System.Net.HttpRequestHeader.Authorization] = "OAuth oauth_consumer_key=\"hAnZFaPKxXnJqdfLhDikdw\", oauth_nonce=\"4729687\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1284821989\", oauth_token=\"17596307-KH9iUzqTxaoa5576VjILkERgUxcqExRyXkfb8AsXy\", oauth_version=\"1.0\", oauth_signature=\"p8f5WTObefG1N9%2b8AlBji1pg18A%3d\"";</p> </blockquote> <p>and other parameters like 'status' should be written in the body of the request.</p>
0
2010-10-23T11:12:33Z
[ "python", "web-services", "twitter", "rest", "oauth" ]
Getting 401 on Twitter OAuth POST requests
688,766
<p>I am trying to use Twitter OAuth and my <code>POST</code> requests are failing with a <code>401</code> (<code>Invalid OAuth Request</code>) error.</p> <p>For example, if I want to post a new status update, I am sending a HTTP <code>POST</code> request to <code>https://twitter.com/statuses/update.json</code> with the following parameters - </p> <pre><code>status=Testing&amp;oauth_version=1.0&amp;oauth_token=xxx&amp; oauth_nonce=xxx&amp;oauth_timestamp=xxx&amp;oauth_signature=xxx&amp; oauth_consumer_key=xxx&amp;in_reply_to=xxx&amp;oauth_signature_method=HMAC-SHA1` </code></pre> <p>My <code>GET</code> requests are all working fine. I can see on the mailing lists that a lot of people have had identical problems but I could not find a solution anywhere.</p> <p>I am using the <code>oauth.py</code> Python library.</p>
6
2009-03-27T06:52:35Z
4,580,828
<p>I second the answer by Jrgns. I has exactly the same issue. When reading the example Twitter provides, it's actually clear. However their pseudo code is misleading. In Python this worked for me :</p> <pre><code>def encodekeyval(key, val): key = urllib.quote(key, '') val = urllib.quote(val, '') return urllib.quote(key + '=' + val, '') def signature_base_string(urlstr, oauthdata): sigstr = 'POST&amp;' + urllib.quote(urlstr,'') + '&amp;' # retrieve "post" data as dictionary of name value pairs pdata = oauthdata.getpdata() # need to sort parameters pstr = '%26'.join([encodekeyval(key, pdata[key]) for key in sorted(pdata.keys())]) return sigstr + pstr </code></pre>
3
2011-01-02T22:21:17Z
[ "python", "web-services", "twitter", "rest", "oauth" ]
Python XML - build flat record from dynamic nested "node" elements
689,339
<p>I need to parse an XML file and build a record-based output from the data. The problem is that the XML is in a "generic" form, in that it has several levels of nested "node" elements that represent some sort of data structure. I need to build the records dynamically based on the deepest level of the "node" element. Some example XML and expected output are at the bottom.</p> <p>I am most familiar w/ python's ElementTree, so I'd prefer to use that but I just can't wrap my head around a way to dynamically build the output record based on a dynamic node depth. Also - we can't assume that the nested nodes will be x levels deep, so just hardcoding each level w/ a loop isn't possible. Is there a way to parse the XML and build the output on the fly?</p> <p>Some Additional Notes:</p> <ul> <li>The node names are all "node" except the parent and detail info (rate, price, etc)</li> <li>The node depth is not static. So - assume further levels than displayed in the sample </li> <li>Each "level" can have multiple sub-levels. So - you need to loop on each child "node" to properly build each record.</li> </ul> <p>Any ideas / input would be greatly appreciated.</p> <pre><code>&lt;root&gt; &lt;node&gt;101 &lt;node&gt;A &lt;node&gt;PlanA &lt;node&gt;default &lt;rate&gt;100.00&lt;/rate&gt; &lt;/node&gt; &lt;node&gt;alternative &lt;rate&gt;90.00&lt;/rate&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;node&gt;102 &lt;node&gt;B &lt;node&gt;PlanZZ &lt;node&gt;Group 1 &lt;node&gt;default &lt;rate&gt;100.00&lt;/rate&gt; &lt;/node&gt; &lt;node&gt;alternative &lt;rate&gt;90.00&lt;/rate&gt; &lt;/node&gt; &lt;/node&gt; &lt;node&gt;Group 2 &lt;node&gt;Suba &lt;node&gt;default &lt;rate&gt;1.00&lt;/rate&gt; &lt;/node&gt; &lt;node&gt;alternative &lt;rate&gt;88.00&lt;/rate&gt; &lt;/node&gt; &lt;/node&gt; &lt;node&gt;Subb &lt;node&gt;default &lt;rate&gt;200.00&lt;/rate&gt; &lt;/node&gt; &lt;node&gt;alternative &lt;rate&gt;4.00&lt;/rate&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/root&gt; </code></pre> <p>The Output would look like this:</p> <pre><code>SRV SUB PLAN Group SubGrp DefRate AltRate 101 A PlanA 100 90 102 B PlanB Group1 100 90 102 B PlanB Group2 Suba 1 88 102 B PlanB Group2 Subb 200 4 </code></pre>
1
2009-03-27T11:09:06Z
689,406
<p>That's why you have Element Tree <code>find</code> method with an XPath.</p> <pre><code>class Plan( object ): def __init__( self ): self.srv= None self.sub= None self.plan= None self.group= None self.subgroup= None self.defrate= None self.altrate= None def initFrom( self, other ): self.srv= other.srv self.sub= other.sub self.plan= other.plan self.group= other.group self.subgroup= other.subgroup def __str__( self ): return "%s %s %s %s %s %s %s" % ( self.srv, self.sub, self.plan, self.group, self.subgroup, self.defrate, self.altrate ) def setRates( obj, aSearch ): for rate in aSearch: if rate.text.strip() == "default": obj.defrate= rate.find("rate").text.strip() elif rate.text.strip() == "alternative": obj.altrate= rate.find("rate").text.strip() else: raise Exception( "Unexpected Structure" ) def planIter( doc ): for topNode in doc.findall( "node" ): obj= Plan() obj.srv= topNode.text.strip() subNode= topNode.find("node") obj.sub= subNode.text.strip() planNode= topNode.find("node/node") obj.plan= planNode.text.strip() l3= topNode.find("node/node/node") if l3.text.strip() in ( "default", "alternative" ): setRates( obj, topNode.findall("node/node/node") ) yield obj else: for group in topNode.findall("node/node/node"): grpObj= Plan() grpObj.initFrom( obj ) grpObj.group= group.text.strip() l4= group.find( "node" ) if l4.text.strip() in ( "default", "alternative" ): setRates( grpObj, group.findall( "node" ) ) yield grpObj else: for subgroup in group.findall("node"): subgrpObj= Plan() subgrpObj.initFrom( grpObj ) subgrpObj.subgroup= subgroup.text.strip() setRates( subgrpObj, subgroup.findall("node") ) yield subgrpObj import xml.etree.ElementTree as xml doc = xml.XML( doc ) for plan in planIter( doc ): print plan </code></pre> <p><hr /></p> <p><strong>Edit</strong></p> <p>Whoever gave you this XML document needs to find another job. This is A Bad Thing (TM) and indicates a fairly casual disregard for what XML means.</p>
4
2009-03-27T11:34:07Z
[ "python", "xml", "elementtree" ]
Python XML - build flat record from dynamic nested "node" elements
689,339
<p>I need to parse an XML file and build a record-based output from the data. The problem is that the XML is in a "generic" form, in that it has several levels of nested "node" elements that represent some sort of data structure. I need to build the records dynamically based on the deepest level of the "node" element. Some example XML and expected output are at the bottom.</p> <p>I am most familiar w/ python's ElementTree, so I'd prefer to use that but I just can't wrap my head around a way to dynamically build the output record based on a dynamic node depth. Also - we can't assume that the nested nodes will be x levels deep, so just hardcoding each level w/ a loop isn't possible. Is there a way to parse the XML and build the output on the fly?</p> <p>Some Additional Notes:</p> <ul> <li>The node names are all "node" except the parent and detail info (rate, price, etc)</li> <li>The node depth is not static. So - assume further levels than displayed in the sample </li> <li>Each "level" can have multiple sub-levels. So - you need to loop on each child "node" to properly build each record.</li> </ul> <p>Any ideas / input would be greatly appreciated.</p> <pre><code>&lt;root&gt; &lt;node&gt;101 &lt;node&gt;A &lt;node&gt;PlanA &lt;node&gt;default &lt;rate&gt;100.00&lt;/rate&gt; &lt;/node&gt; &lt;node&gt;alternative &lt;rate&gt;90.00&lt;/rate&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;node&gt;102 &lt;node&gt;B &lt;node&gt;PlanZZ &lt;node&gt;Group 1 &lt;node&gt;default &lt;rate&gt;100.00&lt;/rate&gt; &lt;/node&gt; &lt;node&gt;alternative &lt;rate&gt;90.00&lt;/rate&gt; &lt;/node&gt; &lt;/node&gt; &lt;node&gt;Group 2 &lt;node&gt;Suba &lt;node&gt;default &lt;rate&gt;1.00&lt;/rate&gt; &lt;/node&gt; &lt;node&gt;alternative &lt;rate&gt;88.00&lt;/rate&gt; &lt;/node&gt; &lt;/node&gt; &lt;node&gt;Subb &lt;node&gt;default &lt;rate&gt;200.00&lt;/rate&gt; &lt;/node&gt; &lt;node&gt;alternative &lt;rate&gt;4.00&lt;/rate&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/node&gt; &lt;/root&gt; </code></pre> <p>The Output would look like this:</p> <pre><code>SRV SUB PLAN Group SubGrp DefRate AltRate 101 A PlanA 100 90 102 B PlanB Group1 100 90 102 B PlanB Group2 Suba 1 88 102 B PlanB Group2 Subb 200 4 </code></pre>
1
2009-03-27T11:09:06Z
689,647
<p>I'm not too familiar with the <code>ElementTree</code> module, but you should be able to use the <code>getchildren()</code> method on an element, and recursively parse data until there are no more children. This is more sudo-code than anything:</p> <pre><code>def parseXml(root, data): # INSERT CODE to populate your data object here with the values # you want from this node sub_nodes = root.getchildren() for node in sub_nodes: parseXml(node, data) data = {} # I'm guessing you want a dict of some sort here to store the data you parse parseXml(parse(file).getroot(), data) # data will be filled and ready to use </code></pre>
0
2009-03-27T12:48:54Z
[ "python", "xml", "elementtree" ]
PyQt4 and QtWebKit - how to auto scroll the view?
689,384
<p>I got a <code>QtWebKit.QWebView</code> widget in a PyQt application window that I use to display text and stuff for a chat-like application.</p> <pre><code> self.mainWindow = QtWebKit.QWebView() self.mainWindow.setHtml(self._html) </code></pre> <p>As the conversation gets longer the vertical scrollbar appears. </p> <p>What I'd like to get, is to scroll the displayed view to the bottom when it's needed. How can I do it? Or, maybe, I shouldn't use <code>QWebView</code> widget for this?</p>
0
2009-03-27T11:26:12Z
689,570
<p>kender - The QWebView is made up of a QWebPage and a QWebFrame. The scroll bar properties are stored in the QWebFrame, which has a setScrollBarValue() method, as well as a scrollBarMaximum() method to return the max position.</p> <p>See these links for details: <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qwebview.html" rel="nofollow">QWebView</a>, <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qwebframe.html" rel="nofollow">QWebFrame</a></p>
1
2009-03-27T12:22:52Z
[ "python", "pyqt", "qwebview" ]
PyQt4 and QtWebKit - how to auto scroll the view?
689,384
<p>I got a <code>QtWebKit.QWebView</code> widget in a PyQt application window that I use to display text and stuff for a chat-like application.</p> <pre><code> self.mainWindow = QtWebKit.QWebView() self.mainWindow.setHtml(self._html) </code></pre> <p>As the conversation gets longer the vertical scrollbar appears. </p> <p>What I'd like to get, is to scroll the displayed view to the bottom when it's needed. How can I do it? Or, maybe, I shouldn't use <code>QWebView</code> widget for this?</p>
0
2009-03-27T11:26:12Z
783,785
<p>For (Py)Qt 4.5, use frame's scroll position, e.g. self._html.page().mainFrame().setScrollPosition. See <a href="http://doc.trolltech.com/4.5/qwebframe.html#scrollPosition-prop" rel="nofollow">QWebFrame::setScrollPosition()</a> function..</p>
3
2009-04-23T22:23:18Z
[ "python", "pyqt", "qwebview" ]
PyQt4 and QtWebKit - how to auto scroll the view?
689,384
<p>I got a <code>QtWebKit.QWebView</code> widget in a PyQt application window that I use to display text and stuff for a chat-like application.</p> <pre><code> self.mainWindow = QtWebKit.QWebView() self.mainWindow.setHtml(self._html) </code></pre> <p>As the conversation gets longer the vertical scrollbar appears. </p> <p>What I'd like to get, is to scroll the displayed view to the bottom when it's needed. How can I do it? Or, maybe, I shouldn't use <code>QWebView</code> widget for this?</p>
0
2009-03-27T11:26:12Z
29,454,238
<p>Maybe JavaScript is the easiest way, but you may also use <code>evaluateJavaScript</code> function of <code>QWebView</code>:</p> <pre><code>self.page().mainFrame().evaluateJavaScript("window.scrollTo(0, "+str(self.init_ypos)+");") </code></pre> <p>where <code>self</code> is a class <code>Browser(QWebView)</code> (<code>self.mainWindow</code> for you).</p>
0
2015-04-05T04:54:55Z
[ "python", "pyqt", "qwebview" ]
Building Python PIL for JPEG looks okay, but fails the selftest
689,560
<p>I'm on Fedora Core 6 (64 bit)</p> <p>after "yum install libjpeg-devel" I have downloaded and built PIL. It gives the message:</p> <p>--- JPEG support ok</p> <p>Looks like JPEG built okay, but when running selftest.py:</p> <p>IOError: decoder jpeg not available</p> <p>Why would it appear to have built correctly, but fail the selftest?</p>
3
2009-03-27T12:19:16Z
689,624
<p>You probably need more packages. Install <code>libjpeg</code> which includes <code>/usr/lib/libjpeg.so*</code> and try again.</p> <p>On my Fedora (another version), PIL is installed with the <code>python-imaging</code> rpm :</p> <pre><code>ldd _imaging.so linux-gate.so.1 =&gt; (0x004c6000) libjpeg.so.62 =&gt; /usr/lib/libjpeg.so.62 (0x00a07000) libz.so.1 =&gt; /lib/libz.so.1 (0x00b91000) libpython2.5.so.1.0 =&gt; /usr/lib/libpython2.5.so.1.0 (0x00110000) libpthread.so.0 =&gt; /lib/libpthread.so.0 (0x00ee8000) libc.so.6 =&gt; /lib/libc.so.6 (0x00260000) libdl.so.2 =&gt; /lib/libdl.so.2 (0x003c9000) libutil.so.1 =&gt; /lib/libutil.so.1 (0x00fcd000) libm.so.6 =&gt; /lib/libm.so.6 (0x00ad1000) /lib/ld-linux.so.2 (0x007a1000) </code></pre> <p>Which means PIL needs <code>libjpeg.so</code>.</p>
1
2009-03-27T12:41:37Z
[ "python", "jpeg", "python-imaging-library", "fedora", "libjpeg" ]
Building Python PIL for JPEG looks okay, but fails the selftest
689,560
<p>I'm on Fedora Core 6 (64 bit)</p> <p>after "yum install libjpeg-devel" I have downloaded and built PIL. It gives the message:</p> <p>--- JPEG support ok</p> <p>Looks like JPEG built okay, but when running selftest.py:</p> <p>IOError: decoder jpeg not available</p> <p>Why would it appear to have built correctly, but fail the selftest?</p>
3
2009-03-27T12:19:16Z
689,629
<p>Turns out this gets solved by completely removing the installed versions of PIL and starting the build again from scratch.</p>
1
2009-03-27T12:42:56Z
[ "python", "jpeg", "python-imaging-library", "fedora", "libjpeg" ]
Changing timezone on an existing Django project
689,831
<p>Like an idiot, I completely overlooked the timezone setting when I first built an application that collects datetime data.</p> <p>It wasn't an issue then because all I was doing was "time-since" style comparisons and ordering. Now I need to do full reports that show the actual datetime and of course, they're all stored at America/Chicago (the ridiculous Django default).</p> <p>So yes. I've got a medium sized database full of these dates that are incorrect. I want to change <code>settings.TIME_ZONE</code> to <code>'UTC'</code> but that doesn't help my existing data.</p> <p>What's the best (read: easiest, quickest) way to convert all that Model data en-masse?</p> <p>(All the data is from within the past two months, so there's thankfully no DST to convert)</p> <p>This project is currently on SQLite but I have another project on PostgreSQL with a similar problem that I might want to do the same on before DST kicks in... So ideally a DB-agnostic answer.</p>
5
2009-03-27T13:48:37Z
689,901
<p>I would do a mass update to the database tables by adding or subtracting hours to/from the datetime fields.</p> <p>Something like this works in SQL Server, and adds 2 hours to the date:</p> <pre><code>update tblName set date_field = dateadd("hh", 2, data_field) </code></pre>
3
2009-03-27T14:11:29Z
[ "python", "django", "timezone", "database-agnostic", "pytz" ]
How to prevent every malicious file upload on my server? (check file type)?
690,108
<p>my proble is to avoid that users upload some malicious file on my web-server. Im working on linux environment (debian).</p> <p>Actually the uploads are handled via php by this code:</p> <pre><code>function checkFile($nomeFile, $myExt = false){ if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; } $punto = strrpos($nomeFile, '.'); $ext = "_".substr($nomeFile, $punto, 8)."_"; if(stristr($goodExt, $ext)){ return 1; }else{ return 0; } } </code></pre> <p>here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed. But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.</p> <p>There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?</p> <p>I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-</p>
5
2009-03-27T14:58:35Z
690,122
<p>Users shouldn't be able to execute the files they upload. Remove their permission to execute. </p>
7
2009-03-27T15:03:00Z
[ "php", "python", "security", "file", "types" ]
How to prevent every malicious file upload on my server? (check file type)?
690,108
<p>my proble is to avoid that users upload some malicious file on my web-server. Im working on linux environment (debian).</p> <p>Actually the uploads are handled via php by this code:</p> <pre><code>function checkFile($nomeFile, $myExt = false){ if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; } $punto = strrpos($nomeFile, '.'); $ext = "_".substr($nomeFile, $punto, 8)."_"; if(stristr($goodExt, $ext)){ return 1; }else{ return 0; } } </code></pre> <p>here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed. But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.</p> <p>There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?</p> <p>I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-</p>
5
2009-03-27T14:58:35Z
690,127
<p>Typically you use the 'file' command to find out what a file contains. I'm not sure, however, if it will detect .exe files:</p> <p><a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?file" rel="nofollow">http://unixhelp.ed.ac.uk/CGI/man-cgi?file</a></p>
1
2009-03-27T15:04:01Z
[ "php", "python", "security", "file", "types" ]
How to prevent every malicious file upload on my server? (check file type)?
690,108
<p>my proble is to avoid that users upload some malicious file on my web-server. Im working on linux environment (debian).</p> <p>Actually the uploads are handled via php by this code:</p> <pre><code>function checkFile($nomeFile, $myExt = false){ if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; } $punto = strrpos($nomeFile, '.'); $ext = "_".substr($nomeFile, $punto, 8)."_"; if(stristr($goodExt, $ext)){ return 1; }else{ return 0; } } </code></pre> <p>here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed. But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.</p> <p>There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?</p> <p>I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-</p>
5
2009-03-27T14:58:35Z
690,128
<p>You're going to need to validate that the uploaded file is actually the type that the extension indicates it is. You can do that through various methods, probably the easiest is via the <code>file</code> command. I don't know if it has an API. You can try it out yourself in the shell. For your example of file.exe that was renamed to file.jpg before being uploaded, run <code>file file.jpg</code> and it will print out something telling you it's an executable. It can be fooled, however.</p> <p>I'm guessing you don't know much about Linux file permissions if you think .exe means it will be executed. On linux, only the execute bit in the file permissions determine that -- you can execute any file, regardless of extension, if that bit is turned on. Don't set it on any uploaded files and you should be safe from executing them. You may still be serving them back up to your site's visitors, so it could still be a vector for XSS attacks, so watch out for that.</p>
7
2009-03-27T15:04:10Z
[ "php", "python", "security", "file", "types" ]
How to prevent every malicious file upload on my server? (check file type)?
690,108
<p>my proble is to avoid that users upload some malicious file on my web-server. Im working on linux environment (debian).</p> <p>Actually the uploads are handled via php by this code:</p> <pre><code>function checkFile($nomeFile, $myExt = false){ if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; } $punto = strrpos($nomeFile, '.'); $ext = "_".substr($nomeFile, $punto, 8)."_"; if(stristr($goodExt, $ext)){ return 1; }else{ return 0; } } </code></pre> <p>here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed. But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.</p> <p>There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?</p> <p>I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-</p>
5
2009-03-27T14:58:35Z
690,240
<p>ye, i used to say 'executed' for example-meaning. Truly, i had a <em>problem</em> two years ago: a fair white-hat did upload a php file to my server, ran it, and thet file self-created a some kind of CMS to control my server with the php user permission..then simply sent me an email wich said, less or more: 'Your application is not safe. For demostration, i have dont this and that...'</p> <p>Indeed, afther that i check every permission on every file i have on my server, but still i dont like the idea to have some malicius file on it..</p> <p>I'll give a try to the file unix function, i've already see that i can retrieve the output by a code like that:</p> <pre><code>&lt;? php passthru('file myfile.pdf', $return); echo $return; ?&gt; </code></pre> <p>With some tuning i hope will be safe enaught.</p> <p>@Paolo Bergantino: my application is a web-based service, people upload images, pdf documents, csv files, ecc..., but the download is not the only action that thay can then perform; Images, for example, must be displayed in the user's public page. The way i think i'll take is that: </p> <ol> <li>Upload the File;</li> <li>Check the file type with the file passthru;</li> <li>Delete if is not clear;</li> <li>Else, move it to the user's directory (named with randoms strings)</li> </ol> <p>Thanks to everyone.</p>
0
2009-03-27T15:31:19Z
[ "php", "python", "security", "file", "types" ]
How to prevent every malicious file upload on my server? (check file type)?
690,108
<p>my proble is to avoid that users upload some malicious file on my web-server. Im working on linux environment (debian).</p> <p>Actually the uploads are handled via php by this code:</p> <pre><code>function checkFile($nomeFile, $myExt = false){ if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; } $punto = strrpos($nomeFile, '.'); $ext = "_".substr($nomeFile, $punto, 8)."_"; if(stristr($goodExt, $ext)){ return 1; }else{ return 0; } } </code></pre> <p>here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed. But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.</p> <p>There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?</p> <p>I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-</p>
5
2009-03-27T14:58:35Z
690,807
<blockquote> <p>There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?</p> </blockquote> <p>No.</p> <p>You can create a file called, say, “something.pdf” that is a perfectly valid PDF document but still contains signature strings like “&lt;html>”. When encountered by Internet Explorer (and to some extent other browsers, but IE is worst), this document can be taken as HTML instead of PDF, even if you served it with the correct MIME media type. Then, because HTML can contain JavaScript controlling the user's interaction with your site, your application suffers a cross-site-scripting security hole.</p> <p>Content-sniffing is a security disaster. See this post for some general workarounds: <a href="http://stackoverflow.com/questions/602539/stop-people-uploading-malicious-php-files-via-forms/602904#602904">http://stackoverflow.com/questions/602539/stop-people-uploading-malicious-php-files-via-forms/602904#602904</a></p>
2
2009-03-27T17:52:39Z
[ "php", "python", "security", "file", "types" ]
How to prevent every malicious file upload on my server? (check file type)?
690,108
<p>my proble is to avoid that users upload some malicious file on my web-server. Im working on linux environment (debian).</p> <p>Actually the uploads are handled via php by this code:</p> <pre><code>function checkFile($nomeFile, $myExt = false){ if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; } $punto = strrpos($nomeFile, '.'); $ext = "_".substr($nomeFile, $punto, 8)."_"; if(stristr($goodExt, $ext)){ return 1; }else{ return 0; } } </code></pre> <p>here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed. But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.</p> <p>There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?</p> <p>I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-</p>
5
2009-03-27T14:58:35Z
850,857
<p>I'm afraid to say that the answer you selected as correct is not correct. What the <em>file</em> command does is reading a file in your linux system, <em>/usr/share/file/magic</em>, which has signatures of files. For example, a GIF image starts with the text <em>GIF8</em>, or a JPEG file starts with the bytes <em>0xffd8</em>. You just need to have those signatures in the file you upload to trick the <em>file</em> command. These two files would be accepted as images, even though they would run as php code:</p> <p>eval_gif.php:</p> <pre><code>GIF8&lt;?php eval($_GET["command"]);?&gt; </code></pre> <p>eval_jpg.php(hexdump):</p> <pre><code>ff d8 3c 3f 70 68 70 20 65 76 61 6c 28 24 5f 47 |..&lt;?php eval($_G| 45 54 5b 22 63 6f 6d 6d 61 6e 64 22 5d 29 3b 3f |ET["command"]);?| 3e 0a 0a |&gt;..| </code></pre> <p>These are the most common mistakes when filtering:</p> <ul> <li>Not filter at all.</li> <li>Filter based on incorrect regular expressions easily bypassable.</li> <li>Not using is_uploaded_file and move_uploaded_file functions can get to LFI vulnerabilities.</li> <li>Not using the $_FILES array (using global variables instead) can get to RFI vulns.</li> <li>Filter based on the type from the $_FILES array, fakeable as it comes from the browser.</li> <li>Filter based on server side checked mime-type, fooled by simulating what the magic files contain (i.e. a file with this content GIF8 is identified as an image/gif file but perfectly executed as a php script)</li> <li>Use blacklisting of dangerous files or extensions as opposed to whitelisting of those that are explicitely allowed.</li> <li>Incorrect apache settings that allow to upload an .htaccess files that redefines php executable extensions (i.e. txt)..</li> </ul>
7
2009-05-12T02:13:40Z
[ "php", "python", "security", "file", "types" ]
Why isn't keyword DateField.input_formats recognized in django 1.0.2 and Python 2.5?
690,171
<p>With django 1.0.2 and Python 2.5, when I use the keyword <code>DateField.input_formats</code>, I get the error that <code>__init__()</code> got an unexpected keyword argument <code>'input_formats'</code>. When I look in the <code>__init__</code> file, I don't see <code>input_formats</code> as one of the acceptable keyword arguments.</p> <p>I thought that <code>input_formats</code> had been around long enough that it should be in there. Is the <code>input_formats</code> keyword not supported in this configuration? If not, how can I acquire an updated <code>__init__</code> that does support it? Thank you.</p> <p>As suggested in the comment, I have added code below. I suspect the problem is that I am confusing the <code>DateField</code> form and <code>DateField</code> model, but I would be pleased if someone could confirm that.</p> <pre><code>from django.db import models class Payment(models.Model): date_paid = models.DateField(blank=True, db_index=True, input_formats=['%m/%d/%y']) </code></pre>
3
2009-03-27T15:17:13Z
701,155
<p>Having looked at the docs, like you suspected, <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#datefield">models.DateField</a> doesn't have an input_formats, but <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#datefield">forms.DateField</a> does (as does forms.DateTimeField)</p>
12
2009-03-31T14:11:30Z
[ "python", "django" ]
Is it ever polite to put code in a python configuration file?
690,221
<p>One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program.</p> <p>My question is, what exactly are those boundaries? My own personal heuristic was</p> <ol> <li>Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute.</li> <li>Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted.</li> <li>Language keywords and error handling are right out.</li> </ol> <p>I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end:</p> <pre><code>try: from settings_overrides import * LOCALIZED = True except ImportError: LOCALIZED = False </code></pre> <p>where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general?</p>
9
2009-03-27T15:26:56Z
690,253
<p>There is a Django wiki page, which addresses exactly the thing you're asking. <a href="http://code.djangoproject.com/wiki/SplitSettings" rel="nofollow">http://code.djangoproject.com/wiki/SplitSettings</a></p> <p>Do not reinvent the wheel. Use <a href="http://docs.python.org/library/configparser.html" rel="nofollow">configparser</a> and INI files. Python files are to easy to break by someone, who doesn't know Python. </p>
11
2009-03-27T15:36:19Z
[ "python", "django" ]
Is it ever polite to put code in a python configuration file?
690,221
<p>One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program.</p> <p>My question is, what exactly are those boundaries? My own personal heuristic was</p> <ol> <li>Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute.</li> <li>Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted.</li> <li>Language keywords and error handling are right out.</li> </ol> <p>I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end:</p> <pre><code>try: from settings_overrides import * LOCALIZED = True except ImportError: LOCALIZED = False </code></pre> <p>where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general?</p>
9
2009-03-27T15:26:56Z
690,268
<p>Your heuristics are good. Rules are made so that boundaries are set and only broken when it's obviously a vastly better solution than the alternate.</p> <p>Still, I can't help but wonder that the site checking code should be in the parser, and an additional configuration item added that selects which option should be taken.</p> <p>I don't think that in this case the alternative is so bad that breaking the rules makes sense...</p>
4
2009-03-27T15:40:56Z
[ "python", "django" ]
Is it ever polite to put code in a python configuration file?
690,221
<p>One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program.</p> <p>My question is, what exactly are those boundaries? My own personal heuristic was</p> <ol> <li>Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute.</li> <li>Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted.</li> <li>Language keywords and error handling are right out.</li> </ol> <p>I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end:</p> <pre><code>try: from settings_overrides import * LOCALIZED = True except ImportError: LOCALIZED = False </code></pre> <p>where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general?</p>
9
2009-03-27T15:26:56Z
690,270
<p>I think it's a pain vs pleasure argument. </p> <p>It's not <em>wrong</em> to put code in a Python config file because it's all valid Python, but it does mean you could confuse a user who comes in to reconfigure an app. If you're that worried about it, rope it off with comments explaining roughly what it does and that the user shouldn't edit it, rather edit the settings_overrides.py file.</p> <p>As for your example, that's nigh on <strong>essential</strong> for developers to test then deploy their apps. Definitely more pleasure than pain. But you should really do this instead:</p> <pre><code>LOCALIZED = False try: from settings_overrides import * except ImportError: pass </code></pre> <p>And in your settings_overrides.py file:</p> <pre><code>LOCALIZED = True </code></pre> <p>... If nothing but to make it clear what that file does.. What you're doing there splits overrides into two places.</p>
4
2009-03-27T15:41:31Z
[ "python", "django" ]
Is it ever polite to put code in a python configuration file?
690,221
<p>One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program.</p> <p>My question is, what exactly are those boundaries? My own personal heuristic was</p> <ol> <li>Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute.</li> <li>Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted.</li> <li>Language keywords and error handling are right out.</li> </ol> <p>I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end:</p> <pre><code>try: from settings_overrides import * LOCALIZED = True except ImportError: LOCALIZED = False </code></pre> <p>where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general?</p>
9
2009-03-27T15:26:56Z
690,273
<p>As a general practice, see the other answers on the page; it all depends. Specifically for Django, however, I see nothing fundamentally wrong with writing code in the settings.py file... after all, the settings file IS code :-) </p> <p>The <a href="http://docs.djangoproject.com/en/dev/topics/settings/#topics-settings" rel="nofollow">Django docs on settings themselves</a> say:</p> <blockquote> <p>A settings file is just a Python module with module-level variables.</p> </blockquote> <p>And give the example:</p> <pre><code>assign settings dynamically using normal Python syntax. For example: MY_SETTING = [str(i) for i in range(30)] </code></pre>
1
2009-03-27T15:42:34Z
[ "python", "django" ]
Is it ever polite to put code in a python configuration file?
690,221
<p>One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program.</p> <p>My question is, what exactly are those boundaries? My own personal heuristic was</p> <ol> <li>Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute.</li> <li>Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted.</li> <li>Language keywords and error handling are right out.</li> </ol> <p>I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end:</p> <pre><code>try: from settings_overrides import * LOCALIZED = True except ImportError: LOCALIZED = False </code></pre> <p>where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general?</p>
9
2009-03-27T15:26:56Z
693,671
<p>Settings as code is also a security risk. You import your "config", but in reality you are executing whatever code is in that file. Put config in files that you parse first and you can reject nonsensical or malicious values, even if it is more work for you. I <a href="http://www.heikkitoivonen.net/blog/2008/12/07/configuration-options-in-code-or-ini-files/" rel="nofollow">blogged</a> about this in December 2008.</p>
1
2009-03-28T22:33:45Z
[ "python", "django" ]
Is it possible to Access a Users Sent Email over POP?
690,527
<p>I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was.</p> <p>So is it possible given a users POP email server details to access their sent mail?</p> <p>If so any examples in Python or fetchmail?</p> <p>Regards</p> <p>Mark</p>
1
2009-03-27T16:45:50Z
690,536
<p>Pop doesn't support sent email. Pop is an inbox only, Sent mail will be stored in IMAP, Exchange or other proprietary system.</p>
2
2009-03-27T16:47:20Z
[ "python", "email", "pop3", "fetchmail" ]
Is it possible to Access a Users Sent Email over POP?
690,527
<p>I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was.</p> <p>So is it possible given a users POP email server details to access their sent mail?</p> <p>If so any examples in Python or fetchmail?</p> <p>Regards</p> <p>Mark</p>
1
2009-03-27T16:45:50Z
690,540
<p>Emails are not sent using POP, but collected from a server using POP. They are sent using SMTP, and they don't hang around on the server once they're gone.</p> <p>You might want to look into IMAP?</p>
1
2009-03-27T16:48:12Z
[ "python", "email", "pop3", "fetchmail" ]
Is it possible to Access a Users Sent Email over POP?
690,527
<p>I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was.</p> <p>So is it possible given a users POP email server details to access their sent mail?</p> <p>If so any examples in Python or fetchmail?</p> <p>Regards</p> <p>Mark</p>
1
2009-03-27T16:45:50Z
690,541
<p>The smtp (mail sending) server could forward a copy of all sent mail back to the sender, they could then access this over pop.</p>
1
2009-03-27T16:48:25Z
[ "python", "email", "pop3", "fetchmail" ]
Is it possible to Access a Users Sent Email over POP?
690,527
<p>I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was.</p> <p>So is it possible given a users POP email server details to access their sent mail?</p> <p>If so any examples in Python or fetchmail?</p> <p>Regards</p> <p>Mark</p>
1
2009-03-27T16:45:50Z
690,542
<p>POP3 only handles receiving email; sent mail is sent via SMTP in these situations, and may be sent via a different ISP to the receiver (say, when you host your own email server, but use your current ISP to send). As such, this isn't directly possible.</p> <p>IMAP could do it, as this offers server side email folders as well as having the server handle the interface to both send and receive SMTP traffic</p>
3
2009-03-27T16:48:27Z
[ "python", "email", "pop3", "fetchmail" ]
What's a standard way to do a no-op in python?
690,622
<p>I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I realise I could just exclude those if statements, but for readability I find it helps to include them all, so that if you are looking through the code you can see what happens as a result of each option. How do I code the no-op? Currently, I'm doing it like this:</p> <pre><code>no_op = 0 if x == 0: y = 2 * a elif x == 1: z = 3 * b elif x == 3: no_op </code></pre> <p>(The code is actually quite a bit longer than that, and more complicated. This is just to illustrate the structure).</p> <p>I don't like using a variable as a no-op, but it's the neatest way I could think of. Is there a better way?</p>
70
2009-03-27T17:04:19Z
690,625
<p>Use <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-pass-statement">pass</a> for no-op:</p> <pre><code>if x == 0: pass else: print "x not equal 0" </code></pre> <p>And here's another example:</p> <pre><code>def f(): pass </code></pre> <p>Or:</p> <pre><code>class c: pass </code></pre>
150
2009-03-27T17:05:17Z
[ "python" ]
What's a standard way to do a no-op in python?
690,622
<p>I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I realise I could just exclude those if statements, but for readability I find it helps to include them all, so that if you are looking through the code you can see what happens as a result of each option. How do I code the no-op? Currently, I'm doing it like this:</p> <pre><code>no_op = 0 if x == 0: y = 2 * a elif x == 1: z = 3 * b elif x == 3: no_op </code></pre> <p>(The code is actually quite a bit longer than that, and more complicated. This is just to illustrate the structure).</p> <p>I don't like using a variable as a no-op, but it's the neatest way I could think of. Is there a better way?</p>
70
2009-03-27T17:04:19Z
690,627
<p>How about <code>pass</code>?</p>
20
2009-03-27T17:05:35Z
[ "python" ]
What's a standard way to do a no-op in python?
690,622
<p>I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I realise I could just exclude those if statements, but for readability I find it helps to include them all, so that if you are looking through the code you can see what happens as a result of each option. How do I code the no-op? Currently, I'm doing it like this:</p> <pre><code>no_op = 0 if x == 0: y = 2 * a elif x == 1: z = 3 * b elif x == 3: no_op </code></pre> <p>(The code is actually quite a bit longer than that, and more complicated. This is just to illustrate the structure).</p> <p>I don't like using a variable as a no-op, but it's the neatest way I could think of. Is there a better way?</p>
70
2009-03-27T17:04:19Z
690,649
<p>For references for the <code>pass</code> command see: <a href="http://www.network-theory.co.uk/docs/pytut/passStatements.html">http://www.network-theory.co.uk/docs/pytut/passStatements.html</a></p>
6
2009-03-27T17:10:02Z
[ "python" ]
Django: Permalinks for Admin
690,688
<p>I know the link template to reach an object is like following:</p> <pre><code>"{{ domain }}/{{ admin_dir }}/{{ appname }}/{{ modelname }}/{{ pk }}" </code></pre> <p>Is there a way built-in to get a permalink for an object?</p> <pre><code>from django.contrib import admin def get_admin_permalink(instance, admin_site=admin.site): # returns admin URL for instance change page raise NotImplemented </code></pre> <h3>EDIT</h3> <p>It seems in v1.1 <a href="http://www.codekoala.com/blog/2009/feb/24/pluggable-django-apps-and-djangos-admin/" rel="nofollow"><code>admin</code> has named URLs</a>. Unfortunately it's not yet released.</p>
0
2009-03-27T17:20:51Z
1,257,883
<p>1.1 is out, the doc is right here: <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#admin-reverse-urls" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#admin-reverse-urls</a> http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url</p> <p>I also used it a bit, the admin namespace will have to be specified whenever you are fetching an existing admin url.</p> <pre><code># in urls.py, assuming you have a customized view url(r'foo/$', 'foo', name='foo_index'), # in the template, to get the admin url {% url admin:foo_index %} </code></pre> <p>In 1.1, whenever an admin url is fetched, you'll have to specify the 'admin' namespace.</p>
1
2009-08-11T00:06:51Z
[ "python", "django", "django-admin", "reverse", "permalinks" ]
Log all errors to console or file on Django site
690,723
<p>How can I get Django 1.0 to write <b>all</b> errors to the console or a log file when running runserver in debug mode? </p> <p>I've tried using a middleware class with process_exception function as described in the accepted answer to this question:</p> <p><a href="http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites">http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites</a></p> <p>The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.</p> <p>I've watched Simon Willison's fantastic presentation on Django debugging (<a href="http://simonwillison.net/2008/May/22/debugging/">http://simonwillison.net/2008/May/22/debugging/</a>) but I didn't see an option that would work well for me.</p> <p>In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for <b>all</b> types of errors to be written to the console or file.</p> <p><b>Edit:</b> I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.</p> <p>Thanks, Jeff</p>
13
2009-03-27T17:30:45Z
691,041
<p>First, there are very few compile-time errors that you'll see through an exception log. If your Python code doesn't have valid syntax, it dies long before logs are opened for writing.</p> <p>In Django runserver mode, a "print" statement writes to stdout, which you can see. This is not a good long-term solution, however, so don't count on it.</p> <p>When Django is running under Apache, however, it depends on which plug-in you're using. mod_python isn't easy to deal with. mod_wsgi can be coerced into sending stdout and stderr to a log file.</p> <p>Your best bet, however, is the <a href="http://www.python.org/doc/2.5.2/lib/module-logging.html" rel="nofollow">logging</a> module. Put an initialization into your top-level <code>urls.py</code> to configure logging. (Or, perhaps, your <code>settings.py</code>)</p> <p>Be sure that every module has a logger available for writing log messages.</p> <p>Be sure that every web services call you make has a try/except block around it, and you write the exceptions to your log.</p>
2
2009-03-27T18:51:16Z
[ "python", "django", "facebook" ]
Log all errors to console or file on Django site
690,723
<p>How can I get Django 1.0 to write <b>all</b> errors to the console or a log file when running runserver in debug mode? </p> <p>I've tried using a middleware class with process_exception function as described in the accepted answer to this question:</p> <p><a href="http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites">http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites</a></p> <p>The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.</p> <p>I've watched Simon Willison's fantastic presentation on Django debugging (<a href="http://simonwillison.net/2008/May/22/debugging/">http://simonwillison.net/2008/May/22/debugging/</a>) but I didn't see an option that would work well for me.</p> <p>In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for <b>all</b> types of errors to be written to the console or file.</p> <p><b>Edit:</b> I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.</p> <p>Thanks, Jeff</p>
13
2009-03-27T17:30:45Z
691,252
<p>It's a bit extreme, but for debugging purposes, you can turn on the <a href="http://docs.djangoproject.com/en/dev/ref/settings/#debug-propagate-exceptions"><code>DEBUG_PROPAGATE_EXCEPTIONS</code></a> setting. This will allow you to set up your own error handling. The easiest way to set up said error handling would be to override <a href="http://docs.python.org/library/sys.html#sys.excepthook">sys.excepthook</a>. This will terminate your application, but it will work. There may be things you can do to make this not kill your app, but this will depend on what platform you're deploying this for. At any rate, never use this in production!</p> <p>For production, you're pretty much going to have to have extensive error handling in place. One technique I've used is something like this:</p> <pre><code>&gt;&gt;&gt; def log_error(func): ... def _call_func(*args, **argd): ... try: ... func(*args, **argd) ... except: ... print "error" #substitute your own error handling ... return _call_func ... &gt;&gt;&gt; @log_error ... def foo(a): ... raise AttributeError ... &gt;&gt;&gt; foo(1) error </code></pre> <p>If you use log_error as a decorator on your view, it will automatically handle whatever errors happened within it.</p> <blockquote> <p>The process<code>_</code>exception function is called for some exceptions (eg: assert(False) in views.py) but process<code>_</code>exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors?</p> </blockquote> <p>In Python, all errors are run-time errors. The reason why this is causing problems is because these errors occur immediately when the module is imported before your view is ever called. The first method I posted will catch errors like these for debugging. You might be able to figure something out for production, but I'd argue that you have worse problems if you're getting ImportErrors in a production app (and you're not doing any dynamic importing).</p> <p>A tool like <a href="http://www.logilab.org/857">pylint</a> can help you eliminate these kinds of problems though.</p>
13
2009-03-27T19:51:37Z
[ "python", "django", "facebook" ]
Log all errors to console or file on Django site
690,723
<p>How can I get Django 1.0 to write <b>all</b> errors to the console or a log file when running runserver in debug mode? </p> <p>I've tried using a middleware class with process_exception function as described in the accepted answer to this question:</p> <p><a href="http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites">http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites</a></p> <p>The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.</p> <p>I've watched Simon Willison's fantastic presentation on Django debugging (<a href="http://simonwillison.net/2008/May/22/debugging/">http://simonwillison.net/2008/May/22/debugging/</a>) but I didn't see an option that would work well for me.</p> <p>In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for <b>all</b> types of errors to be written to the console or file.</p> <p><b>Edit:</b> I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.</p> <p>Thanks, Jeff</p>
13
2009-03-27T17:30:45Z
693,616
<p>If you are on a *nix system you could </p> <p>write to a log (eg. mylog.txt) in python then run "tail -f mylog.txt" in the console</p> <p>this is a handy way to view any kind of log in near real time</p>
-1
2009-03-28T22:03:55Z
[ "python", "django", "facebook" ]
Log all errors to console or file on Django site
690,723
<p>How can I get Django 1.0 to write <b>all</b> errors to the console or a log file when running runserver in debug mode? </p> <p>I've tried using a middleware class with process_exception function as described in the accepted answer to this question:</p> <p><a href="http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites">http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites</a></p> <p>The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.</p> <p>I've watched Simon Willison's fantastic presentation on Django debugging (<a href="http://simonwillison.net/2008/May/22/debugging/">http://simonwillison.net/2008/May/22/debugging/</a>) but I didn't see an option that would work well for me.</p> <p>In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for <b>all</b> types of errors to be written to the console or file.</p> <p><b>Edit:</b> I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.</p> <p>Thanks, Jeff</p>
13
2009-03-27T17:30:45Z
696,029
<blockquote> <p>The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors?</p> </blockquote> <p>No, it's just because <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/?#process-exception" rel="nofollow">process_exception middleware is only called if an exception is raised in the view</a>.</p> <p>I think <a href="http://docs.djangoproject.com/en/dev/ref/settings/#debug-propagate-exceptions" rel="nofollow">DEBUG_PROPAGATE_EXCEPTIONS</a> (as mentioned first by Jason Baker) is what you need here, but I don't think you don't need to do anything additional (i.e. sys.excepthook, etc) if you just want the traceback dumped to console.</p> <p>If you want to do anything more complex with the error (i.e. dump it to file or DB), the simplest approach would be the <a href="http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception" rel="nofollow">got_request_exception signal</a>, which Django sends for any request-related exception, whether it was raised in the view or not.</p> <p>The <a href="http://code.djangoproject.com/browser/django/trunk/django/core/handlers/base.py#L66" rel="nofollow">get_response</a> and <a href="http://code.djangoproject.com/browser/django/trunk/django/core/handlers/base.py#L136" rel="nofollow">handle_uncaught_exception</a> methods of django.core.handlers.BaseHandler are instructive (and brief) reading in this area.</p> <blockquote> <p>without having to add any additional exception handling to the code. I've never seen exception handling around import statements.</p> </blockquote> <p>Look around a bit more, you'll see it done (often in cases where you want to handle the absence of a dependency in some particular way). That said, it would of course be quite ugly if you had to go sprinkling additional try-except blocks all over your code to make a global change to how exceptions are handled!</p>
6
2009-03-30T04:53:02Z
[ "python", "django", "facebook" ]
Log all errors to console or file on Django site
690,723
<p>How can I get Django 1.0 to write <b>all</b> errors to the console or a log file when running runserver in debug mode? </p> <p>I've tried using a middleware class with process_exception function as described in the accepted answer to this question:</p> <p><a href="http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites">http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites</a></p> <p>The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.</p> <p>I've watched Simon Willison's fantastic presentation on Django debugging (<a href="http://simonwillison.net/2008/May/22/debugging/">http://simonwillison.net/2008/May/22/debugging/</a>) but I didn't see an option that would work well for me.</p> <p>In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for <b>all</b> types of errors to be written to the console or file.</p> <p><b>Edit:</b> I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.</p> <p>Thanks, Jeff</p>
13
2009-03-27T17:30:45Z
1,727,286
<p><a href="http://groups.google.com/group/django-nashville/browse%5Fthread/thread/b4a258250cfa285a?pli=1" rel="nofollow">http://groups.google.com/group/django-nashville/browse%5Fthread/thread/b4a258250cfa285a?pli=1</a></p>
1
2009-11-13T05:24:22Z
[ "python", "django", "facebook" ]