title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | 1,583 | 2008-09-25T21:01:57Z | 30,329,887 | 14 | 2015-05-19T15:27:13Z | [
"python"
] | What is the difference between a function decorated with [`@staticmethod`](http://docs.python.org/library/functions.html#staticmethod) and one decorated with [`@classmethod`](http://docs.python.org/library/functions.html#classmethod)? | I think a better question is "When would you use @classmethod vs @staticmethod?"
@classmethod allows you easy access to private members that are associated to the class definition. this is a great way to do singletons, or factory classes that control the number of instances of the created objects exist.
@staticmethod... |
Get last n lines of a file with Python, similar to tail | 136,168 | 122 | 2008-09-25T21:11:11Z | 136,280 | 57 | 2008-09-25T21:30:14Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] | I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a `tail()` method that can read `n` lines from the bottom and supports an offset. What I came up with looks like this... | Assumes a unix-like system.
```
import os
def tail(f, n, offset=0):
stdin,stdout = os.popen2("tail -n "+n+offset+" "+f)
stdin.close()
lines = stdout.readlines(); stdout.close()
return lines[:,-offset]
``` |
Get last n lines of a file with Python, similar to tail | 136,168 | 122 | 2008-09-25T21:11:11Z | 136,368 | 97 | 2008-09-25T21:43:18Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] | I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a `tail()` method that can read `n` lines from the bottom and supports an offset. What I came up with looks like this... | This may be quicker than yours. Makes no assumptions about line length. Backs through the file one block at a time till it's found the right number of '\n' characters.
```
def tail( f, lines=20 ):
total_lines_wanted = lines
BLOCK_SIZE = 1024
f.seek(0, 2)
block_end_byte = f.tell()
lines_to_go = tot... |
Get last n lines of a file with Python, similar to tail | 136,168 | 122 | 2008-09-25T21:11:11Z | 280,083 | 19 | 2008-11-11T05:17:18Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] | I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a `tail()` method that can read `n` lines from the bottom and supports an offset. What I came up with looks like this... | If reading the whole file is acceptable then use a deque.
```
from collections import deque
deque(f, maxlen=n)
```
Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.
```
import itertools
def maxque(items, size):
items = iter(items)
q = deque(itertools.islice(items, size))
... |
Get last n lines of a file with Python, similar to tail | 136,168 | 122 | 2008-09-25T21:11:11Z | 692,616 | 17 | 2009-03-28T11:13:44Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] | I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a `tail()` method that can read `n` lines from the bottom and supports an offset. What I came up with looks like this... | The code I ended up using. I think this is the best so far:
```
def tail(f, n, offset=None):
"""Reads a n lines from f with an offset of offset lines. The return
value is a tuple in the form ``(lines, has_more)`` where `has_more` is
an indicator that is `True` if there are more lines in the file.
"""
... |
Get last n lines of a file with Python, similar to tail | 136,168 | 122 | 2008-09-25T21:11:11Z | 6,813,975 | 11 | 2011-07-25T09:18:10Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] | I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a `tail()` method that can read `n` lines from the bottom and supports an offset. What I came up with looks like this... | Simple and fast solution with mmap:
```
import mmap
import os
def tail(filename, n):
"""Returns last n lines from the filename. No exception handling"""
size = os.path.getsize(filename)
with open(filename, "rb") as f:
# for Windows the mmap parameters are different
fm = mmap.mmap(f.fileno(... |
Get last n lines of a file with Python, similar to tail | 136,168 | 122 | 2008-09-25T21:11:11Z | 7,047,765 | 18 | 2011-08-13T00:43:38Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] | I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a `tail()` method that can read `n` lines from the bottom and supports an offset. What I came up with looks like this... | S.Lott's answer above almost works for me but ends up giving me partial lines. It turns out that it corrupts data on block boundaries because data holds the read blocks in reversed order. When ''.join(data) is called, the blocks are in the wrong order. This fixes that.
```
def tail(f, window=20):
"""
Returns t... |
Get last n lines of a file with Python, similar to tail | 136,168 | 122 | 2008-09-25T21:11:11Z | 13,790,289 | 10 | 2012-12-09T18:21:42Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] | I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a `tail()` method that can read `n` lines from the bottom and supports an offset. What I came up with looks like this... | Here is my answer. Pure python. Using timeit it seems pretty fast. Tailing 100 lines of a log file that has 100,000 lines:
```
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=10)
0.0014600753784179688
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log... |
Key Presses in Python | 136,734 | 13 | 2008-09-25T22:58:01Z | 136,780 | 17 | 2008-09-25T23:09:39Z | [
"python",
"keypress"
] | Is it possible to make it appear to a system that a key was pressed, for example I need to make `A` key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.
A better way to put it, I need to ... | Install the [pywin32](http://sourceforge.net/projects/pywin32/) extensions. Then you can do the following:
```
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want
```
Search for documentation of the W... |
How can I perform a HEAD request with the mechanize library? | 137,580 | 3 | 2008-09-26T03:20:19Z | 137,624 | 8 | 2008-09-26T03:37:33Z | [
"python",
"http-headers",
"mechanize"
] | I know how to do a HEAD request with httplib, but I have to use mechanize for this site.
Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.
Any suggestions how I could accomplish this? | Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example:
```
import mechanize
class HeadRequest(mechanize.Request):
def get_method(self):
return "HEAD"
request = HeadRequest("http://www.example.com/")
response = mechanize.urlopen(request)
print respo... |
Is there something like Python's getattr() in C#? | 138,045 | 12 | 2008-09-26T06:35:30Z | 138,079 | 9 | 2008-09-26T06:57:23Z | [
"c#",
"python",
"user-interface"
] | Is there something like [Python's getattr()](http://effbot.org/zone/python-getattr.htm) in C#? I would like to create a window by reading a list which contains the names of controls to put on the window. | There is also [Type.InvokeMember](http://msdn.microsoft.com/en-us/library/66btctbe.aspx).
```
public static class ReflectionExt
{
public static object GetAttr(this object obj, string name)
{
Type type = obj.GetType();
BindingFlags flags = BindingFlags.Instance |
... |
How can I read the RGB value of a given pixel in Python? | 138,250 | 63 | 2008-09-26T08:10:50Z | 138,260 | 108 | 2008-09-26T08:15:56Z | [
"python",
"graphics",
"rgb"
] | If I open an image with `open("image.jpg")`, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?
Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?
It would be so much better if I didn't have to download any additional libraries... | It's probably best to use the [Python Image Library](http://www.pythonware.com/products/pil/) to do this which I'm afraid is a separate download.
The easiest way to do what you want is via the [load() method on the Image object](http://effbot.org/imagingbook/image.htm) which returns a pixel access object which you can... |
How can I read the RGB value of a given pixel in Python? | 138,250 | 63 | 2008-09-26T08:10:50Z | 139,070 | 20 | 2008-09-26T12:20:38Z | [
"python",
"graphics",
"rgb"
] | If I open an image with `open("image.jpg")`, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?
Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?
It would be so much better if I didn't have to download any additional libraries... | **PyPNG - lightweight PNG decoder/encoder**
Although the question hints at JPG, I hope my answer will be useful to some people.
Here's how to read and write PNG pixels using [PyPNG module](https://pypi.python.org/pypi/pypng/0.0.18):
```
import png, array
point = (2, 10) # coordinates of pixel to be painted red
rea... |
How can I read the RGB value of a given pixel in Python? | 138,250 | 63 | 2008-09-26T08:10:50Z | 5,365,853 | 8 | 2011-03-20T00:10:43Z | [
"python",
"graphics",
"rgb"
] | If I open an image with `open("image.jpg")`, how can I get the RGB values of a pixel, if I have the coordinates of the pixel?
Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?
It would be so much better if I didn't have to download any additional libraries... | As Dave Webb said.
Here is my working code snippet printing the pixel colours from an image:
```
import os, sys
import Image
im = Image.open("image.jpg")
x = 3
y = 4
pix = im.load()
print pix[x,y]
``` |
Pure Python XSLT library | 138,502 | 19 | 2008-09-26T09:43:43Z | 592,466 | 9 | 2009-02-26T21:13:59Z | [
"python",
"xml",
"xslt"
] | Is there an XSLT library that is pure Python?
Installing libxml2+libxslt or any similar C libraries is a problem on some of the platforms I need to support.
I really only need basic XSLT support, and speed is not a major issue. | Unfortunately there are no pure-python XSLT processors at the moment. If you need something that is more platform independent, you may want to use a Java-based XSLT processor like [Saxon](http://saxon.sourceforge.net/). 4Suite is working on a pure-python XPath parser, but it doesn't look like a pure XSLT processor will... |
Is it feasible to compile Python to machine code? | 138,521 | 93 | 2008-09-26T09:51:51Z | 138,553 | 15 | 2008-09-26T10:00:15Z | [
"python",
"c",
"linker",
"compilation"
] | How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?
Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.
Also, you would need to b... | Try [ShedSkin](http://shed-skin.blogspot.com/) Python-to-C++ compiler, but it is far from perfect. Also there is Psyco - Python JIT if only speedup is needed. But IMHO this is not worth the effort. For speed-critical parts of code best solution would be to write them as C/C++ extensions. |
Is it feasible to compile Python to machine code? | 138,521 | 93 | 2008-09-26T09:51:51Z | 138,582 | 11 | 2008-09-26T10:06:06Z | [
"python",
"c",
"linker",
"compilation"
] | How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?
Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.
Also, you would need to b... | [PyPy](http://codespeak.net/pypy/dist/pypy/doc/home.html) is a project to reimplement Python in Python, using compilation to native code as one of the implementation strategies (others being a VM with JIT, using JVM, etc.). Their compiled C versions run slower than CPython on average but much faster for some programs.
... |
Is it feasible to compile Python to machine code? | 138,521 | 93 | 2008-09-26T09:51:51Z | 138,585 | 41 | 2008-09-26T10:06:43Z | [
"python",
"c",
"linker",
"compilation"
] | How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?
Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.
Also, you would need to b... | As @Greg Hewgill says it, there are good reasons why this is not always possible. However, certain kinds of code (like very algorithmic code) can be turned into "real" machine code.
There are several options:
* Use [Psyco](http://psyco.sourceforge.net/), which emits machine code dynamically. You should choose careful... |
Is it feasible to compile Python to machine code? | 138,521 | 93 | 2008-09-26T09:51:51Z | 138,586 | 8 | 2008-09-26T10:06:46Z | [
"python",
"c",
"linker",
"compilation"
] | How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?
Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.
Also, you would need to b... | [Pyrex](http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) is a subset of the Python language that compiles to C, done by the guy that first built [list comprehensions](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) for Python. It was mainly developed for building wrappers but can be used in a mor... |
Is it feasible to compile Python to machine code? | 138,521 | 93 | 2008-09-26T09:51:51Z | 11,415,005 | 14 | 2012-07-10T14:00:44Z | [
"python",
"c",
"linker",
"compilation"
] | How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?
Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.
Also, you would need to b... | py2c ( <http://code.google.com/p/py2c>) can convert python code to c/c++
I am the solo developer of py2c. |
Can Regex be used for this particular string manipulation? | 138,552 | 7 | 2008-09-26T10:00:10Z | 138,615 | 8 | 2008-09-26T10:18:50Z | [
"c#",
"python",
"regex",
"language-agnostic"
] | I need to replace character (say) **x** with character (say) **P** in a string, but only if it is contained in a quoted substring.
An example makes it clearer:
```
axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
```
Let's assume, for the sake of simplicity, that quotes always come in pairs.
The obvious way is to jus... | I was able to do this with Python:
```
>>> import re
>>> re.sub(r"x(?=[^']*'([^']|'[^']*')*$)", "P", "axbx'cxdxe'fxgh'ixj'k")
"axbx'cPdPe'fxgh'iPj'k"
```
What this does is use the non-capturing match (?=...) to check that the character x is within a quoted string. It looks for some nonquote characters up to the next ... |
Can Regex be used for this particular string manipulation? | 138,552 | 7 | 2008-09-26T10:00:10Z | 138,755 | 9 | 2008-09-26T11:04:02Z | [
"c#",
"python",
"regex",
"language-agnostic"
] | I need to replace character (say) **x** with character (say) **P** in a string, but only if it is contained in a quoted substring.
An example makes it clearer:
```
axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
```
Let's assume, for the sake of simplicity, that quotes always come in pairs.
The obvious way is to jus... | I converted Greg Hewgill's python code to C# and it worked!
```
[Test]
public void ReplaceTextInQuotes()
{
Assert.AreEqual("axbx'cPdPe'fxgh'iPj'k",
Regex.Replace("axbx'cxdxe'fxgh'ixj'k",
@"x(?=[^']*'([^']|'[^']*')*$)", "P"));
}
```
That test passed. |
Vim extension (via Python)? | 138,680 | 10 | 2008-09-26T10:45:57Z | 138,709 | 19 | 2008-09-26T10:55:13Z | [
"python",
"vim"
] | is it possible to extend vim functionality via custom extension (preferably, written in Python)?
What I need ideally is custom command when in command mode. E.g.
ESC
:do\_this
:do\_that | vim supports scripting in python (and in perl as well, I think).
You just have to make sure that the vim distribution you are using has been compiled with python support.
If you are using a Linux system, you can download the source and then compile it with
```
./configure --enable-pythoninterp
make
sudo make instal... |
How do I test a django database schema? | 138,851 | 6 | 2008-09-26T11:23:51Z | 139,137 | 8 | 2008-09-26T12:32:46Z | [
"python",
"django",
"unit-testing",
"model"
] | I want to write tests that can show whether or not the database is in sync with my models.py file. Actually I have already written them, only to find out that django creates a new database each time the tests are run based on the models.py file.
Is there any way I can make the **models.py test** use the existing databa... | What we did was override the default test\_runner so that it wouldn't create a new database to test against. This way, it runs the test against whatever our current local database looks like. But be very careful if you use this method because any changes to data you make in your tests will be permanent. I made sure tha... |
listing all functions in a python module | 139,180 | 164 | 2008-09-26T12:38:52Z | 139,193 | 238 | 2008-09-26T12:40:20Z | [
"python"
] | I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?... | You can use `dir(module)` to see all available methods/attributes. Also check out PyDocs. |
listing all functions in a python module | 139,180 | 164 | 2008-09-26T12:38:52Z | 139,198 | 69 | 2008-09-26T12:41:04Z | [
"python"
] | I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?... | The inspect module. Also see the [`pydoc`](http://docs.python.org/2/library/pydoc.html) module, the `help()` function in the interactive interpreter and the `pydoc` command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also gen... |
listing all functions in a python module | 139,180 | 164 | 2008-09-26T12:38:52Z | 139,258 | 44 | 2008-09-26T12:50:39Z | [
"python"
] | I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?... | ```
import types
import yourmodule
print [yourmodule.__dict__.get(a) for a in dir(yourmodule)
if isinstance(yourmodule.__dict__.get(a), types.FunctionType)]
``` |
listing all functions in a python module | 139,180 | 164 | 2008-09-26T12:38:52Z | 140,106 | 76 | 2008-09-26T15:08:54Z | [
"python"
] | I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?... | Once you've `import`ed the module, you can just do:
```
help(modulename)
```
... To get the docs on all the functions at once, interactively. Or you can use:
```
dir(modulename)
```
... To simply list the names of all the functions and variables defined in the module. |
listing all functions in a python module | 139,180 | 164 | 2008-09-26T12:38:52Z | 142,501 | 20 | 2008-09-26T23:41:16Z | [
"python"
] | I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?... | This will do the trick:
```
dir(module)
```
However, if you find it annoying to read the returned list, just use the following loop to get one name per line.
```
for i in dir(module): print i
``` |
listing all functions in a python module | 139,180 | 164 | 2008-09-26T12:38:52Z | 9,794,849 | 37 | 2012-03-20T20:59:57Z | [
"python"
] | I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?... | An example with inspect:
```
from inspect import getmembers, isfunction
from my_project import my_module
functions_list = [o for o in getmembers(my_module) if isfunction(o[1])]
```
getmembers returns a list of (object\_name, object\_type) tuples.
You can replace isfunction with any of the other isXXX functions in t... |
listing all functions in a python module | 139,180 | 164 | 2008-09-26T12:38:52Z | 10,079,706 | 13 | 2012-04-09T20:51:58Z | [
"python"
] | I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?... | `dir(module)` is the standard way when using a script or the standard interpreter, as mentioned in most answers.
However with an interactive python shell like [IPython](http://ipython.org) you can use tab-completion to get an overview of all objects defined in the module.
This is much more convenient, than using a scr... |
listing all functions in a python module | 139,180 | 164 | 2008-09-26T12:38:52Z | 31,005,891 | 10 | 2015-06-23T14:39:55Z | [
"python"
] | I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?... | For completeness' sake, I'd like to point out that sometimes you may want to *parse* code instead of importing it. An `import` will *execute* top-level expressions, and that could be a problem.
For example, I'm letting users select entry point functions for packages being made with [zipapp](https://docs.python.org/dev... |
Why results of map() and list comprehension are different? | 139,819 | 9 | 2008-09-26T14:19:48Z | 139,899 | 9 | 2008-09-26T14:31:47Z | [
"python",
"closures",
"list-comprehension",
"late-binding",
"generator-expression"
] | The following test fails:
```
#!/usr/bin/env python
def f(*args):
"""
>>> t = 1, -1
>>> f(*map(lambda i: lambda: i, t))
[1, -1]
>>> f(*(lambda: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda: i for i in t]) # -> [-1, -1]
[1, -1]
"""
alist = [a() for a in args]
print(ali... | They are different, because the value of `i` in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in `f`.
By that time, `i` is bound to the last value if `t`, which is -1.
So basically, this is what the list comprehension does (likewise for the genexp... |
Authenticating against active directory using python + ldap | 140,439 | 70 | 2008-09-26T16:08:11Z | 140,495 | 37 | 2008-09-26T16:18:18Z | [
"python",
"authentication",
"active-directory",
"ldap"
] | How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.
I can't even bind to perform a simple query:
```
import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.S... | I was missing
```
l.set_option(ldap.OPT_REFERRALS, 0)
```
From the init. |
Authenticating against active directory using python + ldap | 140,439 | 70 | 2008-09-26T16:08:11Z | 141,729 | 22 | 2008-09-26T20:23:04Z | [
"python",
"authentication",
"active-directory",
"ldap"
] | How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.
I can't even bind to perform a simple query:
```
import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.S... | If you are open to using pywin32, you can use Win32 calls from Python. This is what we do in our CherryPy web server:
```
import win32security
token = win32security.LogonUser(
username,
domain,
password,
win32security.LOGON32_LOGON_NETWORK,
win32security.LOGON32_PROVIDER_DEFAULT)
authenticated = bo... |
Authenticating against active directory using python + ldap | 140,439 | 70 | 2008-09-26T16:08:11Z | 1,126,391 | 7 | 2009-07-14T16:02:22Z | [
"python",
"authentication",
"active-directory",
"ldap"
] | How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.
I can't even bind to perform a simple query:
```
import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.S... | That worked for me, **l.set\_option(ldap.OPT\_REFERRALS, 0)** was the key to access the ActiveDirectory. Moreover, I think that you should add an "con.unbind()" in order to close the connection before finishing the script. |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | 10 | 2008-09-26T17:20:14Z | 140,818 | 25 | 2008-09-26T17:30:39Z | [
"java",
"python",
"file-traversal"
] | In Java you can do `File.listFiles()` and receive all of the files in a directory. You can then easily recurse through directory trees.
Is there an analogous way to do this in Python? | Yes, there is. The Python way is even better.
There are three possibilities:
**1) Like File.listFiles():**
Python has the function os.listdir(path). It works like the Java method.
**2) pathname pattern expansion with glob:**
The module glob contains functions to list files on the file system using Unix shell like ... |
How to list only top level directories in Python? | 141,291 | 68 | 2008-09-26T19:01:06Z | 141,313 | 9 | 2008-09-26T19:04:46Z | [
"python",
"filesystems"
] | I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.
Let's see if an example helps. In the current directory we have:
```
>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', ... | ```
directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]
``` |
How to list only top level directories in Python? | 141,291 | 68 | 2008-09-26T19:01:06Z | 141,327 | 61 | 2008-09-26T19:06:57Z | [
"python",
"filesystems"
] | I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.
Let's see if an example helps. In the current directory we have:
```
>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', ... | Filter the result using os.path.isdir() (and use os.path.join() to get the real path):
```
>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curse... |
How to list only top level directories in Python? | 141,291 | 68 | 2008-09-26T19:01:06Z | 141,336 | 26 | 2008-09-26T19:10:36Z | [
"python",
"filesystems"
] | I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.
Let's see if an example helps. In the current directory we have:
```
>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', ... | Filter the list using os.path.isdir to detect directories.
```
filter(os.path.isdir, os.listdir(os.getcwd()))
``` |
How to list only top level directories in Python? | 141,291 | 68 | 2008-09-26T19:01:06Z | 142,368 | 8 | 2008-09-26T22:32:50Z | [
"python",
"filesystems"
] | I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.
Let's see if an example helps. In the current directory we have:
```
>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', ... | Note that, instead of doing `os.listdir(os.getcwd())`, it's preferable to do `os.listdir(os.path.curdir)`. One less function call, and it's as portable.
So, to complete the answer, to get a list of directories in a folder:
```
def listdirs(folder):
return [d for d in os.listdir(folder) if os.path.isdir(os.path.jo... |
How to list only top level directories in Python? | 141,291 | 68 | 2008-09-26T19:01:06Z | 142,535 | 99 | 2008-09-26T23:57:04Z | [
"python",
"filesystems"
] | I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.
Let's see if an example helps. In the current directory we have:
```
>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', ... | ```
os.walk('.').next()[1]
``` |
How do I find what is using memory in a Python process in a production system? | 141,351 | 27 | 2008-09-26T19:13:14Z | 9,567,831 | 18 | 2012-03-05T13:56:17Z | [
"python",
"memory-leaks",
"coredump"
] | My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a [Python memory profiler](http://stackoverflow.com/questions/110259/python-memory-profiler) (specifically, Heapy) with some success in the development environment, but it can't help me wit... | Using Python's `gc` garbage collector interface and `sys.getsizeof()` it's possible to dump all the python objects and their sizes. Here's the code I'm using in production to troubleshoot a memory leak:
```
rss = psutil.Process(os.getpid()).get_memory_info().rss
# Dump variables if using more than 100MB of memory
if r... |
How do I wrap a string in a file in Python? | 141,449 | 49 | 2008-09-26T19:33:55Z | 141,451 | 67 | 2008-09-26T19:34:04Z | [
"python",
"string",
"file",
"wrap"
] | How do I create a file-like object (same duck type as File) with the contents of a string? | Use the [StringIO](https://docs.python.org/2/library/stringio.html) module. For example:
```
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
```
I use cStringIO (which is faster), but note that it doesn't [accept Unicode strings that cannot be encoded as plain ASCII strings](http://docs.... |
How do I wrap a string in a file in Python? | 141,449 | 49 | 2008-09-26T19:33:55Z | 142,251 | 19 | 2008-09-26T22:00:25Z | [
"python",
"string",
"file",
"wrap"
] | How do I create a file-like object (same duck type as File) with the contents of a string? | In Python 3.0:
```
import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
``` |
Is there an easy way to populate SlugField from CharField? | 141,487 | 20 | 2008-09-26T19:40:57Z | 141,554 | 43 | 2008-09-26T19:51:46Z | [
"python",
"django",
"slug"
] | ```
class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
```
Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin. | for Admin in Django 1.0 and up, you'd need to use
```
prepopulated_fields = {'slug': ('title',), }
```
in your admin.py
Your key in the prepopulated\_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.
Outside of admin, you can use the `slugify` function in your... |
overloading __init__ in python | 141,545 | 186 | 2008-09-26T19:49:46Z | 141,777 | 257 | 2008-09-26T20:30:15Z | [
"python",
"constructor",
"operator-overloading"
] | Let's say I have a class that has a member called data which is a list.
I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.
What's your technique for doing this?
Do you just check the type by looking at `__class__`?
Is there so... | A much neater way to get 'alternate constructors' is to use classmethods. For instance:
```
>>> class MyData:
... def __init__(self, data):
... "Initialize MyData from a sequence"
... self.data = data
...
... @classmethod
... def fromfilename(cls, filename):
... "Initialize MyD... |
overloading __init__ in python | 141,545 | 186 | 2008-09-26T19:49:46Z | 212,130 | 26 | 2008-10-17T13:34:31Z | [
"python",
"constructor",
"operator-overloading"
] | Let's say I have a class that has a member called data which is a list.
I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.
What's your technique for doing this?
Do you just check the type by looking at `__class__`?
Is there so... | Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:
Here's a sample (this is a `read` method and not a constructor, but the idea is the same):
```
def read(self, str... |
What limitations have closures in Python compared to language X closures? | 141,642 | 40 | 2008-09-26T20:06:41Z | 141,710 | 39 | 2008-09-26T20:19:27Z | [
"python",
"closures"
] | Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures.
Some limitations are mentioned in the [Closures in Python](http://ivan.truemesh.com/archives/000411.html) (compared to Ruby's closures), but the article is old and many limitations do not exist ... | The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only:
```
>>> def outer(x):
... def inner_reads():
... # Will return outer's 'x'.
... return x
... def inner_writes(y):
... # Will assign to a local 'x', no... |
Python: How to make a cross-module variable? | 142,545 | 82 | 2008-09-26T23:59:47Z | 142,566 | 75 | 2008-09-27T00:09:29Z | [
"python",
"module",
"global"
] | The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?
The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd b... | I don't endorse this solution in any way, shape or form. But if you add a variable to the `__builtin__` module, it will be accessible as if a global from any other module that includes `__builtin__` -- which is all of them, by default.
a.py contains
```
print foo
```
b.py contains
```
import __builtin__
__builtin__... |
Python: How to make a cross-module variable? | 142,545 | 82 | 2008-09-26T23:59:47Z | 142,581 | 17 | 2008-09-27T00:15:19Z | [
"python",
"module",
"global"
] | The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?
The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd b... | Define a module ( call it "globalbaz" ) and have the variables defined inside it. All the modules using this "pseudoglobal" should import the "globalbaz" module, and refer to it using "globalbaz.var\_name"
This works regardless of the place of the change, you can change the variable before or after the import. The imp... |
Python: How to make a cross-module variable? | 142,545 | 82 | 2008-09-26T23:59:47Z | 142,601 | 101 | 2008-09-27T00:25:00Z | [
"python",
"module",
"global"
] | The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?
The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd b... | If you need a global cross-module variable maybe just simple global module-level variable will suffice.
a.py:
```
var = 1
```
b.py:
```
import a
print a.var
import c
print a.var
```
c.py:
```
import a
a.var = 2
```
Test:
```
$ python b.py
# -> 1 2
```
Real-world example: [Django's global\_settings.py](https://... |
Python: How to make a cross-module variable? | 142,545 | 82 | 2008-09-26T23:59:47Z | 3,269,974 | 8 | 2010-07-17T02:22:22Z | [
"python",
"module",
"global"
] | The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?
The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd b... | You can pass the globals of one module to onother:
In Module A:
```
import module_b
my_var=2
module_b.do_something_with_my_globals(globals())
print my_var
```
In Module B:
```
def do_something_with_my_globals(glob): # glob is simply a dict.
glob["my_var"]=3
``` |
Python: How to make a cross-module variable? | 142,545 | 82 | 2008-09-26T23:59:47Z | 15,035,172 | 13 | 2013-02-22T23:48:03Z | [
"python",
"module",
"global"
] | The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?
The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd b... | I believe that there are plenty of circumstances in which it does make sense and it simplifies programming to have some globals that are known across several (tightly coupled) modules. In this spirit, I would like to elaborate a bit on the idea of having a module of globals which is imported by those modules which need... |
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04? | 142,764 | 8 | 2008-09-27T02:15:03Z | 142,770 | 15 | 2008-09-27T02:19:38Z | [
"python",
"linux",
"ubuntu",
"installation"
] | I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.
Thanks
... | With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version:
First, install 2.6rc2. You can download the source from the [Python website](http://www.python.org/download/releases/2.6/). Standard `./configure && make && sudo make install` installation style.
... |
Does Python have a bitfield type? | 142,812 | 34 | 2008-09-27T02:47:40Z | 143,221 | 22 | 2008-09-27T08:20:43Z | [
"python",
"bit-fields",
"bitarray"
] | I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution? | [Bitarray](http://pypi.python.org/pypi/bitarray/) was the best answer I found, when I recently had a similar need. It's a C extension (so much faster than BitVector, which is pure python) and stores its data in an actual bitfield (so it's eight times more memory efficient than a numpy boolean array, which appears to us... |
Does Python have a bitfield type? | 142,812 | 34 | 2008-09-27T02:47:40Z | 1,574,928 | 10 | 2009-10-15T20:43:54Z | [
"python",
"bit-fields",
"bitarray"
] | I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution? | You should take a look at the [bitstring](http://python-bitstring.googlecode.com) module, which has recently reached version 2.0.
The binary data is compactly stored as a byte array and can be easily created, modified and analysed.
You can create `BitString` objects from binary, octal, hex, integers (big or little end... |
Does Python have a bitfield type? | 142,812 | 34 | 2008-09-27T02:47:40Z | 11,481,471 | 24 | 2012-07-14T06:02:45Z | [
"python",
"bit-fields",
"bitarray"
] | I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution? | If you mainly want to be able to name your bit fields and easily manipulate them, e.g. to work with flags represented as single bits in a communications protocol, then you can use the standard Structure and Union features of [ctypes](http://docs.python.org/library/ctypes.html), as described at [How Do I Properly Declar... |
Drag and drop onto Python script in Windows Explorer | 142,844 | 37 | 2008-09-27T03:02:30Z | 142,854 | 46 | 2008-09-27T03:06:25Z | [
"python",
"windows",
"drag-and-drop",
"windows-explorer"
] | I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.
Is there some kind of configuration that needs to be done... | Sure. From a [mindless technology article called "Make Python Scripts Droppable in Windows"](http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/), you can add a drop handler by adding a registry key:
> Hereâs a registry import file that you can use to do this. Copy the
> foll... |
Drag and drop onto Python script in Windows Explorer | 142,844 | 37 | 2008-09-27T03:02:30Z | 10,246,159 | 18 | 2012-04-20T12:21:36Z | [
"python",
"windows",
"drag-and-drop",
"windows-explorer"
] | I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.
Is there some kind of configuration that needs to be done... | write a simple shell script (file.bat)
```
"c:\Python27\python.exe" yourprogram.py %1
```
where %1 stands for the firs argument you pass to the script.
Now drag%drop your target files on the file.bat icon. |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | 22 | 2008-09-27T18:28:42Z | 144,212 | 17 | 2008-09-27T18:42:39Z | [
"python",
"vim",
"code-completion"
] | I'm looking for a suite of plugins that can help me finally switch over to vim full-time.
Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.
What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by impo... | [Here you can find some info](http://www.sontek.net/python-with-a-modular-ide-vim) about this.
It covers code completion, having a list of classes and functions in open files. I haven't got around to do a full configuration for vim, since I don't use Python primarily, but I have the same interests in transforming vim ... |
Python PostgreSQL modules. Which is best? | 144,448 | 20 | 2008-09-27T20:55:04Z | 144,462 | 15 | 2008-09-27T21:00:21Z | [
"python",
"postgresql",
"module"
] | I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore.
Which module do you recommend? Why? | psycopg2 seems to be the most popular. I've never had any trouble with it. There's actually a pure Python interface for PostgreSQL too, called [bpgsql](http://barryp.org/software/bpgsql/). I wouldn't recommend it over psycopg2, but it's recently become capable enough to support Django and is useful if you can't compile... |
Calling C/C++ from python? | 145,270 | 270 | 2008-09-28T05:34:20Z | 145,283 | 23 | 2008-09-28T05:44:11Z | [
"c++",
"python",
"c"
] | What would be the quickest way to construct a python binding to a C or C++ library?
(using windows if this matters) | The quickest way to do this is using [SWIG](http://www.swig.org/).
Example from SWIG [tutorial](http://www.swig.org/tutorial.html):
```
/* File : example.c */
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
```
Interface file:
```
/* example.i */
%module example
%{
/* Put header files her... |
Calling C/C++ from python? | 145,270 | 270 | 2008-09-28T05:34:20Z | 145,287 | 12 | 2008-09-28T05:48:59Z | [
"c++",
"python",
"c"
] | What would be the quickest way to construct a python binding to a C or C++ library?
(using windows if this matters) | Iâve never used it but Iâve heard good things about [ctypes](https://docs.python.org/3.6/library/ctypes.html). If youâre trying to use it with C++, be sure to evade name mangling via [`extern "C"`](http://stackoverflow.com/q/1041866/2157640). *Thanks for the comment, Florian Bösch.* |
Calling C/C++ from python? | 145,270 | 270 | 2008-09-28T05:34:20Z | 145,305 | 9 | 2008-09-28T06:00:56Z | [
"c++",
"python",
"c"
] | What would be the quickest way to construct a python binding to a C or C++ library?
(using windows if this matters) | [This paper, claiming python to be all a scientist needs,](http://openwetware.org/wiki/Julius_B._Lucks/Projects/Python_All_A_Scientist_Needs) basically says: first prototype everything in Python. Then when you need to speed a part up, use SWIG and translate this part to C. |
Calling C/C++ from python? | 145,270 | 270 | 2008-09-28T05:34:20Z | 145,384 | 16 | 2008-09-28T06:53:18Z | [
"c++",
"python",
"c"
] | What would be the quickest way to construct a python binding to a C or C++ library?
(using windows if this matters) | Check out [pyrex](http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) or [cython](http://cython.org/). They're python-like languages for interfacing between C/C++ and python. |
Calling C/C++ from python? | 145,270 | 270 | 2008-09-28T05:34:20Z | 145,436 | 69 | 2008-09-28T07:51:37Z | [
"c++",
"python",
"c"
] | What would be the quickest way to construct a python binding to a C or C++ library?
(using windows if this matters) | You should have a look at [Boost.Python](http://www.boost.org/doc/libs/1_49_0/libs/python/doc/), here is the short introdution taken from their website:
> The Boost Python Library is a framework for interfacing Python and
> C++. It allows you to quickly and seamlessly expose C++ classes
> functions and objects to Pyth... |
Calling C/C++ from python? | 145,270 | 270 | 2008-09-28T05:34:20Z | 145,649 | 339 | 2008-09-28T10:53:31Z | [
"c++",
"python",
"c"
] | What would be the quickest way to construct a python binding to a C or C++ library?
(using windows if this matters) | I like [ctypes](http://docs.python.org/2/library/ctypes.html) a lot, [swig](http://www.swig.org/) always tended to give me [problems](http://groups.google.com/group/comp.lang.python/browse_thread/thread/d94badd9847fe43a?pli=1). Also ctypes has the advantage that you don't need to satisfy any compile time dependency on ... |
Calling C/C++ from python? | 145,270 | 270 | 2008-09-28T05:34:20Z | 23,865,947 | 18 | 2014-05-26T08:30:54Z | [
"c++",
"python",
"c"
] | What would be the quickest way to construct a python binding to a C or C++ library?
(using windows if this matters) | I started my journey in the python <-> C++ binding from this page, with the objective of linking high level data types (multidimensional STL vectors with python lists) :-)
Having tried the solutions based on both [ctypes](https://docs.python.org/2/library/ctypes.html) and [boost.python](http://www.boost.org/doc/libs/1... |
Text difference algorithm | 145,607 | 42 | 2008-09-28T10:12:25Z | 145,609 | 23 | 2008-09-28T10:14:43Z | [
"c#",
"python",
"diff"
] | I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to impleme... | Look at [difflib](http://docs.python.org/lib/module-difflib.html). (Python)
That will calculate the diffs in various formats. You could then use the size of the context diff as a measure of how different two documents are? |
Text difference algorithm | 145,607 | 42 | 2008-09-28T10:12:25Z | 145,634 | 10 | 2008-09-28T10:35:02Z | [
"c#",
"python",
"diff"
] | I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to impleme... | [Bazaar](http://bazaar-vcs.org/) contains an alternative difference algorithm, called [patience diff](http://bramcohen.livejournal.com/37690.html) (there's more info in the comments on that page) which is claimed to be better than the traditional diff algorithm. The file 'patiencediff.py' in the bazaar distribution is ... |
Text difference algorithm | 145,607 | 42 | 2008-09-28T10:12:25Z | 145,659 | 30 | 2008-09-28T11:04:31Z | [
"c#",
"python",
"diff"
] | I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to impleme... | I can recommend to take a look at Neil Fraser's code and articles:
[google-diff-match-patch](http://code.google.com/p/google-diff-match-patch/)
> Currently available in Java,
> JavaScript, C++ and Python. Regardless
> of language, each library features the
> same API and the same functionality.
> All versions also ha... |
Text difference algorithm | 145,607 | 42 | 2008-09-28T10:12:25Z | 146,957 | 25 | 2008-09-28T23:02:33Z | [
"c#",
"python",
"diff"
] | I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to impleme... | In Python, there is [difflib](http://docs.python.org/lib/module-difflib.html), as also others have suggested.
`difflib` offers the [SequenceMatcher](http://docs.python.org/lib/sequence-matcher.html) class, which can be used to give you a similarity ratio. Example function:
```
def text_compare(text1, text2, isjunk=No... |
Text difference algorithm | 145,607 | 42 | 2008-09-28T10:12:25Z | 478,615 | 8 | 2009-01-26T00:44:40Z | [
"c#",
"python",
"diff"
] | I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to impleme... | My current understanding is that the best solution to the Shortest Edit Script (SES) problem is Myers "middle-snake" method with the Hirschberg linear space refinement.
The Myers algorithm is described in:
> E. Myers, ``An O(ND) Difference
> Algorithm and Its Variations,''
> Algorithmica 1, 2 (1986), 251-266.
The ... |
How do I successfully pass a function reference to Djangoâs reverse() function? | 146,522 | 8 | 2008-09-28T19:15:15Z | 146,524 | 8 | 2008-09-28T19:17:44Z | [
"python",
"django"
] | Iâve got a brand new Django project. Iâve added one minimal view function to `views.py`, and one URL pattern to `urls.py`, passing the view by function reference instead of a string:
```
# urls.py
# -------
# coding=utf-8
from django.conf.urls.defaults import *
from myapp import views
urlpatterns = patterns('... | Got it!! The problem is that some of the imports are of `myproject.myapp.views`, and some are just of `myapp.views`. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main `settings.py` probably has a line like:
```
ROOT_URLCONF = `myproj... |
I'm using Python regexes in a criminally inefficient manner | 146,607 | 7 | 2008-09-28T20:03:14Z | 146,671 | 10 | 2008-09-28T20:31:44Z | [
"regex",
"algorithm",
"optimization",
"python"
] | My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:
This input:
> <%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%>
Should produce this output:
> The Web This Is A Test Variable
I've got it working. But looking at my code, I'... | The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled.
Another possibility is to use a single regex as below:
```
MatchedQuotes = re.compile(r"(['\"])(.*)\1", re.LOCALE)
item = MatchedQuotes.s... |
In Django, where is the best place to put short snippets of HTML-formatted data? | 146,789 | 8 | 2008-09-28T21:31:21Z | 146,833 | 12 | 2008-09-28T21:53:27Z | [
"python",
"django",
"model-view-controller",
"design-patterns"
] | This question is related to (but perhaps not quite the same as):
<http://stackoverflow.com/questions/61451/does-django-have-html-helpers>
My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:
I have two classes, Person and Address. There ar... | Sounds like an [inclusion tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags) is what you're looking for. You could have a template and tag for each major variation and use the tag's arguments to customise the context for each template as required.
Basic tag definition:
```
@register... |
How does one do the equivalent of "import * from module" with Python's __import__ function? | 147,507 | 14 | 2008-09-29T04:28:41Z | 147,541 | 26 | 2008-09-29T04:45:07Z | [
"python",
"python-import"
] | Given a string with a module name, how do you import everything in the module as if you had called:
```
from module import *
```
i.e. given string S="module", how does one get the equivalent of the following:
```
__import__(S, fromlist="*")
```
This doesn't seem to perform as expected (as it doesn't import anything... | Please reconsider. The only thing worse than `import *` is *magic* `import *`.
If you really want to:
```
m = __import__ (S)
try:
attrlist = m.__all__
except AttributeError:
attrlist = dir (m)
for attr in attrlist:
globals()[attr] = getattr (m, attr)
``` |
Debug Pylons application through Eclipse | 147,650 | 11 | 2008-09-29T05:41:00Z | 147,768 | 10 | 2008-09-29T07:03:33Z | [
"python",
"eclipse",
"pylons",
"pydev",
"pyramid"
] | I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp? | Create a new launch configuration (Python Run)
**Main tab**
Use paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory)
Don't forget to add the root folder of your application in the PYTHONPATH zone
**Arguments**
Set the base directory to the root folder ... |
How do I manipulate bits in Python? | 147,713 | 24 | 2008-09-29T06:31:27Z | 147,716 | 11 | 2008-09-29T06:34:18Z | [
"python"
] | In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:
```
unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
```
How do I do that in Python ? | ```
value = 0xdeadbeef
value &= ~(1<<10)
``` |
How do I manipulate bits in Python? | 147,713 | 24 | 2008-09-29T06:31:27Z | 147,736 | 36 | 2008-09-29T06:45:34Z | [
"python"
] | In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:
```
unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
```
How do I do that in Python ? | Bitwise operations on Python ints work much like in C. The &, | and ^ operators in Python work just like in C. The ~ operator works as for a signed integer in C; that is, ~x computes -x-1.
You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order ... |
Character reading from file in Python | 147,741 | 60 | 2008-09-29T06:47:47Z | 147,756 | 87 | 2008-09-29T06:55:23Z | [
"python",
"unicode",
"encoding",
"ascii"
] | In a text file, there is a string "I don't like this".
However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use
```
f1 = open (file1, "r")
text = f1.read()
```
command to do the reading.
Now, is it possible to read the str... | Ref: <http://docs.python.org/howto/unicode>
*Reading Unicode from a file is therefore simple:*
```
import codecs
f = codecs.open('unicode.rst', encoding='utf-8')
for line in f:
print repr(line)
```
*It's also possible to open files in update mode, allowing both reading and writing:*
```
f = codecs.open('test', ... |
Character reading from file in Python | 147,741 | 60 | 2008-09-29T06:47:47Z | 147,790 | 8 | 2008-09-29T07:15:17Z | [
"python",
"unicode",
"encoding",
"ascii"
] | In a text file, there is a string "I don't like this".
However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use
```
f1 = open (file1, "r")
text = f1.read()
```
command to do the reading.
Now, is it possible to read the str... | There are a few points to consider.
A \u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:
```
>>> text = u'â'
>>> print repr(text)
u'\u2018'
```
Now if you simply want to print the unicode string prettily, just use unicode's `encode` method:
```
>>> t... |
In Django is there a way to display choices as checkboxes? | 147,752 | 36 | 2008-09-29T06:53:13Z | 147,793 | 66 | 2008-09-29T07:17:46Z | [
"python",
"django"
] | In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:
```
APPROVAL_CHOICES = (
('yes', 'Yes'),
('no', 'No'),
('cancelled', 'Cancelled'),
)
client_approved = models.CharField(choices=APPROVAL_CHOICES)
```
to create a drop down box in... | In terms of the forms library, you would use the [MultipleChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield) field with a [CheckboxSelectMultiple](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple) widget to do that. You could validate the ... |
Preserving signatures of decorated functions | 147,816 | 71 | 2008-09-29T07:32:55Z | 147,835 | 7 | 2008-09-29T07:43:19Z | [
"python",
"decorator"
] | Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.
Here is an example:
```
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int... | Take a look at the [decorator](http://www.phyast.pitt.edu/~micheles/python/documentation.html) module - specifically the [decorator](http://www.phyast.pitt.edu/~micheles/python/documentation.html#decorator-is-a-decorator) decorator, which solves this problem. |
Preserving signatures of decorated functions | 147,816 | 71 | 2008-09-29T07:32:55Z | 147,844 | 8 | 2008-09-29T07:49:23Z | [
"python",
"decorator"
] | Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.
Here is an example:
```
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int... | There is a [decorator module](http://www.phyast.pitt.edu/~micheles/python/documentation.html) with `decorator` decorator you can use:
```
@decorator
def args_as_ints(f, *args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
```
Then ... |
Preserving signatures of decorated functions | 147,816 | 71 | 2008-09-29T07:32:55Z | 147,878 | 50 | 2008-09-29T08:08:30Z | [
"python",
"decorator"
] | Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.
Here is an example:
```
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int... | 1. Install [decorator](http://www.phyast.pitt.edu/~micheles/python/documentation.html#the-solution) module:
```
$ pip install decorator
```
2. Adapt definition of `args_as_ints()`:
```
import decorator
@decorator.decorator
def args_as_ints(f, *args, **kwargs):
args = [int(x) for x in args... |
Using OR comparisons with IF statements | 148,042 | 3 | 2008-09-29T09:12:24Z | 148,048 | 23 | 2008-09-29T09:13:53Z | [
"python",
"comparison",
"boolean"
] | When using IF statements in Python, you have to do the following to make the "cascade" work correctly.
```
if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
```
Is there a way to make Python accept multiple values when checking for "equals to"? Fo... | ```
if job in ("mechanic", "tech"):
print "awesome"
elif job in ("tool", "rock"):
print "dolt"
```
The values in parentheses are a tuple. The `in` operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.
Note that when Python searches a tuple or list using the `in... |
Caching in urllib2? | 148,853 | 11 | 2008-09-29T14:17:13Z | 148,891 | 7 | 2008-09-29T14:25:07Z | [
"python",
"caching",
"urllib2"
] | Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own? | This ActiveState Python recipe might be helpful:
<http://code.activestate.com/recipes/491261/> |
Caching in urllib2? | 148,853 | 11 | 2008-09-29T14:17:13Z | 149,145 | 8 | 2008-09-29T15:21:56Z | [
"python",
"caching",
"urllib2"
] | Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own? | If you don't mind working at a slightly lower level, httplib2 (<http://code.google.com/p/httplib2/>) is an excellent HTTP library that includes caching functionality. |
Caching in urllib2? | 148,853 | 11 | 2008-09-29T14:17:13Z | 149,917 | 7 | 2008-09-29T18:03:38Z | [
"python",
"caching",
"urllib2"
] | Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own? | You could use a decorator function such as:
```
class cache(object):
def __init__(self, fun):
self.fun = fun
self.cache = {}
def __call__(self, *args, **kwargs):
key = str(args) + str(kwargs)
try:
return self.cache[key]
except KeyError:
self.cac... |
Keeping GUIs responsive during long-running tasks | 148,963 | 11 | 2008-09-29T14:37:32Z | 148,979 | 15 | 2008-09-29T14:40:08Z | [
"python",
"user-interface",
"wxpython"
] | Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.
[Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways:
1. Use threads
2. Use wxYield
3. Chunk the work an... | Threads. They're what I always go for because you can do it in every framework you need.
And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks. |
Keeping GUIs responsive during long-running tasks | 148,963 | 11 | 2008-09-29T14:37:32Z | 149,212 | 7 | 2008-09-29T15:34:33Z | [
"python",
"user-interface",
"wxpython"
] | Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.
[Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways:
1. Use threads
2. Use wxYield
3. Chunk the work an... | Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple... |
Background tasks on appengine | 149,307 | 6 | 2008-09-29T15:48:55Z | 1,030,325 | 12 | 2009-06-23T02:11:39Z | [
"python",
"google-app-engine",
"cron"
] | How to run background tasks on appengine ? | You may use the [Task Queue Python API](http://code.google.com/appengine/docs/python/taskqueue/). |
BeautifulSoup's Python 3 compatibility | 149,585 | 18 | 2008-09-29T16:49:50Z | 9,906,160 | 17 | 2012-03-28T11:03:10Z | [
"python",
"python-3.x",
"beautifulsoup",
"porting"
] | Does BeautifulSoup work with Python 3?
If not, how soon will there be a port? Will there be a port at all?
Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?) | Beautiful Soup **4.x** [officially supports Python 3.](https://groups.google.com/forum/#!msg/beautifulsoup/VpNNflJ1rPI/sum07jmEwvgJ)
```
pip install beautifulsoup4
``` |
What is the difference between __reduce__ and __reduce_ex__? | 150,284 | 9 | 2008-09-29T19:31:50Z | 150,309 | 16 | 2008-09-29T19:41:37Z | [
"python",
"pickle"
] | I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both? | [The docs](https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-extension-types) say that
> If provided, at pickling time
> `__reduce__()` will be called with no
> arguments, and it must return either a
> string or a tuple.
On the other hand,
> It is sometimes useful to know the
> protocol version w... |
How do you break into the debugger from Python source code? | 150,375 | 19 | 2008-09-29T19:55:12Z | 150,376 | 26 | 2008-09-29T19:55:20Z | [
"python",
"debugging",
"breakpoints",
"pdb"
] | What do you insert into Python source code to have it break into pdb (when execution gets to that spot)? | ```
import pdb; pdb.set_trace()
```
See [Python: Coding in the Debugger for Beginners](http://jjinux.blogspot.com/2007/08/python-coding-in-debugger-for-beginners.html) for this and more helpful hints. |
How Does One Read Bytes from File in Python | 150,532 | 8 | 2008-09-29T20:37:34Z | 150,584 | 16 | 2008-09-29T20:50:20Z | [
"python",
"id3"
] | Similar to [this](http://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python) question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.
I first read all ten bytes into a string. I then want to parse out the individual p... | If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:
```
>>> s = '\0\x02'
>>> struct.unpack('>H', s)
(2,)
```
Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.
For other sizes of integer, you use different... |
How do I calculate number of days betwen two dates using Python? | 151,199 | 193 | 2008-09-29T23:36:25Z | 151,211 | 301 | 2008-09-29T23:41:22Z | [
"python",
"date"
] | If I have two dates (ex. `'8/18/2008'` and `'9/26/2008'`) what is the best way to get the difference measured in days? | If you have two date objects, you can just subtract them.
```
from datetime import date
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d0 - d1
print delta.days
```
The relevant section of the docs:
<https://docs.python.org/library/datetime.html> |
How do I calculate number of days betwen two dates using Python? | 151,199 | 193 | 2008-09-29T23:36:25Z | 151,212 | 55 | 2008-09-29T23:41:59Z | [
"python",
"date"
] | If I have two dates (ex. `'8/18/2008'` and `'9/26/2008'`) what is the best way to get the difference measured in days? | Using the power of datetime:
```
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print delta.days # that's it
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.