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 |
|---|---|---|---|---|---|---|---|---|---|
Python logging: How to set time to GMT | 6,321,160 | 17 | 2011-06-12T09:16:47Z | 6,321,221 | 26 | 2011-06-12T09:31:04Z | [
"python",
"logging",
"timezone"
] | Is it possible and how to set the logging timezone to GMT?
(i.e. the `%(asctime)s` parameter in the format) | ```
logging.Formatter.converter = time.gmtime
```
(documented in the docstring of [`logging.Formatter.formatTime`](https://docs.python.org/2/library/logging.html#logging.Formatter.formatTime)) |
Django, Jenkins and PyLint looking at everything | 6,321,205 | 4 | 2011-06-12T09:25:58Z | 6,331,696 | 11 | 2011-06-13T14:21:08Z | [
"python",
"django",
"jenkins",
"pylint"
] | I am currently running Jenkins CI with pylint to look at a Django project I've been working on. One thing I have been frustrated by is pylint reporting for all the central django modules I import, meaning that my own project files get buried within mounds of other django modules (e.g. /usr/local/lib/python2.6/dist-pack... | Right, well thanks to the creator of Django\_Jenkins ([kmmbvnr](https://github.com/kmmbvnr/)) the correct way to get it to look at only your project's files is to use the following:
In settings.py, you need:
```
PROJECT_APPS=(
'appname',
)
```
And that sorts out the searching through every dependency out there.
... |
different fields for add and change pages in admin | 6,321,916 | 9 | 2011-06-12T12:24:52Z | 6,323,521 | 17 | 2011-06-12T17:49:43Z | [
"python",
"django",
"django-admin"
] | I have a django app with the following class in my admin.py:
```
class SoftwareVersionAdmin(ModelAdmin):
fields = ("product", "version_number", "description",
"media", "relative_url", "current_version")
list_display = ["product", "version_number", "size",
"current_version", "number_of_clients", "pe... | First have a look at source of ModelAdmin class' `get_form` and `get_formsets` methods located in `django.contrib.admin.options.py`. You can override those methods and use kwargs to get the behavior you want. For example:
```
class SoftwareVersionAdmin(ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
... |
different fields for add and change pages in admin | 6,321,916 | 9 | 2011-06-12T12:24:52Z | 31,791,675 | 11 | 2015-08-03T15:53:20Z | [
"python",
"django",
"django-admin"
] | I have a django app with the following class in my admin.py:
```
class SoftwareVersionAdmin(ModelAdmin):
fields = ("product", "version_number", "description",
"media", "relative_url", "current_version")
list_display = ["product", "version_number", "size",
"current_version", "number_of_clients", "pe... | This is an old question but I wanted to add that the add\_view and change\_view methods can be modified for this purpose:
```
class SoftwareVersionAdmin(ModelAdmin):
...
def add_view(self,request,extra_content=None):
self.exclude = ('product','version_number',)
return super(SoftwareVersionA... |
How to launch getattr function in python with additional parameters? | 6,321,940 | 16 | 2011-06-12T12:30:23Z | 6,321,946 | 28 | 2011-06-12T12:32:18Z | [
"python",
"getattr"
] | I want to call some unknown function with adding parameters using getattr function. Is it possible? | Yes, but you don't pass them to `getattr()`; you call the function as normal once you have a reference to it.
```
getattr(obj, 'func')('foo', 'bar', 42)
``` |
How to launch getattr function in python with additional parameters? | 6,321,940 | 16 | 2011-06-12T12:30:23Z | 6,322,114 | 16 | 2011-06-12T13:10:28Z | [
"python",
"getattr"
] | I want to call some unknown function with adding parameters using getattr function. Is it possible? | If you wish to invoke a dynamic method with a dynamic list of arguments / keyword arguments, you can do the following:
```
function_name = 'wibble'
args = ['flip', 'do']
kwargs = {'foo':'bar'}
getattr(obj, function_name)(*args, **kwargs)
``` |
Python: (sub) String equivalence vs List fast membership testing | 6,322,698 | 4 | 2011-06-12T15:19:08Z | 6,322,716 | 7 | 2011-06-12T15:22:23Z | [
"python"
] | Can somebody explain to me the following (python 2.7)
Two string numbers, from a parsed file:
'410.9'
'410.9 ' (Notice the trailing space)
```
A_LIST = ['410.9 ']
'410.9' in '410.9 '
True
'410.9' in A_LIST
False
```
No problem working around this - just trying to understand why it is so.
Thanks! | `in` with two strings checks or a substring, whereas `in` with a list checks for membership.
What you want is something like `[x for x in A_LIST if '419' in x]` |
Code after threads is executed early, why? | 6,323,176 | 2 | 2011-06-12T16:48:44Z | 6,323,195 | 7 | 2011-06-12T16:51:46Z | [
"python",
"windows"
] | ```
from threading import Thread
import time
print 'start of script'
class MyThread(Thread):
def run(self):
for i in xrange(10):
print 'thread->', '['+self.name+']', '('+str(i)+')'
time.sleep(2)
for i in range(3):
my_thread = MyThread()
my_thread.name = i
my_thread.sta... | That's perfectly normal. You're not waiting for the threads to finish, so there is no reason for your code to block after the `for` loop.
You'll need a second loop in which you call `.join()` on each thread if you want to wait for them.
> Yet, 'end of script' gets printed right after I execute the first thread, inste... |
Simple python question: accessing class data member | 6,323,209 | 2 | 2011-06-12T16:54:20Z | 6,323,228 | 9 | 2011-06-12T16:57:23Z | [
"python",
"class"
] | I have a class which defines data attributes.
```
class channel:
def __init(self,var1, var2):
self.var1 = var1
self.var2 = var1
#etc
```
So far so simple. But what I'd like to do is to have a method that specifies which data attribute to use so that I can generically use it to do the same ... | You can use [getattr](http://docs.python.org/library/functions.html#getattr) like this:
```
def fun(list_of_channels, attr_name):
for chan in list_of_channels:
attr = getattr(chan, attr_name)
...
``` |
Python remove anything that is not a letter or number | 6,323,296 | 6 | 2011-06-12T17:09:48Z | 6,325,804 | 10 | 2011-06-13T01:10:41Z | [
"python",
"regex",
"string"
] | I'm having a little trouble with Python regular expressions.
What is a good way to remove all characters in a string that are not letters or numbers?
Thanks! | `[\w]` matches (alphanumeric or underscore).
`[\W]` matches (not (alphanumeric or underscore)), which is equivalent to (not alphanumeric and not underscore)
You need `[\W_]` to remove ALL non-alphanumerics.
When using re.sub(), it will be much more efficient if you reduce the number of substitutions (expensive) by m... |
Make a 2D pixel plot with matplotlib | 6,323,737 | 8 | 2011-06-12T18:28:06Z | 6,323,845 | 13 | 2011-06-12T18:41:39Z | [
"python",
"grid",
"matplotlib",
"plot",
"pixel"
] | I got the following data from some calculations:
```
x, y, temp
```
where x and y are the coordinates of a point in a 2D box of dimensions 10x10. Spacing is equal to 0.1. So there are 10000 different points and the resulting file looks like:
```
0.0 0.0 5.6
0.1 0.0 3.2
0.2 0.0 4.1
...
9.9 9.9 2.1
```
I would like t... | Based on the way it looks like your x,y,temp triples are ordered (listed out in rows), you can just reshape the "temp" column.
E.g.
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
x,y,temp = np.loadtxt('data.txt').T #Transposed for easier unpacking
nrows, ncols = 100, 100
grid = tem... |
Sibling package imports | 6,323,860 | 33 | 2011-06-12T18:42:51Z | 6,466,139 | 13 | 2011-06-24T09:48:53Z | [
"python",
"packages",
"python-import",
"siblings"
] | I've tried reading through questions about sibling imports and even the
[package documentation](http://docs.python.org/tutorial/modules.html#intra-package-references), but I've yet to find an answer.
With the following structure:
```
âââ LICENSE.md
âââ README.md
âââ api
â  âââ __init__.py... | As already stated elsewhere, the awful truth is that you have to do ugly hacks to allow imports from siblings modules or parents package from a `__main__` module. The issue is detailed in [PEP 366](http://www.python.org/dev/peps/pep-0366/). [PEP 3122](http://www.python.org/dev/peps/pep-3122/) attempted to handle import... |
Sibling package imports | 6,323,860 | 33 | 2011-06-12T18:42:51Z | 9,446,075 | 19 | 2012-02-25T17:02:56Z | [
"python",
"packages",
"python-import",
"siblings"
] | I've tried reading through questions about sibling imports and even the
[package documentation](http://docs.python.org/tutorial/modules.html#intra-package-references), but I've yet to find an answer.
With the following structure:
```
âââ LICENSE.md
âââ README.md
âââ api
â  âââ __init__.py... | Here is another alternative that I insert at top of the Python files in `tests` folder:
```
# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))
``` |
Django TemplateSyntaxError | 6,324,799 | 8 | 2011-06-12T21:28:37Z | 6,324,840 | 14 | 2011-06-12T21:37:00Z | [
"python",
"django"
] | I'm following a Django tutorial and suddenly when I try to access <http://127.0.0.1:8000/admin/> it gives me a TemplateSyntaxError.
TemplateSyntaxError at /admin/
Caught ViewDoesNotExist while rendering: Tried results in module polls.views. Error was: 'module' object has no attribute 'results'
It highlights this lin... | ```
Caught ViewDoesNotExist while rendering: Tried results in module polls.views.
Error was: 'module' object has no attribute 'results'
```
That's pretty much all you need. Ignore the `TemplateSyntaxError`, it's not related to the template at all. Django is telling you that you don't have this:
```
def results(reque... |
Parse HTML table to Python list? | 6,325,216 | 24 | 2011-06-12T22:46:06Z | 6,325,277 | 40 | 2011-06-12T22:59:01Z | [
"python",
"html"
] | I'd like to take an HTML table and parse through it to get a list of dictionaries. Each list element would be a dictionary corresponding to a row in the table.
If, for example, I had an HTML table with three columns (marked by header tags), "Event", "Start Date", and "End Date" and that table had 5 entries, I would li... | You should use some HTML parsing library like [`lxml`](http://lxml.de/):
```
from lxml import etree
s = """<table>
<tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>d</td><td>e</td><td>f</td></tr>
<tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
tab... |
Parse HTML table to Python list? | 6,325,216 | 24 | 2011-06-12T22:46:06Z | 7,315,891 | 19 | 2011-09-06T06:46:09Z | [
"python",
"html"
] | I'd like to take an HTML table and parse through it to get a list of dictionaries. Each list element would be a dictionary corresponding to a row in the table.
If, for example, I had an HTML table with three columns (marked by header tags), "Event", "Start Date", and "End Date" and that table had 5 entries, I would li... | Sven Marnach [excellent solution](http://stackoverflow.com/questions/6325216/parse-html-table-to-python-list/6325277#6325277) is directly translatable into [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html) which is part of recent Python distributions:
```
from xml.etree import ElementTree as ET
... |
Parse HTML table to Python list? | 6,325,216 | 24 | 2011-06-12T22:46:06Z | 22,320,207 | 11 | 2014-03-11T08:31:49Z | [
"python",
"html"
] | I'd like to take an HTML table and parse through it to get a list of dictionaries. Each list element would be a dictionary corresponding to a row in the table.
If, for example, I had an HTML table with three columns (marked by header tags), "Event", "Start Date", and "End Date" and that table had 5 entries, I would li... | If the HTML is **not** XML you can't do it with *etree*. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with `HTMLParser` from `html.parser`. I've the code of the simple derived HTMLParser class [here in a github repo](https://github.com/schmijos/h... |
Python: Matplotlib - probability plot for several data set | 6,326,360 | 4 | 2011-06-13T03:21:28Z | 6,339,311 | 9 | 2011-06-14T05:06:38Z | [
"python",
"numpy",
"matplotlib",
"probability",
"percentile"
] | I have several data sets (distribution) as follows:
```
set1 = [1,2,3,4,5]
set2 = [3,4,5,6,7]
set3 = [1,3,4,5,8]
```
How do I plot a scatter plot with the data sets above with the y-axis being the probability (i.e. the percentile of the distribution in set: 0%-100% ) and the x-axis being the data set names?
in JMP, i... | I'm not entirely clear on what you want, so I'm going to guess, here...
You want the "Probability/Percentile" values to be a cumulative histogram?
So for a single plot, you'd have something like this? (Plotting it with markers as you've shown above, instead of the more traditional step plot...)
```
import scipy.stat... |
Creating a sandbox in virtualenv with python 2.7 fails on ubuntu? | 6,327,689 | 5 | 2011-06-13T07:28:17Z | 6,507,838 | 9 | 2011-06-28T14:11:17Z | [
"python",
"virtualenv",
"python-2.7"
] | Why is virtualenv complaining about missing `_weakrefset`
```
laptop:~/sandbox$ virtualenv --python=/usr/bin/python2.7 --no-site-packages play
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in play/bin/python2.7
Also creating executable in play/bin/python
Traceback (most recent call last)... | See <https://github.com/pypa/virtualenv/issues/76>
For use with Python 2.7, upgrade virtualenv to 1.5.1 or newer. You can check your current version with `virtualenv --version`. |
Authorization in social networking website | 6,328,590 | 11 | 2011-06-13T09:18:35Z | 6,334,860 | 7 | 2011-06-13T18:55:08Z | [
"python",
"django",
"authorization",
"social-networking"
] | I need to accomplish the following related to privileges:
I have 3 users:
```
- User A
- User B
- User C
```
Each of the users has the following documents with associated access settings:
```
- User A
- Document A1, only allow contacts to view
- Document A2, allow everyone to view
- Document A3, allow n... | Unfortunately Django's authorization system does not allow you to assign permissions per object, only per class. Here I assume that each of your "Document" is an instance of a model class.
There are, however, reusable apps that greatly simplify this task. Have a look at [django-guardian](http://djangopackages.com/pack... |
In Python, why is list[] automatically global? | 6,329,499 | 4 | 2011-06-13T10:57:13Z | 6,329,536 | 10 | 2011-06-13T11:00:56Z | [
"python",
"list",
"global",
"python-2.7"
] | This is a weird behavior.
Try this :
```
rep_i=0
print "rep_i is" , rep_i
def test():
global rep_i #without Global this gives error but list , dict , and others dont
if rep_i==0:
print "Testing Integer %s" % rep_i
rep_i=1
return "Done"
rep_lst=[1,2,3]
def test2():
if rep_lst[0]==1:
print "Testi... | It isn't automatically global.
However, there's a difference between `rep_i=1` and `rep_lst[0]=1` - the former rebinds the name `rep_i`, so `global` is needed to prevent creation of a local slot of the same name. In the latter case, you're just modifying an existing, global object, which is found by regular name looku... |
Safe casting in python | 6,330,071 | 4 | 2011-06-13T11:55:40Z | 6,330,109 | 24 | 2011-06-13T11:59:14Z | [
"python",
"casting"
] | I have a problem with casting in python.
I c# I can safe cast by keyword as, e.g.:
```
string word="15";
var x=word as int32// here I get 15
string word="fifteen";
var x=word as int32// here I get null
```
Has python(3.2) something similar to this? | Think not, but you may implement your own:
```
def safe_cast(val, to_type, default=None):
try:
return to_type(val)
except ValueError:
return default
safe_cast('tst', int) # will return None
safe_cast('tst', int, 0) # will return 0
``` |
An elegant way to get hashtags out of a string in Python? | 6,331,497 | 6 | 2011-06-13T14:04:54Z | 6,331,560 | 7 | 2011-06-13T14:08:54Z | [
"python",
"string",
"list-comprehension",
"hashtag"
] | I'm looking for a clean way to get a set (list, array, whatever) of words starting with `#` inside a given string.
In C#, I would write
```
var hashtags = input
.Split (' ')
.Where (s => s[0] == '#')
.Select (s => s.Substring (1))
.Distinct ();
```
What is comparatively elegant code to do this in Pyt... | I'd say
```
hashtags = [word[1:] for word in input.split() if word[0] == '#']
```
Edit: this will create a set without any duplicates.
```
set(hashtags)
``` |
An elegant way to get hashtags out of a string in Python? | 6,331,497 | 6 | 2011-06-13T14:04:54Z | 6,331,563 | 12 | 2011-06-13T14:09:03Z | [
"python",
"string",
"list-comprehension",
"hashtag"
] | I'm looking for a clean way to get a set (list, array, whatever) of words starting with `#` inside a given string.
In C#, I would write
```
var hashtags = input
.Split (' ')
.Where (s => s[0] == '#')
.Select (s => s.Substring (1))
.Distinct ();
```
What is comparatively elegant code to do this in Pyt... | ```
[i[1:] for i in line.split() if i.startswith("#")]
```
This version will get rid of any empty strings (as I have read such concerns in the comments) and strings that are only `"#"`. Also, as in [Bertrand Marron](http://stackoverflow.com/users/212384/bertrand-marron)'s code, it's better to turn this into a set as f... |
An elegant way to get hashtags out of a string in Python? | 6,331,497 | 6 | 2011-06-13T14:04:54Z | 6,331,654 | 7 | 2011-06-13T14:17:32Z | [
"python",
"string",
"list-comprehension",
"hashtag"
] | I'm looking for a clean way to get a set (list, array, whatever) of words starting with `#` inside a given string.
In C#, I would write
```
var hashtags = input
.Split (' ')
.Where (s => s[0] == '#')
.Select (s => s.Substring (1))
.Distinct ();
```
What is comparatively elegant code to do this in Pyt... | the `findall` method of [regular expression objects](http://docs.python.org/library/re.html) can get them all at once:
```
>>> import re
>>> s = "this #is a #string with several #hashtags"
>>> pat = re.compile(r"#(\w+)")
>>> pat.findall(s)
['is', 'string', 'hashtags']
>>>
``` |
An elegant way to get hashtags out of a string in Python? | 6,331,497 | 6 | 2011-06-13T14:04:54Z | 6,331,688 | 12 | 2011-06-13T14:20:37Z | [
"python",
"string",
"list-comprehension",
"hashtag"
] | I'm looking for a clean way to get a set (list, array, whatever) of words starting with `#` inside a given string.
In C#, I would write
```
var hashtags = input
.Split (' ')
.Where (s => s[0] == '#')
.Select (s => s.Substring (1))
.Distinct ();
```
What is comparatively elegant code to do this in Pyt... | With [@inspectorG4dget's answer](http://stackoverflow.com/questions/6331497/an-elegant-way-to-get-hashtags-out-of-a-string-in-python/6331563#6331563), if you want no duplicates, you can use set comprehensions instead of list comprehensions.
```
>>> tags="Hey guys! #stackoverflow really #rocks #rocks #announcement"
>>>... |
pickling error in python? | 6,331,901 | 12 | 2011-06-13T14:38:43Z | 9,628,121 | 13 | 2012-03-09T02:24:52Z | [
"python",
"pickle"
] | I am getting this error, and I dont know what it means. How can I fix this problem?
my code looks like this, I've used it before and it has worked:
```
parentdir = os.getcwd()
dirlist = os.listdir(parentdir)
for dir in dirlist:
if not dir == "pubs_edits": continue
if os.path.isdir(os.path.join(parentdir, dir... | This exact error occurred for me when I tried to unpickle (using pickle.loads) a string representation that I had stored in a database via django. Django changed the charactee representation of my string so that `pickle.loads(mystring)` threw me that error. When I added an explicit string conversion in, it was fine: `p... |
Send Outlook Email Via Python? | 6,332,577 | 10 | 2011-06-13T15:31:43Z | 6,332,621 | 17 | 2011-06-13T15:35:35Z | [
"python",
"outlook"
] | I am using `Outlook 2003`.
What is the best way to send email (through `Outlook 2003`) using `Python`? | Check via Google, there are lots of examples, see [here](http://win32com.goermezer.de/content/view/227/284/) for one.
Inlined for ease of viewing:
```
import win32com.client
def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
s = win32com.client.Dispatch("Mapi.Session")
o = win32com.c... |
Send Outlook Email Via Python? | 6,332,577 | 10 | 2011-06-13T15:31:43Z | 17,887,528 | 13 | 2013-07-26T17:32:53Z | [
"python",
"outlook"
] | I am using `Outlook 2003`.
What is the best way to send email (through `Outlook 2003`) using `Python`? | ```
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'to address'
mail.Subject = 'Message subject'
mail.body = 'Message body'
mail.send
```
Will use your local outlook account to send |
Python dictionary iteration | 6,332,691 | 20 | 2011-06-13T15:39:44Z | 6,332,746 | 34 | 2011-06-13T15:44:35Z | [
"python",
"dictionary"
] | I have a dictionary `dict2` which I want to iter through and remove all entries that contain certain ID numbers in `idlist`. `dict2[x]` is a list of lists (see example dict2 below). This is the code I have written so far, however it does not remove all instances of the IDs (`entry[1]`) that are in the `idlist`. Any hel... | Try a cleaner version perhaps?
```
for k in dict2.keys():
dict2[k] = [x for x in dict2[k] if x[1] not in idlist]
if not dict2[k]:
del dict2[k]
``` |
Python dictionary iteration | 6,332,691 | 20 | 2011-06-13T15:39:44Z | 6,332,862 | 15 | 2011-06-13T15:52:20Z | [
"python",
"dictionary"
] | I have a dictionary `dict2` which I want to iter through and remove all entries that contain certain ID numbers in `idlist`. `dict2[x]` is a list of lists (see example dict2 below). This is the code I have written so far, however it does not remove all instances of the IDs (`entry[1]`) that are in the `idlist`. Any hel... | An approach using sets (Note that I needed to change your variables A, B, C, etc. to strings and the numbers in your idlist to actual integers; also this only works, if your IDs are unique and don't occur in other 'fields'):
```
#!/usr/bin/env python
# 2.6 <= python version < 3
original = {
'G1' : [
['A',... |
Using C# Assemblies from Python via pythonnet | 6,333,044 | 7 | 2011-06-13T16:07:36Z | 13,241,493 | 8 | 2012-11-05T22:33:18Z | [
"python",
".net",
"python.net"
] | I am using Windows 7, 64-bit. I have managed to download and install pythonnet, so
```
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Form
```
works fine. I have also downloaded and compiled/run a C# application which creates lots of assemblies. The application in question is ARD... | Just to provide another method:
```
import sys
sys.path.append("C:\Path\to\your\assemblies")
clr.AddReference('MyAssembly')
from MyAssembly import MyClass
MyClass.does_something()
```
This assumes that in the `C:\Path\to\your\assemblies` folder you have a MyAssembly.dll file.
So the 'trick' is that you have to add... |
Django on Apache web server 'dict' object has no attribute 'render_context' | 6,333,367 | 4 | 2011-06-13T16:33:41Z | 6,333,439 | 9 | 2011-06-13T16:38:46Z | [
"python",
"html",
"django",
"apache",
"mod-python"
] | I'm having a bit of a problem, I uploaded my Django project to a webserver running apache, mod\_python, and django. On the computer I developed on the following works fine
```
nameBox = getNamesBox().render(locals())
```
-
```
def getNamesBox():
users = User.objects.filter()
templateString = '<select name="... | The `render()` method on a `Template` takes a `Context` object as its argument, not a dict. You'll have to construct a `Context` object from the dict, e.g.
```
namedbox = getNamesBox().render(Context(locals()))
``` |
Run all Tests in Directory Using Nose | 6,333,495 | 17 | 2011-06-13T16:45:30Z | 6,334,161 | 40 | 2011-06-13T17:52:41Z | [
"python",
"nose"
] | I need to be able to run all tests in the current directory by typing one line in the Linux shell. In some directories this works fine. But in others, when I type "nosetests" no tests are run. The tests will run if I call for them individually but I need them to all run automatically. Here is one of the directories tha... | From [*Python Testing: Beginner's Guide*](http://www.packtpub.com/python-testing-beginners-guide/book) by Daniel Arbuckle:
> Nose looks for tests in directories and modules whose names start with `test` and `Test`, or contain a `'_'`, `'.'`, or `'-`' followed by `test` or `Test`. That's the default, but it's not actua... |
Run all Tests in Directory Using Nose | 6,333,495 | 17 | 2011-06-13T16:45:30Z | 7,278,617 | 10 | 2011-09-02T02:13:03Z | [
"python",
"nose"
] | I need to be able to run all tests in the current directory by typing one line in the Linux shell. In some directories this works fine. But in others, when I type "nosetests" no tests are run. The tests will run if I call for them individually but I need them to all run automatically. Here is one of the directories tha... | You can use `--exe` in the command line to force nose to consider executables files as valid tests. If you get tired of writting `--exe` everytime, you can put the line:
> exe = True
in a .noserc (for unix/linux) or nose.cfg (for windows) file at yout home directory. |
python logging ensure a handler is added only once | 6,333,916 | 23 | 2011-06-13T17:27:36Z | 6,334,064 | 15 | 2011-06-13T17:42:12Z | [
"python",
"logging"
] | I have a piece of code that is initializing a logger as below.
```
logger = logging.getLogger()
hdlr = logging.FileHandler('logfile.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
```
Unfortunately this c... | Well the [logger.addHandler()](http://docs.python.org/library/logging.html#logging.Logger.addHandler) will not add a handler if the handler already exists. To check if the handler is already there you can check the logger.handlers list:
```
logger = logging.getLogger()
hdlr = logging.FileHandler('logfile.log')
formatt... |
python logging ensure a handler is added only once | 6,333,916 | 23 | 2011-06-13T17:27:36Z | 31,800,084 | 8 | 2015-08-04T03:17:24Z | [
"python",
"logging"
] | I have a piece of code that is initializing a logger as below.
```
logger = logging.getLogger()
hdlr = logging.FileHandler('logfile.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
```
Unfortunately this c... | As @offbyone comments, it is possible to add redundant handlers to the same instance of the logger.
The [python docs for logging](https://docs.python.org/2/howto/logging.html#logging-basic-tutorial) say-
> "Multiple calls to getLogger() with the same name will return a
> reference to the same logger object."
So we do... |
Python Open a txt file without clearing everything in it? | 6,334,382 | 4 | 2011-06-13T18:11:40Z | 6,334,395 | 10 | 2011-06-13T18:12:49Z | [
"python",
"io"
] | ```
file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()
....(Somewhere else in the code)
file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()
```
I was wondering how I can keep a log.txt file that I can write to?
I want to be able to open a txt file, write to it, then... | Change `'w'` to `'a'`, for [append mode](http://docs.python.org/library/functions.html#open). But you really ought to just keep the file open and write to it when you need it. If you are repeating yourself, use the [`logging`](http://docs.python.org/library/logging.html) module. |
Python how to read N number of lines at a time | 6,335,839 | 33 | 2011-06-13T20:20:41Z | 6,335,876 | 33 | 2011-06-13T20:24:41Z | [
"python",
"lines",
"itertools"
] | I am writing a code to take an enormous textfile (several GB) N lines at a time, process that batch, and move onto the next N lines until I have completed the entire file. (I don't care if the last batch isn't the perfect size).
I have been reading about using itertools islice for this operation. I think I am halfway ... | `islice()` can be used to get the next `n` items of an iterator. Thus, `list(islice(f, n))` will return a list of the next `n` lines of the file `f`. Using this inside a loop will give you the file in chunks of `n` lines. At the end of the file, the list might be shorter, and finally the call will return an empty list.... |
python build a dynamic growing truth table | 6,336,424 | 11 | 2011-06-13T21:12:08Z | 6,336,448 | 24 | 2011-06-13T21:14:10Z | [
"python",
"table",
"logic"
] | my question is simple:
"how to build a dynamic growing truth table in python in an elegant way?"
for n=3
```
for p in False, True:
for q in False, True:
for r in False, True:
print '|{0} | {1} | {2} |'.format(int(p),int(q), int(r))
```
for n=4
```
for p in False, True:
for q in False, Tr... | Use [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product):
```
table = list(itertools.product([False, True], repeat=n))
```
Result for `n = 3`:
```
[(False, False, False),
(False, False, True),
(False, True, False),
(False, True, True),
(True, False, False),
(True, False, True... |
Split models.py into several files | 6,336,664 | 33 | 2011-06-13T21:34:46Z | 6,338,719 | 16 | 2011-06-14T03:18:59Z | [
"python",
"django",
"django-models",
"import"
] | I'm trying to split the `models.py` of my app into several files:
My first guess was do this:
```
myproject/
settings.py
manage.py
urls.py
__init__.py
app1/
views.py
__init__.py
models/
__init__.py
model1.py
model2.py
app2/
vi... | I can't even begin to imagine why you'd want to do this. But I'll assume you've got a good reason. If I needed to do this for some reason, I'd do the following:
```
myproject/
...
app1/
views.py
__init__.py
models.py
submodels/
__init__.py
model1.py
... |
Split models.py into several files | 6,336,664 | 33 | 2011-06-13T21:34:46Z | 6,889,847 | 11 | 2011-07-31T13:55:24Z | [
"python",
"django",
"django-models",
"import"
] | I'm trying to split the `models.py` of my app into several files:
My first guess was do this:
```
myproject/
settings.py
manage.py
urls.py
__init__.py
app1/
views.py
__init__.py
models/
__init__.py
model1.py
model2.py
app2/
vi... | I've actually come across a tutorial for exactly what you're asking about, you can view it here:
<http://paltman.com/breaking-apart-models-in-django/>
One key point that's probably relevant - you may want to use the db\_table field on the Meta class to point the relocated classes back at their own table.
I can confi... |
Split models.py into several files | 6,336,664 | 33 | 2011-06-13T21:34:46Z | 37,758,721 | 10 | 2016-06-11T00:11:35Z | [
"python",
"django",
"django-models",
"import"
] | I'm trying to split the `models.py` of my app into several files:
My first guess was do this:
```
myproject/
settings.py
manage.py
urls.py
__init__.py
app1/
views.py
__init__.py
models/
__init__.py
model1.py
model2.py
app2/
vi... | For anyone on Django 1.9, it is now supported by the framework without defining the class meta data.
<https://docs.djangoproject.com/en/1.9/topics/db/models/#organizing-models-in-a-package>
> The `manage.py startapp` command creates an application structure that includes a models.py file. If you have many models, org... |
How do you daemonize a Flask application? | 6,337,119 | 17 | 2011-06-13T22:22:57Z | 6,337,218 | 24 | 2011-06-13T22:36:00Z | [
"python",
"flask"
] | I hav a small application written in Python using Flask. Right now I'm running it under nohup, but I'd like to daemonize it. What's the proper way of doing this? | [There are several ways to deploy a Flask project](http://flask.pocoo.org/docs/deploying/). Deploying with [gunicorn](http://gunicorn.org) might be the easiest, install gunicorn and then:
```
gunicorn project:app --daemon
```
Although you probably want to use supervisor or something of that nature to monitor gunicorn... |
python win32 COM closing excel workbook | 6,337,595 | 2 | 2011-06-13T23:35:18Z | 6,338,030 | 9 | 2011-06-14T00:57:19Z | [
"python",
"winapi",
"excel",
"com",
"win32com"
] | I open several different workbooks (excel xlsx format) in COM, and mess with them. As the program progresses I wish to close one specific workbook but keep the rest open.
How do I close ONE workbook? (instead of the entire excel application)
```
xl = Dispatch("Excel.Application")
xl.Visible = False
try:
output = ... | The the Workbook COM object [has a Close() method](http://msdn.microsoft.com/en-us/library/ff838613.aspx). Basically, it should be something like:
```
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('New Workbook.xlsx')
# do some stuff
wb.Close(True) # save the workbook
```
---
The above was just a skeleto... |
Django-Haystack with Solr contains search | 6,337,811 | 6 | 2011-06-14T00:14:29Z | 6,340,426 | 8 | 2011-06-14T07:31:48Z | [
"python",
"django",
"solr",
"django-haystack"
] | I am using `haystack` within a project using `solr` as the backend. I want to be able to perform a contains search, similar to the Django `.filter(something__contains="...")`
The `__startswith` option does not suit our needs as it, as the name suggests, looks for words that start with the string.
I tried to use somet... | To get "contains" functionallity you can use:
```
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.EdgeNGramFilterFactory" minGramSize="1" maxGramSize="100" side="back"/>
<filter class="solr.LowerCaseFilterFactory" />
```
as index analyzer.
This will create ngrams for every whitespace separat... |
small language in python | 6,338,440 | 6 | 2011-06-14T02:20:13Z | 6,349,062 | 7 | 2011-06-14T19:38:25Z | [
"python",
"parsing",
"programming-languages",
"operators",
"postfix-notation"
] | I'm writing what might not even be called a language in python. I currently have several operators: `+`, `-`, `*`, `^`, `fac`, `@`, `!!`. `fac` computes a factorial, `@` returns the value of a variable, `!!` sets a variable. The code is below. How would I go about writing a way to define functions in this simple langua... | Your program is very confused, and it needs to be fixed before it can be modified to support defining functions. I will do this in several steps and as I complete them, I will add them into the answer. This answer will get to be quite long.
Also, you obviously haven't decided what your language definition should be. Y... |
how to url-safe encode a string with python? and urllib.quote is wrong | 6,338,469 | 3 | 2011-06-14T02:27:08Z | 6,338,518 | 7 | 2011-06-14T02:38:15Z | [
"python",
"encoding",
"url-rewriting"
] | Hello i was wondering if you know any other way to encode a string to a url-safe, because urllib.quote is doing it wrong, the output is different than expected:
If i try
> > > urllib.quote('á')
i get
'%C3%A1'
But thats not the correct output, it should be
%E1
As demostrated by the tool provided here [this site](... | According to [RFC 3986](http://tools.ietf.org/html/rfc3986), `%C3%A1` is correct. Characters are supposed to be converted to an octet stream using UTF-8 before the octet stream is percent-encoded. The site you link is out of date.
See [Why does the encoding's of a URL and the query string part differ?](http://stackove... |
"Friend"ing classes in python | 6,338,867 | 7 | 2011-06-14T03:51:47Z | 6,338,881 | 14 | 2011-06-14T03:54:56Z | [
"python",
"class",
"inheritance",
"friend"
] | is there any way to make certain variables in classes "private" (or whatever `self.__var` really is) but be accessible to another class, like friends in c++, except in python? i do not want the variables in either class being messed with. Nor do i want to copy the entire code over and convert it for the second code. | No, there is not such an option.
Use names that start with single underscores and tell the other people working on your project to not be silly about what they access. |
Draw a transparent rectangle in pygame | 6,339,057 | 15 | 2011-06-14T04:28:29Z | 6,350,227 | 26 | 2011-06-14T21:11:14Z | [
"python",
"pygame"
] | How can I draw a rectangle that has a color with an alpha?
I have:
```
windowSurface = pygame.display.set_mode((1000, 750), pygame.DOUBLEBUF)
pygame.draw.rect(windowSurface, pygame.Color(255, 255, 255, 128), pygame.Rect(0, 0, 1000, 750))
```
But I want the white rectangle to be 50% transparent, but the alpha value do... | `pygame.draw` functions will not draw with alpha. The documentation says:
> Most of the arguments accept a color argument that is an RGB triplet. These can also accept an RGBA quadruplet. The alpha value will be written directly into the Surface if it contains pixel alphas, but the draw function will not draw transpar... |
How to append to the end of an empty list? | 6,339,235 | 32 | 2011-06-14T04:56:26Z | 6,339,248 | 10 | 2011-06-14T04:58:44Z | [
"python"
] | I have a list:
```
list1=[]
```
the length of the list is undetermined so I am trying to append objects to the end of list1 like such:
```
for i in range(0, n):
list1=list1.append([i])
```
But my output keeps giving this error: AttributeError: 'NoneType' object has no attribute 'append'
Is this because list1 ... | You don't need the assignment operator. append returns None. |
How to append to the end of an empty list? | 6,339,235 | 32 | 2011-06-14T04:56:26Z | 6,339,272 | 30 | 2011-06-14T05:01:30Z | [
"python"
] | I have a list:
```
list1=[]
```
the length of the list is undetermined so I am trying to append objects to the end of list1 like such:
```
for i in range(0, n):
list1=list1.append([i])
```
But my output keeps giving this error: AttributeError: 'NoneType' object has no attribute 'append'
Is this because list1 ... | `append` actually *changes* the list. Also, it takes an **item**, not a list. Hence, all you need is
```
for i in range(n):
list1.append(i)
```
(By the way, note that you can use `range(n)`, in this case.)
I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more... |
Python - Iterating through list of list | 6,340,351 | 12 | 2011-06-14T07:25:32Z | 6,340,411 | 18 | 2011-06-14T07:30:35Z | [
"python",
"list"
] | I want to iterate through list of list.
I want to iterate through irregularly nested lists inside list also.
Can anyone let me know how can I do that?
```
x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
```
Thanks | So wait, this is just a list-within-a-list?
The easiest way is probably just to use nested for loops:
```
>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
... for number in list:
... print number
...
1
3
4
2
4
4
3
4
5
```
Or is it something more complic... |
Python - Iterating through list of list | 6,340,351 | 12 | 2011-06-14T07:25:32Z | 6,340,578 | 22 | 2011-06-14T07:48:29Z | [
"python",
"list"
] | I want to iterate through list of list.
I want to iterate through irregularly nested lists inside list also.
Can anyone let me know how can I do that?
```
x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
```
Thanks | This `traverse` generator function can be used to iterate over all the values:
```
def traverse(o, tree_types=(list, tuple)):
if isinstance(o, tree_types):
for value in o:
for subvalue in traverse(value, tree_types):
yield subvalue
else:
yield o
data = [(1,1,(1,1,(1... |
How to call a python script from Perl? | 6,340,479 | 12 | 2011-06-14T07:37:57Z | 6,340,492 | 8 | 2011-06-14T07:39:47Z | [
"python",
"perl"
] | I need to call "/usr/bin/pdf2txt.py" with few arguments from my Perl script. How should i do this ? | ```
my $output = `/usr/bin/pdf2txt.py arg1 arg2`;
``` |
How to call a python script from Perl? | 6,340,479 | 12 | 2011-06-14T07:37:57Z | 6,340,531 | 11 | 2011-06-14T07:43:51Z | [
"python",
"perl"
] | I need to call "/usr/bin/pdf2txt.py" with few arguments from my Perl script. How should i do this ? | If you need to capture **STDOUT**:
```
my $ret = `/usr/bin/pdf2txt.py arg1 arg2`;
```
You can easily capture **STDERR** redirecting it to STDOUT:
```
my $ret = `/usr/bin/pdf2txt.py arg1 arg2 2>&1`;
```
If you need to capture the **exit status**, then you can use:
```
my $ret = system("/usr/bin/pdf2txt.py arg1 arg2... |
Get Request Headers for Urllib2.Request? | 6,340,782 | 6 | 2011-06-14T08:12:45Z | 6,340,973 | 13 | 2011-06-14T08:28:47Z | [
"python",
"urllib2"
] | Is there a way to get the headers from a request created with Urllib2 or to confirm the HTTP headers sent with urllib2.urlopen? | An easy way to see request (and response headers) is to enable debug output:
```
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
```
You then can see the precise headers sent/recieved:
```
>>> opener.open('http://python.org')
send: 'GET / HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: python.org\r\n... |
subprocess.wait() not waiting for Popen process to finish (when using threads)? | 6,341,358 | 12 | 2011-06-14T09:07:03Z | 13,581,615 | 7 | 2012-11-27T09:59:48Z | [
"python",
"multithreading",
"subprocess",
"popen"
] | I am experiencing some problems when using `subprocess.Popen()` to spawn several instances of the same application from my python script using threads to have them running simultaneously. In each thread I run the application using the `popen()` call, and then I wait for it to finish by calling`wait()`. The problem seem... | You could also use [`check_call()`](http://docs.python.org/2/library/subprocess.html) instead of Popen. `check_call()` waits for the command to finish, even when `shell=True` and then returns the exit code of the job. |
Python sending dictionary throught TCP | 6,341,823 | 6 | 2011-06-14T09:52:32Z | 6,341,858 | 9 | 2011-06-14T09:56:05Z | [
"python",
"dictionary",
"tcp"
] | I'm a python beginner, and I'm curious how can I send a dictionary through TCP | You can use [`pickle`](http://docs.python.org/library/pickle.html) to convert any Python object (including a dictionary) to a byte stream, which can then be sent over TCP and un-pickled on the receiving end.
Alternatively, you can use [`json`](http://docs.python.org/library/json.html), which isn't dependent on the rec... |
Python sending dictionary throught TCP | 6,341,823 | 6 | 2011-06-14T09:52:32Z | 6,341,859 | 9 | 2011-06-14T09:56:14Z | [
"python",
"dictionary",
"tcp"
] | I'm a python beginner, and I'm curious how can I send a dictionary through TCP | You should serialize it with [`pickle`](http://docs.python.org/library/pickle.html):
```
import pickle
dict = {...}
tcp_send(pickle.dumps(dict))
```
And on the other end:
```
import pickle
dict = pickle.loads(tcp_recieve())
```
If the other end is not written in python, you can use a data serialization format, like... |
Importing a long list of constants to a Python file | 6,343,330 | 26 | 2011-06-14T12:17:18Z | 6,343,398 | 32 | 2011-06-14T12:23:32Z | [
"python",
"constants",
"python-import"
] | In Python, is there an analogue of the `C` preprocessor statement such as?:
`#define MY_CONSTANT 50`
Also, I have a large list of constants I'd like to import to several classes. Is there an analogue of declaring the constants as a long sequence of statements like the above in a `.py` file and importing it to another... | Python isn't preprocessed. You can just create a file `myconstants.py`:
```
MY_CONSTANT = 50
```
And importing them will just work:
```
import myconstants
print myconstants.MY_CONSTANT * 2
``` |
Importing a long list of constants to a Python file | 6,343,330 | 26 | 2011-06-14T12:17:18Z | 6,343,408 | 11 | 2011-06-14T12:24:30Z | [
"python",
"constants",
"python-import"
] | In Python, is there an analogue of the `C` preprocessor statement such as?:
`#define MY_CONSTANT 50`
Also, I have a large list of constants I'd like to import to several classes. Is there an analogue of declaring the constants as a long sequence of statements like the above in a `.py` file and importing it to another... | Python doesn't have a preprocessor, nor does it have constants in the sense that they can't be changed - you can always change (nearly, you can emulate constant object properties, but doing this for the sake of constant-ness is rarely done and not considered useful) everything. When defining a constant, we define a nam... |
Differences between distribute, distutils, setuptools and distutils2? | 6,344,076 | 467 | 2011-06-14T13:17:27Z | 6,344,724 | 8 | 2011-06-14T14:00:51Z | [
"python",
"packaging",
"setuptools",
"distutils",
"distribute"
] | ## The Situation
Iâm trying to port an open-source library to Python 3. ([SymPy](http://sympy.org/), if anyone is wondering.)
So, I need to run `2to3` automatically when building for Python 3. To do that, I need to use `distribute`. Therefore, I need to port the current system, which (according to the doctest) is `... | NOTE: Answer deprecated, Distribute now obsolete.
Yep, you got it. :-o I think at this time the preferred package is [Distribute](http://pypi.python.org/pypi/distribute), which is a fork of setuptools, which are an extension of distutils (the original packaging system). Setuptools was not being maintained so is was fo... |
Differences between distribute, distutils, setuptools and distutils2? | 6,344,076 | 467 | 2011-06-14T13:17:27Z | 6,522,905 | 250 | 2011-06-29T15:07:17Z | [
"python",
"packaging",
"setuptools",
"distutils",
"distribute"
] | ## The Situation
Iâm trying to port an open-source library to Python 3. ([SymPy](http://sympy.org/), if anyone is wondering.)
So, I need to run `2to3` automatically when building for Python 3. To do that, I need to use `distribute`. Therefore, I need to port the current system, which (according to the doctest) is `... | Iâm a distutils maintainer and distutils2/packaging contributor. I did a talk about Python packaging at ConFoo 2011 and these days Iâm writing an extended version of it. Itâs not published yet, so here are excerpts that should help define things.
* **Distutils** is the standard tool used for packaging. It works ... |
Differences between distribute, distutils, setuptools and distutils2? | 6,344,076 | 467 | 2011-06-14T13:17:27Z | 14,753,678 | 650 | 2013-02-07T14:37:50Z | [
"python",
"packaging",
"setuptools",
"distutils",
"distribute"
] | ## The Situation
Iâm trying to port an open-source library to Python 3. ([SymPy](http://sympy.org/), if anyone is wondering.)
So, I need to run `2to3` automatically when building for Python 3. To do that, I need to use `distribute`. Therefore, I need to port the current system, which (according to the doctest) is `... | As of September 2014, all of the other answers to this question are a year out-of-date. When you come across advice on Python packaging issues, remember to look at the date of publication, and don't trust out-of-date information.
The [Python Packaging User Guide](https://packaging.python.org/) hosted on Readthedocs is... |
regex not matching | 6,344,709 | 3 | 2011-06-14T14:00:15Z | 6,344,763 | 7 | 2011-06-14T14:03:14Z | [
"python",
"regex"
] | I am write a small python script to gather some data from a database, the only problem is when I export data as XML from mysql it includes a \b character in the XML file. I wrote code to remove it, but then realized I didn't need to do that processing everytime, so I put it in a method and am calling it I find a \b in ... | `\b` is a flag for the [regular expression engine](http://docs.python.org/library/re.html):
> Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-unders... |
python: unicode in Windows terminal, encoding used? | 6,344,853 | 5 | 2011-06-14T14:09:43Z | 6,349,430 | 9 | 2011-06-14T20:05:28Z | [
"python",
"windows",
"unicode",
"terminal"
] | I am using the Python interpreter in Windows 7 terminal.
I am trying to wrap my head around unicode and encodings.
I type:
```
>>> s='ë'
>>> s
'\x89'
>>> u=u'ë'
>>> u
u'\xeb'
```
**Question 1**: Why is the encoding used in the string `s` different from the one used in the unicode string `u`?
I continue, and typ... | Unicode is not an encoding. You encode into byte strings and decode into Unicode:
```
>>> '\x89'.decode('cp437')
u'\xeb'
>>> u'\xeb'.encode('cp437')
'\x89'
>>> u'\xeb'.encode('utf8')
'\xc3\xab'
```
The windows terminal uses legacy code pages for DOS. For US Windows it is:
```
>>> import sys
>>> sys.stdout.encoding
'... |
Python: reading a pkcs12 certificate with pyOpenSSL.crypto | 6,345,786 | 10 | 2011-06-14T15:09:35Z | 6,346,268 | 22 | 2011-06-14T15:43:38Z | [
"python",
"cryptography",
"openssl",
"digital-certificate",
"pyopenssl"
] | I have a valid certificate issued by the spanish authority (FNMT) and I want to play with it to learn more about it.
The file has extension .p12
I would like to read the information in it (first and last name) and check if the certificate is valid. Is it possible to do that with pyOpenSSL? I guess I have to use the cr... | It's fairly straight-forward to use. This isn't tested, but should work:
```
# load OpenSSL.crypto
from OpenSSL import crypto
# open it, using password. Supply/read your own from stdin.
p12 = crypto.load_pkcs12(open("/path/to/cert.p12", 'rb').read(), passwd)
# get various properties of said file.
# note these are Py... |
What's the best way to initialise and use contants across Python classes? | 6,345,840 | 8 | 2011-06-14T15:13:00Z | 6,345,909 | 18 | 2011-06-14T15:16:58Z | [
"python"
] | Here's how I am declaring constants and using them across different Python classes:
```
# project/constants.py
GOOD = 1
BAD = 2
AWFUL = 3
# project/question.py
from constants import AWFUL, BAD, GOOD
class Question:
def __init__(self):
...
```
Is the above a good way to store and use contant values? I re... | why not just use
```
import constants
def use_my_constants():
print constants.GOOD, constants.BAD, constants.AWFUL
```
From the python zen:
> Namespaces are good. Lets do more of those!
**EDIT:** Except, when you do quote, you should include a reference and check it, because as others have pointed out, it shou... |
how to stop a for loop | 6,346,492 | 19 | 2011-06-14T16:00:42Z | 6,346,536 | 43 | 2011-06-14T16:03:45Z | [
"python"
] | I am writing a code to determine if every element in my nxn list is the same. i.e. [[0,0],[0,0]] returns true but [[0,1],[0,0]] will return false. I was thinking of writing a code that stops immediately when it finds an element that is not the same as the first element. i.e:
```
n=L[0][0]
m=len(A)
for i in range(m):
... | Use `break` and `continue` to do this. Breaking nested loops can be done in Python using the following:
```
for a in range(...):
for b in range(..):
if some condition:
# break the inner loop
break
else:
# will be called if the previous loop did not end with a `break`
continue... |
how to stop a for loop | 6,346,492 | 19 | 2011-06-14T16:00:42Z | 6,347,107 | 26 | 2011-06-14T16:49:53Z | [
"python"
] | I am writing a code to determine if every element in my nxn list is the same. i.e. [[0,0],[0,0]] returns true but [[0,1],[0,0]] will return false. I was thinking of writing a code that stops immediately when it finds an element that is not the same as the first element. i.e:
```
n=L[0][0]
m=len(A)
for i in range(m):
... | There are several ways to do it:
# The simple Way: a sentinel variable
```
n = L[0][0]
m = len(A)
found = False
for i in range(m):
if found:
break
for j in range(m):
if L[i][j] != n:
found = True
break
```
Pros: easy to understand
Cons: additional conditional statement for every loop
... |
Editing single line in a file using python. Last part of new file is missing | 6,347,494 | 2 | 2011-06-14T17:22:34Z | 6,347,555 | 7 | 2011-06-14T17:28:26Z | [
"python",
"file"
] | I am trying to edit a single line in a povray file using python.
The file starts out like so:
```
camera {
angle 38
location <500,0,0>
right x*image_width/image_height
look_at <0,0,0>
rotate <0,0,0>
}
```
and I want to edit the variables described in the file so it comes out like this:
```
camera {
angle 38
... | Either flush or close the temporary file before copying to be certain that all output has been written to disk. |
Is it possible to import to the global scope from inside a function (Python)? | 6,347,588 | 7 | 2011-06-14T17:30:56Z | 6,347,667 | 9 | 2011-06-14T17:38:22Z | [
"python",
"import",
"globals"
] | I am trying to import a module from inside a function and have it be available to my whole file the same way it would be if I imported outside any functions and before all the other code. The reason it is in a function is because I don't have much control over the structure of the script. Is this possible without resor... | How about something like `globals()["os"] = __import__("os")?`
I guess this could be wrapped in a generic function if you wanted since the module name is a string. |
How to expose data to zabbix | 6,348,053 | 11 | 2011-06-14T18:12:20Z | 6,349,071 | 10 | 2011-06-14T19:38:45Z | [
"python",
"zabbix"
] | Here is my goal: I would like to be able to report various metrics to [zabbix](http://www.zabbix.com/) so that we can display the graphs on a web page.
These metrics include:
* latency per soap service submission
* various query results from one or more databases.
What things do I need to write and/or expose? Or is ... | I can offer 2 suggestions to get the metrics into Zabbix:
1. Use the `zabbix_sender` binary to feed the data from your script directly to the Zabbix server. This allows your script to call on it's own interval and set all the parameters needed. You really only need to know the location to the `zabbix_sender` binary. ... |
Making a POST call instead of GET using urllib2 | 6,348,499 | 28 | 2011-06-14T18:50:10Z | 6,348,623 | 14 | 2011-06-14T19:01:24Z | [
"python",
"urllib2",
"urllib"
] | There's a lot of stuff out there on urllib2 and POST calls, but I'm stuck on a problem.
I'm trying to do a simple POST call to a service:
```
url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe',
'age' : '10'})
content = urllib2.urlopen(url=url, data=data).read()
prin... | The [requests](http://kennethreitz.com/requests-python-http-module.html) module may ease your pain.
```
url = 'http://myserver/post_service'
data = dict(name='joe', age='10')
r = requests.post(url, data=data, allow_redirects=True)
print r.content
``` |
Making a POST call instead of GET using urllib2 | 6,348,499 | 28 | 2011-06-14T18:50:10Z | 6,348,729 | 20 | 2011-06-14T19:11:10Z | [
"python",
"urllib2",
"urllib"
] | There's a lot of stuff out there on urllib2 and POST calls, but I'm stuck on a problem.
I'm trying to do a simple POST call to a service:
```
url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe',
'age' : '10'})
content = urllib2.urlopen(url=url, data=data).read()
prin... | Do it in stages, and modify the object, like this:
```
# make a string with the request type in it:
method = "POST"
# create a handler. you can specify different handlers here (file uploads etc)
# but we go for the default
handler = urllib2.HTTPHandler()
# create an openerdirector instance
opener = urllib2.build_opene... |
Making a POST call instead of GET using urllib2 | 6,348,499 | 28 | 2011-06-14T18:50:10Z | 6,348,765 | 32 | 2011-06-14T19:13:24Z | [
"python",
"urllib2",
"urllib"
] | There's a lot of stuff out there on urllib2 and POST calls, but I'm stuck on a problem.
I'm trying to do a simple POST call to a service:
```
url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe',
'age' : '10'})
content = urllib2.urlopen(url=url, data=data).read()
prin... | This may have been answered before: [Python URLLib / URLLib2 POST](http://stackoverflow.com/questions/3238925/python-urllib-urllib2-post).
Your server is likely performing a 302 redirect from `http://myserver/post_service` to `http://myserver/post_service/`. When the 302 redirect is performed, the request changes from... |
Celery task that runs more tasks | 6,349,371 | 34 | 2011-06-14T20:01:57Z | 6,414,445 | 18 | 2011-06-20T16:27:08Z | [
"python",
"django",
"task",
"celery"
] | I am using celerybeat to kick off a primary task that kicks of a number of secondary tasks. I have both tasks written already.
Is there a way to easily do this? Does Celery allow for tasks to be run from within tasks?
My example:
```
@task
def compute(users=None):
if users is None:
users = User.objects.a... | To answer your opening questions: As of version 2.0, Celery provides an easy way to start tasks from other tasks. What you are calling "secondary tasks" are what it calls "subtasks". See the documentation for [Sets of tasks, Subtasks and Callbacks](http://docs.celeryproject.org/en/2.1-archived/reference/celery.task.set... |
recursion within a class | 6,349,554 | 2 | 2011-06-14T20:14:49Z | 6,349,572 | 7 | 2011-06-14T20:16:13Z | [
"python"
] | I am trying to place a recursive formula inside a class statement
```
class SomeNode:
def __init__(self, a):
leng = len(a)
half= leng/2
self.firstnode=a[0][0]
self.child1=SomeNode([a[i]for k in range(leng)])
self.child2=SomeNode([a[j] for j in range(leng)])
def recurs... | You need to use `self.recursfunc()` |
How to verify in pycrypto signature created by openssl? | 6,350,031 | 7 | 2011-06-14T20:55:34Z | 10,569,944 | 7 | 2012-05-13T07:10:34Z | [
"python",
"openssl",
"python-2.x",
"pycrypto"
] | I've created private/public key in openssl, and signed some data:
```
openssl genrsa -out private.pem 1024
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
echo 'data to sign' > data.txt
openssl dgst -md5 < data.txt > hash
openssl rsautl -sign -inkey private.pem -keyform PEM -in hash > signature
```
... | The [Crypto.Signature](https://www.dlitz.net/software/pycrypto/api/current/Crypto.Signature-module.html) module is what you want. From the `Crypto.Signature.PKCS1_v1_5` documentation:
```
key = RSA.importKey(open('pubkey.der').read())
h = SHA.new(message)
verifier = PKCS1_v1_5.new(key)
if verifier.verify(h, signature)... |
function print in python shell | 6,350,094 | 2 | 2011-06-14T21:00:44Z | 6,350,122 | 7 | 2011-06-14T21:02:45Z | [
"python"
] | Can anyone explain me difference in python shell between output variable through "print" and when I just write variable name to output it?
```
>>> a = 5
>>> a
5
>>> print a
5
>>> b = 'some text'
>>> b
'some text'
>>> print b
some text
```
When I do this with text I understand difference but in int or float - I dont k... | Just entering an expression (such as a variable name) will actually output the representation of the result as returned by the `repr()` function, whereas `print` will convert the result to a string using the `str()` function.>>> s = "abc"
Printing `repr()` will give the same result as entering the expression directly:... |
Providing test data in python | 6,350,334 | 8 | 2011-06-14T21:22:33Z | 6,350,427 | 7 | 2011-06-14T21:34:10Z | [
"python",
"unit-testing"
] | How can I run the same test against a lot of different data? I want to be reported of **all** failures.
For example:
```
def isEven(number):
return True # quite buggy implementation
data = [
(2, True),
(3, False),
(4, True),
(5, False),
]
class MyTest:
def evenTest(self, num, expected):
... | One solution is to make different test case instances for each entry in `data`:
```
class MyTest(unittest.TestCase):
def __init__(self, num, expected):
unittest.TestCase.__init__(self, "evenTest")
self.num = num
self.expected = expected
def evenTest(self):
self.assertEqual(self.... |
How to retrieve executed SQL code from SQLAlchemy | 6,350,411 | 9 | 2011-06-14T21:30:57Z | 6,350,482 | 20 | 2011-06-14T21:41:58Z | [
"python",
"sqlalchemy"
] | I am using SQLAlchemy and would like to log *executed* SQL code (i.e. the code with all bind parameters already quoted and replaced). In case of *psycopg2* it was possible using the `query` attribute of the `Cursor` object (see [psycopg documentation](http://initd.org/psycopg/docs/cursor.html#cursor.query)). In case of... | [SQLAlchemy uses the standard Python logging library](http://www.sqlalchemy.org/docs/core/engines.html#configuring-logging). To log queries to a file named `db.log`:
```
import logging
logging.basicConfig(filename='db.log')
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
```
When using Python logging, ... |
python global variable __name__ (a newbie question) | 6,350,705 | 3 | 2011-06-14T22:06:48Z | 6,350,733 | 8 | 2011-06-14T22:09:42Z | [
"python"
] | What are the following names when I first start my python shell? They do not look like functions from `__builtins__`:
```
>>> dir(__name__)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt_... | `__name__` is a string and those a string methods. It's the name of the module or `'__main__'` on the toplevel. Hence this idiom appears often:
```
if __name__ == '__main__':
# this file was called directly, not imported
main()
``` |
Is `id` a keyword in python? | 6,350,847 | 23 | 2011-06-14T22:21:54Z | 6,350,862 | 43 | 2011-06-14T22:22:56Z | [
"python",
"keyword"
] | My editor (TextMate) shows `id` in an other colour (when used as variable name) then my usual variable names. Is it a keyword? I don't want to shade any keyword... | `id` is not a *keyword* in Python, but it is the name of a [*built-in function*](http://docs.python.org/library/functions.html#id).
The keywords [are](http://docs.python.org/reference/lexical_analysis.html#keywords):
```
and del from not while
as elif global or with
assert... |
Is `id` a keyword in python? | 6,350,847 | 23 | 2011-06-14T22:21:54Z | 6,350,869 | 7 | 2011-06-14T22:23:59Z | [
"python",
"keyword"
] | My editor (TextMate) shows `id` in an other colour (when used as variable name) then my usual variable names. Is it a keyword? I don't want to shade any keyword... | It's a built in function:
```
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
``` |
Is `id` a keyword in python? | 6,350,847 | 23 | 2011-06-14T22:21:54Z | 6,350,968 | 12 | 2011-06-14T22:34:18Z | [
"python",
"keyword"
] | My editor (TextMate) shows `id` in an other colour (when used as variable name) then my usual variable names. Is it a keyword? I don't want to shade any keyword... | You can also get help from python:
```
>>> help(id)
Help on built-in function id in module __builtin__:
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
```
or alternatively ... |
How to execute Python CGI Script? | 6,351,028 | 3 | 2011-06-14T22:42:49Z | 8,982,009 | 7 | 2012-01-24T04:26:58Z | [
"python",
"cgi"
] | I want to execute a Python CGI Script within a `.shtml`
file, but I just can't figure out how. I already found several ways?, but nothing seemed to work. And there it was a lot harder to find something that actually shows how to *execute* a script, and not how to write one ! ;/
My Html:
<http://pastebin.com/4sNZTZNQ>
... | Here is something I wrote up a while ago.
**There are some tips to getting Python working in CGI.**
1. Always browse the pages through Apache.
Note that viewing files in the filesystem through a browser works for most things on an html page but will not work for CGI. For scripts to work they must be opened through... |
Fabric put command gives fatal error: 'No such file' exception | 6,351,370 | 11 | 2011-06-14T23:27:55Z | 6,352,047 | 9 | 2011-06-15T01:34:08Z | [
"python",
"fabric"
] | I'm using Fabric 1.01, and in my fabfile I'm using the put command. The line is:
```
put('file.tar.gz', '~/file.tar.gz')
```
The server is in the env.hosts list. `file.tar.gz` is in the same directory as the fabfile, and i'm running the code from this directory.
When I run the code, it gets up to the point where it ... | Oops, I got lazy when anonymizing the question. My code contained a tilde:
```
put('file.tar.gz', '~/file.tar.gz')
```
Apparently Fabric did the tilde interpolation using the home directory of my local machine, not the server. After replacing the tilde with the explicit path on the server it works fine. |
Fabric put command gives fatal error: 'No such file' exception | 6,351,370 | 11 | 2011-06-14T23:27:55Z | 24,632,573 | 11 | 2014-07-08T13:01:51Z | [
"python",
"fabric"
] | I'm using Fabric 1.01, and in my fabfile I'm using the put command. The line is:
```
put('file.tar.gz', '~/file.tar.gz')
```
The server is in the env.hosts list. `file.tar.gz` is in the same directory as the fabfile, and i'm running the code from this directory.
When I run the code, it gets up to the point where it ... | I found this error message rather misleading. The message that is printed is:
```
Fatal error: put() encountered an exception while uploading 'local/path'
Underlying exception:
No such file
```
Which leads you to think the problem is that somehow Python isn't seeing the file at `local/path`. I'm not certain this... |
Python's super() function | 6,351,508 | 8 | 2011-06-14T23:51:58Z | 6,351,536 | 14 | 2011-06-14T23:56:39Z | [
"python",
"oop",
"inheritance"
] | In the below sample, the last 2 lines in the `B.Go()` method both call the `Go()` method from `class A`. Are they functionally identical? Is the only benefit to using `super()` that I don't have to know the inherited class name?
```
class A(object):
def Go(self):
print "Calling A.Go()"
class B(A):
def... | No, `super()` does something a direct call to `A.Go` *can't*. `super(B, self).Go()` calls the next method in the method resolution order. It calls the method that *would have been called* had `B` not implemented the method at all. In direct linear inheritance this is always `A`, so there is no real difference (besides ... |
Cyclic module dependencies and relative imports in Python | 6,351,805 | 28 | 2011-06-15T00:44:16Z | 6,378,337 | 26 | 2011-06-16T20:41:46Z | [
"python",
"python-import",
"cyclic"
] | Suppose we have two modules with cyclic dependencies:
```
# a.py
import b
def f(): return b.y
x = 42
```
```
# b.py
import a
def g(): return a.x
y = 43
```
The two modules are in the directory `pkg` with an empty `__init__.py`. Importing `pkg.a` or `pkg.b` works fine, as explained in [this answer](http://stackoverfl... | First let's start with how `from import` work in python:
Well first let's look at the byte code:
```
>>> def foo():
... from foo import bar
>>> dis.dis(foo)
2 0 LOAD_CONST 1 (-1)
3 LOAD_CONST 2 (('bar',))
6 IMPORT_NAME 0 (foo)
... |
SQLAlchemy and joins, we have no foreign keys | 6,352,141 | 5 | 2011-06-15T01:51:33Z | 6,352,527 | 17 | 2011-06-15T02:53:53Z | [
"python",
"mysql",
"join",
"foreign-keys",
"sqlalchemy"
] | Assume the following in MySQL:
```
CREATE TABLE users (
id integer auto_increment primary key,
username varchar(30),
active enum('N','Y'),
created_on int(11),
updated_on int(11),
points int(10),
// other fields
);
CREATE TABLE comments (
id integer auto_increment primary key,
user_id integer,
foru... | You have two options. You can pass the join condition in `join` like so:
```
j = join(users, comments, onclause=users.c.id == commends.c.user_id)
```
If you're defining this in terms of a `orm.relationship` property, the keyword parameter will be `primaryjoin` instead of `onclause`.
However, the approach I Prefer is... |
How to use python csv module for splitting double pipe delimited data | 6,352,409 | 6 | 2011-06-15T02:35:17Z | 6,352,843 | 11 | 2011-06-15T03:57:53Z | [
"python",
"csv",
"delimiter"
] | I have got data which looks like:
```
"1234"||"abcd"||"a1s1"
```
I am trying to read and write using Python's csv reader and writer.
As the csv module's delimiter is limited to single char, is there any way to retrieve data cleanly? I cannot afford to remove the empty columns as it is a massively huge data set to be ... | [The docs](http://docs.python.org/library/csv.html#csv.Dialect.delimiter) and experimentation prove that only single-character delimiters are allowed.
Since `cvs.reader` accepts any object that supports iterator protocol, you can use generator syntax to replace `||`-s with `|`-s, and then feed this generator to the re... |
What's the most Pythonic way to identify consecutive duplicates in a list? | 6,352,425 | 16 | 2011-06-15T02:37:42Z | 6,352,456 | 31 | 2011-06-15T02:42:31Z | [
"list",
"duplicates",
"generator",
"python"
] | I've got a list of integers and I want to be able to identify contiguous blocks of duplicates: that is, I want to produce an order-preserving list of duples where each duples contains (int\_in\_question, number of occurrences).
For example, if I have a list like:
```
[0, 0, 0, 3, 3, 2, 5, 2, 6, 6]
```
I want the res... | ```
>>> from itertools import groupby
>>> L = [0, 0, 0, 3, 3, 2, 5, 2, 6, 6]
>>> grouped_L = [(k, sum(1 for i in g)) for k,g in groupby(L)]
>>> # Or (k, len(list(g))), but that creates an intermediate list
>>> grouped_L
[(0, 3), (3, 2), (2, 1), (5, 1), (2, 1), (6, 2)]
```
[Batteries included](http://docs.python.org/li... |
Which is a better __repr__ for a custom Python class? | 6,352,484 | 7 | 2011-06-15T02:47:19Z | 6,352,515 | 8 | 2011-06-15T02:52:36Z | [
"python",
"constructor",
"repr"
] | It seems there are different ways the `__repr__` function can return.
I have a class InfoObj that stores a number of things, some of which I don't particularly want users of the class to set by themselves. I recognize nothing is protected in python and they could just dive in and set it anyway, but seems defining it i... | The `__repr__` method is designed to produce the most useful output for the developer, not the enduser, so only you can really answer this question. However, I'd typically go with option B. Option A isn't very useful, and option C is needlessly verbose -- you don't know how your module is imported anyway. Others may pr... |
Matplotlib - label each bin | 6,352,740 | 37 | 2011-06-15T03:34:06Z | 6,353,051 | 68 | 2011-06-15T04:35:48Z | [
"python",
"matplotlib",
"visualization",
"histogram",
"graphing"
] | I'm currently using Matplotlib to create a histogram:

```
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
...
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1,)
n, bins, patches = ax.hist(measurements, bins=50, range=(graph... | Sure! To set the ticks, just, well... Set the ticks (see `matplotlib.pyplot.xticks` or `ax.set_xticks`). (Also, you don't need to manually set the facecolor of the patches. You can just pass in a keyword argument.)
For the rest, you'll need to do some slightly more fancy things with the labeling, but matplotlib makes ... |
Python: Dictionary merge by updating but not overwriting if value exists | 6,354,436 | 19 | 2011-06-15T07:29:57Z | 6,354,485 | 22 | 2011-06-15T07:33:29Z | [
"python",
"dictionary",
"merge",
"compare"
] | If I have 2 dicts as follows:
```
d1 = {('unit1','test1'):2,('unit1','test2'):4}
d2 = {('unit1','test1'):2,('unit1','test2'):''}
```
In order to 'merge' them:
```
z = dict(d1.items() + d2.items())
z = {('unit1','test1'):2,('unit1','test2'):''}
```
Works fine.
Additionally what to be done, if i would like to compare... | Just switch the order:
```
z = dict(d2.items() + d1.items())
```
By the way, you may also be interested in the potentially faster [`update`](http://docs.python.org/library/stdtypes.html#dict.update) method.
[In response to the edit] If you want to special-case empty strings, you can do the following:
```
def mergeD... |
Python: Dictionary merge by updating but not overwriting if value exists | 6,354,436 | 19 | 2011-06-15T07:29:57Z | 6,355,134 | 7 | 2011-06-15T08:44:57Z | [
"python",
"dictionary",
"merge",
"compare"
] | If I have 2 dicts as follows:
```
d1 = {('unit1','test1'):2,('unit1','test2'):4}
d2 = {('unit1','test1'):2,('unit1','test2'):''}
```
In order to 'merge' them:
```
z = dict(d1.items() + d2.items())
z = {('unit1','test1'):2,('unit1','test2'):''}
```
Works fine.
Additionally what to be done, if i would like to compare... | `d2.update(d1)` instead of `dict(d2.items() + d1.items())` |
Python: Dictionary merge by updating but not overwriting if value exists | 6,354,436 | 19 | 2011-06-15T07:29:57Z | 6,355,248 | 17 | 2011-06-15T08:53:48Z | [
"python",
"dictionary",
"merge",
"compare"
] | If I have 2 dicts as follows:
```
d1 = {('unit1','test1'):2,('unit1','test2'):4}
d2 = {('unit1','test1'):2,('unit1','test2'):''}
```
In order to 'merge' them:
```
z = dict(d1.items() + d2.items())
z = {('unit1','test1'):2,('unit1','test2'):''}
```
Works fine.
Additionally what to be done, if i would like to compare... | Python 2.7. Updates d2 with d1 key/value pairs, but only if d1 value is not None,'' (False):
```
>>> d1 = dict(a=1,b=None,c=2)
>>> d2 = dict(a=None,b=2,c=1)
>>> d2.update({k:v for k,v in d1.iteritems() if v})
>>> d2
{'a': 1, 'c': 2, 'b': 2}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.