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 |
|---|---|---|---|---|---|---|---|---|---|
How to get instance variables in Python? | 109,087 | 66 | 2008-09-20T19:30:24Z | 109,106 | 78 | 2008-09-20T19:34:17Z | [
"python",
"methods",
"instance-variables"
] | Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:
```
class hi:
def __init__(self):
self.ii = "foo"
self.kk = "bar"
```
Is there a way for me to do this:
```
>>> mystery_method(hi)
["ii", "kk"]
```
Thanks guys!
Edit: I originally ha... | Every object has a `__dict__` variable containing all the variables and its values in it.
Try this
```
>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()
``` |
How to get instance variables in Python? | 109,087 | 66 | 2008-09-20T19:30:24Z | 109,118 | 13 | 2008-09-20T19:38:01Z | [
"python",
"methods",
"instance-variables"
] | Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:
```
class hi:
def __init__(self):
self.ii = "foo"
self.kk = "bar"
```
Is there a way for me to do this:
```
>>> mystery_method(hi)
["ii", "kk"]
```
Thanks guys!
Edit: I originally ha... | You normally can't get instance attributes given just a class, at least not without instantiating the class. You can get instance attributes given an instance, though, or class attributes given a class. See the 'inspect' module. You can't get a list of instance attributes because instances really can have anything as a... |
How to get instance variables in Python? | 109,087 | 66 | 2008-09-20T19:30:24Z | 109,122 | 8 | 2008-09-20T19:39:31Z | [
"python",
"methods",
"instance-variables"
] | Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:
```
class hi:
def __init__(self):
self.ii = "foo"
self.kk = "bar"
```
Is there a way for me to do this:
```
>>> mystery_method(hi)
["ii", "kk"]
```
Thanks guys!
Edit: I originally ha... | You can also test if an object has a specific variable with:
```
>>> hi_obj = hi()
>>> hasattr(hi_obj, "some attribute")
``` |
How to get instance variables in Python? | 109,087 | 66 | 2008-09-20T19:30:24Z | 109,173 | 63 | 2008-09-20T20:02:26Z | [
"python",
"methods",
"instance-variables"
] | Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:
```
class hi:
def __init__(self):
self.ii = "foo"
self.kk = "bar"
```
Is there a way for me to do this:
```
>>> mystery_method(hi)
["ii", "kk"]
```
Thanks guys!
Edit: I originally ha... | Use vars()
```
class Foo(object):
def __init__(self):
self.a = 1
self.b = 2
vars(Foo()) #==> {'a': 1, 'b': 2}
vars(Foo()).keys() #==> ['a', 'b']
``` |
How to get instance variables in Python? | 109,087 | 66 | 2008-09-20T19:30:24Z | 4,522,706 | 10 | 2010-12-23T21:50:34Z | [
"python",
"methods",
"instance-variables"
] | Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:
```
class hi:
def __init__(self):
self.ii = "foo"
self.kk = "bar"
```
Is there a way for me to do this:
```
>>> mystery_method(hi)
["ii", "kk"]
```
Thanks guys!
Edit: I originally ha... | Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like:
```
class foo:
a = 'foo'
b = 'bar'
```
To print all non-callable attributes, you can use the following function:
```
def printVars(object):
for i in [v for v in dir(object) if not... |
Change the width of form elements created with ModelForm in Django | 110,378 | 42 | 2008-09-21T06:15:13Z | 110,414 | 91 | 2008-09-21T06:44:02Z | [
"python",
"html",
"django",
"django-forms",
"django-templates"
] | How can i change the width of a textarea form element if i used ModelForm to create it?
Here is my product class:
```
class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
```
And the templa... | **The easiest way for your use case is to use CSS**. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS.
Example for `long_desc` field in your ProductForm (when your form does not have... |
Change the width of form elements created with ModelForm in Django | 110,378 | 42 | 2008-09-21T06:15:13Z | 640,680 | 14 | 2009-03-12T22:02:52Z | [
"python",
"html",
"django",
"django-forms",
"django-templates"
] | How can i change the width of a textarea form element if i used ModelForm to create it?
Here is my product class:
```
class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
```
And the templa... | Excellent answer by zuber, but I believe there's an error in the example code for the third approach. The constructor should be:
```
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
self.fields['long_desc'].widget.attrs['cols'] = 10
sel... |
Is there an easy way to request a URL in python and NOT follow redirects? | 110,498 | 24 | 2008-09-21T07:49:10Z | 110,547 | 34 | 2008-09-21T08:33:12Z | [
"python",
"http",
"redirect"
] | Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple. | [Dive Into Python](http://www.diveintopython.net/http_web_services/redirects.html) has a good chapter on handling redirects with urllib2. Another solution is [httplib](http://docs.python.org/library/httplib.html).
```
>>> import httplib
>>> conn = httplib.HTTPConnection("www.bogosoft.com")
>>> conn.request("GET", "")
... |
Is there an easy way to request a URL in python and NOT follow redirects? | 110,498 | 24 | 2008-09-21T07:49:10Z | 111,066 | 8 | 2008-09-21T13:51:30Z | [
"python",
"http",
"redirect"
] | Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple. | i suppose this would help
```
from httplib2 import Http
def get_html(uri,num_redirections=0): # put it as 0 for not to follow redirects
conn = Http()
return conn.request(uri,redirections=num_redirections)
``` |
Is there an easy way to request a URL in python and NOT follow redirects? | 110,498 | 24 | 2008-09-21T07:49:10Z | 5,352,695 | 10 | 2011-03-18T13:33:06Z | [
"python",
"http",
"redirect"
] | Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple. | This is a urllib2 handler that will not follow redirects:
```
class NoRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
infourl = urllib.addinfourl(fp, headers, req.get_full_url())
infourl.status = code
infourl.code = code
return in... |
Is there an easy way to request a URL in python and NOT follow redirects? | 110,498 | 24 | 2008-09-21T07:49:10Z | 14,678,220 | 36 | 2013-02-03T22:42:27Z | [
"python",
"http",
"redirect"
] | Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple. | Here is the [Requests](http://docs.python-requests.org/en/latest/) way:
```
import requests
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code)
``` |
Dirty fields in django | 110,803 | 26 | 2008-09-21T11:27:24Z | 111,091 | 11 | 2008-09-21T14:04:00Z | [
"python",
"django"
] | In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?
I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not. | You haven't said very much about your specific use case or needs. In particular, it would be helpful to know what you need to do with the change information (how long do you need to store it?). If you only need to store it for transient purposes, @S.Lott's session solution may be best. If you want a full audit trail of... |
Dirty fields in django | 110,803 | 26 | 2008-09-21T11:27:24Z | 111,364 | 10 | 2008-09-21T16:33:51Z | [
"python",
"django"
] | In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?
I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not. | Django is currently sending all columns to the database, even if you just changed one. To change this, some changes in the database system would be necessary. This could be easily implemented on the existing code by adding a set of dirty fields to the model and adding column names to it, each time you `__set__` a colum... |
Dirty fields in django | 110,803 | 26 | 2008-09-21T11:27:24Z | 332,225 | 18 | 2008-12-01T21:09:14Z | [
"python",
"django"
] | In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?
I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not. | I've found Armin's idea very useful. Here is my variation;
```
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
self._original_state = self._as_dict()
def _as_dict(self):
return dict([(f.name, getattr(self, f.n... |
Close a tkinter window? | 110,923 | 32 | 2008-09-21T12:40:04Z | 110,929 | 32 | 2008-09-21T12:44:01Z | [
"python",
"tkinter"
] | How do I end a Tkinter program? Let's say I have this code:
```
from Tkinter import *
def quit():
# code to exit
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
```
How should I define the `quit` function? | We can use:
```
def quit():
root.quit()
```
or
```
def quit():
root.destroy()
``` |
Close a tkinter window? | 110,923 | 32 | 2008-09-21T12:40:04Z | 294,199 | 11 | 2008-11-16T18:36:55Z | [
"python",
"tkinter"
] | How do I end a Tkinter program? Let's say I have this code:
```
from Tkinter import *
def quit():
# code to exit
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
```
How should I define the `quit` function? | ```
import Tkinter as tk
def quit(root):
root.destroy()
root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()
``` |
Close a tkinter window? | 110,923 | 32 | 2008-09-21T12:40:04Z | 15,577,605 | 25 | 2013-03-22T18:39:54Z | [
"python",
"tkinter"
] | How do I end a Tkinter program? Let's say I have this code:
```
from Tkinter import *
def quit():
# code to exit
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
```
How should I define the `quit` function? | ```
root.quit()
```
Above line just **Bypasses** the `root.mainloop()` i.e root.mainloop() will still be running in background if quit() command is executed.
```
root.destroy()
```
While destroy() command vanish out `root.mainloop()` i.e root.mainloop() stops.
So as you just want to quit the program so you should u... |
How do I handle the window close event in Tkinter? | 111,155 | 43 | 2008-09-21T14:46:20Z | 111,160 | 51 | 2008-09-21T14:51:11Z | [
"python",
"events",
"tkinter",
"window"
] | How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program? | Tkinter supports a mechanism called [*protocol handlers*](http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols). Here, the term *protocol* refers to the interaction between the application and the window manager. The most commonly used protocol is called `WM_DELETE_WINDOW`, and is used to define what... |
How do I handle the window close event in Tkinter? | 111,155 | 43 | 2008-09-21T14:46:20Z | 14,819,661 | 7 | 2013-02-11T19:46:39Z | [
"python",
"events",
"tkinter",
"window"
] | How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program? | Matt has shown one classic modification of the close button.
The other is to have the close button minimize the window.
You can reproduced this behavior by having the [*iconify*](http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.iconify-method) method
be the [*protocol*](http://effbot.org/tkinterbook/wm.htm#Tkinter... |
What is a "callable" in Python? | 111,234 | 170 | 2008-09-21T15:34:32Z | 111,251 | 8 | 2008-09-21T15:43:15Z | [
"python",
"callable"
] | Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. ... | A Callable is an object that has the `__call__` method. This means you can fake callable functions or do neat things like [Partial Function Application](http://www.python.org/dev/peps/pep-0309/) where you take a function and add something that enhances it or fills in some of the parameters, returning something that can... |
What is a "callable" in Python? | 111,234 | 170 | 2008-09-21T15:34:32Z | 111,255 | 181 | 2008-09-21T15:44:22Z | [
"python",
"callable"
] | Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. ... | A callable is anything that can be called.
The [built-in *callable* (PyCallable\_Check in objects.c)](http://svn.python.org/projects/python/trunk/Objects/object.c) checks if the argument is either:
* an instance of a class with a *\_\_call\_\_* method or
* is of a type that has a non null *tp\_call* (c struct) member... |
What is a "callable" in Python? | 111,234 | 170 | 2008-09-21T15:34:32Z | 115,349 | 59 | 2008-09-22T15:04:53Z | [
"python",
"callable"
] | Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. ... | From Python's sources [object.c](http://svn.python.org/view/python/trunk/Objects/object.c?rev=64962&view=markup):
```
/* Test whether an object can be called */
int
PyCallable_Check(PyObject *x)
{
if (x == NULL)
return 0;
if (PyInstance_Check(x)) {
PyObject *call = PyObject_GetAttrString(x, "_... |
What is a "callable" in Python? | 111,234 | 170 | 2008-09-21T15:34:32Z | 139,469 | 19 | 2008-09-26T13:22:20Z | [
"python",
"callable"
] | Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. ... | A callable is an object allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions.
Every time you define a function python creates a callable object.
In example, you could define the function **func** in these ways (it's the same):
```
class a(object):
def __call__(self, *ar... |
What is a "callable" in Python? | 111,234 | 170 | 2008-09-21T15:34:32Z | 15,581,536 | 12 | 2013-03-22T23:38:33Z | [
"python",
"callable"
] | Now that it's clear [what a metaclass is](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. ... | Let me explain backwards:
Consider this...
```
foo()
```
... as syntactic sugar for:
```
foo.__call__()
```
Where `foo` can be any object that responds to `__call__`. When I say any object, I mean it: built-in types, your own classes and their instances.
In the case of built-in types, when you write:
```
int('10... |
How do I find out the size of a canvas item in Python/Tkinter? | 111,934 | 3 | 2008-09-21T20:08:56Z | 111,974 | 11 | 2008-09-21T20:19:34Z | [
"python",
"tkinter",
"tkinter-canvas"
] | I want to create some text in a canvas:
```
myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST")
```
Now how do I find the width and height of myText? | ```
bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2)
width = bounds[2] - bounds[0]
height = bounds[3] - bounds[1]
```
See the [TkInter reference](http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas-methods.html). |
Is there any way to do HTTP PUT in python | 111,945 | 166 | 2008-09-21T20:11:05Z | 111,973 | 8 | 2008-09-21T20:18:57Z | [
"python",
"http",
"put"
] | I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python? | You should have a look at the [httplib module](http://docs.python.org/lib/module-httplib.html). It should let you make whatever sort of HTTP request you want. |
Is there any way to do HTTP PUT in python | 111,945 | 166 | 2008-09-21T20:11:05Z | 111,988 | 197 | 2008-09-21T20:24:21Z | [
"python",
"http",
"put"
] | I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python? | ```
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)
``` |
Is there any way to do HTTP PUT in python | 111,945 | 166 | 2008-09-21T20:11:05Z | 114,648 | 8 | 2008-09-22T12:46:40Z | [
"python",
"http",
"put"
] | I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python? | I needed to solve this problem too a while back so that I could act as a client for a RESTful API. I settled on httplib2 because it allowed me to send PUT and DELETE in addition to GET and POST. Httplib2 is not part of the standard library but you can easily get it from the cheese shop. |
Is there any way to do HTTP PUT in python | 111,945 | 166 | 2008-09-21T20:11:05Z | 3,919,484 | 45 | 2010-10-12T22:13:42Z | [
"python",
"http",
"put"
] | I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python? | Httplib seems like a cleaner choice.
```
import httplib
connection = httplib.HTTPConnection('1.2.3.4:1234')
body_content = 'BODY CONTENT GOES HERE'
connection.request('PUT', '/url/path/to/put/to', body_content)
result = connection.getresponse()
# Now result.status and result.reason contains interesting stuff
``` |
Is there any way to do HTTP PUT in python | 111,945 | 166 | 2008-09-21T20:11:05Z | 8,259,648 | 231 | 2011-11-24T15:54:13Z | [
"python",
"http",
"put"
] | I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python? | I've used a variety of python HTTP libs in the past, and I've settled on '[Requests](http://docs.python-requests.org/en/latest/index.html)' as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:
```
payload... |
Using Python's ftplib to get a directory listing, portably | 111,954 | 35 | 2008-09-21T20:13:18Z | 111,966 | 73 | 2008-09-21T20:15:59Z | [
"python",
"ftp",
"portability"
] | You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:
```
# File: ftplib-example-1.py
import ftplib
ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", li... | Try to use `ftp.nlst(dir)`.
However, note that if the folder is empty, it might throw an error:
```
files = []
try:
files = ftp.nlst()
except ftplib.error_perm, resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
``` |
Using Python's ftplib to get a directory listing, portably | 111,954 | 35 | 2008-09-21T20:13:18Z | 8,474,838 | 20 | 2011-12-12T13:10:19Z | [
"python",
"ftp",
"portability"
] | You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:
```
# File: ftplib-example-1.py
import ftplib
ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", li... | The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.
```
import ftplib
f = ftplib.FTP()
f.connect("localhost")
f.login()
ls = []
f.retrlines('MLSD', ls.append)
for entry in ls:
print entry
```
The code above will ... |
python.array versus numpy.array | 111,983 | 27 | 2008-09-21T20:23:02Z | 112,025 | 40 | 2008-09-21T20:31:39Z | [
"python",
"numpy"
] | If you are creating a 1d array in Python is there any benefit to using the NumPy package? | It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the [array](http://docs.python.org/lib/module-array.html) module will do just fine.
If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide... |
List all words in a dictionary that start with <user input> | 112,532 | 7 | 2008-09-21T23:28:06Z | 112,557 | 8 | 2008-09-21T23:35:09Z | [
"python",
"list",
"dictionary"
] | How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
---
Edit: I'm using python, but I assume that this is a fairly language-independent problem. | One of the best ways to do this is to use a directed graph to store your dictionary. It takes a little bit of setting up, but once done it is fairly easy to then do the type of searches you are talking about.
The nodes in the graph correspond to a letter in your word, so each node will have one incoming link and up to... |
List all words in a dictionary that start with <user input> | 112,532 | 7 | 2008-09-21T23:28:06Z | 112,559 | 10 | 2008-09-21T23:35:48Z | [
"python",
"list",
"dictionary"
] | How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
---
Edit: I'm using python, but I assume that this is a fairly language-independent problem. | Use a [trie](http://en.wikipedia.org/wiki/Trie).
Add your list of words to a trie. Each path from the root to a leaf is a valid word. A path from a root to an intermediate node represents a prefix, and the children of the intermediate node are valid completions for the prefix. |
py2exe - generate single executable file | 112,698 | 112 | 2008-09-22T00:49:12Z | 112,713 | 72 | 2008-09-22T00:55:46Z | [
"python",
"packaging",
"py2exe"
] | I thought I heard that [py2exe](http://www.py2exe.org/) was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?
Basically I'm thinking of it giving me a single executable file that does something like unzips itself to may... | [PyInstaller](http://www.pyinstaller.org/) will create a single .exe file with no dependencies; use the `--onefile` option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see [minty's answer](http://sta... |
py2exe - generate single executable file | 112,698 | 112 | 2008-09-22T00:49:12Z | 113,014 | 150 | 2008-09-22T03:19:08Z | [
"python",
"packaging",
"py2exe"
] | I thought I heard that [py2exe](http://www.py2exe.org/) was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?
Basically I'm thinking of it giving me a single executable file that does something like unzips itself to may... | The way to do this using py2exe is to use the bundle\_files option in your setup.py file. For a single file you will want to set `bundle_files` to 1, `compressed` to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.
Here is a more complete description of the bundl... |
py2exe - generate single executable file | 112,698 | 112 | 2008-09-22T00:49:12Z | 333,483 | 8 | 2008-12-02T09:44:45Z | [
"python",
"packaging",
"py2exe"
] | I thought I heard that [py2exe](http://www.py2exe.org/) was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?
Basically I'm thinking of it giving me a single executable file that does something like unzips itself to may... | As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.
Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.
I have used InnoSetup ( <http://www.jrsoftware.org/isinfo.php> ) w... |
Python - When to use file vs open | 112,970 | 119 | 2008-09-22T03:04:14Z | 112,980 | 129 | 2008-09-22T03:07:44Z | [
"python",
"file"
] | What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5) | You should always use `open()`.
As the [documentation](http://docs.python.org/2/library/functions.html#file "BuiltinFuncs Doc") states:
> When opening a file, it's preferable
> to use open() instead of invoking this
> constructor directly. file is more
> suited to type testing (for example,
> writing "isinstance(f, f... |
Python - When to use file vs open | 112,970 | 119 | 2008-09-22T03:04:14Z | 112,989 | 28 | 2008-09-22T03:10:16Z | [
"python",
"file"
] | What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5) | Two reasons: The python philosophy of "There ought to be one way to do it" and `file` is going away.
`file` is the actual type (using e.g. `file('myfile.txt')` is calling its constructor). `open` is a factory function that will return a file object.
In python 3.0 `file` is going to move from being a built-in to being... |
Python - When to use file vs open | 112,970 | 119 | 2008-09-22T03:04:14Z | 113,050 | 16 | 2008-09-22T03:32:08Z | [
"python",
"file"
] | What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5) | `file()` is a type, like an int or a list. `open()` is a function for opening files, and will return a `file` object.
This is an example of when you should use open:
```
f = open(filename, 'r')
for line in f:
process(line)
f.close()
```
This is an example of when you should use file:
```
class LoggingFile(file)... |
Writing to the windows logs in Python | 113,007 | 9 | 2008-09-22T03:15:31Z | 113,011 | 12 | 2008-09-22T03:16:58Z | [
"python",
"windows",
"logging"
] | Is it possible to write to the windows logs in python? | Yes, just use Windows Python Extension, as stated [here](http://www.ravenbrook.com/project/p4dti/master/design/win32-eventlog/).
```
import win32evtlogutil
win32evtlogutil.ReportEvent(ApplicationName, EventID, EventCategory,
EventType, Inserts, Data, SID)
``` |
Is there a function in Python to split a string without ignoring the spaces? | 113,534 | 12 | 2008-09-22T07:02:04Z | 113,555 | 40 | 2008-09-22T07:08:04Z | [
"python",
"split"
] | Is there a function in Python to split a string without ignoring the spaces in the resulting list?
E.g:
```
s="This is the string I want to split".split()
```
gives me
```
>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
```
I want something like
```
['This',' ','is',' ', 'the',' ','string', ' ',... | ```
>>> import re
>>> re.split(r"(\s+)", "This is the string I want to split")
['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']
```
Using the capturing parentheses in re.split() causes the function to return the separators as well. |
Is there a function in python to split a word into a list? | 113,655 | 41 | 2008-09-22T07:40:50Z | 113,662 | 119 | 2008-09-22T07:42:15Z | [
"python",
"function",
"split"
] | Is there a function in python to split a word into a list of single letters? e.g:
```
s="Word to Split"
```
to get
```
wordlist=['W','o','r','d','','t','o' ....]
``` | ```
>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
``` |
Is there a function in python to split a word into a list? | 113,655 | 41 | 2008-09-22T07:40:50Z | 113,680 | 9 | 2008-09-22T07:46:45Z | [
"python",
"function",
"split"
] | Is there a function in python to split a word into a list of single letters? e.g:
```
s="Word to Split"
```
to get
```
wordlist=['W','o','r','d','','t','o' ....]
``` | The easiest way is probably just to use `list()`, but there is at least one other option as well:
```
s = "Word to Split"
wordlist = list(s) # option 1,
wordlist = [ch for ch in s] # option 2, list comprehension.
```
They should *both* give you what you need:
```
['W','o','r','d',' ','t','o',' ',... |
Deploying Django: How do you do it? | 114,112 | 12 | 2008-09-22T10:11:48Z | 114,268 | 7 | 2008-09-22T11:06:01Z | [
"python",
"django-deployment"
] | I have tried following guides like [this one](http://docs.djangoproject.com/en/dev/howto/deployment/modpython/) but it just didnt work for me.
**So my question is this:** What is a good guide for deploying Django, and how do you deploy your Django.
I keep hearing that capastrano is pretty nifty to use, but i have no ... | `mod_wsgi` in combination with a `virtualenv` for all the dependencies, a mercurial checkout into the virtualenv and a `fabric` recipe to check out the changes on the server.
I wrote an article about my usual workflow: [Deploying Python Web Applications](http://lucumr.pocoo.org/2008/7/17/deploying-python-web-applicati... |
Class method differences in Python: bound, unbound and static | 114,214 | 190 | 2008-09-22T10:49:43Z | 114,232 | 10 | 2008-09-22T10:56:27Z | [
"python"
] | What is the difference between the following class methods?
Is it that one is static and the other is not?
```
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
``` | When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable `self` actually means nothing, it's just a coding convention. You could call it `gargaloo` if you wanted. That said, the call to `method_two` would raise a `TypeError`, because Python is automatically ... |
Class method differences in Python: bound, unbound and static | 114,214 | 190 | 2008-09-22T10:49:43Z | 114,267 | 325 | 2008-09-22T11:05:54Z | [
"python"
] | What is the difference between the following class methods?
Is it that one is static and the other is not?
```
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
``` | In Python, there is a distinction between *bound* and *unbound* methods.
Basically, a call to a member function (like `method_one`), a bound function
```
a_test.method_one()
```
is translated to
```
Test.method_one(a_test)
```
i.e. a call to an unbound method. Because of that, a call to your version of `method_two... |
Class method differences in Python: bound, unbound and static | 114,214 | 190 | 2008-09-22T10:49:43Z | 114,289 | 163 | 2008-09-22T11:12:36Z | [
"python"
] | What is the difference between the following class methods?
Is it that one is static and the other is not?
```
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
``` | Methods in Python are a very, very simple thing once you understood the basics of the descriptor system. Imagine the following class:
```
class C(object):
def foo(self):
pass
```
Now let's have a look at that class in the shell:
```
>>> C.foo
<unbound method C.foo>
>>> C.__dict__['foo']
<function foo at ... |
Class method differences in Python: bound, unbound and static | 114,214 | 190 | 2008-09-22T10:49:43Z | 2,696,019 | 10 | 2010-04-23T03:25:12Z | [
"python"
] | What is the difference between the following class methods?
Is it that one is static and the other is not?
```
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
``` | ```
>>> class Class(object):
... def __init__(self):
... self.i = 0
... def instance_method(self):
... self.i += 1
... print self.i
... c = 0
... @classmethod
... def class_method(cls):
... cls.c += 1
... print cls.c
... @staticmethod
... def static_me... |
Is a Python dictionary an example of a hash table? | 114,830 | 88 | 2008-09-22T13:22:28Z | 114,831 | 127 | 2008-09-22T13:23:00Z | [
"python",
"hash",
"dictionary",
"hashmap",
"hashtable"
] | One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it? | Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, [here](http://mail.python.org/pipermail/python-list/2000-March/048085.html).
That's why you can't use something 'not hashable' as a dict key, like a list:
```
>>> a = {}
>>> b = ['some', 'lis... |
Is a Python dictionary an example of a hash table? | 114,830 | 88 | 2008-09-22T13:22:28Z | 114,848 | 14 | 2008-09-22T13:25:27Z | [
"python",
"hash",
"dictionary",
"hashmap",
"hashtable"
] | One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it? | Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 ([source](http://mail.python.org/pipermail/python-list/2000-February/023645.html)). |
Is a Python dictionary an example of a hash table? | 114,830 | 88 | 2008-09-22T13:22:28Z | 114,853 | 25 | 2008-09-22T13:26:19Z | [
"python",
"hash",
"dictionary",
"hashmap",
"hashtable"
] | One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it? | If you're interested in the technical details, one article in [Beautiful Code](http://oreilly.com/catalog/9780596510046/) deals with the internals of Python's `dict` implementation. |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | 102 | 2008-09-22T14:58:53Z | 115,700 | 9 | 2008-09-22T15:55:07Z | [
"python",
"web-services",
"soap"
] | I want to use a WSDL SOAP based web service in Python. I have looked at the [Dive Into Python](http://diveintopython.net/soap_web_services/) code but the SOAPpy module does not work under Python 2.5.
I have tried using [suds](https://fedorahosted.org/suds) which works partly, but breaks with certain types (suds.TypeNo... | Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other. |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | 102 | 2008-09-22T14:58:53Z | 1,793,052 | 30 | 2009-11-24T21:32:02Z | [
"python",
"web-services",
"soap"
] | I want to use a WSDL SOAP based web service in Python. I have looked at the [Dive Into Python](http://diveintopython.net/soap_web_services/) code but the SOAPpy module does not work under Python 2.5.
I have tried using [suds](https://fedorahosted.org/suds) which works partly, but breaks with certain types (suds.TypeNo... | I know this is an old thread but it was showing up at the top of Google's results so I wanted to share a more current discussion on Python and SOAP.
See: <http://www.diveintopython.net/soap_web_services/index.html> |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | 102 | 2008-09-22T14:58:53Z | 2,829,486 | 44 | 2010-05-13T19:02:39Z | [
"python",
"web-services",
"soap"
] | I want to use a WSDL SOAP based web service in Python. I have looked at the [Dive Into Python](http://diveintopython.net/soap_web_services/) code but the SOAPpy module does not work under Python 2.5.
I have tried using [suds](https://fedorahosted.org/suds) which works partly, but breaks with certain types (suds.TypeNo... | I would recommend that you have a look at [SUDS](https://fedorahosted.org/suds/)
"Suds is a lightweight SOAP python client for consuming Web Services." |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | 102 | 2008-09-22T14:58:53Z | 27,302,096 | 12 | 2014-12-04T19:13:20Z | [
"python",
"web-services",
"soap"
] | I want to use a WSDL SOAP based web service in Python. I have looked at the [Dive Into Python](http://diveintopython.net/soap_web_services/) code but the SOAPpy module does not work under Python 2.5.
I have tried using [suds](https://fedorahosted.org/suds) which works partly, but breaks with certain types (suds.TypeNo... | I recently stumbled up on the same problem. Here is the synopsis of my solution.
*(If you need to see the whole discussion, here is the link for complete discussion of the solution:
<http://tedbelay.blogspot.com/2014/12/soap-web-service-client-in-python-27.html>)*
**Basic constituent code blocks needed**
The followin... |
Which is more pythonic, factory as a function in a module, or as a method on the class it creates? | 115,764 | 3 | 2008-09-22T16:03:41Z | 115,853 | 11 | 2008-09-22T16:20:38Z | [
"python",
"factory"
] | I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.
The calendar object just has a method that adds events as they get parsed.
Now I want to create a factory function that creates a calendar from a file object, path, or URL.
I've been using the [iCalendar py... | [**Note**. Be very cautious about separating "Calendar" a collection of events, and "Event" - a single event on a calendar. In your question, it seems like there could be some confusion.]
There are many variations on the Factory design pattern.
1. A stand-alone convenience function (e.g., calendarMaker(data))
2. A se... |
How do I configure the ip address with CherryPy? | 115,773 | 15 | 2008-09-22T16:04:54Z | 115,826 | 13 | 2008-09-22T16:16:12Z | [
"python",
"cherrypy"
] | I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 b... | That depends on how you are running the cherrypy init.
If using cherrypy 3.1 syntax, that wold do it:
```
cherrypy.server.socket_host = 'www.machinename.com'
cherrypy.engine.start()
cherrypy.engine.block()
```
Of course you can have something more fancy, like subclassing the server class, or using config files. Thos... |
How do I configure the ip address with CherryPy? | 115,773 | 15 | 2008-09-22T16:04:54Z | 152,012 | 29 | 2008-09-30T06:55:25Z | [
"python",
"cherrypy"
] | I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 b... | ```
server.socket_host: '0.0.0.0'
```
...would also work. That's IPv4 INADDR\_ANY, which means, "listen on all interfaces".
In a config file, the syntax is:
```
[global]
server.socket_host: '0.0.0.0'
```
In code:
```
cherrypy.server.socket_host = '0.0.0.0'
``` |
Convert mysql timestamp to epoch time in python | 115,866 | 6 | 2008-09-22T16:22:16Z | 115,903 | 24 | 2008-09-22T16:26:51Z | [
"python",
"mysql",
"time",
"timestamp"
] | Convert mysql timestamp to epoch time in python - is there an easy way to do this? | Why not let MySQL do the hard work?
select unix\_timestamp(fieldname) from tablename; |
Convert mysql timestamp to epoch time in python | 115,866 | 6 | 2008-09-22T16:22:16Z | 2,407,400 | 7 | 2010-03-09T07:51:59Z | [
"python",
"mysql",
"time",
"timestamp"
] | Convert mysql timestamp to epoch time in python - is there an easy way to do this? | converting mysql time to epoch:
```
>>> import time
>>> import calendar
>>> mysql_time = "2010-01-02 03:04:05"
>>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S')
>>> print mysql_time_struct
(2010, 1, 2, 3, 4, 5, 5, 2, -1)
>>> mysql_time_epoch = calendar.timegm(mysql_time_struct)
>>> print mysql_tim... |
What would be the simplest way to daemonize a python script in Linux? | 115,974 | 10 | 2008-09-22T16:39:09Z | 116,035 | 20 | 2008-09-22T16:47:31Z | [
"python",
"scripting",
"daemon"
] | What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. | See [Stevens](http://www.kohala.com/start/) and also this [lengthy thread on activestate](http://code.activestate.com/recipes/278731/) which I found personally to be both mostly incorrect and much to verbose, and I came up with this:
```
from os import fork, setsid, umask, dup2
from sys import stdin, stdout, stderr
i... |
Using Pylint with Django | 115,977 | 89 | 2008-09-22T16:39:34Z | 116,025 | 15 | 2008-09-22T16:46:00Z | [
"python",
"django",
"static-analysis",
"pylint"
] | I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:`E1101: *%s %r has no %r
member*`--constantly reports errors when using common django fields,
for example:
... | Because of how pylint works (it examines the source itself, without letting Python actually execute it) it's very hard for pylint to figure out how metaclasses and complex baseclasses actually affect a class and its instances. The 'pychecker' tool is a bit better in this regard, because it *does* actually let Python ex... |
Using Pylint with Django | 115,977 | 89 | 2008-09-22T16:39:34Z | 118,375 | 7 | 2008-09-23T00:17:58Z | [
"python",
"django",
"static-analysis",
"pylint"
] | I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:`E1101: *%s %r has no %r
member*`--constantly reports errors when using common django fields,
for example:
... | This is not a solution, but you can add `objects = models.Manager()` to your Django models without changing any behavior.
I myself only use pyflakes, primarily due to some dumb defaults in pylint and laziness on my part (not wanting to look up how to change the defaults). |
Using Pylint with Django | 115,977 | 89 | 2008-09-22T16:39:34Z | 1,416,297 | 59 | 2009-09-12T22:21:47Z | [
"python",
"django",
"static-analysis",
"pylint"
] | I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:`E1101: *%s %r has no %r
member*`--constantly reports errors when using common django fields,
for example:
... | I use the following: `pylint --generated-members=objects` |
Using Pylint with Django | 115,977 | 89 | 2008-09-22T16:39:34Z | 2,456,436 | 18 | 2010-03-16T17:00:16Z | [
"python",
"django",
"static-analysis",
"pylint"
] | I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:`E1101: *%s %r has no %r
member*`--constantly reports errors when using common django fields,
for example:
... | django-lint is a nice tool which wraps pylint with django specific settings : <http://chris-lamb.co.uk/projects/django-lint/>
github project: <https://github.com/lamby/django-lint> |
Using Pylint with Django | 115,977 | 89 | 2008-09-22T16:39:34Z | 4,162,971 | 27 | 2010-11-12T08:59:11Z | [
"python",
"django",
"static-analysis",
"pylint"
] | I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:`E1101: *%s %r has no %r
member*`--constantly reports errors when using common django fields,
for example:
... | My ~/.pylintrc contains
```
[TYPECHECK]
generated-members=REQUEST,acl_users,aq_parent,objects,_meta,id
```
the last two are specifically for Django.
Note that there is a [bug in PyLint 0.21.1](http://www.logilab.org/ticket/28796) which needs patching to make this work.
Edit: After messing around with this a little ... |
Using Pylint with Django | 115,977 | 89 | 2008-09-22T16:39:34Z | 31,000,713 | 31 | 2015-06-23T10:47:45Z | [
"python",
"django",
"static-analysis",
"pylint"
] | I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:`E1101: *%s %r has no %r
member*`--constantly reports errors when using common django fields,
for example:
... | Do not disable or weaken Pylint functionality by adding `ignores` or `generated-members`.
Use an actively developed Pylint plugin that **understands** Django.
[This Pylint plugin for Django](https://github.com/landscapeio/pylint-django) works quite well:
```
pip install pylint-django
```
and when running pylint a... |
How can I search a word in a Word 2007 .docx file? | 116,139 | 40 | 2008-09-22T17:08:12Z | 116,217 | 30 | 2008-09-22T17:22:10Z | [
"python",
"ms-word",
"openxml",
"docx"
] | I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word.
Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase". | More exactly, a .docx document is a Zip archive in OpenXML format: you have first to uncompress it.
I downloaded a sample (Google: *some search term filetype:docx*) and after unzipping I found some folders. The *word* folder contains the document itself, in file *document.xml*. |
How can I search a word in a Word 2007 .docx file? | 116,139 | 40 | 2008-09-22T17:08:12Z | 118,175 | 14 | 2008-09-22T23:12:59Z | [
"python",
"ms-word",
"openxml",
"docx"
] | I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word.
Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase". | In this example, "Course Outline.docx" is a Word 2007 document, which does contain the word "Windows", and does not contain the phrase "random other string".
```
>>> import zipfile
>>> z = zipfile.ZipFile("Course Outline.docx")
>>> "Windows" in z.read("word/document.xml")
True
>>> "random other string" in z.read("word... |
How can I search a word in a Word 2007 .docx file? | 116,139 | 40 | 2008-09-22T17:08:12Z | 1,737,242 | 13 | 2009-11-15T11:01:08Z | [
"python",
"ms-word",
"openxml",
"docx"
] | I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word.
Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase". | A problem with searching inside a Word document XML file is that the text can be split into elements at any character. It will certainly be split if formatting is different, for example as in Hello **World**. But it *can* be split at any point and that is valid in OOXML. So you will end up dealing with XML like this ev... |
How can I search a word in a Word 2007 .docx file? | 116,139 | 40 | 2008-09-22T17:08:12Z | 1,979,864 | 127 | 2009-12-30T12:08:33Z | [
"python",
"ms-word",
"openxml",
"docx"
] | I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word.
Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase". | After reading your post above, I made a 100% native Python docx module to solve this specific problem.
```
# Import the module
from docx import *
# Open the .docx file
document = opendocx('A document.docx')
# Search returns true if found
search(document,'your search string')
```
The docx module is at <https://p... |
How do you create an osx application/dmg from a python package? | 116,657 | 23 | 2008-09-22T18:35:28Z | 116,901 | 7 | 2008-09-22T19:19:30Z | [
"python",
"osx",
"packaging"
] | I want to create a mac osx application from python package and then put it in a disk image.
Because I load some resources out of the package, the package should **not** reside in a zip file.
The resulting disk image should display the background picture to "drag here -> applications" for installation. | I don't know the correct way to do it, but this manual method is the approach I've used for simple scripts which seems to have preformed suitably.
I'll assume that whatever directory I'm in, the Python files for my program are in the relative `src/` directory, and that the file I want to execute (which has the proper ... |
How to Retrieve name of current Windows User (AD or local) using Python? | 117,014 | 18 | 2008-09-22T19:36:32Z | 117,047 | 26 | 2008-09-22T19:42:41Z | [
"python",
"active-directory"
] | How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user. | Try this:
```
import os;
print os.environ.get( "USERNAME" )
```
That should do the job. |
Python and POST data | 117,167 | 4 | 2008-09-22T19:57:37Z | 117,201 | 10 | 2008-09-22T20:01:12Z | [
"python",
"http",
"post"
] | In PHP I simply write:
```
$bob = $_POST['bob'];
```
How do I do the same in Python?
And yes, I do normally check that it exists etc, I'm just stripping it down specifically to the functionality I am after.
---
Edit: I am not using a framework | The simplest method is the 'cgi' module:
```
import cgi
data = cgi.FieldStorage()
data['bob']
```
But the context you are executing in (frameworks you're using, WSGI or even (heaven forbid) mod\_python) may have different, more efficient or more direct methods of access. |
How do I get a decimal value when using the division operator in Python? | 117,250 | 31 | 2008-09-22T20:06:16Z | 117,264 | 79 | 2008-09-22T20:08:15Z | [
"python",
"math",
"syntax",
"operators"
] | For example, the standard division symbol '/' rounds to zero:
```
>>> 4 / 100
0
```
However, I want it to return 0.04. What do I use? | There are three options:
```
>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04
```
which is the same behavior as the C, C++, Java etc, or
```
>>> from __future__ import division
>>> 4 / 100
0.04
```
You can also activate this behavior by passing the argument `-Qnew` to the Python interpreter:
```
$ python -Qnew
>>> 4 / 1... |
How do I get a decimal value when using the division operator in Python? | 117,250 | 31 | 2008-09-22T20:06:16Z | 117,270 | 7 | 2008-09-22T20:08:45Z | [
"python",
"math",
"syntax",
"operators"
] | For example, the standard division symbol '/' rounds to zero:
```
>>> 4 / 100
0
```
However, I want it to return 0.04. What do I use? | Make one or both of the terms a floating point number, like so:
```
4.0/100.0
```
Alternatively, turn on the feature that will be default in Python 3.0, 'true division', that does what you want. At the top of your module or script, do:
```
from __future__ import division
``` |
How do I get a decimal value when using the division operator in Python? | 117,250 | 31 | 2008-09-22T20:06:16Z | 117,682 | 21 | 2008-09-22T21:12:07Z | [
"python",
"math",
"syntax",
"operators"
] | For example, the standard division symbol '/' rounds to zero:
```
>>> 4 / 100
0
```
However, I want it to return 0.04. What do I use? | Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:
```
>>> 0.4/100.
0.0040000000000000001
```
If you actually want a *decimal* value, do this:
```
>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")
```
That will gi... |
What's the Name of the Python Module that Formats arbitrary Text to nicely looking HTML? | 117,477 | 10 | 2008-09-22T20:39:11Z | 117,824 | 14 | 2008-09-22T21:41:26Z | [
"python",
"formatting",
"markup"
] | A while ago I came across a Python library that formats regular text to HTML similar to Markdown, reStructuredText and Textile, just that it had no syntax at all. It detected indentatations, quotes, links and newlines/paragraphs only.
Unfortunately I lost the name of the library and was unable to Google it. Anyone any... | Okay. I found it now. It's called [PottyMouth](http://glyphobet.net/pottymouth/). |
How do I use timezones with a datetime object in python? | 117,514 | 37 | 2008-09-22T20:44:39Z | 117,523 | 9 | 2008-09-22T20:46:08Z | [
"python",
"datetime",
"timezone"
] | How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()
```
import datetime, re
from datetime import tzinfo
class myTimeZone(tzinfo):
"""docstring for myTimeZone"""
def utf... | The Python standard library doesn't contain timezone information, because unfortunately timezone data changes a lot faster than Python. You need a third-party module for this; the usual choice is [pytz](http://pytz.sourceforge.net) |
How do I use timezones with a datetime object in python? | 117,514 | 37 | 2008-09-22T20:44:39Z | 117,615 | 36 | 2008-09-22T20:59:40Z | [
"python",
"datetime",
"timezone"
] | How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()
```
import datetime, re
from datetime import tzinfo
class myTimeZone(tzinfo):
"""docstring for myTimeZone"""
def utf... | I recommend `babel` and `pytz` when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezon... |
How do I use timezones with a datetime object in python? | 117,514 | 37 | 2008-09-22T20:44:39Z | 1,893,437 | 7 | 2009-12-12T13:35:12Z | [
"python",
"datetime",
"timezone"
] | How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()
```
import datetime, re
from datetime import tzinfo
class myTimeZone(tzinfo):
"""docstring for myTimeZone"""
def utf... | For the current local timezone, you can you use:
```
>>> import time
>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
>>> offset / 60 / 60 * -1
-9
```
The value returned is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actual... |
How can i parse a comma delimited string into a list (caveat)? | 118,096 | 19 | 2008-09-22T22:54:10Z | 118,162 | 39 | 2008-09-22T23:09:45Z | [
"python",
"split",
"escaping",
"quotes"
] | I need to be able to take a string like:
```
'''foo, bar, "one, two", three four'''
```
into:
```
['foo', 'bar', 'one, two', 'three four']
```
I have an feeling (with hints from #python) that the solution is going to involve the shlex module. | It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes?
Your syntax looks very much like the common CSV file format, which is supported by the Python standard library:
```
import csv
reader = csv.reader(['''foo, bar, "one, two", three four'''], skipi... |
How can i parse a comma delimited string into a list (caveat)? | 118,096 | 19 | 2008-09-22T22:54:10Z | 118,187 | 21 | 2008-09-22T23:15:45Z | [
"python",
"split",
"escaping",
"quotes"
] | I need to be able to take a string like:
```
'''foo, bar, "one, two", three four'''
```
into:
```
['foo', 'bar', 'one, two', 'three four']
```
I have an feeling (with hints from #python) that the solution is going to involve the shlex module. | The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports.
```
>>> import shlex
>>> my_splitter = shlex.shlex('''foo, bar, "one, two", three four''', posix=True)
>>> my_splitter.whitespace += ','
>>> my_splitter.whitespace_split = True
>>> print list(my_splitter)
['f... |
Python Regex vs PHP Regex | 118,143 | 3 | 2008-09-22T23:06:02Z | 118,163 | 7 | 2008-09-22T23:10:13Z | [
"php",
"python",
"regex"
] | No not a competition, it is instead me trying to find why a certain regex works in one but not the other.
```
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
```
That's my Regex and I'm trying to run it on
... | It works for me. You must be doing something wrong.
```
>>> re.match(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', '127.255.0.0').groups()
('127', '255', '0', '0')
```
Don't forget to escape the regex ... |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | 43 | 2008-09-22T23:44:21Z | 118,275 | 53 | 2008-09-22T23:49:11Z | [
"python",
"python-idle",
"komodo",
"pywin"
] | I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komo... | There's a file called idle.py in your Python installation directory in Lib\idlelib\idle.py
If you run that file with Python, then IDLE should start.
> c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | 43 | 2008-09-22T23:44:21Z | 118,308 | 8 | 2008-09-22T23:56:03Z | [
"python",
"python-idle",
"komodo",
"pywin"
] | I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komo... | Here's another path you can use. I'm not sure if this is part of the standard distribution or if the file is automatically created on first use of the IDLE.
```
C:\Python25\Lib\idlelib\idle.pyw
``` |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | 43 | 2008-09-22T23:44:21Z | 7,394,470 | 10 | 2011-09-12T21:48:51Z | [
"python",
"python-idle",
"komodo",
"pywin"
] | I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komo... | In Python 3.2.2, I found `\Python32\Lib\idlelib\idle.bat` which was useful because it would let me open python files supplied as args in IDLE. |
How to start IDLE (Python editor) without using the shortcut on Windows Vista? | 118,260 | 43 | 2008-09-22T23:44:21Z | 8,237,399 | 8 | 2011-11-23T04:35:54Z | [
"python",
"python-idle",
"komodo",
"pywin"
] | I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komo... | If you just have a Python shell running, type:
```
import idlelib.PyShell
idlelib.PyShell.main()
``` |
How do you use the ellipsis slicing syntax in Python? | 118,370 | 114 | 2008-09-23T00:17:09Z | 118,395 | 70 | 2008-09-23T00:24:21Z | [
"python",
"numpy",
"subclass",
"slice",
"ellipsis"
] | This came up in [Hidden features of Python](http://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works. | You'd use it in your own class, since no builtin class makes use of it.
Numpy uses it, as stated in the [documentation](http://wiki.scipy.org/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb). Some examples [here](http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61e... |
How do you use the ellipsis slicing syntax in Python? | 118,370 | 114 | 2008-09-23T00:17:09Z | 118,508 | 159 | 2008-09-23T00:55:09Z | [
"python",
"numpy",
"subclass",
"slice",
"ellipsis"
] | This came up in [Hidden features of Python](http://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works. | The ellipsis is used to slice higher-dimensional data structures.
It's designed to mean *at this point, insert as many full slices (`:`) to extend the multi-dimensional slice to all dimensions*.
**Example**:
```
>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)
```
Now, you have a 4-dimensional matri... |
How do you use the ellipsis slicing syntax in Python? | 118,370 | 114 | 2008-09-23T00:17:09Z | 120,055 | 66 | 2008-09-23T09:34:48Z | [
"python",
"numpy",
"subclass",
"slice",
"ellipsis"
] | This came up in [Hidden features of Python](http://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works. | This is another use for Ellipsis, which has nothing to do with slices: I often use it in intra-thread communication with queues, as a mark that signals "Done"; it's there, it's an object, it's a singleton, and its name means "lack of", and it's not the overused None (which could be put in a queue as part of normal data... |
How can I join a list into a string (caveat)? | 118,458 | 6 | 2008-09-23T00:41:25Z | 118,462 | 7 | 2008-09-23T00:43:42Z | [
"python",
"string",
"list",
"csv"
] | Along the lines of my previous [question](http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat), how can i join a list of strings into a string such that values get quoted cleanly. Something like:
```
['a', 'one "two" three', 'foo, bar', """both"'"""]
```
into:
```
a,... | Using the `csv` module you can do that way:
```
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)
```
If you need a string just use `StringIO` instance as a file:
```
f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()
```
The output: `a,"one ""... |
How do I read an Excel file into Python using xlrd? Can it read newer Office formats? | 118,516 | 10 | 2008-09-23T00:58:09Z | 694,688 | 25 | 2009-03-29T14:21:13Z | [
"python",
"xlrd",
"import-from-excel"
] | My issue is below but would be interested comments from anyone with experience with xlrd.
I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the D... | FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points:
1. The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw by... |
Is there a way to convert indentation in Python code to braces? | 118,643 | 73 | 2008-09-23T01:33:13Z | 118,651 | 10 | 2008-09-23T01:35:23Z | [
"python",
"accessibility",
"blind",
"blindness"
] | I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and... | I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited.
I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python?
I'd assume that you use a ... |
Is there a way to convert indentation in Python code to braces? | 118,643 | 73 | 2008-09-23T01:33:13Z | 118,706 | 9 | 2008-09-23T01:51:53Z | [
"python",
"accessibility",
"blind",
"blindness"
] | I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and... | Although I am not blind, I have heard good things about [Emacspeak](http://emacspeak.sourceforge.net/). They've had a Python mode since their [8.0 release](http://emacspeak.sourceforge.net/releases/release-8.0.html) in 1998 (they seem to be up to release 28.0!). Definitely worth checking out. |
Is there a way to convert indentation in Python code to braces? | 118,643 | 73 | 2008-09-23T01:33:13Z | 118,738 | 24 | 2008-09-23T02:02:25Z | [
"python",
"accessibility",
"blind",
"blindness"
] | I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and... | Python supports braces for defining code blocks, and it also supports using 'begin' and 'end' tags.
Please see these code examples:
```
class MyClass(object): #{
def myfunction(self, arg1, arg2): #{
for i in range(arg1): #{
print i
#}
#}
#}
```
And an example with bash style:
``... |
Is there a way to convert indentation in Python code to braces? | 118,643 | 73 | 2008-09-23T01:33:13Z | 118,744 | 52 | 2008-09-23T02:04:01Z | [
"python",
"accessibility",
"blind",
"blindness"
] | I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and... | There's a solution to your problem that is distributed with python itself. `pindent.py`, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have grab it from svn.python.org if you are running on Linux or OSX.
It adds comments when blocks a... |
Iron python, beautiful soup, win32 app | 118,654 | 20 | 2008-09-23T01:37:48Z | 118,713 | 8 | 2008-09-23T01:53:58Z | [
".net",
"python",
"ironpython"
] | Does beautiful soup work with iron python?
If so with which version of iron python?
How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? | I've tested and used BeautifulSoup with both IPy 1.1 and 2.0 (forget which beta, but this was a few months back). Leave a comment if you are still having trouble and I'll dig out my test code and post it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.