content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to get item list from wxpython ListBox
Is there a single method that returns the list of items contained in a wxPython listBox?
I cant seem to find anything anywhere in the documentation or anywhere for that matter. All that I can think to do is to set the selection to all of the items and then get the selected items, though seems like an ugly roundabout way of doing something that should be simple.
Update:
As pointed out by jeremy the way to do this is with GetStrings()
e.g.
listBoxList = yourListBox.GetStrings()
A:
wx.ListBox is derived from wx.ControlWithitems. I think GetStrings() is what you need.
A:
You can get a list of the strings in the listbox like:
[listBox.GetString(i) for i in range(listBox.GetCount())]
| How to get item list from wxpython ListBox | Is there a single method that returns the list of items contained in a wxPython listBox?
I cant seem to find anything anywhere in the documentation or anywhere for that matter. All that I can think to do is to set the selection to all of the items and then get the selected items, though seems like an ugly roundabout way of doing something that should be simple.
Update:
As pointed out by jeremy the way to do this is with GetStrings()
e.g.
listBoxList = yourListBox.GetStrings()
| [
"wx.ListBox is derived from wx.ControlWithitems. I think GetStrings() is what you need.\n",
"You can get a list of the strings in the listbox like:\n[listBox.GetString(i) for i in range(listBox.GetCount())]\n\n"
] | [
10,
1
] | [] | [] | [
"listbox",
"listboxitems",
"python",
"wxpython"
] | stackoverflow_0003229749_listbox_listboxitems_python_wxpython.txt |
Q:
Initialize a django.forms.ModelChoiceField, bound with a foreign key and a default value
I have a model that contains a foreign key value, then in the form generated from this model as a ModelChoiceField. I want to auto select the user's (update_author).
I've tried the below code, using the initial property.
The view creates a formset with the the dates initialized to now() for the empty form. But, I want also the update_author field to be initialized to some value, and it does not work.
Even if the dev shell returns the correct user (print), this one is still not selected in the list.
How to initialize a django.forms.ModelChoiceField, binded with foreign key, with a value?
models.py
from django.db import models
import datetime
class Author(models.Model):
name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class DataReview(models.Model):
comments = models.CharField(max_length=255)
update_author = models.ForeignKey('Author')
creation_date = models.DateTimeField('date data review created')
update_date = models.DateTimeField('date review modified')
def __unicode__(self):
return "%s" % (self.comments)
forms.py corrected
from bamboo.followup.models import *
from django import forms
from django.forms import ModelForm,Form
from django.forms.extras.widgets import SelectDateWidget
import datetime
class DataReviewForm(ModelForm):
def __init__(self, *args, **kwargs):
initial = {
'update_date': datetime.datetime.now(),
'creation_date': datetime.datetime.now(),
'update_author': 1 # not Author.objects.get(id=1)
}
if kwargs.has_key('initial'):
kwargs['initial'].update(initial)
else:
kwargs['initial'] = initial
# Initializing form only after you have set initial dict
super(DataReviewsForm,self).__init__(*args, **kwargs)
self.fields['update_date'].widget.attrs['disabled']=''
self.fields['creation_date'].widget.attrs['disabled']=''
self.fields['update_author'].widget.attrs['disabled'] = ''
class Meta:
model = DataReview
views.py updated
def review(request):
DataReviewsFormSet = modelformset_factory(DataReview, form=DataReviewsForm)
if request.method == 'POST':
formset = DataReviewSet(request.POST)
if formset.is_valid():
# do something with the formset.cleaned_dat
print 'YOUHOU!'
else:
formset = DataReviewSet()
return render_to_response('followup/runs.html', {
"formset": formset,
})
A:
For the core of your question is, as to how to set initial value for ForeignKey field, check the code snippet below.
Note that when you provide initial value to a ForeignKey field, you don't need to pass the object. Pass it the id/pk of that object, and your problem will be solved.
initial = {
'update_date': datetime.datetime.now(),
'creation_date': datetime.datetime.now(),
'update_author': 1 # not Author.objects.get(id=1)
}
if kwargs.has_key('initial'):
kwargs['initial'].update(initial)
else:
kwargs['initial'] = initial
# Initializing form only after you have set initial dict
super(DataReviewsForm,self).__init__(*args, **kwargs)
self.fields['update_date'].widget = forms.HiddenInput()
self.fields['creation_date'].widget = forms.HiddenInput()
self.fields['update_author'].widget = forms.HiddenInput()
A lot cleaner way to do it.
Disabling the fields
As Form exposes 'fields widgets' only after invoking constructor, any updation [be it widget override, or changing attributes of widget], can be done only after that. Or, you can do it in form field definition, which doesn't apply on your case. In short, disabling the field is better after super constructor call.
| Initialize a django.forms.ModelChoiceField, bound with a foreign key and a default value | I have a model that contains a foreign key value, then in the form generated from this model as a ModelChoiceField. I want to auto select the user's (update_author).
I've tried the below code, using the initial property.
The view creates a formset with the the dates initialized to now() for the empty form. But, I want also the update_author field to be initialized to some value, and it does not work.
Even if the dev shell returns the correct user (print), this one is still not selected in the list.
How to initialize a django.forms.ModelChoiceField, binded with foreign key, with a value?
models.py
from django.db import models
import datetime
class Author(models.Model):
name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class DataReview(models.Model):
comments = models.CharField(max_length=255)
update_author = models.ForeignKey('Author')
creation_date = models.DateTimeField('date data review created')
update_date = models.DateTimeField('date review modified')
def __unicode__(self):
return "%s" % (self.comments)
forms.py corrected
from bamboo.followup.models import *
from django import forms
from django.forms import ModelForm,Form
from django.forms.extras.widgets import SelectDateWidget
import datetime
class DataReviewForm(ModelForm):
def __init__(self, *args, **kwargs):
initial = {
'update_date': datetime.datetime.now(),
'creation_date': datetime.datetime.now(),
'update_author': 1 # not Author.objects.get(id=1)
}
if kwargs.has_key('initial'):
kwargs['initial'].update(initial)
else:
kwargs['initial'] = initial
# Initializing form only after you have set initial dict
super(DataReviewsForm,self).__init__(*args, **kwargs)
self.fields['update_date'].widget.attrs['disabled']=''
self.fields['creation_date'].widget.attrs['disabled']=''
self.fields['update_author'].widget.attrs['disabled'] = ''
class Meta:
model = DataReview
views.py updated
def review(request):
DataReviewsFormSet = modelformset_factory(DataReview, form=DataReviewsForm)
if request.method == 'POST':
formset = DataReviewSet(request.POST)
if formset.is_valid():
# do something with the formset.cleaned_dat
print 'YOUHOU!'
else:
formset = DataReviewSet()
return render_to_response('followup/runs.html', {
"formset": formset,
})
| [
"For the core of your question is, as to how to set initial value for ForeignKey field, check the code snippet below. \nNote that when you provide initial value to a ForeignKey field, you don't need to pass the object. Pass it the id/pk of that object, and your problem will be solved.\ninitial = {\n 'upda... | [
2
] | [] | [] | [
"django",
"field",
"forms",
"python"
] | stackoverflow_0003223936_django_field_forms_python.txt |
Q:
Is there a way to have parallel for-each loops?
Let's say I have 2 lists in Python and I want to loop through each one in parallel - e.g. do something with element 1 for both lists, do something with element 2 for both lists... I know that I can do this by using an index:
for listIndex in range(len(list1)):
doSomething(list1[listIndex])
doSomething(list2[listIndex])
But is there a way to do this more intuitively, with a foreach loop? Something like for list1Value in list1, list2Value in list2...?
I've currently run into this situation in Python, but this is a longstanding question and I'd be interested to know if you can do this in any language. (I just assumed that Python is the most likely to have a method of dealing with this.)
A:
Something like this?
for (a,b) in zip(list1, list2):
doSomething(a)
doSomething(b)
Though if doSomething() isn't doing I/O or updating global state, and it just works on one of the elements at a time, the order doesn't matter so you could just use chain() (from itertools):
for x in chain(list1, list2):
doSomething(x)
Apropos, from itertools import * is something I do very often. Consider izip() instead of using the zip() I gave above. Also look into izip_longest(), izip(count(), lst), etc. Welcome to functional programming. :-)
Oh, and zipping also works with more "columns":
for idx, a, b, c in izip(count(), A, B, C):
...
A:
That will depend on the language. Python actually has a rather simple method for that:
a = (0,1,2,3,4,5,6,7,8,9)
b = "ABCDEFGHIJ"
for pair in zip(a,b):
print("%d => %s" % pair)
A:
Use zip or itertools.izip for this:
for item1, item2 in zip(iterable1, iterable2):
# process the items in parallel
itertools.izip in Python < 3 and zip in Python ≥ 3 return iterators; i.e. they provide tuples of pairs (or triplets, quartets etc) on request. Python < 3 zip creates a list of tuples, so the memory requirements could be large if the smallest of the sequences is quite long.
| Is there a way to have parallel for-each loops? | Let's say I have 2 lists in Python and I want to loop through each one in parallel - e.g. do something with element 1 for both lists, do something with element 2 for both lists... I know that I can do this by using an index:
for listIndex in range(len(list1)):
doSomething(list1[listIndex])
doSomething(list2[listIndex])
But is there a way to do this more intuitively, with a foreach loop? Something like for list1Value in list1, list2Value in list2...?
I've currently run into this situation in Python, but this is a longstanding question and I'd be interested to know if you can do this in any language. (I just assumed that Python is the most likely to have a method of dealing with this.)
| [
"Something like this?\nfor (a,b) in zip(list1, list2):\n doSomething(a)\n doSomething(b)\n\nThough if doSomething() isn't doing I/O or updating global state, and it just works on one of the elements at a time, the order doesn't matter so you could just use chain() (from itertools):\nfor x in chain(list1, list2):\... | [
14,
5,
4
] | [] | [] | [
"foreach",
"iteration",
"parallel_processing",
"python"
] | stackoverflow_0003229458_foreach_iteration_parallel_processing_python.txt |
Q:
Popular Django App Libraries
I know there is some really good django app libraries out there (other than the builtin django.contrib.*) but for some reason, my google search abilities are failing me.
I am thinking of one in particular that I cannot remeber the name of for the life of me. I keep wanting to call it pyrex or pixar or something. Obviously, neither of those are correct. Any other libraries out there are also appreciated. I don't really feel like writing a password reset page if I don't have to.
A:
http://code.google.com/p/django-basic-apps/ ?
also:
http://code.google.com/p/django-profile/
and
http://code.google.com/p/django-registration/
I have found useful.
A:
I've found the Python Package Index to be a great place to start searching for Django apps and libraries.
search: django-pi
search: django-py
Maybe you were looking for django-piston?
A:
Almost all django apps are registered at the python package index. If you browse the topic hierarchy you'll see that Django is one of the "framework" topics, so that makes it possible to show all packages which use Django.
As for the app you are searching for, my guess is you are thinking of Pinax
| Popular Django App Libraries | I know there is some really good django app libraries out there (other than the builtin django.contrib.*) but for some reason, my google search abilities are failing me.
I am thinking of one in particular that I cannot remeber the name of for the life of me. I keep wanting to call it pyrex or pixar or something. Obviously, neither of those are correct. Any other libraries out there are also appreciated. I don't really feel like writing a password reset page if I don't have to.
| [
"http://code.google.com/p/django-basic-apps/ ?\nalso:\nhttp://code.google.com/p/django-profile/\nand\nhttp://code.google.com/p/django-registration/\nI have found useful.\n",
"I've found the Python Package Index to be a great place to start searching for Django apps and libraries.\n\nsearch: django-pi\nsearch: dja... | [
1,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003229675_django_python.txt |
Q:
Filter foreignkey field from the selection of another foreignkey in django-admin?
i have the next models
class Region(models.Model):
nombre = models.CharField(max_length=25)
class Departamento(models.Model):
nombre = models.CharField(max_length=25)
region = models.ForeignKey(Region)
class Municipio(models.Model):
nombre = models.CharField(max_length=35)
departamento = models.ForeignKey(Departamento)
i need to filter the options in Departamento according selected Region, and filter the options in Municipio according selected Departamento.
is that possible??
Thanks folks!
A:
Assuming you are talking about doing this in a series of select boxes:
Create two views, one which returns a response containing the Departamentos for a given Region. The other does the same but for Municipios in a Departamento
# views.py
from django.core import serializers
def departamentos_por_region(request, region_id):
region = get_object_or_404(Region, id=region_id)
departamentos = Departamento.objects.filter(region=region)
return render_to_reponse("format_as_option_list.html",
{'departamentos': departamentos})
def municipios_por_departamento(request, departamento_id):
# basically the same as above
I'm assuming that you're filling the Region select box in the initial page view, so no special view needed there.
The template should format the departamentos as an html option list.
Assuming then that the HTML in the initial page view looks something like:
<select id='regions'>
<option value='1'>Region 1</option>
<option value='2'>Region 2</option>
</select>
<select id='departamentos'>
</select>
<select id='municipios'>
</select>
You'd use some javascript like (in jQuery):
// this isn't tested code and likely contains an error or two
$('#regions').change(function(){
// Region has changed, so reset Departamentos and Municipios
$('#departamentos').html("")
$('#municipios').html("")
// now update the departamentos
$.get('/ajax/departamentos_por_region/' + $('#regions').val(),
function(data) {
('#departamentos').html(data)
};
);
});
Do the same for Municipios as for Departamentos.
You'd probably also want to do things like disable fields when they have no available choices, and handle cases where no departamentos or municipios are returned.
| Filter foreignkey field from the selection of another foreignkey in django-admin? | i have the next models
class Region(models.Model):
nombre = models.CharField(max_length=25)
class Departamento(models.Model):
nombre = models.CharField(max_length=25)
region = models.ForeignKey(Region)
class Municipio(models.Model):
nombre = models.CharField(max_length=35)
departamento = models.ForeignKey(Departamento)
i need to filter the options in Departamento according selected Region, and filter the options in Municipio according selected Departamento.
is that possible??
Thanks folks!
| [
"Assuming you are talking about doing this in a series of select boxes:\nCreate two views, one which returns a response containing the Departamentos for a given Region. The other does the same but for Municipios in a Departamento\n# views.py\nfrom django.core import serializers\n\ndef departamentos_por_region(reque... | [
2
] | [] | [] | [
"django",
"django_models",
"foreign_keys",
"python"
] | stackoverflow_0003217556_django_django_models_foreign_keys_python.txt |
Q:
Slicing python lists
If I have a list of say 'n' elements (each element is a single byte ) which represents a rectangular 2d matrix, how can I split this into rectangles of say w * h, starting from the first element of the list , just using the python standard functions
for example
l =
[ 1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15....20.
21,22,23,24,25....30
.....
.................200]
These are in a 1d list
if we choose rectangles of say 2*3 (w*h)
The first would contain 1,2,11,12,21,22
the second would contain 3,4,13,14,23,24 and so on until the end
Thanks
A:
Note that your question specifies that the input list is 1D, but gives no indication into how many items to each logical row; you seem to magically imply it should be 10 items per row.
So, given a 1D list, the count of logical items per row, the width and height of the tiles requested, you can do:
def gettiles(list1d, row_items, width, height):
o_row= 0
row_count, remainder= divmod(len(list1d), row_items)
if remainder != 0:
raise RuntimeError("item count not divisible by %d" % row_items)
if row_count % height != 0:
raise RuntimeError("row count not divisible by height %d" % height)
if row_items % width != 0:
raise RuntimeError("row width not divisible by %d" % width)
for o_row in xrange(0, row_count, height):
for o_col in xrange(0, row_items, width):
result= []
top_left_index= o_row*row_items + o_col
for off_row in xrange(height):
for off_col in xrange(width):
result.append(list1d[top_left_index + off_row*row_items + off_col])
yield result
>>> import pprint
>>> pprint.pprint(list(gettiles(range(100), 10, 2, 5)))
[[0, 1, 10, 11, 20, 21, 30, 31, 40, 41],
[2, 3, 12, 13, 22, 23, 32, 33, 42, 43],
[4, 5, 14, 15, 24, 25, 34, 35, 44, 45],
[6, 7, 16, 17, 26, 27, 36, 37, 46, 47],
[8, 9, 18, 19, 28, 29, 38, 39, 48, 49],
[50, 51, 60, 61, 70, 71, 80, 81, 90, 91],
[52, 53, 62, 63, 72, 73, 82, 83, 92, 93],
[54, 55, 64, 65, 74, 75, 84, 85, 94, 95],
[56, 57, 66, 67, 76, 77, 86, 87, 96, 97],
[58, 59, 68, 69, 78, 79, 88, 89, 98, 99]]
A:
Or this, which is pretty simple.
def genMatrix(rows, cols, mylist):
for x in xrange(rows):
yield mylist[x*cols:x*cols+cols]
Results
>>> L = [1,1,1,1,2,2,2,2]
>>> list(genMatrix(2, 4, L))
[[1, 1, 1, 1], [2, 2, 2, 2]]
>>> L = [1,1,1,1,2,2,2,2,3,3,3,3]
>>> list(genMatrix(3, 4, L))
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
A:
Here is a suggestion (probably quite inefficient, but seems to work):
def rect_slice(seq, cols, width, height):
rows = len(seq) // cols
for i in xrange(0, rows - rows % height, height):
for j in xrange(0, cols - cols % width, width):
yield [seq[k * cols + l] for k in xrange(i, i + height) for l in xrange(j, j + width)]
print list(rect_slice(range(1, 201), 10, 2, 3))
A:
width = 6
height = 4
xs = range(1,25)
w = 3
h = 2
def subrect(x,y):
pos = y*h*width+x*w
return [xs[(pos+row*width):(pos+row*width+w)] for row in range(h)]
print [subrect(x,y) for y in range(height / h) for x in range(width / w)]
splits up the matrix as follows:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
EDIT: Or for the example you gave...
width = 10
height = 20
xs = range(1,201)
w = 2
h = 3
A:
If I understand correctly you have [1,1,1,1,2,2,2,2] and want [[1,1,1,1], [2,2,2,2]]? If so, that's simply:
L = [1,1,1,1,2,2,2,2]
w = 4
matrix = [L[:w], L[w:]]
at least for a 2d.
or you could write this for a more general solution:
def genMatrix(rows, cols, mylist):
matrix = []
for x in xrange(rows):
row = []
for y in xrange(cols):
row.append(mylist[x*cols])
matrix.append(row)
return matrix
print genMatrix(2, 4, L) # => [[1,1,1,1], [2,2,2,2]]
L = [1,1,1,1,2,2,2,2,3,3,3,3]
print getnMatrix(3, 4, L) # => [[1,1,1,1], [2,2,2,2], [3,3,3,3]]
| Slicing python lists | If I have a list of say 'n' elements (each element is a single byte ) which represents a rectangular 2d matrix, how can I split this into rectangles of say w * h, starting from the first element of the list , just using the python standard functions
for example
l =
[ 1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15....20.
21,22,23,24,25....30
.....
.................200]
These are in a 1d list
if we choose rectangles of say 2*3 (w*h)
The first would contain 1,2,11,12,21,22
the second would contain 3,4,13,14,23,24 and so on until the end
Thanks
| [
"Note that your question specifies that the input list is 1D, but gives no indication into how many items to each logical row; you seem to magically imply it should be 10 items per row.\nSo, given a 1D list, the count of logical items per row, the width and height of the tiles requested, you can do:\ndef gettiles(l... | [
2,
1,
1,
1,
0
] | [] | [] | [
"list",
"python",
"slice"
] | stackoverflow_0003229677_list_python_slice.txt |
Q:
No module named preview, FormPreview Django Module
I am trying to get the form preview django module example to work. In polls_app/mysite/urls.py:
from django.conf.urls.defaults import *
from mysite.preview import SomeModelFormPreview
from mysite.forms import SomeModelForm
from django import forms
In polls_app/mysite/SomeModelFormPreview.py:
from django.contrib.formtools.preview
import FormPreview from mysite.models
import SomeModel
class SomeModelFormPreview (FormPreview):
def done(self,request,cleaned_data):
return HttpResponseRedirect("/form/success")
I am following the example here: http://docs.djangoproject.com/en/1.2/ref/contrib/formtools/form-preview/#module-django.contrib.formtools
This is the import error I receive:
ImportError at / No module named preview Request
Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.2.1
Exception Type: ImportError
Exception Value: No module named preview
Exception Location: /home/adam/Desktop/polls_app/mysite/../mysite/urls.py in <module>, line 4 Python
Executable: /usr/bin/python Python
Version: 2.6.2 Python
Path: ['/home/adam/Desktop/polls_app/mysite',
'/usr/lib/python2.6',
'/usr/lib/python2.6/plat-linux2',
'/usr/lib/python2.6/lib-tk',
'/usr/lib/python2.6/lib-old',
'/usr/lib/python2.6/lib-dynload',
'/usr/lib/python2.6/dist-packages',
'/usr/lib/python2.6/dist-packages/PIL',
'/usr/lib/python2.6/dist-packages/gst-0.10',
'/var/lib/python-support/python2.6',
'/usr/lib/python2.6/dist-packages/gtk-2.0',
'/var/lib/python-support/python2.6/gtk-2.0',
'/usr/local/lib/python2.6/dist-packages']
Server time: Mon, 12 Jul 2010 11:16:13 -0500
A:
It would appear that mysite.preview does not exist. That is the error you're seeing. This may be the result of circular includes, or an incorrect name.
| No module named preview, FormPreview Django Module | I am trying to get the form preview django module example to work. In polls_app/mysite/urls.py:
from django.conf.urls.defaults import *
from mysite.preview import SomeModelFormPreview
from mysite.forms import SomeModelForm
from django import forms
In polls_app/mysite/SomeModelFormPreview.py:
from django.contrib.formtools.preview
import FormPreview from mysite.models
import SomeModel
class SomeModelFormPreview (FormPreview):
def done(self,request,cleaned_data):
return HttpResponseRedirect("/form/success")
I am following the example here: http://docs.djangoproject.com/en/1.2/ref/contrib/formtools/form-preview/#module-django.contrib.formtools
This is the import error I receive:
ImportError at / No module named preview Request
Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.2.1
Exception Type: ImportError
Exception Value: No module named preview
Exception Location: /home/adam/Desktop/polls_app/mysite/../mysite/urls.py in <module>, line 4 Python
Executable: /usr/bin/python Python
Version: 2.6.2 Python
Path: ['/home/adam/Desktop/polls_app/mysite',
'/usr/lib/python2.6',
'/usr/lib/python2.6/plat-linux2',
'/usr/lib/python2.6/lib-tk',
'/usr/lib/python2.6/lib-old',
'/usr/lib/python2.6/lib-dynload',
'/usr/lib/python2.6/dist-packages',
'/usr/lib/python2.6/dist-packages/PIL',
'/usr/lib/python2.6/dist-packages/gst-0.10',
'/var/lib/python-support/python2.6',
'/usr/lib/python2.6/dist-packages/gtk-2.0',
'/var/lib/python-support/python2.6/gtk-2.0',
'/usr/local/lib/python2.6/dist-packages']
Server time: Mon, 12 Jul 2010 11:16:13 -0500
| [
"It would appear that mysite.preview does not exist. That is the error you're seeing. This may be the result of circular includes, or an incorrect name.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003230194_django_python.txt |
Q:
Python: how does inspect.ismethod work?
I'm trying to get the name of all methods in my class.
When testing how the inspect module works, i extraced one of my methods by obj = MyClass.__dict__['mymethodname'].
But now inspect.ismethod(obj) returns False while inspect.isfunction(obj) returns True, and i don't understand why. Is there some strange way of marking methods as methods that i am not aware of? I thought it was just that it is defined in the class and takes self as its first argument.
A:
You are seeing some effects of the behind-the-scenes machinery of Python.
When you write f = MyClass.__dict__['mymethodname'], you get the raw implementation of "mymethodname", which is a plain function. To call it, you need to pass in an additional parameter, class instance.
When you write f = MyClass.mymethodname (note the absence of parentheses after mymethodname), you get an unbound method of class MyClass, which is an instance of MethodType that wraps the raw function you obtained above. To call it, you need to pass in an additional parameter, class instance.
When you write f = MyClass().mymethodname (note that i've created an object of class MyClass before taking its method), you get a bound method of an instance of class MyClass. You do not need to pass an additional class instance to it, since it's already stored inside it.
To get wrapped method (bound or unbound) by its name given as a string, use getattr, as noted by gnibbler. For example:
unbound_mth = getattr(MyClass, "mymethodname")
or
bound_mth = getattr(an_instance_of_MyClass, "mymethodname")
A:
Use the source
def ismethod(object):
"""Return true if the object is an instance method.
Instance method objects provide these attributes:
__doc__ documentation string
__name__ name with which this method was defined
__func__ function object containing implementation of method
__self__ instance to which this method is bound"""
return isinstance(object, types.MethodType)
The first argument being self is just by convention. By accessing the method by name from the class's dict, you are bypassing the binding, so it appears to be a function rather than a method
If you want to access the method by name use
getattr(MyClass, 'mymethodname')
A:
Well, do you mean that obj.mymethod is a method (with implicitly passed self) while Klass.__dict__['mymethod'] is a function?
Basically Klass.__dict__['mymethod'] is the "raw" function, which can be turned to a method by something called descriptors. This means that every function on a class can be both a normal function and a method, depending on how you access them. This is how the class system works in Python and quite normal.
If you want methods, you can't go though __dict__ (which you never should anyways). To get all methods you should do inspect.getmembers(Klass_or_Instance, inspect.ismethod)
You can read the details here, the explanation about this is under "User-defined methods".
A:
From a comment made on @THC4k's answer, it looks like the OP wants to discriminate between built-in methods and methods defined in pure Python code. User defined methods are of types.MethodType, but built-in methods are not.
You can get the various types like so:
import inspect
import types
is_user_defined_method = inspect.ismethod
def is_builtin_method(arg):
return isinstance(arg, (type(str.find), type('foo'.find)))
def is_user_or_builtin_method(arg):
MethodType = types.MethodType
return isinstance(arg, (type(str.find), type('foo'.find), MethodType))
class MyDict(dict):
def puddle(self): pass
for obj in (MyDict, MyDict()):
for test_func in (is_user_defined_method, is_builtin_method,
is_user_or_builtin_method):
print [attr
for attr in dir(obj)
if test_func(getattr(obj, attr)) and attr.startswith('p')]
which prints:
['puddle']
['pop', 'popitem']
['pop', 'popitem', 'puddle']
['puddle']
['pop', 'popitem']
['pop', 'popitem', 'puddle']
A:
You could use dir to get the name of available methods/attributes/etc, then iterate through them to see which ones are methods. Like this:
[ mthd for mthd in dir(FooClass) if inspect.ismethod(myFooInstance.__getattribute__(mthd)) ]
I'm expecting there to be a cleaner solution, but this could be something you could use if nobody else comes up with one. I'd like if I didn't have to use an instance of the class to use getattribute.
| Python: how does inspect.ismethod work? | I'm trying to get the name of all methods in my class.
When testing how the inspect module works, i extraced one of my methods by obj = MyClass.__dict__['mymethodname'].
But now inspect.ismethod(obj) returns False while inspect.isfunction(obj) returns True, and i don't understand why. Is there some strange way of marking methods as methods that i am not aware of? I thought it was just that it is defined in the class and takes self as its first argument.
| [
"You are seeing some effects of the behind-the-scenes machinery of Python.\nWhen you write f = MyClass.__dict__['mymethodname'], you get the raw implementation of \"mymethodname\", which is a plain function. To call it, you need to pass in an additional parameter, class instance.\nWhen you write f = MyClass.mymetho... | [
11,
4,
1,
1,
0
] | [] | [] | [
"inspect",
"python"
] | stackoverflow_0003228680_inspect_python.txt |
Q:
Typogrify equivalent for .NET
Does anyone know of, or use a library that has similar functionality to Typogrify (http://code.google.com/p/typogrify/) in a .NET project. Typogrify is a Python/Django library and I am looking for an equivalent that I could use in a .NET project.
Edit: Now I'm just looking for any typography processing library for .NET
A:
Textile has some of the same function
Textile.NET is, surprisingly, a textile formatter for .NET projects.
Textile is a "human web text generator"
(http://www.textism.com/tools/textile/) that is useful for rapid web
writings such as Wiki syntax or blog articles. From a simple and
intuitive syntax it creates well formed HTML with advanced formatting
features, while also allowing the user to customize the output.
| Typogrify equivalent for .NET | Does anyone know of, or use a library that has similar functionality to Typogrify (http://code.google.com/p/typogrify/) in a .NET project. Typogrify is a Python/Django library and I am looking for an equivalent that I could use in a .NET project.
Edit: Now I'm just looking for any typography processing library for .NET
| [
"Textile has some of the same function\n\nTextile.NET is, surprisingly, a textile formatter for .NET projects.\n Textile is a \"human web text generator\"\n (http://www.textism.com/tools/textile/) that is useful for rapid web\n writings such as Wiki syntax or blog articles. From a simple and\n intuitive syntax ... | [
0
] | [] | [] | [
".net",
"assemblies",
"django",
"python",
"typography"
] | stackoverflow_0003230333_.net_assemblies_django_python_typography.txt |
Q:
Python in Plone: trying to append a variable to RESPONSE.redirect
I have a python script in Plone, I'm having trouble appending a variable to RESPONSE.redirect. I get a invalid syntax error.
test = '1000'
RESPONSE.redirect(("/Plone/user_blast/public_blast_results/%s" % (test))
A:
Its me being stupid, theres an extra bracket by redirect.
| Python in Plone: trying to append a variable to RESPONSE.redirect | I have a python script in Plone, I'm having trouble appending a variable to RESPONSE.redirect. I get a invalid syntax error.
test = '1000'
RESPONSE.redirect(("/Plone/user_blast/public_blast_results/%s" % (test))
| [
"Its me being stupid, theres an extra bracket by redirect.\n"
] | [
1
] | [] | [] | [
"plone",
"python"
] | stackoverflow_0003230605_plone_python.txt |
Q:
Switching files to read from in python's .csv reader
I am reading a csv file several times, but cutting its size every time I go through it. So, once I've reached the bottom, I am writing a new csv file which is, say, the bottom half of the .csv file. I then wish to change the csv reader to use this new file instead, but it doesn't seem to be working... Here's what I've done.
sent = open(someFilePath)
r_send = csv.reader(sent)
try:
something = r_send.next()
except StopIteration:
sent.seek(0)
sent.close()
newFile = cutFile(someFilePath, someLineNumber)
sent = open(newFile, "r")
r_send = csv.reader(sent)
where cutFile does..
def cutFile(sender, lines):
sent = open(sender, "r")
new_sent = open(sender + ".temp.csv", "w")
counter = 0
for line in sent:
counter = counter + 1
if counter >= lines:
print >> new_sent, ",".join(line)
new_sent.close()
return sender + ".temp.csv"
Why is this not working?
A:
Is something = r_send.next() in some kind of loop? The way you wrote it, it's only going to read one line.
Why do you need ",".join(line)? You can simply print line itself, and it should work.
Plus, there really is no need to seek(0) before closing a file.
A:
I suggest the following:
Use for something in r_send: rather than something = r_send.next(); you won't even need the try... except blocks, as you'll just put the stuff closing the original file outside that loop (as someone else mentioned, you aren't even looping through the original file in your current code). Then you'll probably want to wrap all that in another loop so it keeps continuing until the file has been fully manipulated.
Use new_sent.write(line) instead of print >> new_sent, ",".join(line). Not that it makes that much of a difference besides the ",".join bit (which you don't need since you aren't using the csv module to write to a file), which you shouldn't be using here anyway, but it makes the fact that you're writing to a file more evident.
So...
sent = open(someFilePath)
r_send = csv.reader(sent)
someLineNumber = len(sent.readlines())
while someLineNumber > 0:
for something in r_send:
# do stuff
someLineNumber /= 2 # //= 2 in Python 3
sent.close()
newFile = cutFile(someFilePath, someLineNumber)
sent = open(newFile, "r")
r_send = csv.reader(sent)
Something like that.
| Switching files to read from in python's .csv reader | I am reading a csv file several times, but cutting its size every time I go through it. So, once I've reached the bottom, I am writing a new csv file which is, say, the bottom half of the .csv file. I then wish to change the csv reader to use this new file instead, but it doesn't seem to be working... Here's what I've done.
sent = open(someFilePath)
r_send = csv.reader(sent)
try:
something = r_send.next()
except StopIteration:
sent.seek(0)
sent.close()
newFile = cutFile(someFilePath, someLineNumber)
sent = open(newFile, "r")
r_send = csv.reader(sent)
where cutFile does..
def cutFile(sender, lines):
sent = open(sender, "r")
new_sent = open(sender + ".temp.csv", "w")
counter = 0
for line in sent:
counter = counter + 1
if counter >= lines:
print >> new_sent, ",".join(line)
new_sent.close()
return sender + ".temp.csv"
Why is this not working?
| [
"\nIs something = r_send.next() in some kind of loop? The way you wrote it, it's only going to read one line. \nWhy do you need \",\".join(line)? You can simply print line itself, and it should work.\nPlus, there really is no need to seek(0) before closing a file.\n\n",
"I suggest the following:\nUse for somethi... | [
1,
0
] | [] | [] | [
"csv",
"file_io",
"python"
] | stackoverflow_0003230554_csv_file_io_python.txt |
Q:
Passing list elements to a for loop
I'm trying to pass elements from a list to a for loop and of course am getting the classic error 'argument 1 must be a string not list' - for the os.chdir() function.
Here is a my code, any suggestions as to how I can get around the above error and still pass the elements of my list on to the rest of the script so it loops through each one would be greatly appreciated!!
path= ['C:\\DataDownload\Administrative', 'C:\\DataDownload\Cadastral', 'C:\\DataDownload\Development']
for x in path[:]:
os.chdir(path)
#Remove all previous files from the current folder
for file in os.listdir(path):
basename=os.path.basename(file)
if basename.endswith('.DXF'):
os.remove(file)
if basename.endswith('.dbf'):
os.remove(file)
if basename.endswith('.kmz'):
os.remove(file)
if basename.endswith('.prj'):
os.remove(file)
if basename.endswith('.sbn'):
os.remove(file)
if basename.endswith('.sbx'):
os.remove(file)
if basename.endswith('.shp'):
os.remove(file)
if basename.endswith('.shx'):
os.remove(file)
if basename.endswith('.zip'):
os.remove(file)
if basename.endswith('.xml'):
os.remove(file)
A:
You want os.chdir(x) instead of os.chdir(path).
path is the list containing all the paths (and should thus probably be named paths), so you can't use it as an argument to chdir.
A:
First of all, double your backslashes if you want to hardcode the Windows paths this way (otherwise you'll have unexpected behaviour pop up once you have a \t in your path for example).
No need for copying the list (with path[:]): for x in path will do just as well.
No need for explicitely calling os.chdir...
And the if clauses are a bit ugly (and hard to maintain); the example can thus be simplified like this:
directories = ['C:\\DataDownload\\Administrative',
'C:\\DataDownload\\Cadastral',
'C:\\DataDownload\\Development']
for directory in directories:
for filename in os.listdir(directory):
base_filename, extension = os.path.splitext(filename)
if extension in ['.DXF','.dbf','.kmz','.prj','.sbn','.sbx',
'.shp','.shx','.zip','.xml']:
os.remove(os.path.join(directory, filename))
It might be helpful to look at the os module documentation.
| Passing list elements to a for loop | I'm trying to pass elements from a list to a for loop and of course am getting the classic error 'argument 1 must be a string not list' - for the os.chdir() function.
Here is a my code, any suggestions as to how I can get around the above error and still pass the elements of my list on to the rest of the script so it loops through each one would be greatly appreciated!!
path= ['C:\\DataDownload\Administrative', 'C:\\DataDownload\Cadastral', 'C:\\DataDownload\Development']
for x in path[:]:
os.chdir(path)
#Remove all previous files from the current folder
for file in os.listdir(path):
basename=os.path.basename(file)
if basename.endswith('.DXF'):
os.remove(file)
if basename.endswith('.dbf'):
os.remove(file)
if basename.endswith('.kmz'):
os.remove(file)
if basename.endswith('.prj'):
os.remove(file)
if basename.endswith('.sbn'):
os.remove(file)
if basename.endswith('.sbx'):
os.remove(file)
if basename.endswith('.shp'):
os.remove(file)
if basename.endswith('.shx'):
os.remove(file)
if basename.endswith('.zip'):
os.remove(file)
if basename.endswith('.xml'):
os.remove(file)
| [
"You want os.chdir(x) instead of os.chdir(path).\npath is the list containing all the paths (and should thus probably be named paths), so you can't use it as an argument to chdir.\n",
"First of all, double your backslashes if you want to hardcode the Windows paths this way (otherwise you'll have unexpected behavi... | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0003230728_python.txt |
Q:
Determine height of Coffee in the pot using Python imaging
We have a web-cam in our office kitchenette focused at our coffee maker. The coffee pot is clearly visible. Both the location of the coffee pot and the camera are static. Is it possible to calculate the height of coffee in the pot using image recognition? I've seen image recognition used for quite complex stuff like face-recognition. As compared to those projects, this seems to be a trivial task of measuring the height.
(That's my best guess and I have no idea of the underlying complexities.)
How would I go about this? Would this be considered a very complex job to partake? FYI, I've never done any kind of imaging-related work.
A:
Since the coffee pot position is stationary, get a sample frame and locate a single column of pixels where the minimum and maximum coffee quantities can easily be seen, in a spot where there are no reflections. Check the green vertical line segment in the following picture:
(source: nullnetwork.net)
The easiest way is to have two frames, one with the pot empty, one with the pot full (obviously under the same lighting conditions, which typically would be the case), convert to grayscale (colorsys.rgb_to_hsv each RGB pixel and keep only the v (3rd) component) and sum the luminosity of all pixels in the chosen line segment. Let's say the pot-empty case reaches a sum of 550 and the pot-full case a sum of 220 (coffee is dark). By comparing an input frame sum to these two sums, you can have a rough estimate of the percentage of coffee in the pot.
I wouldn't bet my life on the accuracy of this method, though, and the fluctuations even from second to second might be wild :)
N.B: in my example, the green column of pixels should extend to the bottom of the pot; I just provided an example of what I meant.
A:
Steps that I'd try:
Convert the image in grayscale.
Binarize the image, and leave only the coffee. You can discover a good threshold manually through experimentation.
Blob extraction. Blob's area (number of pixels) is one way to calculate the height, ie area / width.
A:
First do thresholding, then segmentation. Then you can more easily detect edges.
A:
You're looking for edge detection. But you only need to do it between the brown/black of the coffee and the color of the background behind the pot.
A:
make pictures of the pot with different levels of coffe in it.
downsample the image to maybe 4*10 pixels.
make the same in a loop for each new live picture.
calculate the difference of each pixels value compared to the reference images.
take the reference image with the least difference sum and you get the state of your coffe machine.
you might experiment if a grayscale version or only red or green might give better results.
if it gives problems with different light settings this aproach is useless. just buy a spotlight for the coffe machine, or lighten up, or darken each picture till the sum of all pixels reaches a reference value.
| Determine height of Coffee in the pot using Python imaging | We have a web-cam in our office kitchenette focused at our coffee maker. The coffee pot is clearly visible. Both the location of the coffee pot and the camera are static. Is it possible to calculate the height of coffee in the pot using image recognition? I've seen image recognition used for quite complex stuff like face-recognition. As compared to those projects, this seems to be a trivial task of measuring the height.
(That's my best guess and I have no idea of the underlying complexities.)
How would I go about this? Would this be considered a very complex job to partake? FYI, I've never done any kind of imaging-related work.
| [
"Since the coffee pot position is stationary, get a sample frame and locate a single column of pixels where the minimum and maximum coffee quantities can easily be seen, in a spot where there are no reflections. Check the green vertical line segment in the following picture:\n\n(source: nullnetwork.net)\nThe easies... | [
11,
4,
2,
1,
0
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0003227843_image_processing_python.txt |
Q:
Python: appending a variable to Popen
When i try to carry out the code below i get the error "unsupported operand type(s) for %: 'list' and 'str'"
from subprocess import Popen
z = '10000'
Popen(["formatdb", "-p", "T", "-i", "%s.txt"] % (z)).wait()
How would I insert my variable z into the name of my text file?
A:
% should immediately follow the string that's being formatted, and you don't need parens around the z. Like so:
Popen(["formatdb", "-p", "T", "-i", "%s.txt" % z]).wait()
| Python: appending a variable to Popen | When i try to carry out the code below i get the error "unsupported operand type(s) for %: 'list' and 'str'"
from subprocess import Popen
z = '10000'
Popen(["formatdb", "-p", "T", "-i", "%s.txt"] % (z)).wait()
How would I insert my variable z into the name of my text file?
| [
"% should immediately follow the string that's being formatted, and you don't need parens around the z. Like so:\nPopen([\"formatdb\", \"-p\", \"T\", \"-i\", \"%s.txt\" % z]).wait()\n\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003231239_python.txt |
Q:
Sorting dicts (contained in lists) alphanumerically in Python
I'm having an issue with sorting a list that contains a dict. Currently I am sorting it by a key called 'title' with the following line:
list.sort(key=operator.itemgetter('title'))
The problem with this is that some of my data gets sorted looking like this:
title_text #49
title_text #5
title_text #50
How would I go about sorting it in a way that is more friendly for human consumption while still maintaining the title sort?
A:
You are looking for human sorting.
import re
# Source: http://nedbatchelder.com/blog/200712/human_sorting.html
# Author: Ned Batchelder
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [ tryint(c) for c in re.split('([0-9]+)', s) ]
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
"""
l.sort(key=alphanum_key)
data=[
'title_text #49',
'title_text #5',
'title_text #50']
sort_nicely(data)
print(data)
# ['title_text #5', 'title_text #49', 'title_text #50']
Edit: If your data is a list of dicts then:
data=[{'title': 'title_text #49', 'x':0},
{'title':'title_text #5', 'x':10},
{'title': 'title_text #50','x':20}]
data.sort(key=lambda x: alphanum_key(x['title']))
# [{'x': 10, 'title': 'title_text #5'}, {'x': 0, 'title': 'title_text #49'}, {'x': 20, 'title': 'title_text #50'}]
A:
You're looking for a Natural Sort. Start here:
Python analog of natsort function (sort a list using a "natural order" algorithm)
A:
You'll have to parse that integer from the title manually. This function will do it.
def parse_title_num(title):
val = 0
try:
val = int(title.rsplit('#')[-1])
except ValueError:
pass
return val
list.sort(key=lambda x: parse_title_num(x['title'])
| Sorting dicts (contained in lists) alphanumerically in Python | I'm having an issue with sorting a list that contains a dict. Currently I am sorting it by a key called 'title' with the following line:
list.sort(key=operator.itemgetter('title'))
The problem with this is that some of my data gets sorted looking like this:
title_text #49
title_text #5
title_text #50
How would I go about sorting it in a way that is more friendly for human consumption while still maintaining the title sort?
| [
"You are looking for human sorting.\nimport re\n# Source: http://nedbatchelder.com/blog/200712/human_sorting.html\n# Author: Ned Batchelder\ndef tryint(s):\n try:\n return int(s)\n except:\n return s\n\ndef alphanum_key(s):\n \"\"\" Turn a string into a list of string and number chunks.\n ... | [
4,
2,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"sorting"
] | stackoverflow_0003231352_dictionary_list_python_sorting.txt |
Q:
Python 2.6: containment hierarchy issue: Same Values :S
Hey Everyone, If you've seen my previous post you'll know im working on an airline program using Python.
Another issue that poped up was that after I launch one flight, it calculates the duration of the flight and replaces the button which is used to launch the flight. But when I buy another aircraft, it changes both flight statuses to the same time (status being duration - arrival time leaving time left until it lands again).
My program is pretty big at this point so ill try and sift through all the other **** that's there:
Here is the page where you click 'Launch Flight'
def Flights (GUI, Player):
...
for AP in Player.Airplane_list:
GUI.la(text = AP.aircraft)
GUI.la(text = 'Flight Pax')
if AP.status == 0:
GUI.gr(2)
GUI.bu(text = 'Launch Flight', command = Callable(Launch_refresh, count, GUI, Player))
GUI.bu(text = 'Edit Flight', command = Callable(flight_edit, GUI, count, Player))
Launch_refresh basically refreshes the window and goes to launch (below) which calculates all the times and cash. and Self being the Player class which will be below the launch method which is found inside the player class.
def launch (self, Airplane_No): #Method used to calculate flight-time specific-data and set aircraft into flight
if self.fuel >= (self.Airplane_list[Airplane_No].duration*self.Airplane_list[Airplane_No].fuel_consump):
self.Airplane_list[Airplane_No].Flight.departure_time = datetime.now()#sets Departure Time to Now
self.Airplane_list[Airplane_No].Flight.arrival_time = self.Airplane_list[Airplane_No].Flight.departure_time+timedelta(self.Airplane_list[Airplane_No].duration)#Sets arrival Time
self.Airplane_list[Airplane_No].status = self.Airplane_list[Airplane_No].Flight.arrival_time-datetime.now()#Status to Arrival time minus now
self.fuel -= (self.Airplane_list[Airplane_No].duration*self.Airplane_list[Airplane_No].fuel_consump)#Subtracts Fuel Used
self.bank += self.Airplane_list[Airplane_No].Flight.income#Adds Flight Income to Bank
And here is the Player class
class Player (object):#Player Class to define variables
'''Player class to define variables'''
def __init__ (self, stock = 0, bank = 1, fuel = 0, total_flights = 0, total_pax = 0, Airplane_list = Airplane([]), APValue_Total = 1):
...
Then inside Player.Airplane_list is a list of Airplane Classes which have the Flight Class inside them:
Here is the Airplane Class:
class Airplane (object):
'''Airplane Class'''
def __init__ (self, company = '', aircraft = '', base_price = 0, flight_range = 0, pax = 0,
fuel_consump = 1, speed = 10, crew_pilots = 0, crew_cabin = 0,
crew_mechanics = 0, crew_cleaning = 0, staff_trg = 0, Total_price = 0, status = 0, Flight = Flight(departure_time = datetime(1,1,1),
distance = 2000, arrival_time = datetime(1,1,1)),duration = 1, airplane_details = []):
and as you can see it has the Flight class which uses just those 3 arguments (duration needs to use the Airplane's speed along with the Flight distance)
So im guessing that the issue lies inside the launch method, but I dont know exactly where it starts... Then again it looks fine to me :S
A:
Your __init__ code is defaulting an argument to an object:
class Airplane (object):
'''Airplane Class'''
def __init__(self, ..., Flight = Flight(departure_time = datetime(1,1,1), ...):
Default arguments are only evaluated once, when the class is defined, so every Airplane object will get the same Flight, unless it is specified in the constructor arguments. I can't follow all of what you are asking about, but that could contribute to your problem.
| Python 2.6: containment hierarchy issue: Same Values :S | Hey Everyone, If you've seen my previous post you'll know im working on an airline program using Python.
Another issue that poped up was that after I launch one flight, it calculates the duration of the flight and replaces the button which is used to launch the flight. But when I buy another aircraft, it changes both flight statuses to the same time (status being duration - arrival time leaving time left until it lands again).
My program is pretty big at this point so ill try and sift through all the other **** that's there:
Here is the page where you click 'Launch Flight'
def Flights (GUI, Player):
...
for AP in Player.Airplane_list:
GUI.la(text = AP.aircraft)
GUI.la(text = 'Flight Pax')
if AP.status == 0:
GUI.gr(2)
GUI.bu(text = 'Launch Flight', command = Callable(Launch_refresh, count, GUI, Player))
GUI.bu(text = 'Edit Flight', command = Callable(flight_edit, GUI, count, Player))
Launch_refresh basically refreshes the window and goes to launch (below) which calculates all the times and cash. and Self being the Player class which will be below the launch method which is found inside the player class.
def launch (self, Airplane_No): #Method used to calculate flight-time specific-data and set aircraft into flight
if self.fuel >= (self.Airplane_list[Airplane_No].duration*self.Airplane_list[Airplane_No].fuel_consump):
self.Airplane_list[Airplane_No].Flight.departure_time = datetime.now()#sets Departure Time to Now
self.Airplane_list[Airplane_No].Flight.arrival_time = self.Airplane_list[Airplane_No].Flight.departure_time+timedelta(self.Airplane_list[Airplane_No].duration)#Sets arrival Time
self.Airplane_list[Airplane_No].status = self.Airplane_list[Airplane_No].Flight.arrival_time-datetime.now()#Status to Arrival time minus now
self.fuel -= (self.Airplane_list[Airplane_No].duration*self.Airplane_list[Airplane_No].fuel_consump)#Subtracts Fuel Used
self.bank += self.Airplane_list[Airplane_No].Flight.income#Adds Flight Income to Bank
And here is the Player class
class Player (object):#Player Class to define variables
'''Player class to define variables'''
def __init__ (self, stock = 0, bank = 1, fuel = 0, total_flights = 0, total_pax = 0, Airplane_list = Airplane([]), APValue_Total = 1):
...
Then inside Player.Airplane_list is a list of Airplane Classes which have the Flight Class inside them:
Here is the Airplane Class:
class Airplane (object):
'''Airplane Class'''
def __init__ (self, company = '', aircraft = '', base_price = 0, flight_range = 0, pax = 0,
fuel_consump = 1, speed = 10, crew_pilots = 0, crew_cabin = 0,
crew_mechanics = 0, crew_cleaning = 0, staff_trg = 0, Total_price = 0, status = 0, Flight = Flight(departure_time = datetime(1,1,1),
distance = 2000, arrival_time = datetime(1,1,1)),duration = 1, airplane_details = []):
and as you can see it has the Flight class which uses just those 3 arguments (duration needs to use the Airplane's speed along with the Flight distance)
So im guessing that the issue lies inside the launch method, but I dont know exactly where it starts... Then again it looks fine to me :S
| [
"Your __init__ code is defaulting an argument to an object:\nclass Airplane (object): \n'''Airplane Class'''\n def __init__(self, ..., Flight = Flight(departure_time = datetime(1,1,1), ...):\n\nDefault arguments are only evaluated once, when the class is defined, so every Airplane object will get the same Fli... | [
1
] | [] | [] | [
"class",
"function",
"methods",
"python",
"python_2.6"
] | stackoverflow_0003231509_class_function_methods_python_python_2.6.txt |
Q:
Weird Python behaviour - or am I missing something
The following code:
class House:
links = []
class Link:
pass
class Villa(House):
pass
if __name__ == '__main__':
house = House()
villa = Villa()
link = Link()
house.links.append(link)
print house.links
print villa.links
results in this output:
[<__main__.Link instance at 0xb65a4b0c>]
[<__main__.Link instance at 0xb65a4b0c>]
I find this very weird: Since it is another instance? - I would have expected that the output is - Since it is another instance?:
[<__main__.Link instance at 0xb65a4b0c>]
[]
When changing the line house.links.append(link) to house.links = [link] everything works as expected.
Can somebody explain this behavior?
A:
It is another instance, but you have defined links as a class variable rather than an instance variable.
An instance variable would be defined as such:
class House(object): # Always use new-style classes except for backward compatibility
def __init__(self):
self.links = []
Note that in Python, unlike other languages, an instance variable is explicitly declared to be a property of an instance. This usually happens in the __init__ method, to ensure that every instance has the variable.
Then, the subclass would look like this:
class Villa(House):
def __init__(self):
super(Villa, self).__init__()
And executing your code gives the correct results:
>>> house = House()
>>> villa = Villa()
>>> link = Link()
>>> house.links.append(link)
>>> print house.links
[<__main__.Link instance at 0xcbaa8>]
>>> print villa.links
[]
A:
In your code, links is an attribute on the class, making it shared by all instances of that class:
class House:
links = []
Because of this, your Villa class shares this attribute, because an instance of Villa is (as a subclass) also an instance of House.
If you want to make links an instance variable, write a constructor and set links as an attribute of self, e.g.
class House:
def __init__(self):
self.links = []
| Weird Python behaviour - or am I missing something | The following code:
class House:
links = []
class Link:
pass
class Villa(House):
pass
if __name__ == '__main__':
house = House()
villa = Villa()
link = Link()
house.links.append(link)
print house.links
print villa.links
results in this output:
[<__main__.Link instance at 0xb65a4b0c>]
[<__main__.Link instance at 0xb65a4b0c>]
I find this very weird: Since it is another instance? - I would have expected that the output is - Since it is another instance?:
[<__main__.Link instance at 0xb65a4b0c>]
[]
When changing the line house.links.append(link) to house.links = [link] everything works as expected.
Can somebody explain this behavior?
| [
"It is another instance, but you have defined links as a class variable rather than an instance variable.\nAn instance variable would be defined as such:\nclass House(object): # Always use new-style classes except for backward compatibility\n def __init__(self):\n self.links = []\n\nNote that in Python, unlike... | [
19,
3
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003231832_oop_python.txt |
Q:
How do you pass a Queue reference to a function managed by pool.map_async()?
I want a long-running process to return its progress over a Queue (or something similar) which I will feed to a progress bar dialog. I also need the result when the process is completed. A test example here fails with a RuntimeError: Queue objects should only be shared between processes through inheritance.
import multiprocessing, time
def task(args):
count = args[0]
queue = args[1]
for i in xrange(count):
queue.put("%d mississippi" % i)
return "Done"
def main():
q = multiprocessing.Queue()
pool = multiprocessing.Pool()
result = pool.map_async(task, [(x, q) for x in range(10)])
time.sleep(1)
while not q.empty():
print q.get()
print result.get()
if __name__ == "__main__":
main()
I've been able to get this to work using individual Process objects (where I am alowed to pass a Queue reference) but then I don't have a pool to manage the many processes I want to launch. Any advise on a better pattern for this?
A:
The following code seems to work:
import multiprocessing, time
def task(args):
count = args[0]
queue = args[1]
for i in xrange(count):
queue.put("%d mississippi" % i)
return "Done"
def main():
manager = multiprocessing.Manager()
q = manager.Queue()
pool = multiprocessing.Pool()
result = pool.map_async(task, [(x, q) for x in range(10)])
time.sleep(1)
while not q.empty():
print q.get()
print result.get()
if __name__ == "__main__":
main()
Note that the Queue is got from a manager.Queue() rather than multiprocessing.Queue(). Thanks Alex for pointing me in this direction.
A:
Making q global works...:
import multiprocessing, time
q = multiprocessing.Queue()
def task(count):
for i in xrange(count):
q.put("%d mississippi" % i)
return "Done"
def main():
pool = multiprocessing.Pool()
result = pool.map_async(task, range(10))
time.sleep(1)
while not q.empty():
print q.get()
print result.get()
if __name__ == "__main__":
main()
If you need multiple queues, e.g. to avoid mixing up the progress of the various pool processes, a global list of queues should work (of course, each process will then need to know what index in the list to use, but that's OK to pass as an argument;-).
| How do you pass a Queue reference to a function managed by pool.map_async()? | I want a long-running process to return its progress over a Queue (or something similar) which I will feed to a progress bar dialog. I also need the result when the process is completed. A test example here fails with a RuntimeError: Queue objects should only be shared between processes through inheritance.
import multiprocessing, time
def task(args):
count = args[0]
queue = args[1]
for i in xrange(count):
queue.put("%d mississippi" % i)
return "Done"
def main():
q = multiprocessing.Queue()
pool = multiprocessing.Pool()
result = pool.map_async(task, [(x, q) for x in range(10)])
time.sleep(1)
while not q.empty():
print q.get()
print result.get()
if __name__ == "__main__":
main()
I've been able to get this to work using individual Process objects (where I am alowed to pass a Queue reference) but then I don't have a pool to manage the many processes I want to launch. Any advise on a better pattern for this?
| [
"The following code seems to work:\nimport multiprocessing, time\n\ndef task(args):\n count = args[0]\n queue = args[1]\n for i in xrange(count):\n queue.put(\"%d mississippi\" % i)\n return \"Done\"\n\n\ndef main():\n manager = multiprocessing.Manager()\n q = manager.Queue()\n pool = mu... | [
57,
8
] | [] | [] | [
"multiprocessing",
"pool",
"python",
"queue"
] | stackoverflow_0003217002_multiprocessing_pool_python_queue.txt |
Q:
Dial into FTP server (Data logger) using python (OS independent)
I have a few data loggers in the field. The manufacturer set them up as dial up ftp servers. I'm writing a python program that automagically downloads all the latest files from the server into a specified folder on my computer.
Which OS independent library do you recommend for dial up?
Do you have any suggestions, comments, or concerns that you can share?
Thanks
A:
Why not use Python's built-in ftplib? Looks pretty straightforward, unless I'm missing something?
For using a modem with Python, this thread talks about using the pyserial module.
I've never used pyserial with a modem, but I have with a USB port and an arduino. It was pretty straight forward, so I'm sure with some research about modem communication you could do it pretty easily. PySerial doesn't come with python by default, but from their site,
[PySerial] provides backends for Python running on Windows, Linux, BSD (possibly any POSIX compliant system), Jython and IronPython (.NET and Mono).
and earlier versions exist for MacOS and others.
| Dial into FTP server (Data logger) using python (OS independent) | I have a few data loggers in the field. The manufacturer set them up as dial up ftp servers. I'm writing a python program that automagically downloads all the latest files from the server into a specified folder on my computer.
Which OS independent library do you recommend for dial up?
Do you have any suggestions, comments, or concerns that you can share?
Thanks
| [
"Why not use Python's built-in ftplib? Looks pretty straightforward, unless I'm missing something?\nFor using a modem with Python, this thread talks about using the pyserial module.\nI've never used pyserial with a modem, but I have with a USB port and an arduino. It was pretty straight forward, so I'm sure with so... | [
1
] | [] | [] | [
"dial_up",
"ftp",
"modem",
"python"
] | stackoverflow_0003229407_dial_up_ftp_modem_python.txt |
Q:
a list > a list of lists
In python, how can I split a long list into a list of lists wherever I come across '-'. For example, how can I convert:
['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
to
[['1', 'a', 'b'],['2','c','d'],['3','123','e'],['4']]
Many thanks in advance.
A:
In [17]: import itertools
# putter around 22 times
In [39]: l=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
In [40]: [list(g) for k,g in itertools.groupby(l,'---'.__ne__) if k]
Out[40]: [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]
A:
import itertools
l = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
r = []
i = iter(l)
while True:
a = [x for x in itertools.takewhile(lambda x: x != '---', i)]
if not a:
break
r.append(a)
print r
# [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]
A:
import itertools
a = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
b = [list(x[1]) for x in itertools.groupby(a, '---'.__eq__) if not x[0]]
print b # or print(b) in Python 3
Result is
[['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]
A:
Here's one way to do it:
lst=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
indices=[-1]+[i for i,x in enumerate(lst) if x=='---']+[len(lst)]
answer=[lst[indices[i-1]+1:indices[i]] for i in xrange(1,len(indices))]
print answer
Basically, this finds the locations of the string '---' in the list and then slices the list accordingly.
A:
Here's a solution without itertools:
def foo(input):
output = []
currentGroup = []
for value in input:
if '-' in value: #if we should break on this element
currentGroup.append( value )
elif currentGroup:
output.append( currentGroup )
currentGroup = []
if currentGroup:
output.append(currentGroup) #appends the rest if not followed by separator
return output
print ( foo ( ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] ) )
| a list > a list of lists | In python, how can I split a long list into a list of lists wherever I come across '-'. For example, how can I convert:
['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
to
[['1', 'a', 'b'],['2','c','d'],['3','123','e'],['4']]
Many thanks in advance.
| [
"In [17]: import itertools\n# putter around 22 times\nIn [39]: l=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']\n\nIn [40]: [list(g) for k,g in itertools.groupby(l,'---'.__ne__) if k]\nOut[40]: [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]\n\n",
"import itertools\n\nl = ['1', 'a',... | [
17,
4,
1,
1,
0
] | [
"It's been a while since I've done any python so my syntax is going to be way off, but a simple loop should suffice.\nKeep track of the indexes in two numbers\nfirstList = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']\nlistIndex = 0\nitemIndex = 0\nii = 0\nforeach item in firstList\n if(firstLis... | [
-1
] | [
"python"
] | stackoverflow_0003231894_python.txt |
Q:
numpy join entries intersecting at a cell
In numpy, how can I join the entries that intersects at a cell?
For example: Example http://img153.imageshack.us/img153/5162/matd.png
In the example, I want to join rows/columns B and F into one row/column BF, where each element is the average of the ones with the same color.
A:
What you want to do doesn't seem straightforward from a matrix point of view so doing in a "pure numpy" manner is likely unfeasible.
I'd probably break it up into 2 or 3 operations:
Pull out row F, transpose it and average it with column B.
Take the first value of the row F you pulled out and average it with the first value of row B.
Pull out column F and average it with column B.
| numpy join entries intersecting at a cell | In numpy, how can I join the entries that intersects at a cell?
For example: Example http://img153.imageshack.us/img153/5162/matd.png
In the example, I want to join rows/columns B and F into one row/column BF, where each element is the average of the ones with the same color.
| [
"What you want to do doesn't seem straightforward from a matrix point of view so doing in a \"pure numpy\" manner is likely unfeasible.\nI'd probably break it up into 2 or 3 operations:\n\nPull out row F, transpose it and average it with column B.\nTake the first value of the row F you pulled out and average it wit... | [
1
] | [] | [] | [
"intersection",
"numpy",
"python"
] | stackoverflow_0003230774_intersection_numpy_python.txt |
Q:
lxml removing tags when parsing?
I'm currently working with parsing XML documents (adding elements, adding attributes, etc). So I first need to parse the XML in before working on it. However, lxml seems to be removing the element <?xml ...>. For example
from lxml import etree
tree = etree.fromstring('<?xml version="1.0" encoding="utf-8"?><dmodule>test</dmodule>', etree.XMLParser())
print etree.tostring(tree)
will result in
<dmodule>test</dmodule>
Does anyone know why the <?xml ...> element is being removed? I thought encoding tags were valid XML. Thanks for your time.
A:
The <?xml> element is an XML declaration, so it's not strictly an element. It just gives info about the XML tree below it.
If you need to print it out with lxml, there is some info here about the xmlDeclaration=TRUE flag you can use.
http://lxml.de/api.html#serialisation
etree.tostring(tree, xml_declaration=True)
A:
Does anyone know why the <?xml ...> element is being removed?
XML defaults to version 1.0 in UTF-8 so the document is equivalent if you remove them.
You are parsing some XML to a data structure and then converting that data structure back to XML. You will get a representation of that data structure in XML, but it might not be expressed in the same way (so the prolog can be removed and <foo /> can be exchanged with <foo></foo> and so on).
| lxml removing tags when parsing? | I'm currently working with parsing XML documents (adding elements, adding attributes, etc). So I first need to parse the XML in before working on it. However, lxml seems to be removing the element <?xml ...>. For example
from lxml import etree
tree = etree.fromstring('<?xml version="1.0" encoding="utf-8"?><dmodule>test</dmodule>', etree.XMLParser())
print etree.tostring(tree)
will result in
<dmodule>test</dmodule>
Does anyone know why the <?xml ...> element is being removed? I thought encoding tags were valid XML. Thanks for your time.
| [
"The <?xml> element is an XML declaration, so it's not strictly an element. It just gives info about the XML tree below it.\nIf you need to print it out with lxml, there is some info here about the xmlDeclaration=TRUE flag you can use.\nhttp://lxml.de/api.html#serialisation\netree.tostring(tree, xml_declaration=Tru... | [
7,
0
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0003232252_lxml_python_xml.txt |
Q:
How do I search from the bottom up using a regular expression?
Here is an example of the type of text file I am trying to search (named usefile):
DOCK onomatopoeia
DOCK blah blah
blah DOCK blah
DOCK
blah blah blah
onomatopoeia
blah blah blah
blah blah DOCK
DOCK blah blah
DOCK blah
onomatopoeia
I am using a finditer statement to find everything between DOCK and onomatopoeia as follows:
re.finditer(r'((dock)(.+?)(onomatopoeia))', usefile, re.I|re.DOTALL)
Obviously Dock is a much more common word than onomatopoeia and I only want to grab text between the first instance of Dock before onomatopoeia. The regex I am using above grabs text between the first instance of Dock and stops when it hits onomatopoeia, so I might get Dock Dock Dock Dock onomatopoeia when I really only wanted Dock onomatopoeia.
To be clear what I want from above is:
1. DOCK onomatopoeia
2. DOCK blah blah blah onomatopoeia
3. DOCK blah onomatopoeia
Is there a way to search for onomatopoeia and go UP to the first instance of Dock, or a better way to solve my problem?
Thanks!
A:
A negative lookahead assertion will do the trick.
DOCK((?!DOCK).)+?onomatopoeia
A:
Here's an algorithmic approach:
set pushing==false.
Break your text apart into words (e.g. spans of letters) and loop over those.
upon hitting a DOCK and pushing==false, push it onto a stack and set pushing = true
if you hit ono... and pushing==true, print out whatever's on the stack plus ono..., then clear the stack and set pushing = false.
any other word, if pushing==true, push it.
DOCK, if pushing==true, clear the stack, then push your new DOCK.
| How do I search from the bottom up using a regular expression? | Here is an example of the type of text file I am trying to search (named usefile):
DOCK onomatopoeia
DOCK blah blah
blah DOCK blah
DOCK
blah blah blah
onomatopoeia
blah blah blah
blah blah DOCK
DOCK blah blah
DOCK blah
onomatopoeia
I am using a finditer statement to find everything between DOCK and onomatopoeia as follows:
re.finditer(r'((dock)(.+?)(onomatopoeia))', usefile, re.I|re.DOTALL)
Obviously Dock is a much more common word than onomatopoeia and I only want to grab text between the first instance of Dock before onomatopoeia. The regex I am using above grabs text between the first instance of Dock and stops when it hits onomatopoeia, so I might get Dock Dock Dock Dock onomatopoeia when I really only wanted Dock onomatopoeia.
To be clear what I want from above is:
1. DOCK onomatopoeia
2. DOCK blah blah blah onomatopoeia
3. DOCK blah onomatopoeia
Is there a way to search for onomatopoeia and go UP to the first instance of Dock, or a better way to solve my problem?
Thanks!
| [
"A negative lookahead assertion will do the trick.\nDOCK((?!DOCK).)+?onomatopoeia\n\n",
"Here's an algorithmic approach:\n\nset pushing==false.\nBreak your text apart into words (e.g. spans of letters) and loop over those.\nupon hitting a DOCK and pushing==false, push it onto a stack and set pushing = true\nif yo... | [
3,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003232659_python_regex.txt |
Q:
How do I convert a padded string to an integer while preserving padding?
I followed the great example at Python: Nicest way to pad zeroes to string (4)
but now I need to turn that padded string to a padded integer.
I tried:
list_padded=['0001101', '1100101', '0011011', '0011011', '1101111',
'0000001', '1110111', 1101111', '0111001', '0011011',
'0011001'] # My padded sting list.
int_list=[int(x) for x in list_padded] # convert the string to an INT
But what I get is a list of integers sans the padding.
Appreciate any direction or suggestions.
Many thanks,
Jack
Edit: After learning the revelation that integers don't get padded, I'm thinking a little differently, however it would probably be a good idea to explain more:
I'm working through a basic encryption exercise in a book. It has given me a list of pseduocode to work through - get cipher string 1-127 and a message, convert both to binary, strip off the 0b, and pad with zeroes. However it wants me to do the rest WITHOUT XOR! I've gotten that far one line at a time, but now comes this (where the problem begins):
Perform manual XOR operation & append binary 7-bit result to encrypted string
Convert each binary bit of message character and key to an integer
Perform XOR operation on these two bits
Convert literal True and False to binary bit & append to output
I've love to use the XOR operation but I'm afraid doing so I'm not going to learn what I need to.
-J
A:
Applying idea of padding to integers is meaningless. If you want to print/represent them you need strings, integers just don't have padding.
A:
Integers don't have a concept of padding, but if you want then you can store both the value and the original length instead of just the value:
int_list = [(int(x), len(x)) for x in list_padded]
Then if you want to reconstruct the original data you have enough information to do so. You may even want to make a custom class to store both these fields instead of using a tuple.
A:
Leading zeros is just for data representation:
"{0:b}".format(4).zfill(8)
You can change XOR with other bit-wise operations:
def xor(x, y):
return (~x & y) | (~y & x)
def bool_xor(x, y):
return ((not x) and y) or ((not y) and x)
Actually, you can express all bitwise operations with just one logical operation:
http://en.wikipedia.org/wiki/Functional_completeness
| How do I convert a padded string to an integer while preserving padding? | I followed the great example at Python: Nicest way to pad zeroes to string (4)
but now I need to turn that padded string to a padded integer.
I tried:
list_padded=['0001101', '1100101', '0011011', '0011011', '1101111',
'0000001', '1110111', 1101111', '0111001', '0011011',
'0011001'] # My padded sting list.
int_list=[int(x) for x in list_padded] # convert the string to an INT
But what I get is a list of integers sans the padding.
Appreciate any direction or suggestions.
Many thanks,
Jack
Edit: After learning the revelation that integers don't get padded, I'm thinking a little differently, however it would probably be a good idea to explain more:
I'm working through a basic encryption exercise in a book. It has given me a list of pseduocode to work through - get cipher string 1-127 and a message, convert both to binary, strip off the 0b, and pad with zeroes. However it wants me to do the rest WITHOUT XOR! I've gotten that far one line at a time, but now comes this (where the problem begins):
Perform manual XOR operation & append binary 7-bit result to encrypted string
Convert each binary bit of message character and key to an integer
Perform XOR operation on these two bits
Convert literal True and False to binary bit & append to output
I've love to use the XOR operation but I'm afraid doing so I'm not going to learn what I need to.
-J
| [
"Applying idea of padding to integers is meaningless. If you want to print/represent them you need strings, integers just don't have padding.\n",
"Integers don't have a concept of padding, but if you want then you can store both the value and the original length instead of just the value:\nint_list = [(int(x), le... | [
9,
4,
0
] | [
"Since the INT type is a number it will be stored without leading zeros. Why would you want to store 675 as 00675? That's meaningless in the realm of integers. I would suggest storing the integers as integers and then only apply the padding when you access them and print them out (or whatever you are doing with the... | [
-1
] | [
"integer",
"padding",
"python",
"string"
] | stackoverflow_0003232256_integer_padding_python_string.txt |
Q:
Adding attributes to existing elements, removing elements, etc with lxml
I parse in the XML using
from lxml import etree
tree = etree.parse('test.xml', etree.XMLParser())
Now I want to work on the parsed XML. I'm having trouble removing elements with namespaces or just elements in general such as
<rdf:description><dc:title>Example</dc:title></rdf:description>
and I want to remove that entire element as well as everything within the tags. I also want to add attributes to existing elements as well. The methods I need are in the Element class but I have no idea how to use that with the ElementTree object here. Any pointers would definitely be appreciated, thanks
A:
You can get to the root element via this call: root=tree.getroot()
Using that root element, you can use findall() and remove elements that match your criteria:
deleteThese = root.findall("title")
for element in deleteThese: root.remove(element)
Finally, you can see what your new tree looks like with this: etree.tostring(root, pretty_print=True)
Here is some info about how find/findall work:
http://infohost.nmt.edu/tcc/help/pubs/pylxml/class-ElementTree.html#ElementTree-find
To add an attribute to an element, try something like this:
root.attrib['myNewAttribute']='hello world'
A:
The remove method should do what you want:
>>> from lxml import etree
>>> from StringIO import StringIO
>>> s = '<Root><Description><Title>foo</Title></Description></Root>'
>>> tree = etree.parse(StringIO(s))
>>> print(etree.tostring(tree.getroot()))
<Root><Description><Title>foo</Title></Description></Root>
>>> title = tree.find('//Title')
>>> title.getparent().remove(title)
>>> etree.tostring(tree.getroot())
'<Root><Description/></Root>'
>>> print(etree.tostring(tree.getroot()))
<Root><Description/></Root>
| Adding attributes to existing elements, removing elements, etc with lxml | I parse in the XML using
from lxml import etree
tree = etree.parse('test.xml', etree.XMLParser())
Now I want to work on the parsed XML. I'm having trouble removing elements with namespaces or just elements in general such as
<rdf:description><dc:title>Example</dc:title></rdf:description>
and I want to remove that entire element as well as everything within the tags. I also want to add attributes to existing elements as well. The methods I need are in the Element class but I have no idea how to use that with the ElementTree object here. Any pointers would definitely be appreciated, thanks
| [
"You can get to the root element via this call: root=tree.getroot()\nUsing that root element, you can use findall() and remove elements that match your criteria:\ndeleteThese = root.findall(\"title\")\nfor element in deleteThese: root.remove(element)\n\nFinally, you can see what your new tree looks like with this: ... | [
24,
1
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0003232618_lxml_python_xml.txt |
Q:
Class attributes reset when imported from package
I have a project that is organized something like
project/
__init__.py
builder.py
component/
__init__.py
Within builder.py, I have a class called Builder that has several class attributes in order to implement the Borg pattern. The trouble arises when I try to import Builder in component/__init__.py and make changes to class attributes. It seems that whatever changes I make to the class attributes in the package are undone when the function returns.
UPDATE: Here is a simple example of what is happening.
builder.py
class Builder(object):
attribute = True
import component
print Builder.attribute
component/___init___.py
from project.builder import Builder
Builder.attribute = False
Output:
False
True
Judging by the fact that two lines are printed, I would guess that the code in builder.py is being executed twice, which resets the value of attribute to True.
A:
What you have is a circular import: builder imports component, component imports builder.
At the time builder imports component, builder is not yet fully constructed. Then component imports builder, which executes the rest of builder module (all after import component). Later, when component is loaded, builder continues again with everything after import component.
Note that the behaviour would be different if component was loaded first!
Basically, you should not do circular imports. Try to organise the code in some other way.
A:
You should really show (a simplified version of) your code. Something like (assuming e.g. that project is in sys.path):
import builder
builder.Builder.baah = 'boo!'
in component/__init__.py, for example, should work just fine with no "undoing" nor "resetting".
But what code exactly are you using instead, to perform those "whatever changes"...?
| Class attributes reset when imported from package | I have a project that is organized something like
project/
__init__.py
builder.py
component/
__init__.py
Within builder.py, I have a class called Builder that has several class attributes in order to implement the Borg pattern. The trouble arises when I try to import Builder in component/__init__.py and make changes to class attributes. It seems that whatever changes I make to the class attributes in the package are undone when the function returns.
UPDATE: Here is a simple example of what is happening.
builder.py
class Builder(object):
attribute = True
import component
print Builder.attribute
component/___init___.py
from project.builder import Builder
Builder.attribute = False
Output:
False
True
Judging by the fact that two lines are printed, I would guess that the code in builder.py is being executed twice, which resets the value of attribute to True.
| [
"What you have is a circular import: builder imports component, component imports builder. \nAt the time builder imports component, builder is not yet fully constructed. Then component imports builder, which executes the rest of builder module (all after import component). Later, when component is loaded, builder c... | [
1,
0
] | [] | [] | [
"package",
"python"
] | stackoverflow_0003216908_package_python.txt |
Q:
Assist with Python script
I have written a code in Python, and I want to change it.
I use it when I am performing a penetration tests in my organization and I want to make my script better.
The script gets a username that I entering and it connect to the SMTP server over port 25 and check if the user exists or not.
Here is the script:
#!/usr/bin/python
import socket
import sys
if len(sys.argv) != 2:
print "Usage: vrfy.py <username>"
sys.exit(0)
# Create a Socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the Server
connect=s.connect(('192.168.0.10',25))
# Recieve the banner
banner=s.recv(1024)
print banner
# VRFY a user
s.send('VRFY ' + sys.argv[1] + '\r\n')
result=s.recv(1024)
print result
# Close the socket
s.close()
The changes that I want to perform are the following:
Instead of entering only one username to check, I want to mention a location of a txt file and the script will read all the usernames it contains.
Also, I what that the IP address at the script wont be hard coded and I will need to insert it every time I am using the script.
Many thanks in advance,
Bar Aviv
A:
You're not really supposed to use the low-level socket send() and recv() directly like that. They're not guaranteed to send/receive any particular amount of data. It might just happen to work the way you want talking to one particular mail server, but as soon as commands/responses don't fit one-to-one into IP packets, you're going to get weird results.
If you want a simple blocking conversational stream, try the file interface you get from socket.makefile.
You should probably implement a little more of SMTP as well... at least say helo!
The below reads usernames from standard input, so you can direct a file of usernames to it by saying:
python vrfy.py 127.0.0.1 < usernames.txt
though you could change it to read sys.argv[2] for another filename parameter if you wanted.
users= []
for line in sys.stdin:
line= line.strip()
if line!='':
users.append(line)
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((sys.argv[1], 25))
fp= s.makefile('rwb')
fp.readline() # ignore banner
fp.write('HELO test.example.com\r\n')
fp.flush()
fp.readline() # ignore response
for user in users:
fp.write('VRFY %s\r\n' % user)
fp.flush()
print '%s: %s' % (user, fp.readline().strip())
fp.write('QUIT\r\n')
fp.flush()
s.close()
A:
Use something like the following:
with open(sys.argv[1]) as f:
for line in f:
username = line.replace('\n', '')
print 'Testing with user: %s' % user
For the IP address, you can pass it as a second argument -- verify.py username-list-file server-ip-address -- and reference as sys.argv[2].
You can also do something like:
try:
userlist = sys.argv[1]
server_address = sys.argv[2]
except IndexError:
print 'Usage: verify.py username-list-file server-ip-address'
sys.exit(-1)
| Assist with Python script | I have written a code in Python, and I want to change it.
I use it when I am performing a penetration tests in my organization and I want to make my script better.
The script gets a username that I entering and it connect to the SMTP server over port 25 and check if the user exists or not.
Here is the script:
#!/usr/bin/python
import socket
import sys
if len(sys.argv) != 2:
print "Usage: vrfy.py <username>"
sys.exit(0)
# Create a Socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the Server
connect=s.connect(('192.168.0.10',25))
# Recieve the banner
banner=s.recv(1024)
print banner
# VRFY a user
s.send('VRFY ' + sys.argv[1] + '\r\n')
result=s.recv(1024)
print result
# Close the socket
s.close()
The changes that I want to perform are the following:
Instead of entering only one username to check, I want to mention a location of a txt file and the script will read all the usernames it contains.
Also, I what that the IP address at the script wont be hard coded and I will need to insert it every time I am using the script.
Many thanks in advance,
Bar Aviv
| [
"You're not really supposed to use the low-level socket send() and recv() directly like that. They're not guaranteed to send/receive any particular amount of data. It might just happen to work the way you want talking to one particular mail server, but as soon as commands/responses don't fit one-to-one into IP pack... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003232648_python.txt |
Q:
How can I read an xml document/file into a DOM in python?
I need to do screen scraping and for that I need to read some xml from python. I want to get a proper DOM tree out of it. How can I do that?
A:
Check out the minidom package which also has examples.
BTW if your screen scraping is HTML don't use XML parsing. There's other stuff for that.
(Question about screen scraping, Question about python HTML screen scraping).
A:
The lxml library works well for scraping HTML. Here are some links to get you started:
Parsing XML and HTML with lxml
lxml: an underappreciated web scraping library
| How can I read an xml document/file into a DOM in python? | I need to do screen scraping and for that I need to read some xml from python. I want to get a proper DOM tree out of it. How can I do that?
| [
"Check out the minidom package which also has examples.\nBTW if your screen scraping is HTML don't use XML parsing. There's other stuff for that.\n(Question about screen scraping, Question about python HTML screen scraping).\n",
"The lxml library works well for scraping HTML. Here are some links to get you start... | [
1,
0
] | [] | [] | [
"dom",
"python",
"screen",
"screen_scraping",
"xml"
] | stackoverflow_0003231155_dom_python_screen_screen_scraping_xml.txt |
Q:
Python variable assignment confusion
Why is it that when I do the following:
x = y = {}
Everytime I modify, x like x[1] = 5, I also end up modifying y and vice versa?
A:
You assign the names x and y to be pointing to one and the same dictionary, what behaviour would you expect?
If you want them to point to different dictionaries, use
x = {}
y = {}
or
x,y = {},{}
A:
Because x and y references the same dictionary.
What happens under the hood:
----- -------
| x | = | ref |-----
----- ------- |
v
------
| {} |
------
^
----- ------- |
| y | = | ref |-----
----- -------
Read about mutable and immutable data:
http://docs.python.org/glossary.html#term-immutable
http://docs.python.org/glossary.html#term-mutable
A:
That is how references works. With x = y = {}, there are two reference variables, but they're both pointing to the same object. With x[1] = 5, you're not really modifying x itself, but rather, the object referred to by x. This is the same object referred to by y, unless you set x and/or y to refer to new objects.
See also
Wikipedia/Reference (computer science)
A:
Variables on Python don't work like "boxes" (where you put objects), but as "labels" (where you assign names to objects).
So when you do:
x = y = {}
You are really saying to Python:
I want to call {} as x and y.
Another way to understand this is that the {} syntax is just a shortcut for dict(), which simply returns a new Dict object. So another way to see would be:
x = y = dict()
This returns just one dict object, and assigns two names to it (x and y).
A:
As the other answers say, the original gotcha happens because you're assigning a reference. The next level of confusion is when you do something like this:
a = [[1]]
b = a[:] # You might think [:] will protect you from the original gotcha.
a[0][0] = 2
print b[0][0] # It's 2...why did this change?
It changed because the a[:] slice is actually copying a reference to a[0]. In other words, even though a and b refer to different lists because you used [:], the first element in each is referring to the same list. It's the original problem in a new form. The correct approach here is to do
import copy
a = [[1]]
b = copy.deepcopy(a)
a[0][0] = 2
print b[0][0] # 1
| Python variable assignment confusion | Why is it that when I do the following:
x = y = {}
Everytime I modify, x like x[1] = 5, I also end up modifying y and vice versa?
| [
"You assign the names x and y to be pointing to one and the same dictionary, what behaviour would you expect?\nIf you want them to point to different dictionaries, use\nx = {}\ny = {}\n\nor\nx,y = {},{}\n\n",
"Because x and y references the same dictionary.\nWhat happens under the hood:\n----- ------- \n| x | =... | [
7,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003232376_python.txt |
Q:
App Engine Unique Non Numeric Code
Using an alphabet like "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ" I'd like to generate 2 to 4 letter codes to identify unique datastore entries. I have a python function capable of doing this when passed an list indicating the letter positions of the last code [7,17,11] -> "7GA". the next code can be made by incrementing that right most element by one and carrying one up when the alphabet length is exceeded.
This method has the advantage of keeping codes short, sequential, consistent, easy to communicate, and looking how I want them to.
I'm wondering though if this would work on app engine since the function must hold onto or be passed the last identifier to enforce uniqueness which may not play well with the non-continuous nature of Google's infrastructure. Alternate ways to make this happen or reasoned arguments against it are welcome.
A:
If you're attached to having the codes be sequential, you'll need to have a single counter object that is transactionally locked and incremented each time a new entity is created. The argument against this is that you're defeating one of the major advantages of App Engine: concurrency. Unless your application has a specific need for sequential IDs, it's a bad idea.
If you let App Engine auto-assign IDs they will be non-sequential, but you can convert the integer to and from base 36 when displaying it to the user. Here's a python function to convert an integer to and from arbitrary bases.
A:
This would be difficult to use as-is on app engine because many copies of your application could be running at once. Each copy would need access to the "last identifier" and be able to update it atomically. This would likely require too much overhead, unless you only need to generate new IDs in this fashion rather infrequently.
Why not use GAE's built-in numeric IDs? They are guaranteed to be unique and are also easy to communicate. They are also generally sequential and increasing, though this is not guaranteed.
| App Engine Unique Non Numeric Code | Using an alphabet like "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ" I'd like to generate 2 to 4 letter codes to identify unique datastore entries. I have a python function capable of doing this when passed an list indicating the letter positions of the last code [7,17,11] -> "7GA". the next code can be made by incrementing that right most element by one and carrying one up when the alphabet length is exceeded.
This method has the advantage of keeping codes short, sequential, consistent, easy to communicate, and looking how I want them to.
I'm wondering though if this would work on app engine since the function must hold onto or be passed the last identifier to enforce uniqueness which may not play well with the non-continuous nature of Google's infrastructure. Alternate ways to make this happen or reasoned arguments against it are welcome.
| [
"If you're attached to having the codes be sequential, you'll need to have a single counter object that is transactionally locked and incremented each time a new entity is created. The argument against this is that you're defeating one of the major advantages of App Engine: concurrency. Unless your application has ... | [
5,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003232833_google_app_engine_python.txt |
Q:
Should I place custom registration code in Views, Models or Managers?
I'm rolling my own custom registration module in Django based on django.contrib.auth. My registration module will have some extra functionality and help me reduce my dependency on other django modules that I'm currently using like django-registration and django-emailchange. I've run into a what-the-best-way-to-do-it problem here.
Note: All the user accounts are based on django.contrib.auth.models.User model.
When the user clicks the "sign-up" link, the request gets passed to my view named register. I have a custom form which has four fields — username, email, password1 and password2. The form is based on django.forms.Form. The form provides basic validation e.g. passoword1 and password2 are the email; the email/username do not exist.
When the data gets POSTed back to my register view, I call the is_valid() method of the form, after which, I create a new user by calling a Manager method called create_user() in django.contrib.auth.models.UserManager. I need to add more custom functionality at this point like sending activation emails, etc. As a best-practice method, where should this logic be? Should this be in a method of the User Model? Should it be where it is currently - the Manager of the Model? Or should this be placed into a custom save() method of my sign-up Form?
Thanks.
A:
Different from Chris, I believe on the philosophy of fat models, thin views.
The more code you can factor inside models, the more reusable your codebase is. Views concerns should be simply managing the request/response cycle and dealing with GET/POST parameters.
In this case, sending activation emails is related to the event of creating a new User. For those cases, Django already provides this abstraction through signals.
http://docs.djangoproject.com/en/1.2/topics/signals/#topics-signals
So, as an example, you can have in your models.py:
from django.contrib.models import User
from django.db.models.signals import post_save
def send_welcome_email(self):
# Reusable email sending code
User.send_welcome_email = send_welcome_email
def welcome_emails(sender, instance, created, **kwargs):
if created:
instance.send_welcome_email() # `instance` is User
post_save.connect(welcome_emails, sender=User)
Similarly, you can have this for when a User is deleted, or everytime a User is saved, etc. Signals are a good abstraction to event-driven tasks.
A:
My recommendation is to not re-solve a problem that django-registration solves quite nicely. It has a pluggable backend system that lets you customize it as much or as little as needed.
| Should I place custom registration code in Views, Models or Managers? | I'm rolling my own custom registration module in Django based on django.contrib.auth. My registration module will have some extra functionality and help me reduce my dependency on other django modules that I'm currently using like django-registration and django-emailchange. I've run into a what-the-best-way-to-do-it problem here.
Note: All the user accounts are based on django.contrib.auth.models.User model.
When the user clicks the "sign-up" link, the request gets passed to my view named register. I have a custom form which has four fields — username, email, password1 and password2. The form is based on django.forms.Form. The form provides basic validation e.g. passoword1 and password2 are the email; the email/username do not exist.
When the data gets POSTed back to my register view, I call the is_valid() method of the form, after which, I create a new user by calling a Manager method called create_user() in django.contrib.auth.models.UserManager. I need to add more custom functionality at this point like sending activation emails, etc. As a best-practice method, where should this logic be? Should this be in a method of the User Model? Should it be where it is currently - the Manager of the Model? Or should this be placed into a custom save() method of my sign-up Form?
Thanks.
| [
"Different from Chris, I believe on the philosophy of fat models, thin views.\nThe more code you can factor inside models, the more reusable your codebase is. Views concerns should be simply managing the request/response cycle and dealing with GET/POST parameters.\nIn this case, sending activation emails is related... | [
2,
0
] | [] | [] | [
"django",
"django_authentication",
"django_contrib",
"python"
] | stackoverflow_0003226529_django_django_authentication_django_contrib_python.txt |
Q:
Which of `if x:` or `if x != 0:` is preferred in Python?
Assuming that x is an integer, the construct if x: is functionally the same as if x != 0: in Python. Some languages' style guides explicitly forbid against the former -- for example, ActionScript/Flex's style guide states that you should never implicitly cast an int to bool for this sort of thing.
Does Python have a preference? A link to a PEP or other authoritative source would be best.
A:
The construct: if x: is generally used to check against boolean values.
For ints the use of the explicit x != 0 is preferred - along the lines of explicit is better than implicit (PEP 20 - Zen of Python).
A:
There's no hard and fast rule here. Here are some examples where I would use each:
Suppose that I'm interfacing to some function that returns -1 on error and 0 on success. Such functions are pretty common in C, and they crop up in Python frequently when using a library that wraps C functions. In that case, I'd use if x:.
On the other hand, if I'm about to divide by x and I want to make sure that x isn't 0, then I'm going to be explicit and write if x != 0.
As a rough rule of thumb, if I treat x as a bool throughout a function, then I'm likely to use if x: -- even if I can prove that x will be an int. If in the future I decide I want to pass a bool (or some other type!) to the function, I wouldn't need to modify it.
On the other hand, if I'm genuinely using x like an int, then I'm likely to spell out the 0.
A:
Typically, I read:
if(x) to be a question about existence.
if( x != 0) to be a question about a number.
A:
It depends on what you want; if x is an integer, they're equivalent, but you should write the code that matches your exact intention.
if x:
# x is anything that evaluates to a True value
if x != 0:
# x is anything that is not equal to 0
A:
If you want to test x in a boolean context:
if x:
More explicit, for x validity (doesn't match empty containers):
if x is not None:
If you want to test strictly in integer context:
if x != 0:
This last one is actually implicitly comparing types.
A:
Might I suggest that the amount of bickering over this question is enough to answer it?
Some argue that it "if x" should only be used for Z, others for Y, others for X.
If such a simple statement is able to create such a fuss, to me it is clear that the statement is not clear enough. Write what you mean.
If you want to check that x is equal to 0, then write "if x == 0". If you want to check if x exists, write "if x is not None".
Then there is no confusion, no arguing, no debate.
| Which of `if x:` or `if x != 0:` is preferred in Python? | Assuming that x is an integer, the construct if x: is functionally the same as if x != 0: in Python. Some languages' style guides explicitly forbid against the former -- for example, ActionScript/Flex's style guide states that you should never implicitly cast an int to bool for this sort of thing.
Does Python have a preference? A link to a PEP or other authoritative source would be best.
| [
"The construct: if x: is generally used to check against boolean values.\nFor ints the use of the explicit x != 0 is preferred - along the lines of explicit is better than implicit (PEP 20 - Zen of Python).\n",
"There's no hard and fast rule here. Here are some examples where I would use each:\nSuppose that I'm ... | [
8,
4,
2,
1,
1,
0
] | [
"Wouldn't if x is not 0: be the preferred method in Python, compared to if x != 0:?\nYes, the former is a bit longer to write, but I was under the impression that is and is not are preferred over == and !=. This makes Python easier to read as a natural language than as a programming language.\n"
] | [
-2
] | [
"coding_style",
"conditional",
"python"
] | stackoverflow_0003216681_coding_style_conditional_python.txt |
Q:
SOAP Client for Python 3
Although this question is very popular here in StackOverflow, after spending some time here and in the Google, I still haven't find a concrete answer on what is the most appropriate way to do SOAP consuming in Python 3.
I took a look at Does a Python 3 SOAP client module exist?, and I hope it is outdated and today some solution to this may have appeared.
I was thinking about some ideas:
Use 2to3 script to port some existing libraries to Python 3 (SOAPy, suds, etc).
Load an external module, by mixing technologies (Py3k + Jython, Py3k + Python 2.6, etc.)
Write in hardcode Python classes that corresponds to definitions of WSDL files (which implies in tight-coupling/high maintenance).
Write the software in Python 3.0, call the "python2.6-only" module functions through the execnet package. Which requires the Python 2.6 to be installed on the machine and the software written in Python3.0 to be a frozen binary.
Any ideas?
Thanks in advance
A:
I would probably start by trying your suggested 2to3 port. For many things, it works pretty well. It would still be a day or two worth of work to convert something like suds, I imagine.
| SOAP Client for Python 3 | Although this question is very popular here in StackOverflow, after spending some time here and in the Google, I still haven't find a concrete answer on what is the most appropriate way to do SOAP consuming in Python 3.
I took a look at Does a Python 3 SOAP client module exist?, and I hope it is outdated and today some solution to this may have appeared.
I was thinking about some ideas:
Use 2to3 script to port some existing libraries to Python 3 (SOAPy, suds, etc).
Load an external module, by mixing technologies (Py3k + Jython, Py3k + Python 2.6, etc.)
Write in hardcode Python classes that corresponds to definitions of WSDL files (which implies in tight-coupling/high maintenance).
Write the software in Python 3.0, call the "python2.6-only" module functions through the execnet package. Which requires the Python 2.6 to be installed on the machine and the software written in Python3.0 to be a frozen binary.
Any ideas?
Thanks in advance
| [
"I would probably start by trying your suggested 2to3 port. For many things, it works pretty well. It would still be a day or two worth of work to convert something like suds, I imagine.\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x",
"soap",
"web_services",
"wsdl"
] | stackoverflow_0003233298_python_python_3.x_soap_web_services_wsdl.txt |
Q:
Python: dynamic list parsing and processing
I have popened a process which is producing a list of dictionaries, something like:
[{'foo': '1'},{'bar':2},...]
The list takes a long time to create and could be many gigabytes, so I don't want to reconstitute it in memory and then iterate over it.
How can I parse the partially completed list such that I can process each dictionary as it is received?
A:
The Python tokenizer is available as part of the Python standard library, module tokenize. It relies for its input on receiving at the start a readline function (which must supply to it a "line" of input), so it can operate incrementally -- if there are no newlines in your input, you can simulate that as long as you can identify spots where adding a newline is innocuous (not breaking up a token -- thanks to the starting [ everything will be one "logical" line anyway). The only tokens that will require care to avoid being broken will be quoted strings. I'm not pursuing this in depth at this time since if you actually have newlines in your input you won't need to worry.
From the stream of tokens you can reconstruct the string representing each dict in the list (from an opening brace token, to the balancing closed bracket), and use ast.literal_eval to get the corresponding Python dict.
So, do you have newlines in your input? if so, then the whole task should be very easy.
A:
Pickle each dictionary separately. Shelve can help you do this.
Writer
import shelve
db= shelve.open(filename)
count= 0
for ...whatever...
# build the object
db[count]= object
count += 1
db['size']= count
db.close
Reader
import shelve
db= shelve.open(filename)
size= db['size']
for i in xrange(size):
object= db[i]
# process the object
db.close()
| Python: dynamic list parsing and processing | I have popened a process which is producing a list of dictionaries, something like:
[{'foo': '1'},{'bar':2},...]
The list takes a long time to create and could be many gigabytes, so I don't want to reconstitute it in memory and then iterate over it.
How can I parse the partially completed list such that I can process each dictionary as it is received?
| [
"The Python tokenizer is available as part of the Python standard library, module tokenize. It relies for its input on receiving at the start a readline function (which must supply to it a \"line\" of input), so it can operate incrementally -- if there are no newlines in your input, you can simulate that as long a... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003233043_python.txt |
Q:
How to use decorator?
In SharpDevelop, I want to create a dll which contains a static methon, void Main(string[] args).
Some one said I should use decorator to restrict the function in IronPython.
I found "@staticmethod", but others, "void", "string[] args", how to restrict them?
class MyClass:
def __init__(self):
pass
@staticmethod
def Main(args):
pass
A:
Python doesn't have return types. Just don't return anything. You can do this either by using an empty return statement or by not using a return statement at all
| How to use decorator? | In SharpDevelop, I want to create a dll which contains a static methon, void Main(string[] args).
Some one said I should use decorator to restrict the function in IronPython.
I found "@staticmethod", but others, "void", "string[] args", how to restrict them?
class MyClass:
def __init__(self):
pass
@staticmethod
def Main(args):
pass
| [
"Python doesn't have return types. Just don't return anything. You can do this either by using an empty return statement or by not using a return statement at all\n"
] | [
0
] | [] | [] | [
"decorator",
"ironpython",
"python"
] | stackoverflow_0003233710_decorator_ironpython_python.txt |
Q:
Map network drive with a Python service
(There are other questions along these lines but none of them have any real answers, let alone answers dealing with python...)
I have a Windows Service (XP SP3) written in Python that needs to be able to mount a network drive for ALL users. I tried using net use with subprocess (even with the full path to net.exe), but given that your service runs as the SYSTEM user, net is pretty unhappy with you (it complains about the lack of a user context). There's probably a way to do this via WMI, but I haven't been able to figure it out.
EDIT: Actually, maybe you can't do this with WMI. This article seems to indicate that this functionality is available in WSH but not WMI. Maybe some way to use net or map to do this after all?
A:
Er... sadly, the short answer is no. If the Python program is running as a Windows service, there are multiple complications here... so let me explain.
First, in order to even allow the service program itself to access the network, it'll have to be running under a user account that is allowed network access. The SYSTEM account is out (all network access is forbidden), but you could use the "NETWORK SERVICE" account (which, in a domain environment, is really the machine's domain account), or another actual user account.
But you're not going to be able to map a drive in the service account, because it is not loading the user profile stuff that includes the ability to "map" to a drive letter. (Well, technically, if the service is running a CMD batch file, that script can map a drive letter and use it, but then it will not be persistent for the next logon... but nevermind that.) Instead, anything the program wants to get on the network should be accessed via the UNC paths (like \SERVERNAME\SHARENAME).
Lastly, it is not possible to make a drive mapping work "for all users"--a mapped drive is unique to each user profile (even if it uses the same letter to point to the same server share). If you have multiple users logged into a machine (for example, on a Terminal Server, or with a user and a service running under another user account), they cannot share the mapped drive--each must get his own.
However, you can do something like this: Make a login script (or Group Policy, etc.) that maps the drive with the expected letter (let's say "M:" for example) to the server share (\server\share). If this script runs for every user upon login, they'll all have the same mapping. Then when your program-running-as-a-service needs to access that share, it'll have to use UNC paths (and a user account with appropriate privileges, of course).
Hope that helps!
| Map network drive with a Python service | (There are other questions along these lines but none of them have any real answers, let alone answers dealing with python...)
I have a Windows Service (XP SP3) written in Python that needs to be able to mount a network drive for ALL users. I tried using net use with subprocess (even with the full path to net.exe), but given that your service runs as the SYSTEM user, net is pretty unhappy with you (it complains about the lack of a user context). There's probably a way to do this via WMI, but I haven't been able to figure it out.
EDIT: Actually, maybe you can't do this with WMI. This article seems to indicate that this functionality is available in WSH but not WMI. Maybe some way to use net or map to do this after all?
| [
"Er... sadly, the short answer is no. If the Python program is running as a Windows service, there are multiple complications here... so let me explain.\nFirst, in order to even allow the service program itself to access the network, it'll have to be running under a user account that is allowed network access. The ... | [
1
] | [] | [] | [
"python",
"service",
"wmi"
] | stackoverflow_0003233756_python_service_wmi.txt |
Q:
wxPython on Mac OS X: creating a wx.Frame without stealing focus
I managed to get it working on Win32 (inheriting from wx.MiniFrame does the trick), on wxGTK (wx.PopupWindow) but whatever I try, when I create a frame on wxMac, my main window loses focus and the new frame gets it.
wxMac does not seem to have a way to interact with the native platform (something like GetHandle() on Win32 and GetGTKWidget() on wxGTK), so I can't hack around it this way.
I managed to get this working in another situation, by creating the frame at startup and moving it outside of the display area, then moving it in a visible position when needed. But right now this would be cumbersome because I don't know in advance how many frames I will need.
So, any simpler way to do this ?
A:
If you want to get native handle to window in Mac you can do
frame.MacGetTopLevelWindowRef()
and may be you can use pyobjc to interact with windows natively, but why don't you set focus on the window you want to after opening mini-frame?
| wxPython on Mac OS X: creating a wx.Frame without stealing focus | I managed to get it working on Win32 (inheriting from wx.MiniFrame does the trick), on wxGTK (wx.PopupWindow) but whatever I try, when I create a frame on wxMac, my main window loses focus and the new frame gets it.
wxMac does not seem to have a way to interact with the native platform (something like GetHandle() on Win32 and GetGTKWidget() on wxGTK), so I can't hack around it this way.
I managed to get this working in another situation, by creating the frame at startup and moving it outside of the display area, then moving it in a visible position when needed. But right now this would be cumbersome because I don't know in advance how many frames I will need.
So, any simpler way to do this ?
| [
"If you want to get native handle to window in Mac you can do\nframe.MacGetTopLevelWindowRef()\n\nand may be you can use pyobjc to interact with windows natively, but why don't you set focus on the window you want to after opening mini-frame?\n"
] | [
0
] | [] | [] | [
"macos",
"pyobjc",
"python",
"wxpython"
] | stackoverflow_0003222927_macos_pyobjc_python_wxpython.txt |
Q:
How to regex in python?
I am trying to parse the keywords from google suggest, this is the url:
http://google.com/complete/search?output=toolbar&q=test
I've done it with php using:
'|<CompleteSuggestion><suggestion data="(.*?)"/><num_queries int="(.*?)"/></CompleteSuggestion>|is'
But that wont work with python re.match(pattern, string), I tried a few but some show error and some return None.
How can I parse that info? I dont want to use minidom because I think regex will be less code.
A:
You could use etree:
>>> from xml.etree.ElementTree import XMLParser
>>> x = XMLParser()
>>> x.feed('<toplevel><CompleteSuggestion><suggestion data=...')
>>> tree = x.close()
>>> [(e.find('suggestion').get('data'), int(e.find('num_queries').get('int')))
for e in tree.findall('CompleteSuggestion')]
[('test internet speed', 31800000), ('test', 686000000), ...]
It is more code than a regex, but it also does more. Specifically, it will fetch the entire list of matches in one go, and unescape any weird stuff like double-quotes in the data attribute. It also won't get confused if additional elements start appearing in the XML.
A:
RegEx match open tags except XHTML self-contained tags
This is an XML document. Please, reconsider an XML parser. It will be more robust and probably take you less time in the end, even if it is more code.
| How to regex in python? | I am trying to parse the keywords from google suggest, this is the url:
http://google.com/complete/search?output=toolbar&q=test
I've done it with php using:
'|<CompleteSuggestion><suggestion data="(.*?)"/><num_queries int="(.*?)"/></CompleteSuggestion>|is'
But that wont work with python re.match(pattern, string), I tried a few but some show error and some return None.
How can I parse that info? I dont want to use minidom because I think regex will be less code.
| [
"You could use etree:\n>>> from xml.etree.ElementTree import XMLParser\n>>> x = XMLParser()\n>>> x.feed('<toplevel><CompleteSuggestion><suggestion data=...')\n>>> tree = x.close()\n>>> [(e.find('suggestion').get('data'), int(e.find('num_queries').get('int')))\n for e in tree.findall('CompleteSuggestion')]\n[('t... | [
5,
2
] | [] | [] | [
"parsing",
"python",
"regex",
"xml"
] | stackoverflow_0003234194_parsing_python_regex_xml.txt |
Q:
python, regex split and special character
How can I split correctly a string containing a sentence with special chars using whitespaces as separator ?
Using regex split method I cannot obtain the desired result.
Example code:
# -*- coding: utf-8 -*-
import re
s="La felicità è tutto" # "The happiness is everything" in italian
l=re.compile("(\W)").split(s)
print " s> "+s
print " wordlist> "+str(l)
for i in l:
print " word> "+i
The output is :
s> La felicità è tutto
wordlist> ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto']
word> La
word>
word> felicit
word> Ã
word>
word> ?
word>
word>
word>
word> Ã
word>
word> ?
word>
word>
word> tutto
while I'm looking for an output like:
s> La felicità è tutto
wordlist> ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto']
word> La
word>
word> felicità
word>
word> è
word>
word> tutto
To be noted that s is a string that is returned from another method so I cannot force the encoding like
s=u"La felicità è tutto"
On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation.
Thanks.
Alessandro
A:
Your regex should be (\s) instead of (\W) like this:
l = re.compile("(\s)").split(s)
The code above will give you the exact output you requested. However the following line makes more sense:
l = re.compile("\s").split(s)
which splits on whitespace characters and doesn't give you all the spaces as matches. You may need them though so I posted both answers.
A:
Try defining an encoding for the regular expression:
l=re.compile("\W", re.UNICODE).split(s)
A:
I think it's overkill to use a regexp in this case. If the only thing you want to do is split the string on whitespace characters I recommend using the split method on the string
s = 'La felicità è tutto'
words = s.split()
A:
using a unicode regular expression will work, provided you give it a unicode string to start with (which you haven't in the provided example). Try this:
s=u"La felicità è tutto" # "The happiness is everything" in italian
l=re.compile("(\W)",re.UNICODE).split(s)
print " s> "+s
print " wordlist> "+str(l)
for i in l:
print " word> "+i
Results:
s> La felicità è tutto
wordlist> [u'La', u' ', u'felicit\xe0', u' ', u'\xe8', u' ', u'tutto']
word> La
word>
word> felicità
word>
word> è
word>
word> tutto
Your string s is created as a str type, and will probably be in utf-8 coding, which is different than unicode.
A:
Well,
after some further tests on Andrew Hare answer I've seen that character as ()[]- and so on are no more considered as separator while I want to split a sentence (maintaining all the separator) in words composed with ensemble of alphanumerical values set eventually expanded with accented chars (that is, everything marked as alphanumeric in unicode).
So, the solution of kgiannakakis is more correct but it miss a conversion of string s into unicode format.
Take this extension of the first example:
# -*- coding: utf-8 -*-
import re
s="(La felicità è tutto)"#no explicit unicode given string (UTF8)
l=re.compile("([\W])",re.UNICODE).split(unicode(s,'utf-8'))#split on s converted to unicode from utf8
print " string> "+s
print " wordlist> "+str(l)
for i in l:
print " word> "+i
The output now is :
string> (La felicità è tutto)
wordlist> [u'', u'(', u'La', u' ', u'felicit\xe0', u' ', u'\xe8', u' ', u'tutto', u')', u'']
word>
word> (
word> La
word>
word> felicità
word>
word> è
word>
word> tutto
word> )
word>
That is exactly what I'm looking for.
Cheers :)
Alessandro
| python, regex split and special character | How can I split correctly a string containing a sentence with special chars using whitespaces as separator ?
Using regex split method I cannot obtain the desired result.
Example code:
# -*- coding: utf-8 -*-
import re
s="La felicità è tutto" # "The happiness is everything" in italian
l=re.compile("(\W)").split(s)
print " s> "+s
print " wordlist> "+str(l)
for i in l:
print " word> "+i
The output is :
s> La felicità è tutto
wordlist> ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto']
word> La
word>
word> felicit
word> Ã
word>
word> ?
word>
word>
word>
word> Ã
word>
word> ?
word>
word>
word> tutto
while I'm looking for an output like:
s> La felicità è tutto
wordlist> ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto']
word> La
word>
word> felicità
word>
word> è
word>
word> tutto
To be noted that s is a string that is returned from another method so I cannot force the encoding like
s=u"La felicità è tutto"
On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation.
Thanks.
Alessandro
| [
"Your regex should be (\\s) instead of (\\W) like this:\nl = re.compile(\"(\\s)\").split(s)\n\nThe code above will give you the exact output you requested. However the following line makes more sense:\nl = re.compile(\"\\s\").split(s)\n\nwhich splits on whitespace characters and doesn't give you all the spaces as... | [
16,
4,
3,
3,
0
] | [] | [] | [
"python",
"regex",
"split",
"unicode"
] | stackoverflow_0000647655_python_regex_split_unicode.txt |
Q:
How to parse command line arguments in Python?
Possible Duplicate:
What's the best way to grab/parse command line arguments passed to a Python script?
I would like to be able to parse command line arguments in my Python 2.6 program.
Ideally, I want to be able to handle these cases:
# Show some help
./myprogram --help
# These are equivalent
./myprogram --block=1
./myprogram -b 1
# This means verbose, and twice as verbose:
./myprogram -v
./myprogram -vv
A:
Check out the argparse module (or optparse for older Python versions).
Note that argparse/optparse are newer, better replacements for getopt, so if you're new to this they're the recommended option. From the getopt docs:
Note The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.
A:
Python has argument processing built in, with the getopt module.
It can handle long and short forms of arguments as well as "naked" and parameterised versions (--help versus --num=7).
For your specific use cases (with a little more), you'd probably be looking at something like:
opts,args = getopt.getopt(argv,"b:vVh",["block=", "verbose", "very-verbose", "help"])
I'm not sure off the top of my head if it allows multi-character single-hyphen variants like -vv. I'd just use -v and -V myself to make my life easier.
A:
A better option than that link is the modules OptParse or GetOpt, and depending on which version of Python you're using, the newest ones..2.7, and 3.1.2, have an even newer module built in. The documentation on the official python.org reference has a very informative set of documentation and examples for those modules. If you go to python.org and just do a quick search for OptParse or GetOpt, you'll have everything you need.
A:
optfunc is an interesting little module. It's great if you want to quickly write a little script. For larger things I would go with argparse as others wrote.
| How to parse command line arguments in Python? |
Possible Duplicate:
What's the best way to grab/parse command line arguments passed to a Python script?
I would like to be able to parse command line arguments in my Python 2.6 program.
Ideally, I want to be able to handle these cases:
# Show some help
./myprogram --help
# These are equivalent
./myprogram --block=1
./myprogram -b 1
# This means verbose, and twice as verbose:
./myprogram -v
./myprogram -vv
| [
"Check out the argparse module (or optparse for older Python versions).\nNote that argparse/optparse are newer, better replacements for getopt, so if you're new to this they're the recommended option. From the getopt docs:\n\nNote The getopt module is a parser for command line options whose API is designed to be fa... | [
33,
3,
1,
1
] | [
"There might be a better way but I would just uses sys.argv and put in conditionals wherever needed i.e.\nif '--v' or '--vv' in sys.argv :\n print 'verbose message'\n\n"
] | [
-5
] | [
"arguments",
"command_line",
"python"
] | stackoverflow_0003234216_arguments_command_line_python.txt |
Q:
What is the best way to publish RSS Feed on Facebook?
What is the best way to publish an rss feed or a sitemap to facebook?
I am using google app engine as the platform and the python language
A:
I don't know of a library that can do the feed to Facebook publication. There are a few apps that do this, like this one.
One an Application is granted the publish_stream extended permission it can post on behalf of the User (or Page) using the api. There is a Python SDK which should work on AppEngine.
| What is the best way to publish RSS Feed on Facebook? | What is the best way to publish an rss feed or a sitemap to facebook?
I am using google app engine as the platform and the python language
| [
"I don't know of a library that can do the feed to Facebook publication. There are a few apps that do this, like this one.\nOne an Application is granted the publish_stream extended permission it can post on behalf of the User (or Page) using the api. There is a Python SDK which should work on AppEngine.\n"
] | [
1
] | [] | [] | [
"facebook",
"google_app_engine",
"publish",
"python",
"rss"
] | stackoverflow_0003227630_facebook_google_app_engine_publish_python_rss.txt |
Q:
view other computers on the network programatically in Python
Is it possible to view other devices that are on the same network in Python (or any programming language for that matter)?
Edit: For clarification, what I'd like to do (just to start out) is to display a list of devices connected and their local IP addresses. So on my router, it'll show the info:
family_pc, 192.168.1.2
work_laptop, 192.168.1.3
I'd like to retrieve this info.
A:
What are you trying to do exactly?
nmap is a pretty common tool for scanning networks, which seems like you want to do. There is also a python-nmap package which lets you use nmap directly from within Python with ease.
Please be more detailed so we can give you a better answer, cheers.
A:
You have a couple of options here.
You can run port scans over the entire network address space, but that's pretty wasteful and unfriendly. I don't recommend it.
A nicer approach would be to query for devices using a service discovery protocol like DNS-SD / Zeroconf (aka Bonjour). Most Linux and Mac systems will respond, as will many network printers and other network devices. Windows systems don't ship with a DNS-SD agent, but one can be installed.
A pure python implementation of DNS-SD is available here. I have used it on Linux, MacOS, and Windows.
If you prefer a Microsoft approach, you can try the discovery features of UPnP, though I can't vouch for how well it works or how many systems will respond.
| view other computers on the network programatically in Python | Is it possible to view other devices that are on the same network in Python (or any programming language for that matter)?
Edit: For clarification, what I'd like to do (just to start out) is to display a list of devices connected and their local IP addresses. So on my router, it'll show the info:
family_pc, 192.168.1.2
work_laptop, 192.168.1.3
I'd like to retrieve this info.
| [
"What are you trying to do exactly?\nnmap is a pretty common tool for scanning networks, which seems like you want to do. There is also a python-nmap package which lets you use nmap directly from within Python with ease.\nPlease be more detailed so we can give you a better answer, cheers.\n",
"You have a couple o... | [
8,
3
] | [
"If you don't mind using a little third party software you could use Netresview which works nicely on windows systems, avoid reinventing the wheel and all that. You could this kind of thing.\nos.system('NetResView.exe /DisplayComputers 1 /RetrieveIPAddresses /stext ipfile')\nmy_file = open('ipfile')\nfor line in my... | [
-2
] | [
"device",
"networking",
"python"
] | stackoverflow_0003233065_device_networking_python.txt |
Q:
help me understand python
Initialize an array of arrays:
M = [[]]*(24*60/5)
Append the number 2 to the 51st array in M
M[50].append(2)
What is in M?
...
[2]
[2]
[2]
[2]
[2]
[2]
[2]
[2]
...
Every element in M is the array [2]
What am I missing? I suspect that every [] that I initially initialize is a reference to the same space in memory.
A:
You did create an array of arrays. But you then assigned the same [] to every one of its entries.
It's not that every time you call [] it gives you the same array - it's that you only called [] once.
Get it?
A:
Yes, you got it, as Borealid pointed out.
If you want many times a different list, you can do:
M = [[] for _ in range(24*60/5)]
The _ is just a regular variable name (variables can start with an underscore), but it tells readers of the code "I'm an unimportant variable, with no special meaning associated to it".
A:
Take a look at http://www.python.org/dev/peps/pep-0020/.
The construct you liked to use is really hard to read and "Readability counts".
| help me understand python | Initialize an array of arrays:
M = [[]]*(24*60/5)
Append the number 2 to the 51st array in M
M[50].append(2)
What is in M?
...
[2]
[2]
[2]
[2]
[2]
[2]
[2]
[2]
...
Every element in M is the array [2]
What am I missing? I suspect that every [] that I initially initialize is a reference to the same space in memory.
| [
"You did create an array of arrays. But you then assigned the same [] to every one of its entries.\nIt's not that every time you call [] it gives you the same array - it's that you only called [] once.\nGet it?\n",
"Yes, you got it, as Borealid pointed out.\nIf you want many times a different list, you can do:\n... | [
5,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0003234559_python.txt |
Q:
Python : match string inside double quotes and bracket
I want to match text inside double quotes and bracket as two groups by use regex, How can I do that?
from
“作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為;
“行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補)
“成人”、“成年人”(adult)* 指年滿18歲的人; (由1990年第32號第6條修訂)
“飛機”、“航空器”(aircraft) 指任何可憑空氣的反作用而在大氣中獲得支承力的機器;
“外籍人士”(alien) 指並非中國公民的人; (由1998年第26號第4條增補)
“修訂”(amend) 包括廢除、增補或更改,亦指同時進行,或以同一條例或文書進行上述全部或其中任何事項; (由1993年第89號第3條修訂)
“可逮捕的罪行”(arrestable offence) 指由法律規限固定刑罰的罪行,或根據、憑藉法例對犯者可處超過12個月監禁的罪行,亦指犯任何這類罪行的企圖; (由1971年第30號第2條增補)
“《基本法》”(Basic Law) 指《中華人民共和國香港特別行政區基本法》; (由1998年第26號第4條增補)
“行政長官”(Chief Executive) 指─
to become
作為 act
行政上訴委員會 Administrative Appeals Board
成人, 成年人 adult
飛機, 航空器 aircraft
外籍人士 alien
修訂 amend
Please help me, Thank you.
A:
>>> import re
>>> s = u"""“作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為;
“行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補)
“成人”、“成年人”(adult)* 指年滿18歲的人; (由1990年第32號第6條修訂)
“飛機”、“航空器”(aircraft) 指任何可憑空氣的反作用而在大氣中獲得支承力的機器;
“外籍人士”(alien) 指並非中國公民的人; (由1998年第26號第4條增補)
“修訂”(amend) 包括廢除、增補或更改,亦指同時進行,或以同一條例或文書進行上述全部或其中任何事項; (由1993年第89號第3條修訂)
“可逮捕的罪行”(arrestable offence) 指由法律規限固定刑罰的罪行,或根據、憑藉法例對犯者可處超過12個月監禁的罪行,亦指犯任何這類罪行的企圖; (由1971年第30號第2條增補)
“《基本法》”(Basic Law) 指《中華人民共和國香港特別行政區基本法》; (由1998年第26號第4條增補)
“行政長官”(Chief Executive) 指─"""
>>> for x,y in re.findall(u"“(.*?)”\((.*?)\)",s):
... print x, y
...
作為 act
行政上訴委員會 Administrative Appeals Board
成年人 adult
航空器 aircraft
外籍人士 alien
修訂 amend
可逮捕的罪行 arrestable offence
《基本法》 Basic Law
行政長官 Chief Executive
If you want to use this in a program, you should use
# -*- coding: utf-8 -*-
at the top of the file, so the “ and ” are interpreted correctly
A:
You want to use the groups feature of regular expressions:
import re
myRegExp = re.compile('"(?P<val1>.*?)".*?\((?P<val2>.*?)\)')
myRegExp.finall(YourStringHere)
A:
To match multiple definitions you need multiple regexes.
# Assume Python 3.x. Use u'...' instead of '...' for Python 2.x.
import re
collector_re = re.compile('((?:“[^”]+”、?)+)\\(([^)]+)\\)')
splitter_re = re.compile('“([^”]+)”')
def find_all_definitions(text):
def_pairs = collector_re.finditer(text)
for match in def_pairs:
(chinese, english) = match.groups()
terms = splitter_re.findall(chinese)
yield (terms, english)
Usage:
text = '''“作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為;
“行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補)
“成人”、“成年人”(adult)* 指年滿18歲的人; (由1990年第32號第6條修訂)
“飛機”、“航空器”(aircraft) 指任何可憑空氣的反作用而在大氣中獲得支承力的機器;
“外籍人士”(alien) 指並非中國公民的人; (由1998年第26號第4條增補)
“修訂”(amend) 包括廢除、增補或更改,亦指同時進行,或以同一條例或文書進行上述全部或其中任何事項; (由1993年第89號第3條修訂)
“可逮捕的罪行”(arrestable offence) 指由法律規限固定刑罰的罪行,或根據、憑藉法例對犯者可處超過12個月監禁的罪行,亦指犯任何這類罪行的企圖; (由1971年第30號第2條增補)
“《基本法》”(Basic Law) 指《中華人民共和國香港特別行政區基本法》; (由1998年第26號第4條增補)
“行政長官”(Chief Executive) 指─'''
for terms, english in find_all_definitions(text):
print (', '.join(terms), "\t", english)
A:
If you want to get both Chinese phrases when there are two of them (as in adult and aircraft), you'll need to work harder. The code below is for Python 3.x.
#coding: utf8
import re
s = """“作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為;
“行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補)
“成人”、“成年人”(adult)* 指年滿18歲的人; (由1990年第32號第6條修訂)
“飛機”、“航空器”(aircraft) 指任何可憑空氣的反作用而在大氣中獲得支承力的機器;
“外籍人士”(alien) 指並非中國公民的人; (由1998年第26號第4條增補)
“修訂”(amend) 包括廢除、增補或更改,亦指同時進行,或以同一條例或文書進行上述全部或其中任何事項; (由1993年第89號第3條修訂)
“可逮捕的罪行”(arrestable offence) 指由法律規限固定刑罰的罪行,或根據、憑藉法例對犯者可處超過12個月監禁的罪行,亦指犯任何這類罪行的企圖; (由1971年第30號第2條增補)
“《基本法》”(Basic Law) 指《中華人民共和國香港特別行政區基本法》; (由1998年第26號第4條增補)
“行政長官”(Chief Executive) 指─"""
for zh1, zh2, en in re.findall(r"“([^”]*)”(?:、“([^”]*)”)?\((.*?)\)",s):
print(ascii((zh1, zh2, en)))
resulting in:
('\u4f5c\u70ba', '', 'act')
('\u884c\u653f\u4e0a\u8a34\u59d4\u54e1\u6703', '', 'Administrative Appeals Board')
('\u6210\u4eba', '\u6210\u5e74\u4eba', 'adult')
('\u98db\u6a5f', '\u822a\u7a7a\u5668', 'aircraft')
('\u5916\u7c4d\u4eba\u58eb', '', 'alien')
('\u4fee\u8a02', '', 'amend')
('\u53ef\u902e\u6355\u7684\u7f6a\u884c', '', 'arrestable offence')
('\u300a\u57fa\u672c\u6cd5\u300b', '', 'Basic Law')
('\u884c\u653f\u9577\u5b98', '', 'Chief Executive')
| Python : match string inside double quotes and bracket | I want to match text inside double quotes and bracket as two groups by use regex, How can I do that?
from
“作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為;
“行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補)
“成人”、“成年人”(adult)* 指年滿18歲的人; (由1990年第32號第6條修訂)
“飛機”、“航空器”(aircraft) 指任何可憑空氣的反作用而在大氣中獲得支承力的機器;
“外籍人士”(alien) 指並非中國公民的人; (由1998年第26號第4條增補)
“修訂”(amend) 包括廢除、增補或更改,亦指同時進行,或以同一條例或文書進行上述全部或其中任何事項; (由1993年第89號第3條修訂)
“可逮捕的罪行”(arrestable offence) 指由法律規限固定刑罰的罪行,或根據、憑藉法例對犯者可處超過12個月監禁的罪行,亦指犯任何這類罪行的企圖; (由1971年第30號第2條增補)
“《基本法》”(Basic Law) 指《中華人民共和國香港特別行政區基本法》; (由1998年第26號第4條增補)
“行政長官”(Chief Executive) 指─
to become
作為 act
行政上訴委員會 Administrative Appeals Board
成人, 成年人 adult
飛機, 航空器 aircraft
外籍人士 alien
修訂 amend
Please help me, Thank you.
| [
">>> import re\n>>> s = u\"\"\"“作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為;\n “行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補)\n “成人”、“成年人”(adult)* 指年滿18歲的人; (由1990年第32號第6條修訂)\n “飛機”、“航空器”(aircraft) 指任何可憑空氣的反作用而在大氣中獲得支承力的機器;\n “外籍人士”(alien) 指並非中國公民的人; (由19... | [
1,
0,
0,
0
] | [] | [] | [
"match",
"python",
"regex",
"regex_group"
] | stackoverflow_0003234114_match_python_regex_regex_group.txt |
Q:
how can we run python script(which uses nltk and scrapy) from java
I have written python scripts that use scrapy,nltk and simplejson in my project but i need to run them from java as my mentor wants to deploy them on a server and i have very less time to do this.I took a glance at runtime.exec() in java and jython, needless to say that running system commands from java doesn't look simple either.
So I would like to know if running the python scripts from java as system command -'python example.py ' using runtime.exec() or alternatively using jython would be more simpler and actually feasible or whether there is a simpler workaround .It would also be great to know if anyone had run python code that uses nltk from java using Jython and whether they encountered any problems.Please help me as I have to do this as asap.Any thoughts and suggestions regarding this are welcome.
Thanking in advance!!
A:
The Jepp project lets you call python scripts from Java. It provides an easy mechanism to pass variables into a script and extract values back. I've used on a few projects with good success
| how can we run python script(which uses nltk and scrapy) from java | I have written python scripts that use scrapy,nltk and simplejson in my project but i need to run them from java as my mentor wants to deploy them on a server and i have very less time to do this.I took a glance at runtime.exec() in java and jython, needless to say that running system commands from java doesn't look simple either.
So I would like to know if running the python scripts from java as system command -'python example.py ' using runtime.exec() or alternatively using jython would be more simpler and actually feasible or whether there is a simpler workaround .It would also be great to know if anyone had run python code that uses nltk from java using Jython and whether they encountered any problems.Please help me as I have to do this as asap.Any thoughts and suggestions regarding this are welcome.
Thanking in advance!!
| [
"The Jepp project lets you call python scripts from Java. It provides an easy mechanism to pass variables into a script and extract values back. I've used on a few projects with good success\n"
] | [
3
] | [] | [] | [
"java",
"jython",
"nltk",
"python",
"scrapy"
] | stackoverflow_0003234965_java_jython_nltk_python_scrapy.txt |
Q:
What are the differences between struct_time and datetime?
Is one preferred over the other? If so, in all cases or just a few?
I am intending to use some form of date class for keeping long lists of date and time data, e.g. '2009-01-01 10:12:00'.
A:
struct_time is the old way of representing times, modeled after the C standard library. datetime came later, is more pythonic, is more featureful, and has more predictable behavior in edge cases than the struct_time functions. I would use datetime except in the rare cases where a measured performance difference is significant enough to matter, or where it makes the code significantly less readable.
A:
datetime is more object oriented and offers many convenient features, e.g. arithmetic with timedelta-objects.
| What are the differences between struct_time and datetime? | Is one preferred over the other? If so, in all cases or just a few?
I am intending to use some form of date class for keeping long lists of date and time data, e.g. '2009-01-01 10:12:00'.
| [
"struct_time is the old way of representing times, modeled after the C standard library. datetime came later, is more pythonic, is more featureful, and has more predictable behavior in edge cases than the struct_time functions. I would use datetime except in the rare cases where a measured performance difference ... | [
5,
2
] | [] | [] | [
"date_format",
"python"
] | stackoverflow_0003235133_date_format_python.txt |
Q:
Backend processing for Django
I'm working on a turn-based web game that will perform all world updates (player orders, physics, scripted events, etc.) on the server. For now, I could simply update the world in a web request callback. Unfortunately, that naive approach is not at all scalable. I don't want to bog down my web server when I start running many concurrent games.
So what is the best way to separate the load from the web server, ideally in a way that could even be run on a separate machine?
A simple python module with infinite loop?
A distributed task in something like Celery?
Some sort of cross-platform Cron scheduler?
Some other fancy Django feature or third-party library that I don't know about?
I also want to minimize code duplication by using the same model layer. That probably means my service would need access to the Django model code, so that definitely determines how I architect the service.
A:
I think Celery, which you mention in your question, is the way to go here. It will interface nicely with the rest of your setup, support your eventual aim of separating out the systems, and is compatible with Django.
A:
I'd just write the backend to just use the Django database interface (look at the setup code in your manage.py), spawn it as its own process, and interface to it with Protocol Buffers. That route should move to a separate machine with little work. MPI may be an option, too.
Pipes, FIFOs, and most other IPC requires both processes to be on the same box.
Though I have to point out a flaw in your premise:
Unfortunately, that naive approach is not at all scalable. I don't want to bog down my web server when I start running many concurrent games.
If you run concurrent games, so long as you keep all the parts for a given game on the same server, this is a non-issue, unless there's a common resource needed by all games. Then the real issue becomes load balancing across the servers.
| Backend processing for Django | I'm working on a turn-based web game that will perform all world updates (player orders, physics, scripted events, etc.) on the server. For now, I could simply update the world in a web request callback. Unfortunately, that naive approach is not at all scalable. I don't want to bog down my web server when I start running many concurrent games.
So what is the best way to separate the load from the web server, ideally in a way that could even be run on a separate machine?
A simple python module with infinite loop?
A distributed task in something like Celery?
Some sort of cross-platform Cron scheduler?
Some other fancy Django feature or third-party library that I don't know about?
I also want to minimize code duplication by using the same model layer. That probably means my service would need access to the Django model code, so that definitely determines how I architect the service.
| [
"I think Celery, which you mention in your question, is the way to go here. It will interface nicely with the rest of your setup, support your eventual aim of separating out the systems, and is compatible with Django.\n",
"I'd just write the backend to just use the Django database interface (look at the setup cod... | [
6,
0
] | [] | [] | [
"distributed",
"django",
"python",
"service"
] | stackoverflow_0003233844_distributed_django_python_service.txt |
Q:
Why do Selenium Python tests look so weird?
I've used the Selenium IDE to generate some test code for my application. The generated Python code for an assertion looks like this.
try: self.failUnless(sel.is_text_present("Path"))
except AssertionError, e: self.verificationErrors.append(str(e))
Instead of failing fast, the error is added to a list, and the script continues.
I was wondering what the rationale for this is? Isn't it better to fail fast? Or would this leave the page in an inconsistent state?
A:
This is the difference between a verify and an assert in Selenium. When using verify any failures will be logged but the test will continue, they are in effect a 'soft assertion'. If you want to stop executing your test on a failure try using assert instead.
//verifyTextPresent
try: self.failUnless(sel.is_text_present("My Text"))
except AssertionError, e: self.verificationErrors.append(str(e))
//assertTextPresent
self.failUnless(sel.is_text_present("My Text"))
| Why do Selenium Python tests look so weird? | I've used the Selenium IDE to generate some test code for my application. The generated Python code for an assertion looks like this.
try: self.failUnless(sel.is_text_present("Path"))
except AssertionError, e: self.verificationErrors.append(str(e))
Instead of failing fast, the error is added to a list, and the script continues.
I was wondering what the rationale for this is? Isn't it better to fail fast? Or would this leave the page in an inconsistent state?
| [
"This is the difference between a verify and an assert in Selenium. When using verify any failures will be logged but the test will continue, they are in effect a 'soft assertion'. If you want to stop executing your test on a failure try using assert instead.\n//verifyTextPresent\ntry: self.failUnless(sel.is_text_p... | [
6
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0003234869_python_selenium.txt |
Q:
Why am I encountering an ImportError when I try to 're-import' a module?
I have a series of python modules written which are held in the same directory and I am having trouble with an ImportError.
The three modules I am using are draw_menu.py, errors.py and file_operations.py.
In errors.py I requires a list of error codes, I am using a custom method defined in file_operations.py to open a file containing the codes therefore I am using import file_operations just below the she-bang (above the class definition).
In file_operations.py I use a method defined in error.py to print error messages upon errors (e.g. file not found etc.). I therefore import errors in the same way here.
The above has been working fine but when I come to using draw_menu.py which uses a file to define the options in an ascii menu (therefore I am using import file_operations) an ImportError is encountered.
ImportError: cannot import name file_operations
I understand that this is because the 'import tree' if you like flows as follows:
draw_menu <- file_operations <- errors <- file_operations
It is important that each module can be used individually, why is this an issue and how can I overcome this without removing import file_operations from errors.py?
Thankyou
Tom
A:
Circular imports can cause issues in Python (as you might expect). It's probably worth checking if:
A) errors.py and file_operation.py should be single module (if they both rely so heavily on each other, do they need to be separate?)
B) you can delay the import in one or the other module. An import statement in a function will not run until the function is called, and while it's normally good practice to import at the beginning of a module there is no requirement to in Python. In situations like this it can avoid the circular reference during import.
A:
The problem is not the imports themselves, but the dependencies. file_operations cannot be processed until it has imported errors, but errors cannot be processed until it has imported file_operations. Python recognises this as an impossible situation, and raises an error.
The best solution to this is to refactor your files so that you don't have this circular dependency any more. If this really isn't possible, the alternative solution is to change one of the modules so that the offending import happens inside the function that needs it, rather than at the top level. This means the initial processing of the module isn't dependent on the import, so it will succeed.
A:
Apart from breaking the circular dependency you can try moving the locations of your import calls. Don't forget that imports in Python are just regular statements, so you can import inside functions for example.
The trouble is that import (as a side-effect) will actually run the module being imported (the first time you call import). So if you are importing a module, which imports the original module things get confused.
You may find that you can ease the problem by only importing errors/file_operations at the point you actually need to use it. This could be inside a function. So maybe wrap the call to the function in errors:
def print_error_message(err):
from errors import print_error_message as _print_error_message
_print_error_message(err)
That way you will only import errors after the regular imports have run.
| Why am I encountering an ImportError when I try to 're-import' a module? | I have a series of python modules written which are held in the same directory and I am having trouble with an ImportError.
The three modules I am using are draw_menu.py, errors.py and file_operations.py.
In errors.py I requires a list of error codes, I am using a custom method defined in file_operations.py to open a file containing the codes therefore I am using import file_operations just below the she-bang (above the class definition).
In file_operations.py I use a method defined in error.py to print error messages upon errors (e.g. file not found etc.). I therefore import errors in the same way here.
The above has been working fine but when I come to using draw_menu.py which uses a file to define the options in an ascii menu (therefore I am using import file_operations) an ImportError is encountered.
ImportError: cannot import name file_operations
I understand that this is because the 'import tree' if you like flows as follows:
draw_menu <- file_operations <- errors <- file_operations
It is important that each module can be used individually, why is this an issue and how can I overcome this without removing import file_operations from errors.py?
Thankyou
Tom
| [
"Circular imports can cause issues in Python (as you might expect). It's probably worth checking if:\nA) errors.py and file_operation.py should be single module (if they both rely so heavily on each other, do they need to be separate?)\nB) you can delay the import in one or the other module. An import statement in ... | [
2,
1,
0
] | [] | [] | [
"import",
"importerror",
"python"
] | stackoverflow_0003235684_import_importerror_python.txt |
Q:
storing the output of a cursor object in csv format
i've accessed a database and have the result in a cursor object. but i couldn't save it :(
cur_deviceauth.execute('select * from device_auth')
for row in cur_deviceauth:
print row
writer = csv.writer(open("out.csv", "w"))
writer.writerows(cur_deviceauth)
i don't get an error msg and i couldn't write it. how do i make it? any advice would be of much help and what is the best place to learn this stuff?
A:
When you're printing rows before writing to a file, you're exhausting cursor object that works as a generator. Just write to file without any intermediate steps.
| storing the output of a cursor object in csv format | i've accessed a database and have the result in a cursor object. but i couldn't save it :(
cur_deviceauth.execute('select * from device_auth')
for row in cur_deviceauth:
print row
writer = csv.writer(open("out.csv", "w"))
writer.writerows(cur_deviceauth)
i don't get an error msg and i couldn't write it. how do i make it? any advice would be of much help and what is the best place to learn this stuff?
| [
"When you're printing rows before writing to a file, you're exhausting cursor object that works as a generator. Just write to file without any intermediate steps.\n"
] | [
2
] | [] | [] | [
"csv",
"file_io",
"python",
"sqlite"
] | stackoverflow_0003235887_csv_file_io_python_sqlite.txt |
Q:
Dumping Collection to YAML file with PyYaml
I am writing a python application. I am trying to dump my python object into yaml using PyYaml. I am using Python 2.6 and running Ubuntu Lucid 10.04. I am using the PyYAML package in Ubuntu Package: http://packages.ubuntu.com/lucid/python/python-yaml
My object has 3 text variables and a list of objects. Roughly it is something like this:
ClassToDump:
#3 text variables
text_variable_1
text_variable_2
text_variable_3
#a list of AnotherObjectsClass instances
list_of_another_objects = [object1,object2,object3]
AnotherObjectsClass:
text_variable_1
text_variable_2
text_variable_3
The class that I want to dump contains a list of AnotherObjectClass instances. This class has a few text variables.
PyYaml somehow does not dump the collections in AnotherObjectClass instance. PyYAML does dump text_variable_1, text_variable_2, and text_variable_3.
I am using the following pyYaml API to dump ClassToDump instance:
classToDump = ClassToDump();
yaml.dump(ClassToDump,yaml_file_to_dump)
Does any one has any experience with dumping a list of objects into YAML ?
Here is the actual full code snippet:
def write_config(file_path,class_to_dump):
config_file = open(file_path,'w');
yaml.dump(class_to_dump,config_file);
def dump_objects():
rule = Miranda.Rule();
rule.rule_condition = Miranda.ALL
rule.rule_setting = ruleSetting
rule.rule_subjects.append(rule1)
rule.rule_subjects.append(rule2)
rule.rule_verb = ruleVerb
write_config(rule ,'./config.yaml');
This is the output :
!!python/object:Miranda.Rule
rule_condition: ALL
rule_setting: !!python/object:Miranda.RuleSetting {confirm_action: true, description: My
Configuration, enabled: true, recursive: true, source_folder: source_folder}
rule_verb: !!python/object:Miranda.RuleVerb {compression: true, dest_folder: /home/zainul/Downloads,
type: Move File}
A:
The PyYaml module takes care of the details for you, hopefully the following snippet will help
import sys
import yaml
class AnotherClass:
def __init__(self):
pass
class MyClass:
def __init__(self):
self.text_variable_1 = 'hello'
self.text_variable_2 = 'world'
self.text_variable_3 = 'foobar'
self.list_of_another_objects = [
AnotherClass(),
AnotherClass(),
AnotherClass()
]
obj = MyClass()
yaml.dump(obj, sys.stdout)
The output of that code is:
!!python/object:__main__.MyClass
list_of_another_objects:
- !!python/object:__main__.AnotherClass {}
- !!python/object:__main__.AnotherClass {}
- !!python/object:__main__.AnotherClass {}
text_variable_1: hello
text_variable_2: world
text_variable_3: foobar
| Dumping Collection to YAML file with PyYaml | I am writing a python application. I am trying to dump my python object into yaml using PyYaml. I am using Python 2.6 and running Ubuntu Lucid 10.04. I am using the PyYAML package in Ubuntu Package: http://packages.ubuntu.com/lucid/python/python-yaml
My object has 3 text variables and a list of objects. Roughly it is something like this:
ClassToDump:
#3 text variables
text_variable_1
text_variable_2
text_variable_3
#a list of AnotherObjectsClass instances
list_of_another_objects = [object1,object2,object3]
AnotherObjectsClass:
text_variable_1
text_variable_2
text_variable_3
The class that I want to dump contains a list of AnotherObjectClass instances. This class has a few text variables.
PyYaml somehow does not dump the collections in AnotherObjectClass instance. PyYAML does dump text_variable_1, text_variable_2, and text_variable_3.
I am using the following pyYaml API to dump ClassToDump instance:
classToDump = ClassToDump();
yaml.dump(ClassToDump,yaml_file_to_dump)
Does any one has any experience with dumping a list of objects into YAML ?
Here is the actual full code snippet:
def write_config(file_path,class_to_dump):
config_file = open(file_path,'w');
yaml.dump(class_to_dump,config_file);
def dump_objects():
rule = Miranda.Rule();
rule.rule_condition = Miranda.ALL
rule.rule_setting = ruleSetting
rule.rule_subjects.append(rule1)
rule.rule_subjects.append(rule2)
rule.rule_verb = ruleVerb
write_config(rule ,'./config.yaml');
This is the output :
!!python/object:Miranda.Rule
rule_condition: ALL
rule_setting: !!python/object:Miranda.RuleSetting {confirm_action: true, description: My
Configuration, enabled: true, recursive: true, source_folder: source_folder}
rule_verb: !!python/object:Miranda.RuleVerb {compression: true, dest_folder: /home/zainul/Downloads,
type: Move File}
| [
"The PyYaml module takes care of the details for you, hopefully the following snippet will help \nimport sys\nimport yaml\n\nclass AnotherClass:\n def __init__(self):\n pass\n\nclass MyClass:\n def __init__(self):\n self.text_variable_1 = 'hello'\n self.text_variable_2 = 'world'\n ... | [
2
] | [] | [] | [
"python",
"pyyaml",
"ubuntu_10.04"
] | stackoverflow_0003233921_python_pyyaml_ubuntu_10.04.txt |
Q:
Ordered ManyToManyField that can be used in fieldsets
I've been working through an ordered ManyToManyField widget, and have the front-end aspect of it working nicely:
Unfortunately, I'm having a great deal of trouble getting the backend working. The obvious way to hook up the backend is to use a through table keyed off a model with ForeignKeys to both sides of the relationship and overwrite the save method. This would work great, except that due to idiosyncrasies of the content, it is an absolute requirement that this widget be placed in a fieldset (using the ModelAdmin fieldsets property), which is apparently not possible.
I'm out of ideas. Any suggestions?
Thanks!
A:
In regard to how to set up the models, you're right in that a through table with an "order" column is the ideal way to represent it. You're also right in that Django will not let you refer to that relationship in a fieldset. The trick to cracking this problem is to remember that the field names you specify in the "fieldsets" or "fields" of a ModelAdmin do not actually refer to the fields of the Model, but to the fields of the ModelForm, which we are free to override to our heart's delight. With many2many fields, this gets tricky, but bear with me:
Let's say you're trying to represent contests and competitors that compete in them, with an ordered many2many between contests and competitors where the order represents the competitors' ranking in that contest. Your models.py would then look like this:
from django.db import models
class Contest(models.Model):
name = models.CharField(max_length=50)
# More fields here, if you like.
contestants = models.ManyToManyField('Contestant', through='ContestResults')
class Contestant(models.Model):
name = models.CharField(max_length=50)
class ContestResults(models.Model):
contest = models.ForeignKey(Contest)
contestant = models.ForeignKey(Contestant)
rank = models.IntegerField()
Hopefully, this is similar to what you're dealing with. Now, for the admin. I've written an example admin.py with plenty of comments to explain what's happening, but here's a summary to help you along:
Since I don't have the code to the ordered m2m widget you've written, I've used a placeholder dummy widget that simply inherits from TextInput. The input holds a comma-separated list (without spaces) of contestant IDs, and the order of their appearance in the string determines the value of their "rank" column in the ContestResults model.
What happens is that we override the default ModelForm for Contest with our own, and then define a "results" field inside it (we can't call the field "contestants", since there would be a name conflict with the m2m field in the model). We then override __init__(), which is called when the form is displayed in the admin, so we can fetch any ContestResults that may have already been defined for the Contest, and use them to populate the widget. We also override save(), so that we can in turn get the data from the widget and create the needed ContestResults.
Note that for the sake of simplicity this example omits things like validation of the data from the widget, so things will break if you try to type in anything unexpected in the text input. Also, the code for creating the ContestResults is quite simplistic, and could be greatly improved upon.
I should also add that I've actually ran this code and verified that it works.
from django import forms
from django.contrib import admin
from models import Contest, Contestant, ContestResults
# Generates a function that sequentially calls the two functions that were
# passed to it
def func_concat(old_func, new_func):
def function():
old_func()
new_func()
return function
# A dummy widget to be replaced with your own.
class OrderedManyToManyWidget(forms.widgets.TextInput):
pass
# A simple CharField that shows a comma-separated list of contestant IDs.
class ResultsField(forms.CharField):
widget = OrderedManyToManyWidget()
class ContestAdminForm(forms.models.ModelForm):
# Any fields declared here can be referred to in the "fieldsets" or
# "fields" of the ModelAdmin. It is crucial that our custom field does not
# use the same name as the m2m field field in the model ("contestants" in
# our example).
results = ResultsField()
# Be sure to specify your model here.
class Meta:
model = Contest
# Override init so we can populate the form field with the existing data.
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance', None)
# See if we are editing an existing Contest. If not, there is nothing
# to be done.
if instance and instance.pk:
# Get a list of all the IDs of the contestants already specified
# for this contest.
contestants = ContestResults.objects.filter(contest=instance).order_by('rank').values_list('contestant_id', flat=True)
# Make them into a comma-separated string, and put them in our
# custom field.
self.base_fields['results'].initial = ','.join(map(str, contestants))
# Depending on how you've written your widget, you can pass things
# like a list of available contestants to it here, if necessary.
super(ContestAdminForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
# This "commit" business complicates things somewhat. When true, it
# means that the model instance will actually be saved and all is
# good. When false, save() returns an unsaved instance of the model.
# When save() calls are made by the Django admin, commit is pretty
# much invariably false, though I'm not sure why. This is a problem
# because when creating a new Contest instance, it needs to have been
# saved in the DB and have a PK, before we can create ContestResults.
# Fortunately, all models have a built-in method called save_m2m()
# which will always be executed after save(), and we can append our
# ContestResults-creating code to the existing same_m2m() method.
commit = kwargs.get('commit', True)
# Save the Contest and get an instance of the saved model
instance = super(ContestAdminForm, self).save(*args, **kwargs)
# This is known as a lexical closure, which means that if we store
# this function and execute it later on, it will execute in the same
# context (i.e. it will have access to the current instance and self).
def save_m2m():
# This is really naive code and should be improved upon,
# especially in terms of validation, but the basic gist is to make
# the needed ContestResults. For now, we'll just delete any
# existing ContestResults for this Contest and create them anew.
ContestResults.objects.filter(contest=instance).delete()
# Make a list of (rank, contestant ID) tuples from the comma-
# -separated list of contestant IDs we get from the results field.
formdata = enumerate(map(int, self.cleaned_data['results'].split(',')), 1)
for rank, contestant in formdata:
ContestResults.objects.create(contest=instance, contestant_id=contestant, rank=rank)
if commit:
# If we're committing (fat chance), simply run the closure.
save_m2m()
else:
# Using a function concatenator, ensure our save_m2m closure is
# called after the existing save_m2m function (which will be
# called later on if commit is False).
self.save_m2m = func_concat(self.save_m2m, save_m2m)
# Return the instance like a good save() method.
return instance
class ContestAdmin(admin.ModelAdmin):
# The precious fieldsets.
fieldsets = (
('Basic Info', {
'fields': ('name', 'results',)
}),)
# Here's where we override our form
form = ContestAdminForm
admin.site.register(Contest, ContestAdmin)
In case you're wondering, I had ran into this problem myself on a project I've been working on, so most of this code comes from that project. I hope you find it useful.
| Ordered ManyToManyField that can be used in fieldsets | I've been working through an ordered ManyToManyField widget, and have the front-end aspect of it working nicely:
Unfortunately, I'm having a great deal of trouble getting the backend working. The obvious way to hook up the backend is to use a through table keyed off a model with ForeignKeys to both sides of the relationship and overwrite the save method. This would work great, except that due to idiosyncrasies of the content, it is an absolute requirement that this widget be placed in a fieldset (using the ModelAdmin fieldsets property), which is apparently not possible.
I'm out of ideas. Any suggestions?
Thanks!
| [
"In regard to how to set up the models, you're right in that a through table with an \"order\" column is the ideal way to represent it. You're also right in that Django will not let you refer to that relationship in a fieldset. The trick to cracking this problem is to remember that the field names you specify in th... | [
9
] | [] | [] | [
"django",
"django_admin",
"manytomanyfield",
"python"
] | stackoverflow_0003190735_django_django_admin_manytomanyfield_python.txt |
Q:
Parsing Python HTML POST data from BaseHTTPServer
I'm sending a couple of files from an HTML form to my server which is based on BaseHTTPServer.
Within my do_POST I'm getting a string from rfile.read(length) which looks like some sort of multipart MIME string. Google is not being helpful on how I can decode this into something usable.
The output looks like this :
-----------------------------122422713313797828591978698502
Content-Disposition: form-data; name="MAX_FILE_SIZE"
1000000
-----------------------------122422713313797828591978698502
Content-Disposition: form-data; name="and_title_input"
and so on.
I've tried email.parser
from email.parser import Parser
p=Parser()
msg=p.parsestr(s)
but msg doesn't seem to get me any nearer to my goal - it's not multipart and contains no payload.
I'm reduced to parsing the data myself - which is surely not the Pythonic way of doing things!
Have I missed something obvious? Has Google let me down? Can Stack Overflow save the day?
A:
Would cgi.parse_multipart meet your need? Also see a relevant discussion on comp.lang.python.
| Parsing Python HTML POST data from BaseHTTPServer | I'm sending a couple of files from an HTML form to my server which is based on BaseHTTPServer.
Within my do_POST I'm getting a string from rfile.read(length) which looks like some sort of multipart MIME string. Google is not being helpful on how I can decode this into something usable.
The output looks like this :
-----------------------------122422713313797828591978698502
Content-Disposition: form-data; name="MAX_FILE_SIZE"
1000000
-----------------------------122422713313797828591978698502
Content-Disposition: form-data; name="and_title_input"
and so on.
I've tried email.parser
from email.parser import Parser
p=Parser()
msg=p.parsestr(s)
but msg doesn't seem to get me any nearer to my goal - it's not multipart and contains no payload.
I'm reduced to parsing the data myself - which is surely not the Pythonic way of doing things!
Have I missed something obvious? Has Google let me down? Can Stack Overflow save the day?
| [
"Would cgi.parse_multipart meet your need? Also see a relevant discussion on comp.lang.python.\n"
] | [
6
] | [] | [] | [
"basehttpserver",
"http",
"post",
"python"
] | stackoverflow_0003236597_basehttpserver_http_post_python.txt |
Q:
Google app engine: reverse reference lookups
Is reverse referencing possible in Google app engine? I am using app engine patch to develope an application and my model is something like:
class Portfolio(db.Model):
user = db.ReferenceProperty(User)
pic = db.BlobProperty()
Now, If I have the user object, is it possible to retrieve the pic associated with the users portfolio? i.e. the reverse reference from the User to Portfolio.
A:
Yes. You can access the pics, via:
user = User()
pics = user.portfolio_set
You can change the default name (which is modelname_set) by passing the collection_name argument to the ReferenceProperty constructor. For example:
class Portfolio(db.Model):
user = db.ReferenceProperty(User, collection_name="Portfolio")
See more information and examples here: http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html
A:
Yes it is possible.
By default you can access users portfolio through user.portfolio_set.
Read here for more info: http://code.google.com/intl/pl/appengine/articles/modeling.html
| Google app engine: reverse reference lookups | Is reverse referencing possible in Google app engine? I am using app engine patch to develope an application and my model is something like:
class Portfolio(db.Model):
user = db.ReferenceProperty(User)
pic = db.BlobProperty()
Now, If I have the user object, is it possible to retrieve the pic associated with the users portfolio? i.e. the reverse reference from the User to Portfolio.
| [
"Yes. You can access the pics, via:\nuser = User()\npics = user.portfolio_set\n\nYou can change the default name (which is modelname_set) by passing the collection_name argument to the ReferenceProperty constructor. For example:\nclass Portfolio(db.Model):\n user = db.ReferenceProperty(User, collection_name=\"Port... | [
1,
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003236890_django_google_app_engine_python.txt |
Q:
Term-Topic Matrix for a huge file
I have a list of 17 million sentences in a text file. Each sentence contains at max 200 characters. Each sentence is also accompanied by one or more annotation(s) with it. I have a list of unique annotations and a list of unique words obtained from the 17 million sentences. I have to create a sparse matrix with the rows as the unique words and the columns as the annotations(318k). Each value of the matrix would be the number of times each word has appeared with the annotation.
Matrix Data Structure
The size of the matrix is obviously going to be very large. Pointers towards handling such huge matrix sizes? One immediate thought to my mind was the use of a CSV file.
Co-occurrence word search
Each sentence may contain one or more annotations. Pointers on things I should do to speed up my search and things to take care of.
I am fine with Python/Java. If there's something else like a Shell Script/Perl etc. which would ease my task, I would be glad to use it
I am thinking about using Lucene for the search. I am NOT sure if Lucene is required as all my sentences are indexed in a DB
I apologize for posting no code, but this ain't no homework! An idea/suggestion/pointer will work for me.
A:
For sparse matrices, do not use an actual matrix or list.
Use a dictionary, keyed, by word and annotation. Much simpler.
matrix[ (word,annotation) ] += 1
A:
In python2.7+ you can use a Counter
>>> from collections import Counter
>>> matrix = Counter()
>>> matrix[(word,annotation)]+=1
for older python use a defaultdict
>>> from collections import defaultdict
>>> matrix = defaultdict(int)
>>> matrix[(word,annotation)]+=1
| Term-Topic Matrix for a huge file | I have a list of 17 million sentences in a text file. Each sentence contains at max 200 characters. Each sentence is also accompanied by one or more annotation(s) with it. I have a list of unique annotations and a list of unique words obtained from the 17 million sentences. I have to create a sparse matrix with the rows as the unique words and the columns as the annotations(318k). Each value of the matrix would be the number of times each word has appeared with the annotation.
Matrix Data Structure
The size of the matrix is obviously going to be very large. Pointers towards handling such huge matrix sizes? One immediate thought to my mind was the use of a CSV file.
Co-occurrence word search
Each sentence may contain one or more annotations. Pointers on things I should do to speed up my search and things to take care of.
I am fine with Python/Java. If there's something else like a Shell Script/Perl etc. which would ease my task, I would be glad to use it
I am thinking about using Lucene for the search. I am NOT sure if Lucene is required as all my sentences are indexed in a DB
I apologize for posting no code, but this ain't no homework! An idea/suggestion/pointer will work for me.
| [
"For sparse matrices, do not use an actual matrix or list.\nUse a dictionary, keyed, by word and annotation. Much simpler.\nmatrix[ (word,annotation) ] += 1\n\n",
"In python2.7+ you can use a Counter\n>>> from collections import Counter\n>>> matrix = Counter()\n>>> matrix[(word,annotation)]+=1\n\nfor older pytho... | [
3,
0
] | [] | [] | [
"java",
"lucene",
"mysql",
"python",
"search"
] | stackoverflow_0003236181_java_lucene_mysql_python_search.txt |
Q:
Inserting utf8 characters in DB using Django
In Django how to use unicode when inserting into DB
Example:
name =request.POST["name"] //This may be in Chinese or any other lanuages
usr = Users(name=name)
usr.save()
The Python version that is used in Cent os is python 2.4.3 and mod python version is 1.2.1_p2-1
A:
you should check if your database has utf8 charset on table in which you are trying to insert.
for mysql
show create table TableName;
to change encoding
alter table TableName DEFAULT CHARACTER SET utf8;
A:
What database are you using? If it's MySQL, make sure you follow the Django documentation on creating UTF-8 compatible MySQL databases.
A:
Use unicode('some string') in order to send the string to DB in Unicode. You might have different settings for the DB, but this is not connected with Django.
| Inserting utf8 characters in DB using Django | In Django how to use unicode when inserting into DB
Example:
name =request.POST["name"] //This may be in Chinese or any other lanuages
usr = Users(name=name)
usr.save()
The Python version that is used in Cent os is python 2.4.3 and mod python version is 1.2.1_p2-1
| [
"you should check if your database has utf8 charset on table in which you are trying to insert.\nfor mysql \nshow create table TableName;\n\nto change encoding\n alter table TableName DEFAULT CHARACTER SET utf8;\n\n",
"What database are you using? If it's MySQL, make sure you follow the Django documentation on ... | [
5,
1,
0
] | [] | [] | [
"django",
"django_views",
"python",
"utf_8"
] | stackoverflow_0003237326_django_django_views_python_utf_8.txt |
Q:
Is there a direct equivalent in Java for Python's str.join?
Possible Duplicates:
What’s the best way to build a string of delimited items in Java?
Java: convert List<String> to a join()d string
In Java, given a collection, getting the iterator and doing a separate case for the first (or last) element and the rest to get a comma separated string seems quite dull, is there something like str.join in Python?
Extra clarification for avoiding it being closed as duplicate: I'd rather not use external libraries like Apache Commons.
Thanks!
update a few years after...
Java 8 came to the rescue
A:
Nope there is not. Here is my attempt:
/**
* Join a collection of strings and add commas as delimiters.
* @require words.size() > 0 && words != null
*/
public static String concatWithCommas(Collection<String> words) {
StringBuilder wordList = new StringBuilder();
for (String word : words) {
wordList.append(word + ",");
}
return new String(wordList.deleteCharAt(wordList.length() - 1));
}
A:
For a long time Java offered no such method. Like many others I did my versions of such join for array of strings and collections (iterators).
But Java 8 added String.join():
String[] arr = { "ala", "ma", "kota" };
String joined = String.join(" ", arr);
System.out.println(joined);
A:
There is nothing in the standard library, but Guava for example has Joiner that does this.
Joiner joiner = Joiner.on(";").skipNulls();
. . .
return joiner.join("Harry", null, "Ron", "Hermione");
// returns "Harry; Ron; Hermione"
You can always write your own using a StringBuilder, though.
A:
A compromise solution between not writing extra "utils" code and not using external libraries that I've found is the following two-liner:
/* collection is an object that formats to something like "[1, 2, 3...]"
(as the case of ArrayList, Set, etc.)
That is part of the contract of the Collection interface.
*/
String res = collection.toString();
res = res.substring(1, res.length()-1);
A:
Not in the standard library. It is in StringUtils of commons lang.
| Is there a direct equivalent in Java for Python's str.join? |
Possible Duplicates:
What’s the best way to build a string of delimited items in Java?
Java: convert List<String> to a join()d string
In Java, given a collection, getting the iterator and doing a separate case for the first (or last) element and the rest to get a comma separated string seems quite dull, is there something like str.join in Python?
Extra clarification for avoiding it being closed as duplicate: I'd rather not use external libraries like Apache Commons.
Thanks!
update a few years after...
Java 8 came to the rescue
| [
"Nope there is not. Here is my attempt:\n/**\n * Join a collection of strings and add commas as delimiters.\n * @require words.size() > 0 && words != null\n */\npublic static String concatWithCommas(Collection<String> words) {\n StringBuilder wordList = new StringBuilder();\n for (String word : words) {\n ... | [
15,
14,
8,
3,
0
] | [] | [] | [
"java",
"python",
"string"
] | stackoverflow_0003236213_java_python_string.txt |
Q:
How to install python on Samsung S5600 halley EVO
I would like to know how to install python on Samsung S5600 Halley Evo. Do I have to do something like a jailbreak? Is it possible? and, if yes, how?
A:
What you actually need is to download Android Scripting Environment, since I guess your Samsung is an Android phone. Within the ASE, you can determine which programming languages to use, weather its plain unix Shell, Python or Perl. Up to 10 different scripting languages are supported.
Jailbreaking is something you do on an iPhone, since its locked by Apple. The Android handheld device is not locked, so you can install all you want, without using the Android Market. You can even uninstall applications, like the built in Messaging app if you want to use Handcent SMS instead :)
Ref: Android Scripting Environment
| How to install python on Samsung S5600 halley EVO | I would like to know how to install python on Samsung S5600 Halley Evo. Do I have to do something like a jailbreak? Is it possible? and, if yes, how?
| [
"What you actually need is to download Android Scripting Environment, since I guess your Samsung is an Android phone. Within the ASE, you can determine which programming languages to use, weather its plain unix Shell, Python or Perl. Up to 10 different scripting languages are supported.\nJailbreaking is something y... | [
0
] | [] | [] | [
"jailbreak",
"mobile",
"python"
] | stackoverflow_0003235837_jailbreak_mobile_python.txt |
Q:
Can we learn Django for a python beginner?
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
A:
Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once.
Python's a pretty easy language to pick up too. Just have to get used to the significant white space and lack of semi-colons :P
A:
I'm going to disagree with previous answers. You could learn Python by learning Django, but I don't think it's a very good idea. You won't really understand why things are the way they are, or how things really work.
My advice would be to follow a Python tutorial first - if you're an experienced programmer already then Dive Into Python is an excellent one - and then run through the Django tutorial. You'll be in a much better shape if you do.
A:
Sure you can!
Django requires minimal knowledge about using python from the command line, but if you're comfortable with that, then there shouldn't be an issue. Django has excellent documentation and a good tutorial aimed at beginners that does not expect you to be a high-level Python programmer.
Here's the link to the beginner's tutorial for Django: http://docs.djangoproject.com/en/dev/intro/tutorial01/
A:
I tried starting just by going through the Django tutorial, which got me going fast, but without enough Python knowledge, I got stuck when starting to write my own first app. Python terms like "tuples", "lists", and "dictionaries" were new to me and I didn't have any background to understand how and why to use them.
Spending time to go through the free Google Python Class was well worth it and made many things clear. Otherwise, too much of what's in Django will seem like magic and you'll get stuck as soon as you need to write some functions to manipulate your data.
In short, I found that I could learn Django & Python concurrently, but not just by focusing on Django alone. Besides, learning Python is fun in itself and won't take you more than a day or two to learn the basics. I liked the Google class because it has video lectures and good exercises that focus on the practical use of Python.
Good luck!
A:
Starting from Django it's good way to learn Python in fact. Django allows you to do nice things in a short time, which might be good motivation to dive into that language.
| Can we learn Django for a python beginner? | Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
| [
"Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once.\nPython's a pretty easy language to pick up too. Just have to get used to the significant w... | [
9,
6,
2,
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003234402_django_python.txt |
Q:
Python Plugin for XCode
I'm searching for a Xcode plugin to develop Python applications on Mac OS X platform. Can you give me some links please ? That will be very kind of you.
Cordially, Vynile.
A:
XCode can create Cocoa-Python application projects by default.
Why do you want a plugin?
EDIT
It seems Apple removed (since XCode 3.2) the project templates for third-party languages, like Python.
So on a fresh XCode installation, they are not available.
You can still get them from here: http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-xcode/
The templates needs to be installed in /Developer/Library/Xcode/Project Templates/
| Python Plugin for XCode | I'm searching for a Xcode plugin to develop Python applications on Mac OS X platform. Can you give me some links please ? That will be very kind of you.
Cordially, Vynile.
| [
"XCode can create Cocoa-Python application projects by default.\nWhy do you want a plugin?\nEDIT\nIt seems Apple removed (since XCode 3.2) the project templates for third-party languages, like Python.\nSo on a fresh XCode installation, they are not available.\nYou can still get them from here: http://svn.red-bean.c... | [
3
] | [] | [] | [
"python",
"xcode"
] | stackoverflow_0003237674_python_xcode.txt |
Q:
How to create decorator for lazy initialization of a property
I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example:
def SomeClass(object):
@LazilyInitializedProperty
def foo(self):
print "Now initializing"
return 5
>>> x = SomeClass()
>>> x.foo
Now initializing
5
>>> x.foo
5
My idea was to write a custom decorator for this. So i started, and this is how far I came:
class LazilyInitializedProperty(object):
def __init__(self, function):
self._function = function
def __set__(self, obj, value):
raise AttributeError("This property is read-only")
def __get__(self, obj, type):
# problem: where to store the value once we have calculated it?
As you can see, I do not know where to store the cached value. The simplest solution seems to be to just maintain a dictionary, but I am wondering if there is a more elegant solution for this.
EDIT Sorry for that, I forgot to mention that I want the property to be read-only.
A:
Denis Otkidach's CachedAttribute is a method decorator which makes attributes lazy (computed once, accessible many). To make it also read-only, I added a __set__ method. To retain the ability to recalculate (see below) I added a __delete__ method:
class ReadOnlyCachedAttribute(object):
'''Computes attribute value and caches it in the instance.
Source: Python Cookbook
Author: Denis Otkidach https://stackoverflow.com/users/168352/denis-otkidach
This decorator allows you to create a property which can be computed once and
accessed many times. Sort of like memoization
'''
def __init__(self, method, name=None):
self.method = method
self.name = name or method.__name__
self.__doc__ = method.__doc__
def __get__(self, inst, cls):
if inst is None:
return self
elif self.name in inst.__dict__:
return inst.__dict__[self.name]
else:
result = self.method(inst)
inst.__dict__[self.name]=result
return result
def __set__(self, inst, value):
raise AttributeError("This property is read-only")
def __delete__(self,inst):
del inst.__dict__[self.name]
For example:
if __name__=='__main__':
class Foo(object):
@ReadOnlyCachedAttribute
# @read_only_lazyprop
def bar(self):
print 'Calculating self.bar'
return 42
foo=Foo()
print(foo.bar)
# Calculating self.bar
# 42
print(foo.bar)
# 42
try:
foo.bar=1
except AttributeError as err:
print(err)
# This property is read-only
del(foo.bar)
print(foo.bar)
# Calculating self.bar
# 42
One of the beautiful things about CachedAttribute (and
ReadOnlyCachedAttribute) is that if you del foo.bar, then the next time you
access foo.bar, the value is re-calculated. (This magic is made possible by
the fact that del foo.bar removes 'bar' from foo.__dict__ but the property
bar remains in Foo.__dict__.)
If you don't need or don't want this ability to recalculate,
then the following (based on Mike Boers' lazyprop) is a simpler way to make a read-only lazy property.
def read_only_lazyprop(fn):
attr_name = '_lazy_' + fn.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
@_lazyprop.setter
def _lazyprop(self,value):
raise AttributeError("This property is read-only")
return _lazyprop
| How to create decorator for lazy initialization of a property | I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example:
def SomeClass(object):
@LazilyInitializedProperty
def foo(self):
print "Now initializing"
return 5
>>> x = SomeClass()
>>> x.foo
Now initializing
5
>>> x.foo
5
My idea was to write a custom decorator for this. So i started, and this is how far I came:
class LazilyInitializedProperty(object):
def __init__(self, function):
self._function = function
def __set__(self, obj, value):
raise AttributeError("This property is read-only")
def __get__(self, obj, type):
# problem: where to store the value once we have calculated it?
As you can see, I do not know where to store the cached value. The simplest solution seems to be to just maintain a dictionary, but I am wondering if there is a more elegant solution for this.
EDIT Sorry for that, I forgot to mention that I want the property to be read-only.
| [
"Denis Otkidach's CachedAttribute is a method decorator which makes attributes lazy (computed once, accessible many). To make it also read-only, I added a __set__ method. To retain the ability to recalculate (see below) I added a __delete__ method:\nclass ReadOnlyCachedAttribute(object): \n '''Computes attrib... | [
15
] | [] | [] | [
"decorator",
"descriptor",
"lazy_initialization",
"python"
] | stackoverflow_0003237678_decorator_descriptor_lazy_initialization_python.txt |
Q:
How to update document's metadata in Sharepoint? (Linux -> WebServices -> Sharepoint)
I managed to upload a file (crud PUT khe khe :) from Linux to Sharepoint.
The absolute path of the file is:
http://myhost/mysite/reports/2010-04-13/file.txt
Now, I'm trying to add some metadata to the file:
from suds.transport.https import WindowsHttpAuthenticated
url='http://myhost/mysite/_vti_bin/lists.asmx?WSDL'
n=WindowsHttpAuthenticated(username='me',password='password')
from suds.client import Client
c=Client(url,transport=n)
xml="""<Batch OnError='Continue' PreCalc='' ListVersion='0'>
<Method ID='1' Cmd='Update'>
<Field Name='ID'/>
<Field Name='FileRef'>%s</Field>
<Field Name='Jurisdiction'>%s</Field>
</Method>
</Batch>"""
fn = 'http://myhost/mysite/reports/2010-04-13/file.txt'
print c.service.UpdateListItems('reports',xml % (fn,'UK'))
The code returns:
soap:Server
... and nothing happens.
Am I missing anything? Is there any other way to do it?
Thanks
A:
Found it! :)
Instead of a plain text XML one must use DOM objects, something like this:
b = Element("Batch")
b.append(Attribute("OnError","Continue")).append(Attribute("ListVersion","3"))
bm= Element("Method")
bm.append(Attribute("ID","1")).append(Attribute("Cmd","Update"))
bm.append(Element("Field").append(Attribute("Name","ID")).setText(''))
bm.append(Element('Field').append(Attribute('Name','FileRef')).setText('http://.....'))
bm.append(Element('Field').append(Attribute('Name','Jurisdiction')).setText('UK'))
bm.append(Element('Field').append(Attribute('Name','Desk')).setText('Structured Equity Derivatives'))
bm.append(Element('Field').append(Attribute('Name','Business Area')).setText('Back Office'))
bm.append(Element('Field').append(Attribute('Name','Title')).setText('whatever'))
b.append(bm)
u = Element("ns1:updates")
u.append(b)
c.service.UpdateListItems("Reports",u)
Now it works perfect!
A:
As requested, a sample script that creates a new folder and uploads files into SharePoint site from linux command line.
The full SharePoint path looks like this:
http:// mysite / MyFirstSPSite / Reports / [current_iso_date] / [uploaded_file.txt]
#!/usr/bin/python2.4
import datetime as dt
import sys
from suds.transport.https import WindowsHttpAuthenticated
from suds.sax.element import Element
from suds.sax.element import Attribute
from suds import client
from ntlm import HTTPNtlmAuthHandler
import urllib2
import os.path
FOLDER = dt.date.today().strftime("%Y-%m-%d") #folder name that will be created
FNAME = sys.argv[1] #file name to upload
SITE = "http://mysite/MyFirstSPSite"
FURL = "%s/Reports/%s/%s" % (SITE,FOLDER,os.path.basename(FNAME))
USER = "uk\\user_name_goes_here" # AD user name
PASS = "password_goes_here"
def main():
wss_lists = client.Client("%s/_vti_bin/lists.asmx?WSDL" % SITE,transport=WindowsHttpAuthenticated(username=USER,password=PASS))
wss_dws = client.Client("%s/_vti_bin/dws.asmx?WSDL" % SITE,transport=WindowsHttpAuthenticated(username=USER,password=PASS))
wss_dws.service.CreateFolder("Reports/%s" % FOLDER)
print uploadReport(FURL,sys.argv[1])
wss_lists.service.UpdateListItems("Reports",getUpdatesElement(FURL,"Title goes here"))
def getUpdatesElement(furl,title = ''):
b = Element("Batch")
b.append(Attribute("OnError","Continue")).append(Attribute("ListVersion","3"))
bm= Element("Method")
bm.append(Attribute("ID","1")).append(Attribute("Cmd","Update"))
bm.append(Element("Field").append(Attribute("Name","ID")).setText(''))
bm.append(Element('Field').append(Attribute('Name','FileRef')).setText(furl))
bm.append(Element('Field').append(Attribute('Name','CustomProperty1')).setText('Value1'))
bm.append(Element('Field').append(Attribute('Name','CustomProperty2')).setText('Value2'))
bm.append(Element('Field').append(Attribute('Name','Title')).setText(title))
b.append(bm)
u = Element("ns1:updates")
u.append(b)
return u
def uploadReport(furl,fname):
pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
pm.add_password(None,'http://mysite',USER,PASS)
op = urllib2.build_opener(HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(pm))
#import pdb;pdb.set_trace()
fh = open(fname)
data = fh.read()
fh.close()
req = urllib2.Request(furl,data=data)
req.get_method = lambda: 'PUT'
req.add_header('Content-Type','text/csv')
r = op.open(req)
return r.read()
if __name__=="__main__": main()
Hope that helps :)
| How to update document's metadata in Sharepoint? (Linux -> WebServices -> Sharepoint) | I managed to upload a file (crud PUT khe khe :) from Linux to Sharepoint.
The absolute path of the file is:
http://myhost/mysite/reports/2010-04-13/file.txt
Now, I'm trying to add some metadata to the file:
from suds.transport.https import WindowsHttpAuthenticated
url='http://myhost/mysite/_vti_bin/lists.asmx?WSDL'
n=WindowsHttpAuthenticated(username='me',password='password')
from suds.client import Client
c=Client(url,transport=n)
xml="""<Batch OnError='Continue' PreCalc='' ListVersion='0'>
<Method ID='1' Cmd='Update'>
<Field Name='ID'/>
<Field Name='FileRef'>%s</Field>
<Field Name='Jurisdiction'>%s</Field>
</Method>
</Batch>"""
fn = 'http://myhost/mysite/reports/2010-04-13/file.txt'
print c.service.UpdateListItems('reports',xml % (fn,'UK'))
The code returns:
soap:Server
... and nothing happens.
Am I missing anything? Is there any other way to do it?
Thanks
| [
"Found it! :)\nInstead of a plain text XML one must use DOM objects, something like this:\nb = Element(\"Batch\")\nb.append(Attribute(\"OnError\",\"Continue\")).append(Attribute(\"ListVersion\",\"3\"))\nbm= Element(\"Method\")\nbm.append(Attribute(\"ID\",\"1\")).append(Attribute(\"Cmd\",\"Update\"))\nbm.append(Elem... | [
4,
3
] | [] | [] | [
"linux",
"python",
"sharepoint",
"web_services"
] | stackoverflow_0002629918_linux_python_sharepoint_web_services.txt |
Q:
How can I freeze a dual-mode (GUI and console) application using cx_Freeze?
I've developed a Python application that runs both in the GUI mode and the console mode. If any arguments are specified, it runs in a console mode else it runs in the GUI mode.
I've managed to freeze this using cx_Freeze. I had some problems hiding the black console window that would pop up with wxPython and so I modified my setup.py script like this:
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "simple_PyQt4",
version = "0.1",
description = "Sample cx_Freeze PyQt4 script",
executables = [Executable("PyQt4app.py", base = base)])
This works fine but now when I try to open up my console and run the executable from there, it doesn't output anything. I don't get any errors or messages so it seems that cx_Feeze is redirecting the stdout somewhere else.
Is is possible to get it to work with both mode? Nothing similar to this seems to be documented anywhere. :(
Thanks in advance.
Mridang
A:
I found this bit on this page:
Tip for the console-less version: If
you try to print anything, you will
get a nasty error window, because
stdout and stderr do not exist (and
the cx_freeze Win32gui.exe stub will
display an error Window). This is a
pain when you want your program to be
able to run in GUI mode and
command-line mode. To safely disable
console output, do as follows at the
beginning of your program:
try:
sys.stdout.write("\n")
sys.stdout.flush()
except IOError:
class dummyStream:
''' dummyStream behaves like a stream but does nothing. '''
def __init__(self): pass
def write(self,data): pass
def read(self,data): pass
def flush(self): pass
def close(self): pass
# and now redirect all default streams to this dummyStream:
sys.stdout = dummyStream()
sys.stderr = dummyStream()
sys.stdin = dummyStream()
sys.__stdout__ = dummyStream()
sys.__stderr__ = dummyStream()
sys.__stdin__ = dummyStream()
This way, if the program starts in
console-less mode, it will work even
if the code contains print statements.
And if run in command-line mode, it
will print out as usual. (This is
basically what I did in webGobbler,
too.)
A:
Raymond Chen has written about this. In short, it's not possible directly under Windows but there are some workarounds.
I'd suggest shipping two executables - a CLI and GUI one.
| How can I freeze a dual-mode (GUI and console) application using cx_Freeze? | I've developed a Python application that runs both in the GUI mode and the console mode. If any arguments are specified, it runs in a console mode else it runs in the GUI mode.
I've managed to freeze this using cx_Freeze. I had some problems hiding the black console window that would pop up with wxPython and so I modified my setup.py script like this:
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "simple_PyQt4",
version = "0.1",
description = "Sample cx_Freeze PyQt4 script",
executables = [Executable("PyQt4app.py", base = base)])
This works fine but now when I try to open up my console and run the executable from there, it doesn't output anything. I don't get any errors or messages so it seems that cx_Feeze is redirecting the stdout somewhere else.
Is is possible to get it to work with both mode? Nothing similar to this seems to be documented anywhere. :(
Thanks in advance.
Mridang
| [
"I found this bit on this page:\n\nTip for the console-less version: If\n you try to print anything, you will\n get a nasty error window, because\n stdout and stderr do not exist (and\n the cx_freeze Win32gui.exe stub will\n display an error Window). This is a\n pain when you want your program to be\n able t... | [
14,
2
] | [] | [] | [
"cx_freeze",
"python",
"wxpython"
] | stackoverflow_0002883205_cx_freeze_python_wxpython.txt |
Q:
Python webservice client
Can anyone make a webservice client in python from the following JAX-WS API?
https://109.231.73.12:8090/API?wsdl
As I'm running this of a virtual server it's self signed. Both the username and password are 'querty123'
We can get it to work in php just fine not python.
So a working example explaining how you managed to do it would be great
Thanks
A:
The suds library makes this a snap in Python:
>>> from suds.client import Client
>>> url = 'https://109.231.73.12:8090/API?wsdl'
>>> client = Client(url, username='qwerty123', password='qwerty123')
>>> client.service.addition(1, 2)
3
>>> client.service.hello('John')
HelloJohn
>>> client.service.xToThePowerOfy(2, 16)
18
>>> print client # automagic documentation
Suds ( https://fedorahosted.org/suds/ ) version: 0.4 (beta) build: R685-20100513
Service ( BasicService ) tns="http://service.basic.com/"
Prefixes (1)
ns0 = "http://service.basic.com/"
Ports (1):
(BasicPort)
Methods (3):
addition(xs:int x, xs:int y, )
hello(xs:string name, )
xToThePowerOfy(xs:int x, xs:int y, )
Types (6):
addition
additionResponse
hello
helloResponse
xToThePowerOfy
xToThePowerOfyResponse
| Python webservice client | Can anyone make a webservice client in python from the following JAX-WS API?
https://109.231.73.12:8090/API?wsdl
As I'm running this of a virtual server it's self signed. Both the username and password are 'querty123'
We can get it to work in php just fine not python.
So a working example explaining how you managed to do it would be great
Thanks
| [
"The suds library makes this a snap in Python:\n>>> from suds.client import Client\n>>> url = 'https://109.231.73.12:8090/API?wsdl'\n>>> client = Client(url, username='qwerty123', password='qwerty123')\n>>> client.service.addition(1, 2)\n3\n>>> client.service.hello('John')\nHelloJohn\n>>> client.service.xToThePower... | [
5
] | [] | [] | [
"python",
"web_services"
] | stackoverflow_0003237985_python_web_services.txt |
Q:
lazy event publish subscribe in python
I need an event messaging system in my google app engine application.
and i was referring to following python library.
http://pubsub.sourceforge.net/apidocs/concepts.html
my question is , is it must that the listener function i want to execute must be imported ( or exist otherwise) somewhere in to the execution path in order to run it on event ?
There are many lots of event, and I want to make it as lazy loaded as possible.
what could be the work around ?
is there any lazy event publish subscribe framework in python ?
A:
tipfy (an App-Engine specific micro framework) has lazy loading, but only for the specific "events" that are web requests your code is serving. Other web frameworks have it too, but tipfy is small and simple enough to easily study and imitate its sources for the purpose.
So, if you can't find a richer event framework that's exactly to your taste because of the "lazy loading" issue, you could pick one which requires registration/subscription of callable objects, and allow strings naming functions to be registered as well, just as tipfy does. The function thus named, of course, would be loaded just in time if an when needed to serve some event.
Let me exemplify with some simplified, hypothetical code. Say that you have an event framework that includes something like:
import collections
servers = collections.defaultdict(list)
def register(eventname, callable):
servers[eventname].append(callable)
def raise(eventname, *a, **k):
for s in servers.get(eventname, ()):
s(*a, **k)
The internals of any real-world event framework will be richer, of course, but something like this will be discernible at the lowest layers of it.
So, this requires the callable to be loaded at registration time... and yet, even without touching the internals of your framework, you can easily extend it. Consider:
import sys
class LazyCall(object):
def __init__(self, name):
self.name = name
self.f = None
def __call__(self, *a, **k):
if self.f is None:
modname, funname = self.name.rsplit('.', 1)
if modname not in sys.modules:
__import__(modname)
self.f = getattr(sys.modules[modname], funname)
self.f(*a, **k)
You'll want better error handling &c, of course, but this is the gist of it: wrap the string naming the function (e.g. 'package.module.func') into a wrapper object that knows how to lazily load it. Now, register(LazyCall('package.module.func')) will register, in the untouched framework, such a wrapper -- and lazy-load it on request.
This use case, btw, could be used as a reasonably good example of a Python idiom that some obstreperous fools claim, loudly and stridently, doesn't exist, or shouldn't exist, or something: an object dynamically changing its own class. Use cases for this idiom are to "cut the middleman" for objects that exist in one of two states, with the transition from the first to the second being irreversible. Here, the first state of a lazy caller is "I know the function's name but don't have the object", the second one is "I know the function object". Since moving from the first to the second is irreversible, you can cut the small overhead of testing every time (or the indirection overhead of the Strategy design pattern), if you wish:
class _JustCallIt(object):
def __call__(self, *a, **k):
self.f(*a, **k)
class LazyCall(object):
def __init__(self, name):
self.name = name
self.f = None
def __call__(self, *a, **k):
modname, funname = self.name.rsplit('.', 1)
if modname not in sys.modules:
__import__(modname)
self.f = getattr(sys.modules[modname], funname)
self.__class__ = _JustCallIt
self.f(*a, **k)
The gain here is modest, as it basically just cuts one if self.f is None: check from each call; but it's a real gain, without real downsides except for causing the previously named obstreperous fools to flail into their typical angry and mindless frenzy (if you count that as a downside).
Anyway, the implementation choice is up to you, not to me -- or, lucky you, to them;-).
As is one design choice: whether to patch register itself to directly accept string arguments (and wrap them as needed), basically as tipfy does, or go for the explicit wrapping at the registration site, leaving register (or subscribe or however it's called) pristine. I don't set much weight by the "explicit is better than implicit" mantra in this particular case, since something like
register(somevent, 'package.module.function')
is quite as explicit as
register(somevent, LazyCall('package.module.function'))
i.e., it is quite clear what's going on, and it's arguably cleaner / more readable.
Nevertheless, it is really nice that the explicit wrapping approach leaves the underlying framework untouched: wherever you could pass a function, you can now pass the name of that function (as a string naming packages, module, and the function itself), seamlessly. So, were I retrofitting existing frameworks, I'd go for the explicit approach.
Finally, if you want to register callables that are not functions but (for example) instances of certain classes, or bound methods of such instances, you can enrich LazyCall into variants such as LazyInstantiateAndCall &c for the purpose. The architecture becomes a tad more complex, of course (since you want ways to instantiate new objects and ways to identify already existing ones, for example), but by delegating that work to a well designed system of factories, it shouldn't be too bad. However, I'm not getting any deeper in such refinements, since this answer is already rather long, and anyway, in many cases, the simple "name a function" approach should suffice!-)
| lazy event publish subscribe in python | I need an event messaging system in my google app engine application.
and i was referring to following python library.
http://pubsub.sourceforge.net/apidocs/concepts.html
my question is , is it must that the listener function i want to execute must be imported ( or exist otherwise) somewhere in to the execution path in order to run it on event ?
There are many lots of event, and I want to make it as lazy loaded as possible.
what could be the work around ?
is there any lazy event publish subscribe framework in python ?
| [
"tipfy (an App-Engine specific micro framework) has lazy loading, but only for the specific \"events\" that are web requests your code is serving. Other web frameworks have it too, but tipfy is small and simple enough to easily study and imitate its sources for the purpose.\nSo, if you can't find a richer event fr... | [
1
] | [] | [] | [
"events",
"lazy_loading",
"publish_subscribe",
"python"
] | stackoverflow_0003237859_events_lazy_loading_publish_subscribe_python.txt |
Q:
Is it possible to repeat an iteration of a loop?
I have defined a for loop as follows which scans through a file made up of two columns, when it finds the keyword DEFINE_MENU the second column on this line refers to the title for a screen. The next instance of the keyword will define a title for a seperate screen and so on to the nth screen. At the moment the code is capable of defining the first menu title.
Is it possible, when I reach the second instance of the keyword DEFINE_MENU to repeat the loop for the same line, setting the title_flag = 0 thereby repeating itself, capturing the second menu title?
def getInfo():
title_flag = 0
number = 1
menus = {}
items = {}
title = None
file = open('some_file', 'r')
for line in file:
# Test for comments, if they exist pass and move on
if line[0] == '#':
continue
# Hop over blank lines
if re.search(r'^\s+$', line):
continue
# Find the line where the title is defined
if re.search('DEFINE_MENU', line) and title_flag == 0:
type, name = line.split()
title = name
title_flag = 1
continue
# If DEFINE_MENU is found and flag has been raised, this
# signifies a new menu definition so break.
if re.search('DEFINE_MENU', line) and title_flag == 1:
break
if re.search('PRIV', line):
(type, name, priv_holder, *description) = line.split()
else:
(type, name, *description) = line.split()
# If flag has been raised, the line must follow the definition
# of the menu, it must contains info regarding a menu item.
if title_flag == 1:
description = ' '.join(description)
items[str(number)] = name
number += 1
file.close()
menus[title] = items
return menus
Thank you for your input!
Tom
EDIT: First, apologies for the confusion caused. Perhaps I thought of the problem as being simpler than I thought and gave less information than required. I will delve deeper, the input file i am using is of the form:
# MENU TYPE NAME PRIV? DESCRIPTION
DEFINE_MENU CRAGINS
MENU menu_name1 This takes you to menu 1
MENU menu_name2 This takes you to menu 2
VARIABLE var_name1 Alter variable1
VARIABLE var_name2 PRIV Alter variable1
COMMAND command1 Perform command1
DEFINE_MENU MENU2
MENU menu_name3 This takes you to menu 3
MENU menu_name4 This takes you to menu 4
VARIABLE var_name3 Alter variable3
VARIABLE var_name4 PRIV Alter variable4
COMMAND command3 Perform command3
I had raised the flag as I further manipulate the data between the DEFINE_MENU calls. I have edited the code to include the full method that I have written.
The outcome is currently a dictionary where the key is the menu title and value is the another dictionary containing the menu items (values following the title) as follows:
{'title1': {'1': 'menu_name1', '3': 'var_name1', '2': 'menu_name2', '5': 'command1', '4': 'var_name2'}}
What I would like to have is a larger dictionary containing the menu titles as keys with the lowest level dictionary as the value. I understand that this is complicated so I'm sorry if it unclear, let me know if more information is required.
Thanks again
Tom
A:
If I understand your problem description correctly, you want to repeat the loop body (in certain cases) rather than "the iteration". If that's the case, one workable approach is to make the loop body into a possibly-recursive function, returning True if the loop is to break, False if it is to continue, as well as the possible title. For example, a most-direct (though probably not maximally elegant) function:
def body(line):
global title_flag
# skip over comments
if line[0] == '#':
return None, False
# skip over blank lines
if re.search(r'^\s+$', line):
return None, False
# Find the line where the title is defined
if 'DEFINE_MENU' in line and title_flag == 0:
type, name = line.split()
title = name
title_flag = 1
return title, body(line)
# If DEFINE_MENU is found and flag has been raised, this
# signifies a new menu definition.
if 'DEFINE_MENU' in line and title_flag == 1:
return None, True
and the main-line code becomes:
title_flag = 0
with open('some_file', 'r') as afile:
for line in afile:
thetitle, mustbreak = body(line)
if thetitle is not Note: title = thetitle
if mustbreak: break
BTW: do not name your own variables by usurping built-in names like file -- that's a separate subject;-). BTW2: I'm using with (assuming Python 2.6 or better, or 2.5 with an "import from the future") only because it's the right way to open and close a file;-). BTW3: I removed the re.search because it's wanton, inexplicable overkill when a simple in operator clearly does the same job.
I'm posting this code mostly to check in a concrete way whether I understood your specs, because, behavior-wise, this is definitely overkill -- there's no need (from the code you posted) to repeat the checks for comments and empty lines, nor the search for 'DEFINE_MENU", etc... you could just exit as soon as you've set the title (and body could then become inline code again).
But, I imagine that you have a reason for posting your question, i.e., that the simple behavior this has (and which could be had much more simply) is not optimal for you -- maybe by seeing the solution to your literal question you can point out what you want different than this, and then we can actually help you;-).
A:
Does this somewhat capture your logic?
menus = []
current_menu = None
for line in file:
# ...
# Find the line where the title is defined
if re.search('DEFINE_MENU', line):
if not current_menu is None:
menus.append(current_menu)
current_menu = Menu()
type, name = line.split()
current_menu.setTitle(name)
continue
Menu would be a helper class for storing all the information that belongs to one menu. Also, since it seems all your cases are mutually exclusive, consider using elif instead of continue.
A:
I'm not sure exactly what you're after, but would it be possible to just store your titles in a list?
titles = []
for line in infile: # don't shadow "file" keyword...
if "DEFINE_MENU" in line:
titles.append(line.split()[-1]) # append the last item
if you only want the first two titles, you could add an extra test:
if len(titles) == 2: break
| Is it possible to repeat an iteration of a loop? | I have defined a for loop as follows which scans through a file made up of two columns, when it finds the keyword DEFINE_MENU the second column on this line refers to the title for a screen. The next instance of the keyword will define a title for a seperate screen and so on to the nth screen. At the moment the code is capable of defining the first menu title.
Is it possible, when I reach the second instance of the keyword DEFINE_MENU to repeat the loop for the same line, setting the title_flag = 0 thereby repeating itself, capturing the second menu title?
def getInfo():
title_flag = 0
number = 1
menus = {}
items = {}
title = None
file = open('some_file', 'r')
for line in file:
# Test for comments, if they exist pass and move on
if line[0] == '#':
continue
# Hop over blank lines
if re.search(r'^\s+$', line):
continue
# Find the line where the title is defined
if re.search('DEFINE_MENU', line) and title_flag == 0:
type, name = line.split()
title = name
title_flag = 1
continue
# If DEFINE_MENU is found and flag has been raised, this
# signifies a new menu definition so break.
if re.search('DEFINE_MENU', line) and title_flag == 1:
break
if re.search('PRIV', line):
(type, name, priv_holder, *description) = line.split()
else:
(type, name, *description) = line.split()
# If flag has been raised, the line must follow the definition
# of the menu, it must contains info regarding a menu item.
if title_flag == 1:
description = ' '.join(description)
items[str(number)] = name
number += 1
file.close()
menus[title] = items
return menus
Thank you for your input!
Tom
EDIT: First, apologies for the confusion caused. Perhaps I thought of the problem as being simpler than I thought and gave less information than required. I will delve deeper, the input file i am using is of the form:
# MENU TYPE NAME PRIV? DESCRIPTION
DEFINE_MENU CRAGINS
MENU menu_name1 This takes you to menu 1
MENU menu_name2 This takes you to menu 2
VARIABLE var_name1 Alter variable1
VARIABLE var_name2 PRIV Alter variable1
COMMAND command1 Perform command1
DEFINE_MENU MENU2
MENU menu_name3 This takes you to menu 3
MENU menu_name4 This takes you to menu 4
VARIABLE var_name3 Alter variable3
VARIABLE var_name4 PRIV Alter variable4
COMMAND command3 Perform command3
I had raised the flag as I further manipulate the data between the DEFINE_MENU calls. I have edited the code to include the full method that I have written.
The outcome is currently a dictionary where the key is the menu title and value is the another dictionary containing the menu items (values following the title) as follows:
{'title1': {'1': 'menu_name1', '3': 'var_name1', '2': 'menu_name2', '5': 'command1', '4': 'var_name2'}}
What I would like to have is a larger dictionary containing the menu titles as keys with the lowest level dictionary as the value. I understand that this is complicated so I'm sorry if it unclear, let me know if more information is required.
Thanks again
Tom
| [
"If I understand your problem description correctly, you want to repeat the loop body (in certain cases) rather than \"the iteration\". If that's the case, one workable approach is to make the loop body into a possibly-recursive function, returning True if the loop is to break, False if it is to continue, as well ... | [
2,
0,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0003238080_for_loop_python.txt |
Q:
Using Django's memcache API on Dynamically created models
So I have a function which creates a dynamic model. I accomplish this in a way very similar to AuditTrail (see django wiki).
Sample of code is here:
https://gist.github.com/0212845ae00891efe555
Is there any way I can make a dynamically-generated class pickle-able? Ideally something thats not a crazy monkeypatch/hack?
A:
I am aware of the problem where pickle can't store a generated or dynamic class. I solved this by rigging in my dynamic type into the modules dict like so:
new_class = type(name, (models.Model,), attrs)
mod = sys.modules[new_class.__module__]
mod.__dict__[new_class.__name__] = new_class
It's FAR from a clean or elegant solution, so if someone can think of a more django-friendly way to make this happen, I am all ears. However, the above code does work.
A:
The reason there aren't answers for this is because the answer is likely hackish. I don't think you can unpickle an object in Python without knowing the structure of the class on the receiving end without some sort of hackish solution. A big reason pickle doesn't support it is probably because it's a fantastic way to introduce malicious code into your application.
http://www.mofeel.net/871-comp-lang-python/2898.aspx explains a bit why dynamically created classes can't be unpickled.
In every case, I've either just serialized a dictionary of the attributes of the object using the dict method, or just figured out some awful work around. I hope you come up with something better.
Good Luck!
| Using Django's memcache API on Dynamically created models | So I have a function which creates a dynamic model. I accomplish this in a way very similar to AuditTrail (see django wiki).
Sample of code is here:
https://gist.github.com/0212845ae00891efe555
Is there any way I can make a dynamically-generated class pickle-able? Ideally something thats not a crazy monkeypatch/hack?
| [
"I am aware of the problem where pickle can't store a generated or dynamic class. I solved this by rigging in my dynamic type into the modules dict like so:\nnew_class = type(name, (models.Model,), attrs)\nmod = sys.modules[new_class.__module__]\nmod.__dict__[new_class.__name__] = new_class\n\nIt's FAR from a clean... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"memcached",
"pickle",
"python"
] | stackoverflow_0002966957_django_django_models_memcached_pickle_python.txt |
Q:
Basic SSL Server Using Twisted Not Responding
I am currently trying to pull together a basic SSL server in twisted. I pulled the following example right off their website:
from twisted.internet import ssl, reactor
from twisted.internet.protocol import Factory, Protocol
class Echo(Protocol):
def dataReceived(self, data):
"""As soon as any data is received, write it back."""
print "dataReceived: %s" % data
self.transport.write(data)
if __name__ == '__main__':
factory = Factory()
factory.protocol = Echo
print "running reactor"
reactor.listenSSL(8080, factory,
ssl.DefaultOpenSSLContextFactory(
"./test/privatekey.pem", "./test/cacert.pem"))
reactor.run()
I then tried to hit this server using firefox by setting the url to https://localhost:8080 yet I receive no response. I do, however, see the data arriving at the server. Any ideas why I'm not getting a response?
A:
You're not sending an http header back to the browser, and you're not closing the connection
A:
You've implemented an SSL echo server here, not an HTTPS server. Use the openssl s_client command to test it interactively, not firefox (or any other HTTP client, for that matter).
| Basic SSL Server Using Twisted Not Responding | I am currently trying to pull together a basic SSL server in twisted. I pulled the following example right off their website:
from twisted.internet import ssl, reactor
from twisted.internet.protocol import Factory, Protocol
class Echo(Protocol):
def dataReceived(self, data):
"""As soon as any data is received, write it back."""
print "dataReceived: %s" % data
self.transport.write(data)
if __name__ == '__main__':
factory = Factory()
factory.protocol = Echo
print "running reactor"
reactor.listenSSL(8080, factory,
ssl.DefaultOpenSSLContextFactory(
"./test/privatekey.pem", "./test/cacert.pem"))
reactor.run()
I then tried to hit this server using firefox by setting the url to https://localhost:8080 yet I receive no response. I do, however, see the data arriving at the server. Any ideas why I'm not getting a response?
| [
"You're not sending an http header back to the browser, and you're not closing the connection\n",
"You've implemented an SSL echo server here, not an HTTPS server. Use the openssl s_client command to test it interactively, not firefox (or any other HTTP client, for that matter).\n"
] | [
2,
1
] | [] | [] | [
"python",
"ssl",
"twisted"
] | stackoverflow_0003237675_python_ssl_twisted.txt |
Q:
python introspection - how to detect the object i am in
Suppose I have a free function which has been called from a class method. Is there a way for me to introspect the call stack in the free function and determine what object called me?
def foo(arg1) :
s = ? #Introspect call stack and determine what object called me
# Do something with s
Thanks!
A:
There isn't really the concept of "a calling object". You can introspect the stack and find if your calling function has a first argument named self, I guess -- if you're called directly from a normally-coded instance method (absolutely not a class method as you say... I imagine you're just horribly mis-speaking, because the very purpose of a classmethod is to not have "an object", i.e. an instance, involved!-), that should detect that.
The inspect module offers you the tools for advanced introspection (recommended only for debugging and development purposes, never for "actual production use"!!!). However, note that even tracing the function is not trivial: you get stack frames which point to the code object (which doesn't point back to the function).
Still, it can be arranged, because there are pseudo-dicts of local variables also pointed from stack frames, and arguments are local variables, so what you're looking for is an entry in the local variables of your caller's stack frame that is named self (and in addition of course you need a lot of optimism and a smidgeon of luck as nobody forces your caller to be coded sensibly -- the argument normally named self could be named otherwise, and then you're in trouble;-).
| python introspection - how to detect the object i am in | Suppose I have a free function which has been called from a class method. Is there a way for me to introspect the call stack in the free function and determine what object called me?
def foo(arg1) :
s = ? #Introspect call stack and determine what object called me
# Do something with s
Thanks!
| [
"There isn't really the concept of \"a calling object\". You can introspect the stack and find if your calling function has a first argument named self, I guess -- if you're called directly from a normally-coded instance method (absolutely not a class method as you say... I imagine you're just horribly mis-speakin... | [
2
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0003238673_introspection_python.txt |
Q:
Documenting public global functions with epydoc
I have a module containing multiple global functions, and a global variable. The variable and some of the functions follow the 'private' naming convention for Python, with a leading underscore for the name. The other functions are intended to be public, and do not have a leading underscore.
I have declared __all__, with a list of my public function names, at the beginning of my file.
When trying to generate documentation for this module using epydoc, epydoc is considering everything in the module as private. And, since I'm using the --no-private flag, this means that the output only shows the documentation on the module itself, not the elements of the module or their individual documentation.
If I don't use the --no-private flag with epydoc, everything gets documented. But I don't want the private things there. Here's the kicker: If I comment out my __all__, epydoc correctly documents only the public elements of my module.
I'm a relative Python newbie, but as I understand it, __all__ is meant to keep you out of trouble when you import other modules and then other modules import yours, and for trying to keep a tighter lid on things when everything is technically public, so long as you know the name of what you're trying to access. Omitting __all__ can lead to Bad Things™, or so I'm told. At the same time, epydoc claims right and left that it honors __all__ for deciding what is public and what isn't.
Is it that I'm using epydoc wrong, assuming incorrectly about the usage of __all__ in my code, or a bug in epydoc? (I've already resolved one error handling bug in epydoc which is apparently caused by newer versions of docutils.)
A:
This problem disappears when using epydoc to document more than one file. It seems to be a bug in epydoc, but it's easily worked around, so long as you have an actual package to document, rather than a single module.
| Documenting public global functions with epydoc | I have a module containing multiple global functions, and a global variable. The variable and some of the functions follow the 'private' naming convention for Python, with a leading underscore for the name. The other functions are intended to be public, and do not have a leading underscore.
I have declared __all__, with a list of my public function names, at the beginning of my file.
When trying to generate documentation for this module using epydoc, epydoc is considering everything in the module as private. And, since I'm using the --no-private flag, this means that the output only shows the documentation on the module itself, not the elements of the module or their individual documentation.
If I don't use the --no-private flag with epydoc, everything gets documented. But I don't want the private things there. Here's the kicker: If I comment out my __all__, epydoc correctly documents only the public elements of my module.
I'm a relative Python newbie, but as I understand it, __all__ is meant to keep you out of trouble when you import other modules and then other modules import yours, and for trying to keep a tighter lid on things when everything is technically public, so long as you know the name of what you're trying to access. Omitting __all__ can lead to Bad Things™, or so I'm told. At the same time, epydoc claims right and left that it honors __all__ for deciding what is public and what isn't.
Is it that I'm using epydoc wrong, assuming incorrectly about the usage of __all__ in my code, or a bug in epydoc? (I've already resolved one error handling bug in epydoc which is apparently caused by newer versions of docutils.)
| [
"This problem disappears when using epydoc to document more than one file. It seems to be a bug in epydoc, but it's easily worked around, so long as you have an actual package to document, rather than a single module.\n"
] | [
3
] | [] | [] | [
"documentation_generation",
"epydoc",
"python"
] | stackoverflow_0003231938_documentation_generation_epydoc_python.txt |
Q:
Making QProgressDialog update, also value does not change
I have a progress which I "mintor" with a QProgessDialog in PyQt4. Basicly, I have a loop like this:
while progressThread.isRunning():
self.progressDialog.setRange(0, self.progressTotal_)
self.progressDialog.setValue(self.progress_)
del self.progressDialog
The progressThread upades the variables self.progessTotal_ and self.progress_
This works pretty well, when the value of progress_ changes constantly.
But for some task, this is not the case (because the progress report is just not that detailed).
The result is, the progressDialog showing a gray window until something changes. Can I insert something in the while loop, that forces the progressDialog to upadate also nothing changes?
Thanks!
nathan
A:
You should connect an update signal from your thread to the progress dialog. You're blocking the UI thread with your loop. You could add a QApplication::processEvents call in the loop, but just don't block the UI thread and you'll be fine.
| Making QProgressDialog update, also value does not change | I have a progress which I "mintor" with a QProgessDialog in PyQt4. Basicly, I have a loop like this:
while progressThread.isRunning():
self.progressDialog.setRange(0, self.progressTotal_)
self.progressDialog.setValue(self.progress_)
del self.progressDialog
The progressThread upades the variables self.progessTotal_ and self.progress_
This works pretty well, when the value of progress_ changes constantly.
But for some task, this is not the case (because the progress report is just not that detailed).
The result is, the progressDialog showing a gray window until something changes. Can I insert something in the while loop, that forces the progressDialog to upadate also nothing changes?
Thanks!
nathan
| [
"You should connect an update signal from your thread to the progress dialog. You're blocking the UI thread with your loop. You could add a QApplication::processEvents call in the loop, but just don't block the UI thread and you'll be fine.\n"
] | [
0
] | [] | [] | [
"progressdialog",
"pyqt4",
"python"
] | stackoverflow_0003238927_progressdialog_pyqt4_python.txt |
Q:
Urllib quoting problem: dealing with â characters from a latin-1 database
I need to get an â character into a format that can be passed to a URL. I'm obtaining some names as a json list, and then passing them elsewhere.
result = json.load(urllib2.urlopen(LIST_URL), encoding='latin-1')
for item in result:
name = item["name"]
print name
print urllib2.quote(name.lower())
This produces a urllib error when the name is Siân:
Siân
Line 24 - print urllib2.quote(mp_name.lower())
/usr/lib/python2.6/urllib.py -- quote((s=u'si\xe2n', safe='/'))
KeyError(u'\xe2')
Please could anyone advise?
A:
quote() function requires str argument, not unicode. Use urllib2.quote(name.lower().encode('latin1')) (assuming your site accepts latin1 encoding).
| Urllib quoting problem: dealing with â characters from a latin-1 database | I need to get an â character into a format that can be passed to a URL. I'm obtaining some names as a json list, and then passing them elsewhere.
result = json.load(urllib2.urlopen(LIST_URL), encoding='latin-1')
for item in result:
name = item["name"]
print name
print urllib2.quote(name.lower())
This produces a urllib error when the name is Siân:
Siân
Line 24 - print urllib2.quote(mp_name.lower())
/usr/lib/python2.6/urllib.py -- quote((s=u'si\xe2n', safe='/'))
KeyError(u'\xe2')
Please could anyone advise?
| [
"quote() function requires str argument, not unicode. Use urllib2.quote(name.lower().encode('latin1')) (assuming your site accepts latin1 encoding).\n"
] | [
2
] | [] | [] | [
"encoding",
"python",
"urllib"
] | stackoverflow_0003238913_encoding_python_urllib.txt |
Q:
Python URLLib / URLLib2 POST
I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data:
data = urllib.urlencode({'q': 'Status'})
u = urllib2.urlopen('http://myserver/inout-tracker', data)
for line in u.readlines():
print line
Nothing special going on there. The problem I'm having is that, based on how I read the docs, this should perform a Post Request because I've provided the data parameter and that's not happening. I have this code in the index for that url:
if (!isset($_POST['q'])) { die ('No action specified'); }
echo $_POST['q'];
And every time I run my Python App I get the 'No action specified' text printed to my console. I'm going to try to implement it using the Request Objects as I've seen a few demos that include those, but I'm wondering if anyone can help me explain why I don't get a Post Request with this code. Thanks!
-- EDITED --
This code does work and Posts to my web page properly:
data = urllib.urlencode({'q': 'Status'})
h = httplib.HTTPConnection('myserver:8080')
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
h.request('POST', '/inout-tracker/index.php', data, headers)
r = h.getresponse()
print r.read()
I am still unsure why the urllib2 library doesn't Post when I provide the data parameter - to me the docs indicate that it should.
A:
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.
Doing a 302 will typically cause clients to convert a POST to a GET request.
| Python URLLib / URLLib2 POST | I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data:
data = urllib.urlencode({'q': 'Status'})
u = urllib2.urlopen('http://myserver/inout-tracker', data)
for line in u.readlines():
print line
Nothing special going on there. The problem I'm having is that, based on how I read the docs, this should perform a Post Request because I've provided the data parameter and that's not happening. I have this code in the index for that url:
if (!isset($_POST['q'])) { die ('No action specified'); }
echo $_POST['q'];
And every time I run my Python App I get the 'No action specified' text printed to my console. I'm going to try to implement it using the Request Objects as I've seen a few demos that include those, but I'm wondering if anyone can help me explain why I don't get a Post Request with this code. Thanks!
-- EDITED --
This code does work and Posts to my web page properly:
data = urllib.urlencode({'q': 'Status'})
h = httplib.HTTPConnection('myserver:8080')
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
h.request('POST', '/inout-tracker/index.php', data, headers)
r = h.getresponse()
print r.read()
I am still unsure why the urllib2 library doesn't Post when I provide the data parameter - to me the docs indicate that it should.
| [
"u = urllib2.urlopen('http://myserver/inout-tracker', data)\nh.request('POST', '/inout-tracker/index.php', data, headers)\n\nUsing the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.\nDoing a 302 will typically cause ... | [
47
] | [] | [] | [
"post",
"python",
"urllib",
"urllib2"
] | stackoverflow_0003238925_post_python_urllib_urllib2.txt |
Q:
Can Ironpython be used to run multiple Python Virtual Machine Instances in parallel?
Inspired from the game GunTactyx, where you write programs controlling fighting robots. Guntactyx used the Small language, that later is called Pawn.
I am looking into using Python as the scripting language.
My concerns are:
Interfacing to C# The scripts
should interface into C# through
simple functions, doing stuff like
scanning for enemies, rotating and
firing. I guess each function should
be delayed, so they would take x ms
to return.
Bad programs. The system should
be tolerant to infinite loops or
crashes. I would like each virtual
machine to be given X ticks to
execute at a time.
Limited memory usage Scripts
should not be allowed to use
unlimited usage. I would like some
sort of cap.
Probably alot of other problems
I would like to end up with something in this "pseudo" style.
robots = a list of robots
while(1)
foreach robot in robots
robot.tick()
gameworld.update()
A:
The answer to your subject question is yes, you can run multiple interpreters in parallel. Generally each script will run in its own ScriptScope, but you can also use isolated ScriptEngines if necessary.
You can inject variables/functions into a script's scope before running it using scope.SetVariable.
Your best bet is to run the Python code on a separate thread and watch it; if it takes too long to return, interrupt the thread. (this is tricky to get right, but that's a different question)
I'm not sure that can enforced easily. It may be possible if you run the scripts in a different AppDomain or process, but that's a lot of extra work for minimal gain.
Just ask!
| Can Ironpython be used to run multiple Python Virtual Machine Instances in parallel? | Inspired from the game GunTactyx, where you write programs controlling fighting robots. Guntactyx used the Small language, that later is called Pawn.
I am looking into using Python as the scripting language.
My concerns are:
Interfacing to C# The scripts
should interface into C# through
simple functions, doing stuff like
scanning for enemies, rotating and
firing. I guess each function should
be delayed, so they would take x ms
to return.
Bad programs. The system should
be tolerant to infinite loops or
crashes. I would like each virtual
machine to be given X ticks to
execute at a time.
Limited memory usage Scripts
should not be allowed to use
unlimited usage. I would like some
sort of cap.
Probably alot of other problems
I would like to end up with something in this "pseudo" style.
robots = a list of robots
while(1)
foreach robot in robots
robot.tick()
gameworld.update()
| [
"The answer to your subject question is yes, you can run multiple interpreters in parallel. Generally each script will run in its own ScriptScope, but you can also use isolated ScriptEngines if necessary.\n\nYou can inject variables/functions into a script's scope before running it using scope.SetVariable.\nYour be... | [
1
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0003237909_ironpython_python.txt |
Q:
How to suppress carriage return after a variable?
Don't flame but I'm still a python newbie. I need to suppress the carriage return after I display a variable.
data = """
[virtual_machines: %s]
\taddress %s.domain.com
""" % (line, line)
fg = file('munin.txt', 'a')
fg.write(stuff)
When printing this out, it creates a new line after the variable gets printed. I tried using %r but that displays the "\n" code.
Edit: I'm actually trying to write it into another file.
A:
If I understand your question correctly, you are seeing a new-line after the %s. It looks like line may have a newline in it, in which case you can do line.strip() to remove all whitespace around it:
... " % (line.strip(), line.strip())
or
... " % (line.strip(), ) * 2
If you are seeing an unwanted newline at the end of the whole thing, it is because you have a newline in your multi-line string and should refer to Jared Updike's answer.
A:
data = """
[virtual_machines: %s]
\taddress %s.domain.com""" % (line, line)
A:
How are you printing this out?
If you are using print, simply append a trailing comma:
print data,
which will suppress the newline.
| How to suppress carriage return after a variable? | Don't flame but I'm still a python newbie. I need to suppress the carriage return after I display a variable.
data = """
[virtual_machines: %s]
\taddress %s.domain.com
""" % (line, line)
fg = file('munin.txt', 'a')
fg.write(stuff)
When printing this out, it creates a new line after the variable gets printed. I tried using %r but that displays the "\n" code.
Edit: I'm actually trying to write it into another file.
| [
"If I understand your question correctly, you are seeing a new-line after the %s. It looks like line may have a newline in it, in which case you can do line.strip() to remove all whitespace around it:\n... \" % (line.strip(), line.strip())\n\nor\n ... \" % (line.strip(), ) * 2\n\nIf you are seeing an unwanted newl... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003240017_python.txt |
Q:
IOError: [Errno 22] Invalid Argument with clock() being passed in
I have not had much luck hunting for finding a good explanation of what invalid argument errors are and what would cause them.
My current sample I am working with is
import sys
mylog="mylog.log"
sys.stdout = open(mylog,'w')
#lots of code
#.
#.
#.
#End of lots of code
from time import clock
print "blablabla",clock()
I receive an IOError Invalid Argument error on the clock line. I have also tried
print "blablabla\t%s"%clock()
Any information about this error would be great help. Those lines work perfectly fine on short runs, it just after running the code for a while it breaks. I have tried to setting the buffer size to something low like 45-100 lines.
A:
I can't reproduce this exact problem on my own computer, so I can't give specific advice, but here is some general commentary on how to debug this sort of thing.
When you see "Invalid argument" in an IOError or OSError exception from python, that means the interpreter tried to make a system call, which failed and set errno to the code EINVAL. (Tangentially, python really shouldn't print the numeric values for errno codes - the symbolic names are standardized but the numbers aren't.) The first thing you need to do is find out which system call it was, and the easiest way to do that is run your program under the strace utility, like this:
$ strace -f -o strace.log python yourscript.py [arguments...]
Wait for it to fail, then search the file strace.log for "-1 E" (exactly that string). You will find something like this:
times({tms_utime=162, tms_stime=123, tms_cutime=0, tms_cstime=0}) = 1718279979
write(1, "2.85\n", 5) = -1 EINVAL (Invalid argument)
You then read the man page for the system call that failed ("man 2 write" in this case) and look for the errno code name (EINVAL in this case), and see what it says has gone wrong.
In this case I strongly suspect you have found a bug in either the Python interpreter or the operating system. "Invalid argument" means what it says - one of the input arguments to the system call had an invalid value. You're not doing anything tricky in your script, so either the interpreter is messing up its system calls, or the kernel misunderstood what the interpreter wanted.
| IOError: [Errno 22] Invalid Argument with clock() being passed in | I have not had much luck hunting for finding a good explanation of what invalid argument errors are and what would cause them.
My current sample I am working with is
import sys
mylog="mylog.log"
sys.stdout = open(mylog,'w')
#lots of code
#.
#.
#.
#End of lots of code
from time import clock
print "blablabla",clock()
I receive an IOError Invalid Argument error on the clock line. I have also tried
print "blablabla\t%s"%clock()
Any information about this error would be great help. Those lines work perfectly fine on short runs, it just after running the code for a while it breaks. I have tried to setting the buffer size to something low like 45-100 lines.
| [
"I can't reproduce this exact problem on my own computer, so I can't give specific advice, but here is some general commentary on how to debug this sort of thing.\nWhen you see \"Invalid argument\" in an IOError or OSError exception from python, that means the interpreter tried to make a system call, which failed a... | [
3
] | [] | [] | [
"invalid_argument",
"ioerror",
"python",
"stdout"
] | stackoverflow_0003239883_invalid_argument_ioerror_python_stdout.txt |
Q:
multiple instances of django on a single domain
I'm looking for a good way to install multiple completely different Django projects on the same server using only a single domain name. The point is that I want to browse to something like:
http://192.168.0.1/gallery/ # a Django photo gallery project
http://192.168.0.1/blog/ # a blogging project
This way, I can develop and test multiple django projects on the same server by just referring to different URLs. (note: I don't think this Django Sites module is what I am looking for because the projects need to be distinct). As an example, PHP kind of behaves in this way as I can install something like php-gallery and phpmyadmin on the same server, just with different URL paths.
Does anyone know of any good resources of how to setup multiple Django projects under multiple URLs on a single server using Apache (with either mod_python or mod_wsgi)? Things I'd be interested in knowing is how to setup the apache.conf, possible virtualenv setup, and changes to the urls.py to accommodate this. Most of the Django deployment examples that I see are for one application per domain or subdomain.
Any advice is much appreciated.
Thanks,
Joe
A:
I've been in situations where I couldn't use subdomains, and the way to handle this with Django is pretty simple actually.
Pretty much everything in your settings file will be just like a regular Django app, with the exception of making sure these settings include your project path:
MEDIA_URL = 'http://192.168.0.1/gallery/media/'
ADMIN_MEDIA_PREFIX = '/gallery/admin_media/'
SESSION_COOKIE_PATH = '/gallery'
LOGIN_REDIRECT_URL = '/gallery/'
LOGIN_URL = '/gallery/accounts/login/'
LOGOUT_URL = '/gallery/accounts/logout/'
The SESSION_COOKIE_PATH is critical to prevent all your apps on the same domain from rewriting each others cookies.
The above instructions should cover the Django side, but there's still more work to do on the web server side. For example, if you use apache+mod_wsgi you'll need to make sure each project has their own wsgi script that is loaded like this:
WSGIScriptAlias /gallery /path/to/gallery/apache/gallery.wsgi
Alias /gallery/media /path/to/gallery/media
Alias /gallery/admin_media /path/to/gallery/venv/lib/python2.6/site-packages/django/contrib/admin/media
etc.
A:
In your question, you seem to be using projects and apps interchangeably. They mean separate things in Django. A project includes the setup file, database configuration, and overall urlconf, and is what you want at the root of your domain. An app is an individual functional piece of code that (generally) does one task.
If you want to deploy multiple apps, you want to create a single project and copy each app into the project directory. If you look at the tutorial, you'll see how to include an app in the urlconf. Simply repeat that for each one, making sure that the regexes are correct.
The key point here is that you get apache working for your overall django project, and then you use Django's internal urlconf to set up where each app may be accessed. Don't try to run multiple projects under the root of the same url - that's almost certainly a sign that you're doing it wrong.
If you're referring to running multiple projects under a single domain, we solve this problem is with subdomains.
Since the Django projects we're building are (generally) designed to live at the root of the domain when they're actually deployed, if you use app1.example.com and app2 etc., you can test like you will be deploying, in the root of each domain. You can configure subdomains exactly as you would configure top level domains, and then moving to your final deploy is easy.
If you're trying to actually deploy applications like that, create a single overarching Django project and use the urlconfs to include each Django app at a different sub url.
A:
Others have covered use of multiple applications within one Django project. If however you meant projects and/or only have one application in each project, then the simple answer is to use a separate WSGIScriptAlias directive for each project if using mod_wsgi. Each such project may optionally be delegated to a mod_wsgi daemon process group so as to allow each to be separately restarted without restarting the whole of Apache, but daemon mode is an extra thing that can be done and not the solution itself.
A:
Let's get straight on the terminology.
Most examples you see on the web are for one Django project per domain. Each project can hold several applications.
From here on I'll assume you are referring to deploying several projects on a single domain. (Otherwise - your question is nullified).
This can easily be solved with proper deployment per directory (this depends on what deployment method you are using), and ensuring your URLs are not assuming that they exist on the domain root.
A:
Make multiple django projects, each with a single app (frontend for example) and use django's url mapping to do something like this:
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns('',
url(r'^/', include('myproj.frontend.urls')
)
I use this, and it comes off without a hitch.
If you're asking for a full-fledged tutorial/walkthrough on setting something like this up, I'm sorry I don't have that. I just followed along the Django documentation and came up with this.
A:
One approach is to deploy the applications to Apache running under mod_wsgi in daemon mode. Documentation can be found here: http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango
| multiple instances of django on a single domain | I'm looking for a good way to install multiple completely different Django projects on the same server using only a single domain name. The point is that I want to browse to something like:
http://192.168.0.1/gallery/ # a Django photo gallery project
http://192.168.0.1/blog/ # a blogging project
This way, I can develop and test multiple django projects on the same server by just referring to different URLs. (note: I don't think this Django Sites module is what I am looking for because the projects need to be distinct). As an example, PHP kind of behaves in this way as I can install something like php-gallery and phpmyadmin on the same server, just with different URL paths.
Does anyone know of any good resources of how to setup multiple Django projects under multiple URLs on a single server using Apache (with either mod_python or mod_wsgi)? Things I'd be interested in knowing is how to setup the apache.conf, possible virtualenv setup, and changes to the urls.py to accommodate this. Most of the Django deployment examples that I see are for one application per domain or subdomain.
Any advice is much appreciated.
Thanks,
Joe
| [
"I've been in situations where I couldn't use subdomains, and the way to handle this with Django is pretty simple actually.\nPretty much everything in your settings file will be just like a regular Django app, with the exception of making sure these settings include your project path:\nMEDIA_URL = 'http://192.168.0... | [
16,
6,
3,
2,
1,
1
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0003232349_apache_django_python.txt |
Q:
Python and HTML: Assign a variable to a submit button
I'm writing this to a text file which is then read in by my browser. How do I assign the variable "i[0]" to the to the "submit" button so it is passed to my edit_python script?
k.write('<table>')
for i in row:
k.write('<tr>')
k.write('<td><form action="edit_python" method="post" name="edit_python"><input type="submit" value="Submit" /><></FORM></td><td>'+i[0]+'</td><td>'+i[1]+'</td>')
k.write('</tr>')
k.write('</table>')
A:
Put it in a hidden input element. In this case, it will be assigned to the ivalue post request variable.
k.write('<table>')
for i in row:
k.write('<tr>')
k.write('<td><form action="edit_python" method="post" name="edit_python"><input type="hidden" name="ivalue" value="' + i[0] + '"/><input type="submit" value="Submit" /></form></td><td>'+i[0]+'</td><td>'+i[1]+'</td>')
k.write('</tr>')
k.write('</table>')
I cleaned up your HTML a bit too, what was this about before the end form tag?
<></FORM>
If you want a literal <> in your page, use <>. Also, the case of the tags should match for HTML, and should be lowercase for XHTML (which you appear to be using).
EDIT:
I'm writing this to a text file which is then read in by my browser
Also, you do realise the browser won't interpret Python? You need a web server set up correctly to do that.
A:
You want to pass the i[0] attribute to your edit_python script? I think you're looking for a hidden field. So you would modify your script to write out:
Also when using Python variables in strings, I recommend not using the method you did. Check out Python string formatting for some great examples.
I also modified your write method to use dictionary passing for the attributes, which works well when you are calling the same variable multiple times in a stirng.
k.write('<table>')
for i in row:
k.write('<tr>')
k.write('<td><form action="edit_python" method="post" name="edit_python">
<input type="hidden" name="some_attr" value="%(some_attr)s" />
<input type="submit" value="Submit" /></form>
</td><td>%(some_attr)s</td><td>%(some_other_attr)s</td>'
% {"some_attr": i[0], "some_other_attr": i[1]})
k.write('</tr>')
k.write('</table>')
| Python and HTML: Assign a variable to a submit button | I'm writing this to a text file which is then read in by my browser. How do I assign the variable "i[0]" to the to the "submit" button so it is passed to my edit_python script?
k.write('<table>')
for i in row:
k.write('<tr>')
k.write('<td><form action="edit_python" method="post" name="edit_python"><input type="submit" value="Submit" /><></FORM></td><td>'+i[0]+'</td><td>'+i[1]+'</td>')
k.write('</tr>')
k.write('</table>')
| [
"Put it in a hidden input element. In this case, it will be assigned to the ivalue post request variable.\nk.write('<table>')\n for i in row:\n k.write('<tr>')\n k.write('<td><form action=\"edit_python\" method=\"post\" name=\"edit_python\"><input type=\"hidden\" name=\"ivalue\" value=\"' + i[0] + ... | [
2,
2
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003240271_html_python.txt |
Q:
Recompiling Python to fix arrow keys in interactive mode issue
I am working in python 2.6 (installed alongside Python2.4.3 required for CentOS) and I am having issues with the arrow keys and backspace etc.
I compiled from source and I imagine the solution is to recompile after installing readline-devel as outlined in:
Seeing escape characters when pressing the arrow keys in python shell
Question is, I have a lot of modules installed and am worried of things breaking. Is it normal to be able to just recompile without breaking existing modules.
Thanks
A:
As long as you use the same compiler that was originally used, you should be fine, I think. Especially if you don't have any extensions to recompile, because those are what would be affected.
http://docs.python.org/release/2.6.5/install/index.html#building-extensions-tips-and-tricks
the same compiler and linker flags used to compile Python will also be used for compiling extensions.
I might have missed something, though, so...
| Recompiling Python to fix arrow keys in interactive mode issue | I am working in python 2.6 (installed alongside Python2.4.3 required for CentOS) and I am having issues with the arrow keys and backspace etc.
I compiled from source and I imagine the solution is to recompile after installing readline-devel as outlined in:
Seeing escape characters when pressing the arrow keys in python shell
Question is, I have a lot of modules installed and am worried of things breaking. Is it normal to be able to just recompile without breaking existing modules.
Thanks
| [
"As long as you use the same compiler that was originally used, you should be fine, I think. Especially if you don't have any extensions to recompile, because those are what would be affected.\nhttp://docs.python.org/release/2.6.5/install/index.html#building-extensions-tips-and-tricks\n\nthe same compiler and linke... | [
2
] | [] | [] | [
"python",
"python_module",
"readline"
] | stackoverflow_0003240516_python_python_module_readline.txt |
Q:
How to specify python interpreter on Windows
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6.
I know that it's possible to specify the interpreter in Unix #!/usr/bin/python2.6. But what if I use Windows? Does any way to specify the interpreter exist in Windows?
Edit: I want to be able to use both interpreters simultaneously.
A:
the shebang line:
#!/usr/bin/python2.6
... will be ignored in Windows.
In Windows, you must call the correct python interpreter directly (AFAIK). Normally, people add their Python version specific directory (c:\Python26) to their PATH (environment variable) so you can just type "python" at any command line and it will invoke the interpreter.
However, you can also call any specific interpreter you want.
for example,
on Windows I have both Python 2.6 and 3.1 installed (residing in c:\Python26 and c:\Python31 respectively). I can run a script with each one like this:
c:\python26\python foo.py
or
c:\python31\python foo.py
A:
If you want to mix in the same runtime both 2.6 and 3.1 you may be interested in execnet.
Never tested directly, however
Edit: looking at you comments on another answer, I understood better the question
A:
Maybe "Open with..." + 'Remember my choice' in context menu of explorer?
A:
If you want to go back from Python 3 to Python 2 you could try 3to2 to convert your code back to Python 2. You can't easily mix Python 2 and 3 in the same program.
A:
If you go into Control Panel -> System -> Advanced -> Environment Variables, and then add Python 2.6 to the PATH variable (it's probably located at C:\Python26 or C:\Program Files\Python26) -- and make sure Python 3.1 isn't in it -- then if you type python at the command prompt, you'll get 2.6 instead. As for Explorer, you'll want to associate it by using the Open With... dialog. Browse to the path (probably C:\Python26\python.exe) and set it. Make sure you check to make it the default before you hit OK.
To add the to PATH variable, you'll have to add a ; on the end of the current PATH variable and then add the folder's path after it (remove 3.1 if needed). For example:
PATH="C:\Program Files\Emacs23\bin;C:\Cygwin\bin;C:\Python31"
would become:
PATH="C:\Program Files\Emacs23\bin;C:\Cygwin\bin;C:\Python26"
| How to specify python interpreter on Windows | My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6.
I know that it's possible to specify the interpreter in Unix #!/usr/bin/python2.6. But what if I use Windows? Does any way to specify the interpreter exist in Windows?
Edit: I want to be able to use both interpreters simultaneously.
| [
"the shebang line: \n#!/usr/bin/python2.6\n\n... will be ignored in Windows.\nIn Windows, you must call the correct python interpreter directly (AFAIK). Normally, people add their Python version specific directory (c:\\Python26) to their PATH (environment variable) so you can just type \"python\" at any command l... | [
5,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003236983_python.txt |
Q:
Issues with BeautifulSoup parsing
I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens?
import urllib2
from BeautifulSoup import BeautifulSoup
url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&mfr=&logon=&langid=FR&sort=0&page=1"
html = "".join(urllib2.urlopen(url).readlines())
print "-- HTML ------------------------------------------"
print html
print "-- BeautifulSoup ---------------------------------"
print BeautifulSoup(html).prettify()
The is the output produced by BeautifulSoup.
-- BeautifulSoup ---------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript">
<!--
function highlight(img) {
document[img].src = "/marketing/sony/images/en/" + img + "_on.gif";
}
function unhighlight(img) {
document[img].src = "/marketing/sony/images/en/" + img + "_off.gif";
}
//-->
</script>
Thanks!
UPDATE: I am using the following version, which appears to be the latest.
__author__ = "Leonard Richardson (leonardr@segfault.org)"
__version__ = "3.1.0.1"
__copyright__ = "Copyright (c) 2004-2009 Leonard Richardson"
__license__ = "New-style BSD"
A:
Try with version 3.0.7a as Łukasz suggested. BeautifulSoup 3.1 was designed to be compatible with Python 3.0 so they had to change the parser from SGMLParser to HTMLParser which seems more vulnerable to bad HTML.
From the changelog for BeautifulSoup 3.1:
"Beautiful Soup is now based on HTMLParser rather than SGMLParser, which is gone in Python 3. There's some bad HTML that SGMLParser handled but HTMLParser doesn't"
A:
Try lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup, so it might work better for you. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.
Ian Blicking agrees.
There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.
A:
BeautifulSoup isn't magic: if the incoming HTML is too horrible then it isn't going to work.
In this case, the incoming HTML is exactly that: too broken for BeautifulSoup to figure out what to do. For instance it contains markup like:
SCRIPT type=""javascript""
(Notice the double quoting.)
The BeautifulSoup docs contains a section what you can do if BeautifulSoup can't parse you markup. You'll need to investigate those alternatives.
A:
Samj: If I get things like
HTMLParser.HTMLParseError: bad end tag: u"</scr' + 'ipt>"
I just remove the culprit from markup before I serve it to BeautifulSoup and all is dandy:
html = urllib2.urlopen(url).read()
html = html.replace("</scr' + 'ipt>","")
soup = BeautifulSoup(html)
A:
I had problems parsing the following code too:
<script>
function show_ads() {
document.write("<div><sc"+"ript type='text/javascript'src='http://pagead2.googlesyndication.com/pagead/show_ads.js'></scr"+"ipt></div>");
}
</script>
HTMLParseError: bad end tag: u'', at line 26, column 127
Sam
A:
I tested this script on BeautifulSoup version '3.0.7a' and it returns what appears to be correct output. I don't know what changed between '3.0.7a' and '3.1.0.1' but give it a try.
A:
import urllib
from BeautifulSoup import BeautifulSoup
>>> page = urllib.urlopen('http://www.futureshop.ca/catalog/subclass.asp?catid=10607&mfr=&logon=&langid=FR&sort=0&page=1')
>>> soup = BeautifulSoup(page)
>>> soup.prettify()
In my case by executing the above statements, it returns the entire HTML page.
| Issues with BeautifulSoup parsing | I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens?
import urllib2
from BeautifulSoup import BeautifulSoup
url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&mfr=&logon=&langid=FR&sort=0&page=1"
html = "".join(urllib2.urlopen(url).readlines())
print "-- HTML ------------------------------------------"
print html
print "-- BeautifulSoup ---------------------------------"
print BeautifulSoup(html).prettify()
The is the output produced by BeautifulSoup.
-- BeautifulSoup ---------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript">
<!--
function highlight(img) {
document[img].src = "/marketing/sony/images/en/" + img + "_on.gif";
}
function unhighlight(img) {
document[img].src = "/marketing/sony/images/en/" + img + "_off.gif";
}
//-->
</script>
Thanks!
UPDATE: I am using the following version, which appears to be the latest.
__author__ = "Leonard Richardson (leonardr@segfault.org)"
__version__ = "3.1.0.1"
__copyright__ = "Copyright (c) 2004-2009 Leonard Richardson"
__license__ = "New-style BSD"
| [
"Try with version 3.0.7a as Łukasz suggested. BeautifulSoup 3.1 was designed to be compatible with Python 3.0 so they had to change the parser from SGMLParser to HTMLParser which seems more vulnerable to bad HTML.\nFrom the changelog for BeautifulSoup 3.1:\n\"Beautiful Soup is now based on HTMLParser rather than SG... | [
6,
3,
2,
2,
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0000601166_beautifulsoup_python.txt |
Q:
Authentication in Google App Engine: app.yaml vs. python code
I am writing a small app that uses the GAE. I have parts of my app that are for administrative use only. I have two options using login: admin option in the app.yaml or google.appengine.api.users.is_current_user_admin() in python code. The basic authentication is sufficient for my case.
Which solution is better?
The advantage of using app.yaml is that the python code is a bit cleaner. Plus it may be the case that app.yaml may be more efficient, since it can be handled in the server. (In worst case it is equal in terms of performance.) The only drawback is that I do not display a custom page, but I don't care to much for that.
I am unsure if my assertions are correct.
A:
I would say your assertions are correct. Let's say you have the following in your app.yaml:
- url: /admin/.*
script: admin.py
login: admin
If you want everything in admin.py to be restricted to administrators, the configuration above ought to be more performant: you can fail unauthorized requests without ever spinning up admin.py.
Checking users.is_current_user_admin() is useful when you want to define more granular logic and behavior. Perhaps you have a handler that should be available whether the user is an admin, a non-admin, or not logged in, you just need to check their current state so you can return the appropriate HTML.
A:
If you have handlers which are only accessible to admins, then app.yaml certainly seems like the easiest way to secure the pages those handlers expose.
However, if you have some handlers which serve both admin and non-admin views (e.g., your main.py), then you'll have to use something more fine-grained than app.yaml (e.g., google.appengine.api.users.is_current_user_admin()).
I'd expect performance to be roughly equivalent once your application is running (a negligible fraction of the time it takes to load your page).
| Authentication in Google App Engine: app.yaml vs. python code | I am writing a small app that uses the GAE. I have parts of my app that are for administrative use only. I have two options using login: admin option in the app.yaml or google.appengine.api.users.is_current_user_admin() in python code. The basic authentication is sufficient for my case.
Which solution is better?
The advantage of using app.yaml is that the python code is a bit cleaner. Plus it may be the case that app.yaml may be more efficient, since it can be handled in the server. (In worst case it is equal in terms of performance.) The only drawback is that I do not display a custom page, but I don't care to much for that.
I am unsure if my assertions are correct.
| [
"I would say your assertions are correct. Let's say you have the following in your app.yaml:\n- url: /admin/.*\n script: admin.py\n login: admin\n\nIf you want everything in admin.py to be restricted to administrators, the configuration above ought to be more performant: you can fail unauthorized requests without... | [
13,
2
] | [] | [] | [
"authentication",
"google_app_engine",
"python"
] | stackoverflow_0003240990_authentication_google_app_engine_python.txt |
Q:
set process name in mod_wsgi
I'm running a site by apache2.x with mod_wsgi 2.5, and python2.5. It is configured to run in multi-processes and each process only contains one thread.
When I read this post, I try to set the process name to PATH_INFO, but it doesn't work. My code is like:
import ctypes
libc = ctypes.CDLL('/lib/libc.so.6')
def application (environ, start_response):
libc.prctl(15, environ.get('PATH_INFO', 'WSGI'), 0, 0, 0);
# other codes
A:
If you are using mod_wsgi daemon mode, is there anything wrong with the display-name option to WSGIDaemonProcess. That option is precisely for changing the name of the process to a fixed value using setproctitle() or argv[0] assignment as believed works for specific platforms. See:
http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess
Note that it only makes sense to do this for daemon mode processes and not the Apache server processes themselves. Thus why is only available for WSGIDaemonProcess directive. It only makes sense to set it once on process start as well and not dynamically based on request.
| set process name in mod_wsgi | I'm running a site by apache2.x with mod_wsgi 2.5, and python2.5. It is configured to run in multi-processes and each process only contains one thread.
When I read this post, I try to set the process name to PATH_INFO, but it doesn't work. My code is like:
import ctypes
libc = ctypes.CDLL('/lib/libc.so.6')
def application (environ, start_response):
libc.prctl(15, environ.get('PATH_INFO', 'WSGI'), 0, 0, 0);
# other codes
| [
"If you are using mod_wsgi daemon mode, is there anything wrong with the display-name option to WSGIDaemonProcess. That option is precisely for changing the name of the process to a fixed value using setproctitle() or argv[0] assignment as believed works for specific platforms. See:\nhttp://code.google.com/p/modwsg... | [
3
] | [] | [] | [
"mod_wsgi",
"python"
] | stackoverflow_0003238010_mod_wsgi_python.txt |
Q:
Programmatically Uncheck a Checkbox in a wx.CheckListBox
Is there a method to uncheck a checkbox in a wx.CheckListBox as I need to implement an "uncheck all" button, can't seem to find anything... although there is number of methods for setting a checkbox/s.
A:
Try this:
for cb in mycblist.Checked:
mycblist.Check(cb, False)
A:
There is an optional "check" argument for Check() - see http://docs.wxwidgets.org/stable/wx_wxchecklistbox.html#wxchecklistboxcheck
Example: clb.Check(itemnum, check=False)
A:
Use void wxCheckListBox::Check Check(int item, bool check = true) to do the unchecking of each of the items. The item count should be available through the unsigned int wxControlWithItems::GetCount GetCount() const method (wxCheckListBox is derived from wxControlWithItems).
| Programmatically Uncheck a Checkbox in a wx.CheckListBox | Is there a method to uncheck a checkbox in a wx.CheckListBox as I need to implement an "uncheck all" button, can't seem to find anything... although there is number of methods for setting a checkbox/s.
| [
"Try this:\nfor cb in mycblist.Checked:\n mycblist.Check(cb, False)\n\n",
"There is an optional \"check\" argument for Check() - see http://docs.wxwidgets.org/stable/wx_wxchecklistbox.html#wxchecklistboxcheck\nExample: clb.Check(itemnum, check=False)\n",
"Use void wxCheckListBox::Check Check(int item, bool ch... | [
2,
1,
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003241273_python_user_interface_wxpython.txt |
Q:
Change package import name in python
I was wondering if it was possible to import a library in python, and completely change its name.
say i need to do :
import plop.blah.wii
but I want it to be recognized as foo.bar.yeah
something like
import plop.blah.wii as foo.bar.yeah
Any idea how can this be done ?
When unpickling an object, Python expects a library that I have under plop.blah.wii, and I can't change that name .. but the pickle wants it to be foo.bar.yeah .
Thanks a lot for your help. Sorry for the confusion. It's been confusing me for a while now ..
Martin
A:
Rather than aliasing the module, there's a way to more directly solve your problem. You can override the method used by the pickler to resolve globals to map the old module name to the new module name. The details are here.
| Change package import name in python | I was wondering if it was possible to import a library in python, and completely change its name.
say i need to do :
import plop.blah.wii
but I want it to be recognized as foo.bar.yeah
something like
import plop.blah.wii as foo.bar.yeah
Any idea how can this be done ?
When unpickling an object, Python expects a library that I have under plop.blah.wii, and I can't change that name .. but the pickle wants it to be foo.bar.yeah .
Thanks a lot for your help. Sorry for the confusion. It's been confusing me for a while now ..
Martin
| [
"Rather than aliasing the module, there's a way to more directly solve your problem. You can override the method used by the pickler to resolve globals to map the old module name to the new module name. The details are here.\n"
] | [
2
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003241379_import_python.txt |
Q:
How do i extract specific lines of data from a huge Excel sheet using Python?
I need to get specific lines of data that have certain key words in them (names) and write them to another file. The starting file is a 1.5 GB Excel file. I can't just open it up and save it as a different format. How should I handle this using python?
A:
I'm the author and maintainer of xlrd. Please edit your question to provide answers to the following questions. [Such stuff in SO comments is VERY hard to read]
How big is the file in MB? ["Huge" is not a useful answer]
What software created the file?
How much memory do you have on your computer?
Exactly what happens when you try to open the file using Excel? Please explain "I can open it partially".
Exactly what is the error message that you get when you try to open "C:\bigfile.xls" with your script using xlrd.open_workbook? Include the script that you ran, the full traceback, and the error message
What operating system, what version of Python, what version of xlrd?
Do you know how many worksheets there are in the file?
A:
It sounds to me like you have a spreadsheet that was created using Excel 2007 and you have only Excel 2003.
Excel 2007 can create worksheets with 1,048,576 rows by 16,384 columns while Excel 2003 can only work with 65,536 rows by 256 columns. Hence the reason you can't open the entire worksheet in Excel.
If the workbook is just bigger in dimension then xlrd should work for reading the file, but if the file is actually bigger than the amount of memory you have in your computer (which I don't think is the case here since you can open the file with EditPad lite) then you would have to find an alternate method because xlrd reads the entire workbook into memory.
Assuming the first case:
import xlrd
wb_path = r'c:\bigfile.xls'
output_path = r'c:\output.txt'
wb = xlrd.open(wb_path)
ws = wb.sheets()[0] # assuming you want to work with the first sheet in the workbook
with open(output_path, 'w') as output_file:
for i in xrange(ws.nrows):
row = [cell.value for cell in ws.row(i)]
# ... replace the following if statement with your own conditions ...
if row[0] == u'interesting':
output_file.write('\t'.join(row) + '\r\n')
This will give you a tab-delimited output file that should open in Excel.
Edit:
Based on your answer to John Machin's question 5, make sure there is a file called 'bigfile.xls' located in the root of your C drive. If the file isn't there, change the wb_path to the correct location of the file you want to open.
A:
I haven't used it, but xlrd looks like it does a good job reading Excel data.
A:
Your problem is that you are using Excel 2003 .. You need to use a more recent version to be able to read this file. 2003 will not open files bigger than 1M rows.
| How do i extract specific lines of data from a huge Excel sheet using Python? | I need to get specific lines of data that have certain key words in them (names) and write them to another file. The starting file is a 1.5 GB Excel file. I can't just open it up and save it as a different format. How should I handle this using python?
| [
"I'm the author and maintainer of xlrd. Please edit your question to provide answers to the following questions. [Such stuff in SO comments is VERY hard to read]\n\nHow big is the file in MB? [\"Huge\" is not a useful answer]\nWhat software created the file?\nHow much memory do you have on your computer?\nExactly w... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003241039_python.txt |
Q:
ValueError: need more than 1 value to unpack
Here's the line that throws this error
(x,neighbor) = random.sample(out_edge_list,1)
A:
You're asking for 1 unique random element. So you're getting back something like [5]. If the 5 goes into x, what goes into neighbor?
Perhaps you meant to ask for 2 elements?
(x, neighbor) = random.sample(out_edge_list, 2)
A:
Here the solution. I changed the line to
(x,neighbor) = random.sample(out_edge_list,1)[0]
| ValueError: need more than 1 value to unpack | Here's the line that throws this error
(x,neighbor) = random.sample(out_edge_list,1)
| [
"You're asking for 1 unique random element. So you're getting back something like [5]. If the 5 goes into x, what goes into neighbor?\nPerhaps you meant to ask for 2 elements?\n(x, neighbor) = random.sample(out_edge_list, 2)\n\n",
"Here the solution. I changed the line to \n(x,neighbor) = random.sample(out_edge_l... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0003241409_python.txt |
Q:
Send Raw hex data in jython udp packet
I'm experience with Java, but I have to integrate a java library into a co-workers python code. Enter jython, yay!
We are trying to send a UDP packet with a very specific data section.
We are building up the packet like so:
version = 0x0001
referenceNumber = 0x2323
bookID = byteArray('df82818293819dbafde818ef')
For easy of explanation assume byteArray takes in a string of hex digits and returns a byte array
We then build the packet:
packet = hex(version)
packet += hex(referenceNumber)
packet += bookID
and send it out the socket.
I know this is incorrect, the data types can't be right ,so the concat wont do the right thing. How do we build up this packet properly? The python documentation say that s.sendTo() takes a string? I think I want an alternative to s.sendTo() that takes a byte array.
We want the packet to arrive at the server with the udp data section looking like:
00 01 23 23 df 82 81 82 93 81 9d ba fd e8 18 ef
What is the proper approach to do this in python?
We are using wireshark to verify the packet arrives properly and right now the udp data section looks as if python converts each field as an ascii representation. For example, the referenceNumber field comes accross as the ascii values for the literal string '0x2323'. Which makes sense because s.sendTo() takes a string.
====================SOLUTION==============================
Yup, that does it... shows how new I am to python. For the curious, here is the code:
version = '0001'
referenceNumber = '2323'
packet = a2b_hex(version)
packet += a2b_hex(referenceNumber)
.. etc
then just
s.send(packet)
A:
Check out the binascii module.
| Send Raw hex data in jython udp packet | I'm experience with Java, but I have to integrate a java library into a co-workers python code. Enter jython, yay!
We are trying to send a UDP packet with a very specific data section.
We are building up the packet like so:
version = 0x0001
referenceNumber = 0x2323
bookID = byteArray('df82818293819dbafde818ef')
For easy of explanation assume byteArray takes in a string of hex digits and returns a byte array
We then build the packet:
packet = hex(version)
packet += hex(referenceNumber)
packet += bookID
and send it out the socket.
I know this is incorrect, the data types can't be right ,so the concat wont do the right thing. How do we build up this packet properly? The python documentation say that s.sendTo() takes a string? I think I want an alternative to s.sendTo() that takes a byte array.
We want the packet to arrive at the server with the udp data section looking like:
00 01 23 23 df 82 81 82 93 81 9d ba fd e8 18 ef
What is the proper approach to do this in python?
We are using wireshark to verify the packet arrives properly and right now the udp data section looks as if python converts each field as an ascii representation. For example, the referenceNumber field comes accross as the ascii values for the literal string '0x2323'. Which makes sense because s.sendTo() takes a string.
====================SOLUTION==============================
Yup, that does it... shows how new I am to python. For the curious, here is the code:
version = '0001'
referenceNumber = '2323'
packet = a2b_hex(version)
packet += a2b_hex(referenceNumber)
.. etc
then just
s.send(packet)
| [
"Check out the binascii module.\n"
] | [
1
] | [] | [] | [
"java",
"jython",
"python",
"sockets"
] | stackoverflow_0003241612_java_jython_python_sockets.txt |
Q:
Is there a reason that a ReferenceProperty might not generate a back-reference?
In my current project, I have two models, Version and Comment. There is a one-to-many relationship between the two; each Version can have many Comment and the Comment model has a ReferenceProperty to record which Version it belongs to:
class Comment(db.Model):
version = db.ReferenceProperty(version.Version, collection_name="comments")
The problem is that instances of Version are not getting a comments property as I would expect. According to the docs, I should get an automagical property on each Version that is a query that returns all Comment instances that have their version set to the Version instance in question. Doesn't seem to work for my code.
I know that the ReferenceProperty is set correctly, because I can get the Comments with this query:
comments = comment.Comment.all().filter('version = ', self).order('-added_on').fetch(500)
but this does not:
comments = self.comments.order('-added_on').fetch(500)
it crashes because self has no property comments.
The complete code for the two models is included below. Does anyone have any idea why the back-reference property is not given to my Verson instance?
from version.py:
from google.appengine.ext import db
import piece
class Version(db.Model):
parent_piece = db.ReferenceProperty(piece.Piece, collection_name="versions")
note = db.TextProperty()
content = db.TextProperty()
published_on = db.DateProperty(auto_now_add=True)
def add_comment(self, member, content):
import comment
new_comment = None
try:
new_comment = comment.Comment()
new_comment.version = self
new_comment.author = member
new_comment.author_moniker = member.moniker
new_comment.content = content
new_comment.put()
except:
# TODO: handle datastore exceptions here
pass
return new_comment
def get_comments(self):
import comment
comments = None
try:
comments = comment.Comment.all().filter('version = ', self).order('-added_on').fetch(500)
except:
pass
from comment.py:
import version
import member
from google.appengine.ext import db
class Comment(db.Model):
version = db.ReferenceProperty(version.Version, collection_name="comments")
author = db.ReferenceProperty(member.Member)
author_moniker = db.StringProperty()
author_thumbnail_avatar_url = db.StringProperty()
content = db.TextProperty()
added_on = db.DateProperty(auto_now_add=True)
A:
It looks like you are overwriting the automagical property called comments with your own property comments, in this line:
comments = self.comments.order('-added_on').fetch(500)
What happens if you change the collection_name argument in your Comment model to be "comments_set", then change the above line to:
comments = self.comments_set.order('-added_on').fetch(500)
| Is there a reason that a ReferenceProperty might not generate a back-reference? | In my current project, I have two models, Version and Comment. There is a one-to-many relationship between the two; each Version can have many Comment and the Comment model has a ReferenceProperty to record which Version it belongs to:
class Comment(db.Model):
version = db.ReferenceProperty(version.Version, collection_name="comments")
The problem is that instances of Version are not getting a comments property as I would expect. According to the docs, I should get an automagical property on each Version that is a query that returns all Comment instances that have their version set to the Version instance in question. Doesn't seem to work for my code.
I know that the ReferenceProperty is set correctly, because I can get the Comments with this query:
comments = comment.Comment.all().filter('version = ', self).order('-added_on').fetch(500)
but this does not:
comments = self.comments.order('-added_on').fetch(500)
it crashes because self has no property comments.
The complete code for the two models is included below. Does anyone have any idea why the back-reference property is not given to my Verson instance?
from version.py:
from google.appengine.ext import db
import piece
class Version(db.Model):
parent_piece = db.ReferenceProperty(piece.Piece, collection_name="versions")
note = db.TextProperty()
content = db.TextProperty()
published_on = db.DateProperty(auto_now_add=True)
def add_comment(self, member, content):
import comment
new_comment = None
try:
new_comment = comment.Comment()
new_comment.version = self
new_comment.author = member
new_comment.author_moniker = member.moniker
new_comment.content = content
new_comment.put()
except:
# TODO: handle datastore exceptions here
pass
return new_comment
def get_comments(self):
import comment
comments = None
try:
comments = comment.Comment.all().filter('version = ', self).order('-added_on').fetch(500)
except:
pass
from comment.py:
import version
import member
from google.appengine.ext import db
class Comment(db.Model):
version = db.ReferenceProperty(version.Version, collection_name="comments")
author = db.ReferenceProperty(member.Member)
author_moniker = db.StringProperty()
author_thumbnail_avatar_url = db.StringProperty()
content = db.TextProperty()
added_on = db.DateProperty(auto_now_add=True)
| [
"It looks like you are overwriting the automagical property called comments with your own property comments, in this line: \ncomments = self.comments.order('-added_on').fetch(500)\n\nWhat happens if you change the collection_name argument in your Comment model to be \"comments_set\", then change the above line to:\... | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003240505_google_app_engine_python.txt |
Q:
Problems adding path and calling external program from Python
I have an executable called "foo" in "/home/myname/mydir/" and am trying to call it from Python, but I am doing something basic and wrong here. Can you help me?
import os, sys
sys.path.append("/home/myname/mydir/")
os.system("foo") # os.system("./foo") doesn't work either
Thanks
A:
sys.path is the path to Python libraries, not the system PATH to search for binaries. Try changing os.environ['PATH'] instead.
>>> sys.path.append("/opt/local/bin")
>>> os.system("wget")
sh: wget: command not found
32512
>>> os.environ['PATH'] += os.pathsep + '/opt/local/bin'
>>> os.system("wget")
wget: missing URL
A:
You'll want to use the subprocess module instead of os.system, for anything serious. For os.system, do this:
os.system('/home/myname/mydir/foo ')
For subprocess:
p = subprocess.Popen(['/home/myname/mydir/foo'])
p.communicate('')
if p.returncode != 0:
raise Exception('foo failed')
If you care about foo's argv[0] being 'foo' and not '/home/myname/mydir/foo', do this:
p = subprocess.Popen(['foo'], executable='/home/myname/mydir/foo')
The reason subprocess is so much better than os.system is that it provides better control over the argument list: it does not require the command line to be parsed by the shell, and that avoids a whole slew of potential security problems, particularly with user-supplied filenames and such. The other reason is that subprocess provides better handling of errors, and better redirection of stdin, stdout, and stderr. (Not shown in the example above.)
| Problems adding path and calling external program from Python | I have an executable called "foo" in "/home/myname/mydir/" and am trying to call it from Python, but I am doing something basic and wrong here. Can you help me?
import os, sys
sys.path.append("/home/myname/mydir/")
os.system("foo") # os.system("./foo") doesn't work either
Thanks
| [
"sys.path is the path to Python libraries, not the system PATH to search for binaries. Try changing os.environ['PATH'] instead.\n>>> sys.path.append(\"/opt/local/bin\")\n>>> os.system(\"wget\")\nsh: wget: command not found\n32512\n>>> os.environ['PATH'] += os.pathsep + '/opt/local/bin'\n>>> os.system(\"wget\")\nwge... | [
16,
3
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003241735_linux_python.txt |
Q:
Can python3.1 scripts be freezed in mac os x using cxfreeze?
I m new to this and i need to freeze python3.1 scripts so that it can be run in other machines which does'nt have python3.1. CXFREEZE is the one which supports python 3.1 as far as i know. But i could not find any thread saying that freeze is successful for python3.x.
So can anybody tell me will it be done with cxfreeze or i have to choose something else to get my app ready to execute in other machines.
A:
It sounds like you should be able to using cx_Freeze from SVN trunk according to this: http://www.mail-archive.com/cx-freeze-users@lists.sourceforge.net/msg00522.html
Not many other executable builders for Python support 3.0 yet. cx_Freeze sounds like your best shot.
| Can python3.1 scripts be freezed in mac os x using cxfreeze? | I m new to this and i need to freeze python3.1 scripts so that it can be run in other machines which does'nt have python3.1. CXFREEZE is the one which supports python 3.1 as far as i know. But i could not find any thread saying that freeze is successful for python3.x.
So can anybody tell me will it be done with cxfreeze or i have to choose something else to get my app ready to execute in other machines.
| [
"It sounds like you should be able to using cx_Freeze from SVN trunk according to this: http://www.mail-archive.com/cx-freeze-users@lists.sourceforge.net/msg00522.html\nNot many other executable builders for Python support 3.0 yet. cx_Freeze sounds like your best shot.\n"
] | [
1
] | [] | [] | [
"cx_freeze",
"macos",
"python",
"python_3.x"
] | stackoverflow_0003210812_cx_freeze_macos_python_python_3.x.txt |
Q:
Only allow 1 instance of a python script
Possible Duplicate:
Python: single instance of program
What is the best way to insure that only 1 copy of a python script is running? I am having trouble with python zombies. I tired creating a write lock using open("lock","w"), but python doesn't notify me if the file already has a write lock, it just seems to wait.
A:
Try:
import os
os.open("lock", os.O_CREAT|os.O_EXCL)
The documentation for os.open and its flags.
A:
Your question is similar to this one: What is the best way to open a file for exclusive access in Python?. The answers given there should help you with your issue.
(Use the flag combination portalocker.LOCK_EX!|portalocker.LOCK_NB to return quickly. If the file is locked by another process, your script should get an exception.)
| Only allow 1 instance of a python script |
Possible Duplicate:
Python: single instance of program
What is the best way to insure that only 1 copy of a python script is running? I am having trouble with python zombies. I tired creating a write lock using open("lock","w"), but python doesn't notify me if the file already has a write lock, it just seems to wait.
| [
"Try:\nimport os\nos.open(\"lock\", os.O_CREAT|os.O_EXCL)\n\nThe documentation for os.open and its flags.\n",
"Your question is similar to this one: What is the best way to open a file for exclusive access in Python?. The answers given there should help you with your issue.\n(Use the flag combination portalocker... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003241754_python.txt |
Q:
python and search?
am looking for method and function watch i can search in web page !
ok I'll explain it :
i tell my python file .. go to www.example.com and search for that world "Hello guest"
and if my python file found that world "Hello guest" my python file print "the world found!"
and if he don't found he print "the world not found"
A:
Use Python's urllib module to fetch the content, and its re module to look for the word (make sure you use search instead of match; it's a common noob slip-up).
A:
The other answers here I believe are searching the html rather than the rendered content. If that's what you want that's fine, but if you want to exclude stuff in tags then you're probably going to want to look at something that can understand html. Beautiful Soup should be able to help parse it and extract the actual text content (and a lot more)
A:
if you need to match exact string, this is faster and less complicated
a = urllib.urlopen('http://www.google.com')
if 'new' in a.read():
print 'found'
else:
print 'not found'
| python and search? | am looking for method and function watch i can search in web page !
ok I'll explain it :
i tell my python file .. go to www.example.com and search for that world "Hello guest"
and if my python file found that world "Hello guest" my python file print "the world found!"
and if he don't found he print "the world not found"
| [
"Use Python's urllib module to fetch the content, and its re module to look for the word (make sure you use search instead of match; it's a common noob slip-up).\n",
"The other answers here I believe are searching the html rather than the rendered content. If that's what you want that's fine, but if you want to ... | [
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003242114_python.txt |
Q:
Pythonic syntax for appending an arbitrary class object list property
Is there an analog of setattr() that allows for appending an arbitrary list property of an instantiated class object? If not, is there a recommended way of doing so?
This is a trivialized version of what I'm doing currently:
foo = SomeClass()
...
attr = "names"
value = "Eric"
values = getattr(foo, attr)
values.append(value)
setattr(foo, attr, values)
This seems clunky and inefficient.
Edit: this assumes that foo.names (or whatever arbitrary value might be assigned to the attr variable) is in fact a list.
A:
The setattr call is redundant, if foo.names is indeed a list (if it's something else, could you please clarify?). getattr(foo, attr).append(value) is all you need.
| Pythonic syntax for appending an arbitrary class object list property | Is there an analog of setattr() that allows for appending an arbitrary list property of an instantiated class object? If not, is there a recommended way of doing so?
This is a trivialized version of what I'm doing currently:
foo = SomeClass()
...
attr = "names"
value = "Eric"
values = getattr(foo, attr)
values.append(value)
setattr(foo, attr, values)
This seems clunky and inefficient.
Edit: this assumes that foo.names (or whatever arbitrary value might be assigned to the attr variable) is in fact a list.
| [
"The setattr call is redundant, if foo.names is indeed a list (if it's something else, could you please clarify?). getattr(foo, attr).append(value) is all you need.\n"
] | [
15
] | [] | [] | [
"python"
] | stackoverflow_0003242391_python.txt |
Q:
the best search engine written with python
i want to build an information support system which is an web app.
and we gonna use Django as the frame,but i don't know which search engine to use ?
can you give me some suggestions on the search engine which we can use in our project,it must be written with python.
thanks
A:
I believe you'd be happy with whoosh, possibly "fronted" by Haystack which is a neat way to support any of several search engines in Django (but the other underlying engines it supports are not "pure Python"... whoosh is).
I believe both whoosh and haystack support Unicode, so, in particular, Chinese too.
A:
Xapian with the Python bindings is the best solution for Python.
A:
If you looking for Performance , Try Sphinx Search : http://sphinxsearch.com/ , best known highest performance /highly stable search engine and it have easy to use python API.
But please note it is Search engine for MySQL *You have to parse files and import them to database yourself.
| the best search engine written with python | i want to build an information support system which is an web app.
and we gonna use Django as the frame,but i don't know which search engine to use ?
can you give me some suggestions on the search engine which we can use in our project,it must be written with python.
thanks
| [
"I believe you'd be happy with whoosh, possibly \"fronted\" by Haystack which is a neat way to support any of several search engines in Django (but the other underlying engines it supports are not \"pure Python\"... whoosh is).\nI believe both whoosh and haystack support Unicode, so, in particular, Chinese too.\n",... | [
12,
1,
0
] | [] | [] | [
"django",
"python",
"search_engine"
] | stackoverflow_0003239576_django_python_search_engine.txt |
Q:
Python Popen.waitpid returns "[Errno 10] No child processes"
I have a working Python script that executes an external command and calls Popen.communicate(). However when I call this script from a C process, it fails in os.waitpid() with "[Errno 10] No child processes". Why?
This looks like a certain bug in Python, but I'm not using threads.
The C process forks, changes its UID, GID, and calls setsid() and then execle() (with "/bin/sh -c /python/script").
A:
The problem in my case was that the C process was ignoring SIGCHLD. Since ignored signals are inherited by a forked process, Python process was ignoring it as well, which made waitpid() fail.
Solution: set signal handlers in the C process after forking to SIG_DFL, if you've ignored any.
| Python Popen.waitpid returns "[Errno 10] No child processes" | I have a working Python script that executes an external command and calls Popen.communicate(). However when I call this script from a C process, it fails in os.waitpid() with "[Errno 10] No child processes". Why?
This looks like a certain bug in Python, but I'm not using threads.
The C process forks, changes its UID, GID, and calls setsid() and then execle() (with "/bin/sh -c /python/script").
| [
"The problem in my case was that the C process was ignoring SIGCHLD. Since ignored signals are inherited by a forked process, Python process was ignoring it as well, which made waitpid() fail.\nSolution: set signal handlers in the C process after forking to SIG_DFL, if you've ignored any.\n"
] | [
1
] | [] | [] | [
"fork",
"linux",
"process",
"python"
] | stackoverflow_0003234569_fork_linux_process_python.txt |
Q:
make data struct iterable in python
So I've done some looking online and throught the documentation, but I'm having troubling finding out how to do this. I am working on creating an adventure game. I have a level class (which contains a bunch of rooms) and a Room class. I would like to be able to do something like the following.
l = Level()
for room in l:
#following code here
This seems pretty simple to me, however I can't find the correct procedures for implementing a custom iterator. This may be an easy answer, but I'm having trouble finding it online. Any help is greatly appreciated!
A:
Use __iter__ with an iterator-generator. E.g.
def __iter__(self):
for r in rooms:
yield r
An iterator-generator is basically a psuedo-method used to implement an iterator. Note that there is no requirement that the generator use a for loop. It can use any combination of constructs (if, for, while, etc.) as needed. Basically, you just have to remember that the caller will get elements in the order you "call" yield, and the iteration will end when the method does.
See this section of the Python tutorial.
A:
If you define a member method called __iter__(self), Python will know how to iterate through it.
In this method, I suggest you use yield to return your data (this is called a generator). You could also return a list or tuple, but this is more efficient memory-wise. Here is an example:
class Test(object):
def __iter__(self):
for x in range(10):
yield x
l = Test()
for room in l:
print room
A:
As an alternative to writing a generator, the __iter__ method just needs to return an iterator - if your Level object has an internal datastructure that holds the rooms then you could return it's iterator directly:
class Level(object):
def __init__(self):
self.rooms = []
def __iter__(self):
return iter(self.rooms)
If the rooms container is a dictionary e.g. mapping room names to Room objects then you can get a iterator to the Room objects with the dict.itervalues method:
class Level(object):
def __init__(self):
self.rooms = {}
def __iter__(self):
return self.rooms.itervalues()
| make data struct iterable in python | So I've done some looking online and throught the documentation, but I'm having troubling finding out how to do this. I am working on creating an adventure game. I have a level class (which contains a bunch of rooms) and a Room class. I would like to be able to do something like the following.
l = Level()
for room in l:
#following code here
This seems pretty simple to me, however I can't find the correct procedures for implementing a custom iterator. This may be an easy answer, but I'm having trouble finding it online. Any help is greatly appreciated!
| [
"Use __iter__ with an iterator-generator. E.g.\ndef __iter__(self):\n for r in rooms:\n yield r\n\nAn iterator-generator is basically a psuedo-method used to implement an iterator. Note that there is no requirement that the generator use a for loop. It can use any combination of constructs (if, for, while, e... | [
3,
3,
1
] | [
"Why not use generator.\n>>> import timeit\n>>> class Test:\n def __iter__(self):\n for i in range(10):\n yield i\n\n>>> t1 = lambda: [k for k in Test()]\n>>> timeit.timeit(t1)\n3.529460948082189\n\n\n>>> def test2():\n for i in range(10):\n yield i\n\n>>> t2 = lambda: [k for k in tes... | [
-1
] | [
"for_loop",
"iterator",
"loops",
"python"
] | stackoverflow_0003240643_for_loop_iterator_loops_python.txt |
Q:
Using random.choice in conjuction with if statements
So I'm really new to programming, I just started learning Python yesterday and I'm having a little trouble. I've looked through a few tutorials and haven't come up with how to answer my question on my own, so I'm coming to you guys.
quickList = ["string1", "string2"]
anotherList1 = ["another1a", "another1b"]
anotherList2 = ["another2a", "another2b"]
for i in range(1):
quick=random.choice(quickList)
another1=random.choice(anotherList1)
another2=random.choice(anotherList2)
What I want to do is write the code so that if quick turns up string1, it will print string1 and then print another1, but if quick generates string2, it will print string2 and then an entry from anotherList2.
Any hints?
Thanks in advance for your help!
A:
Try storing them in a dictionary:
d = {
'string1': ['another1a', 'another1b'],
'string2': ['another2a', 'another2b'],
}
choice = random.choice(d.keys())
print choice, random.choice(d[choice])
A:
Try to think that logic through. I have formatted your exact words for you:
if (quick turns up string1):
print string1
print another1 //I assume you mean a string from this list
but if (quick generates string2):
print string2
and then an entry from anotherList2
This is the logic you want, now you just have to translate that back to python. I will leave that to you.
In general, try to relate if statements to literal choices in logic. It will help you write code in any language.
(As an extra note, why is it in a for loop? There is no need if you only do it one time.)
A:
This will work for you:
quickList = ["string1", "string2"]
anotherList1 = ["another1a", "another1b"]
anotherList2 = ["another2a", "another2b"]
for i in range(1):
if random.choice(quickList) == 'string1':
another1=random.choice(anotherList1)
else:
another2=random.choice(anotherList2)
A:
if? What if?
quickList = ["string1", "string2"]
anotherList1 = ["another1a", "another1b"]
anotherList2 = ["another2a", "another2b"]
for i in range(1):
quick = random.choice(list(enumerate(quickList)))
anothers = [random.choice(x) for x in (anotherList1, anotherList2)]
print quick[1]
print anothers[quick[0]]
A:
Your words don't match your code - does "string1" imply "another1" or does it imply a choice from anotherList1? If the latter, I'd make the association between the quicks and the anothers explicit in the data:
combinedList = [ ("string1", ["another1a", "another1b"]),
("string2", ["another2a", "another2b"]) ]
quick,anotherList = random.choice( combinedList )
another = random.choice(anotherList)
A:
Since you're new to Python, let me suggest another way of doing this.
quickList = ["string1", "string2"]
anotherList = {"string1": ["another1a", "another1b"],
"string2": ["another2a", "another2b"]}
for i in range(1):
quick = random.choice(quickList)
print quick
print random.choice(anotherList[quick])
Also as others have mentioned, not sure why your code is in a for loop. You could take that out as well, but I have left it in for this example.
This let's you expand your list more easily and saves you from building a bunch of if statements. It could be further optimized, but try and see if you understand this approach :-)
| Using random.choice in conjuction with if statements | So I'm really new to programming, I just started learning Python yesterday and I'm having a little trouble. I've looked through a few tutorials and haven't come up with how to answer my question on my own, so I'm coming to you guys.
quickList = ["string1", "string2"]
anotherList1 = ["another1a", "another1b"]
anotherList2 = ["another2a", "another2b"]
for i in range(1):
quick=random.choice(quickList)
another1=random.choice(anotherList1)
another2=random.choice(anotherList2)
What I want to do is write the code so that if quick turns up string1, it will print string1 and then print another1, but if quick generates string2, it will print string2 and then an entry from anotherList2.
Any hints?
Thanks in advance for your help!
| [
"Try storing them in a dictionary:\nd = {\n 'string1': ['another1a', 'another1b'],\n 'string2': ['another2a', 'another2b'],\n}\nchoice = random.choice(d.keys())\nprint choice, random.choice(d[choice])\n\n",
"Try to think that logic through. I have formatted your exact words for you:\nif (quick turns up stri... | [
2,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003242637_python.txt |
Q:
Shared pointers and building in SIP4 (was: Dynamic casting in SWIG/python?)
So I'm playing about with Python, C++0x, and SWIG 2.0. I've got a header that looks like this:
#include <string>
#include <iostream>
#include <memory>
using namespace std;
struct Base {
virtual string name();
int foo;
shared_ptr<Base> mine;
Base(int);
virtual ~Base() {}
virtual void doit(shared_ptr<Base> b) {
cout << name() << " doing it to " << b->name() << endl;
mine = b;
}
virtual shared_ptr<Base> getit() {
return mine;
}
};
struct Derived : Base {
virtual string name();
int bar;
Derived(int, int);
};
Meanwhile, the interface file looks like this:
%module(directors="1") foo
%feature("director");
%include <std_string.i>
%include <std_shared_ptr.i>
%shared_ptr(Base)
%shared_ptr(Derived)
%{
#define SWIG_FILE_WITH_INIT
#include "foo.hpp"
%}
%include "foo.hpp"
My Python session then goes like this:
>>> import foo
>>> b = foo.Base(42)
>>> d = foo.Derived(23,64)
>>> b.doit(d)
Base doing it to Derived
>>> g = b.getit()
>>> g
<foo.Base; proxy of <Swig Object of type 'std::shared_ptr< Base > *' at 0x7f7bd1391930> >
>>> d
<foo.Derived; proxy of <Swig Object of type 'std::shared_ptr< Derived > *' at 0x7f7bd137ce10> >
>>> d == g
False
>>> d is g
False
>>> d.foo == g.foo
True
>>> d.bar
64
>>> g.bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Base' object has no attribute 'bar'
I can't seem to figure out how to retrieve the "original" proxy object here. Must I produce a function for each and every base class to perform the dynamic_pointer_cast? And if so, what of Director subclasses implemented in Python?
I get the feeling there's a switch or feature I can turn on here to get SWIG to do the necessary table lookups and produce the object I want, but I haven't found it yet.
(Note: The behavior is similar if I use raw pointers instead of shared pointers, and I can't figure out how to get SWIG to dynamic_cast those either)
Update
If this sort of behavior (specifically, retrieving the most-derived proxy from a C++ container class that holds pointers to the base class) isn't possible in SWIG, then how about SIP or some other wrapper generator for Python?
Update #2
Since SIP4 looks like it works a bit better as far as retrieving the wrapped object sensibly, I'll change the question once again. Check my self answer below for details on my current issues. I'll still accept a good answer for the original SWIG question since I prefer it overall, but my new questions are, basically:
How can I deal sanely with wrappers around shared_ptrs rather than raw pointers? If it helps, all of my classes subclass enable_shared_from_this from their generic base classes and expose an appropriate function to get the shared pointer.
How can I, using either of SIP4's build systems (Makefile generator or distutils extension), build my little example project without having to first generate and install a shared library or manually edit the generated Makefile?
A:
To (partially) answer my own question, SIP appears to do the right thing, both for the C++ "Derived" class as well as for a Python-level subclass — at least, when I use raw pointers.
Looks like I'll need to figure out how to get it to work with shared_ptrs (looks not quite as easy as %include <std_shared_ptr.i> in SWIG).
Also, both of SIPs "build system" options (Makefile generator and distutils extension) seem a little odd. Neither example in their manual "just works" - it looks like they expect it to be obvious that you're supposed to compile and install a shared library and header file in your library/include paths for the little Hello World library you're trying to wrap. Perhaps there's an "I just want to build and run this self-contained thing right here" option that I missed, but even python setup.py build_ext --inplace fails because it can't find the wrapped header that I've placed in the current directory, which is obviously a confusing place for it, I know.
| Shared pointers and building in SIP4 (was: Dynamic casting in SWIG/python?) | So I'm playing about with Python, C++0x, and SWIG 2.0. I've got a header that looks like this:
#include <string>
#include <iostream>
#include <memory>
using namespace std;
struct Base {
virtual string name();
int foo;
shared_ptr<Base> mine;
Base(int);
virtual ~Base() {}
virtual void doit(shared_ptr<Base> b) {
cout << name() << " doing it to " << b->name() << endl;
mine = b;
}
virtual shared_ptr<Base> getit() {
return mine;
}
};
struct Derived : Base {
virtual string name();
int bar;
Derived(int, int);
};
Meanwhile, the interface file looks like this:
%module(directors="1") foo
%feature("director");
%include <std_string.i>
%include <std_shared_ptr.i>
%shared_ptr(Base)
%shared_ptr(Derived)
%{
#define SWIG_FILE_WITH_INIT
#include "foo.hpp"
%}
%include "foo.hpp"
My Python session then goes like this:
>>> import foo
>>> b = foo.Base(42)
>>> d = foo.Derived(23,64)
>>> b.doit(d)
Base doing it to Derived
>>> g = b.getit()
>>> g
<foo.Base; proxy of <Swig Object of type 'std::shared_ptr< Base > *' at 0x7f7bd1391930> >
>>> d
<foo.Derived; proxy of <Swig Object of type 'std::shared_ptr< Derived > *' at 0x7f7bd137ce10> >
>>> d == g
False
>>> d is g
False
>>> d.foo == g.foo
True
>>> d.bar
64
>>> g.bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Base' object has no attribute 'bar'
I can't seem to figure out how to retrieve the "original" proxy object here. Must I produce a function for each and every base class to perform the dynamic_pointer_cast? And if so, what of Director subclasses implemented in Python?
I get the feeling there's a switch or feature I can turn on here to get SWIG to do the necessary table lookups and produce the object I want, but I haven't found it yet.
(Note: The behavior is similar if I use raw pointers instead of shared pointers, and I can't figure out how to get SWIG to dynamic_cast those either)
Update
If this sort of behavior (specifically, retrieving the most-derived proxy from a C++ container class that holds pointers to the base class) isn't possible in SWIG, then how about SIP or some other wrapper generator for Python?
Update #2
Since SIP4 looks like it works a bit better as far as retrieving the wrapped object sensibly, I'll change the question once again. Check my self answer below for details on my current issues. I'll still accept a good answer for the original SWIG question since I prefer it overall, but my new questions are, basically:
How can I deal sanely with wrappers around shared_ptrs rather than raw pointers? If it helps, all of my classes subclass enable_shared_from_this from their generic base classes and expose an appropriate function to get the shared pointer.
How can I, using either of SIP4's build systems (Makefile generator or distutils extension), build my little example project without having to first generate and install a shared library or manually edit the generated Makefile?
| [
"To (partially) answer my own question, SIP appears to do the right thing, both for the C++ \"Derived\" class as well as for a Python-level subclass — at least, when I use raw pointers. \nLooks like I'll need to figure out how to get it to work with shared_ptrs (looks not quite as easy as %include <std_shared_ptr.i... | [
0
] | [] | [] | [
"c++",
"c++11",
"python",
"swig"
] | stackoverflow_0003217004_c++_c++11_python_swig.txt |
Q:
Edit .RAR file comments from python
Ok, I need to be able to edit the file comments in .rar files from python.
I can already view the comments using UnRAR. However, I need to embed metadata in the files in a way that is preserved over multiple file systems (e.g. alternate datastreams are out), so I can't really think of any other alternatives.
rarfile seems like it might work, but it doesn't really function correctly under windows, despite it's claim of platform independence (or the .rar format has changed, but that seems unlikely considering other utilities from the same time period work). It opens the archive fine, but it does not recognize that there are comments.
To pre-emptively answer some of the inevitable comments -
No, I cannot convert the archives (there's thousands of them).
Any file-system-dependent mode of storing metadata is out, as I need to support NTFS, XFS and ext3.
Hidden files would be a mess, and you need to ensure they are moved with the associated file, which I cannot do.
A:
I think you are out of luck. Unfortunately the RAR format is closed source and not documented, and there is no Python module that does what you want to do.
The only open-source tool I know that uncompress RAR files is The Unarchiver. I think that your best bet is check their sources and write your own Python tool to change the file comments.
You might also try to ask this question at the comp.compression boards, I had a similar issue some years ago with an obscure compression format and the people over there were able to help me in no time.
| Edit .RAR file comments from python | Ok, I need to be able to edit the file comments in .rar files from python.
I can already view the comments using UnRAR. However, I need to embed metadata in the files in a way that is preserved over multiple file systems (e.g. alternate datastreams are out), so I can't really think of any other alternatives.
rarfile seems like it might work, but it doesn't really function correctly under windows, despite it's claim of platform independence (or the .rar format has changed, but that seems unlikely considering other utilities from the same time period work). It opens the archive fine, but it does not recognize that there are comments.
To pre-emptively answer some of the inevitable comments -
No, I cannot convert the archives (there's thousands of them).
Any file-system-dependent mode of storing metadata is out, as I need to support NTFS, XFS and ext3.
Hidden files would be a mess, and you need to ensure they are moved with the associated file, which I cannot do.
| [
"I think you are out of luck. Unfortunately the RAR format is closed source and not documented, and there is no Python module that does what you want to do.\nThe only open-source tool I know that uncompress RAR files is The Unarchiver. I think that your best bet is check their sources and write your own Python tool... | [
1
] | [] | [] | [
"archive",
"python",
"python_2.6",
"windows"
] | stackoverflow_0003201409_archive_python_python_2.6_windows.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.