title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
How do I split a huge text file in python | 291,740 | <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p>
<p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p>
<p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p>
<p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
| 15 | 2008-11-14T23:12:14Z | 2,203,848 | <p>don't forget <a href="http://docs.python.org/library/stdtypes.html#file.seek" rel="nofollow">seek()</a> and <a href="http://docs.python.org/library/mmap.html" rel="nofollow">mmap()</a> for random access to files.</p>
<pre><code>def getSomeChunk(filename, start, len):
fobj = open(filename, 'r+b')
m = mmap.mmap(fobj.fileno(), 0)
return m[start:start+len]
</code></pre>
| 3 | 2010-02-04T22:53:33Z | [
"python",
"text-files"
]
|
How do I split a huge text file in python | 291,740 | <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p>
<p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p>
<p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p>
<p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
| 15 | 2008-11-14T23:12:14Z | 2,204,075 | <p>This generator method is a (slow) way to get a slice of lines without blowing up your memory.</p>
<pre><code>import itertools
def slicefile(filename, start, end):
lines = open(filename)
return itertools.islice(lines, start, end)
out = open("/blah.txt", "w")
for line in slicefile("/python27/readme.txt", 10, 15):
out.write(line)
</code></pre>
| 4 | 2010-02-04T23:42:15Z | [
"python",
"text-files"
]
|
How do I split a huge text file in python | 291,740 | <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p>
<p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p>
<p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p>
<p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
| 15 | 2008-11-14T23:12:14Z | 10,599,406 | <p>As an alternative method, using the logging library:</p>
<pre><code>>>> import logging.handlers
>>> log = logging.getLogger()
>>> fh = logging.handlers.RotatingFileHandler("D://filename.txt",
maxBytes=2**20*100, backupCount=100)
# 100 MB each, up to a maximum of 100 files
>>> log.addHandler(fh)
>>> log.setLevel(logging.INFO)
>>> f = open("D://biglog.txt")
>>> while True:
... log.info(f.readline().strip())
</code></pre>
<p>Your files will appear as follows:</p>
<blockquote>
<p>filename.txt (end of file)<br>
filename.txt.1<br>
filename.txt.2<br>
...<br>
filename.txt.10 (start of file)</p>
</blockquote>
<p>This is a quick and easy way to make a huge log file match your <code>RotatingFileHandler</code> implementation.</p>
| 7 | 2012-05-15T11:04:13Z | [
"python",
"text-files"
]
|
How do I split a huge text file in python | 291,740 | <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p>
<p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p>
<p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p>
<p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
| 15 | 2008-11-14T23:12:14Z | 20,335,874 | <p>This worked for me</p>
<pre><code>import os
fil = "inputfile"
outfil = "outputfile"
f = open(fil,'r')
numbits = 1000000000
for i in range(0,os.stat(fil).st_size/numbits+1):
o = open(outfil+str(i),'w')
segment = f.readlines(numbits)
for c in range(0,len(segment)):
o.write(segment[c]+"\n")
o.close()
</code></pre>
| 1 | 2013-12-02T19:05:08Z | [
"python",
"text-files"
]
|
How do I split a huge text file in python | 291,740 | <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p>
<p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p>
<p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p>
<p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
| 15 | 2008-11-14T23:12:14Z | 23,847,737 | <p>I had a requirement to split csv files for import into Dynamics CRM since the file size limit for import is 8MB and the files we receive are much larger. This program allows user to input FileNames and LinesPerFile, and then splits the specified files into the requested number of lines. I can't believe how fast it works!</p>
<pre><code># user input FileNames and LinesPerFile
FileCount = 1
FileNames = []
while True:
FileName = raw_input('File Name ' + str(FileCount) + ' (enter "Done" after last File):')
FileCount = FileCount + 1
if FileName == 'Done':
break
else:
FileNames.append(FileName)
LinesPerFile = raw_input('Lines Per File:')
LinesPerFile = int(LinesPerFile)
for FileName in FileNames:
File = open(FileName)
# get Header row
for Line in File:
Header = Line
break
FileCount = 0
Linecount = 1
for Line in File:
#skip Header in File
if Line == Header:
continue
#create NewFile with Header every [LinesPerFile] Lines
if Linecount % LinesPerFile == 1:
FileCount = FileCount + 1
NewFileName = FileName[:FileName.find('.')] + '-Part' + str(FileCount) + FileName[FileName.find('.'):]
NewFile = open(NewFileName,'w')
NewFile.write(Header)
NewFile.write(Line)
Linecount = Linecount + 1
NewFile.close()
</code></pre>
| 0 | 2014-05-24T17:16:39Z | [
"python",
"text-files"
]
|
How do I split a huge text file in python | 291,740 | <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p>
<p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p>
<p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p>
<p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
| 15 | 2008-11-14T23:12:14Z | 27,641,636 | <p>While <a href="http://stackoverflow.com/a/2204075/198633">Ryan Ginstrom's answer</a> is correct, it does take longer than it should (as he has already noted). Here's a way to circumvent the multiple calls to <code>itertools.islice</code> by successively iterating over the open file descriptor:</p>
<pre><code>def splitfile(infilepath, chunksize):
fname, ext = infilepath.rsplit('.',1)
i = 0
written = False
with open(infilepath) as infile:
while True:
outfilepath = "{}{}.{}".format(fname, i, ext)
with open(outfilepath, 'w') as outfile:
for line in (infile.readline() for _ in range(chunksize)):
outfile.write(line)
written = bool(line)
if not written:
break
i += 1
</code></pre>
| 2 | 2014-12-24T19:53:47Z | [
"python",
"text-files"
]
|
How do I split a huge text file in python | 291,740 | <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p>
<p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p>
<p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p>
<p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
| 15 | 2008-11-14T23:12:14Z | 33,151,466 | <p>usage - split.py filename splitsizeinkb</p>
<pre><code>import os
import sys
def getfilesize(filename):
with open(filename,"rb") as fr:
fr.seek(0,2) # move to end of the file
size=fr.tell()
print("getfilesize: size: %s" % size)
return fr.tell()
def splitfile(filename, splitsize):
# Open original file in read only mode
if not os.path.isfile(filename):
print("No such file as: \"%s\"" % filename)
return
filesize=getfilesize(filename)
with open(filename,"rb") as fr:
counter=1
orginalfilename = filename.split(".")
readlimit = 5000 #read 5kb at a time
n_splits = filesize//splitsize
print("splitfile: No of splits required: %s" % str(n_splits))
for i in range(n_splits+1):
chunks_count = int(splitsize)//int(readlimit)
data_5kb = fr.read(readlimit) # read
# Create split files
print("chunks_count: %d" % chunks_count)
with open(orginalfilename[0]+"_{id}.".format(id=str(counter))+orginalfilename[1],"ab") as fw:
fw.seek(0)
fw.truncate()# truncate original if present
while data_5kb:
fw.write(data_5kb)
if chunks_count:
chunks_count-=1
data_5kb = fr.read(readlimit)
else: break
counter+=1
if __name__ == "__main__":
if len(sys.argv) < 3: print("Filename or splitsize not provided: Usage: filesplit.py filename splitsizeinkb ")
else:
filesize = int(sys.argv[2]) * 1000 #make into kb
filename = sys.argv[1]
splitfile(filename, filesize)
</code></pre>
| 1 | 2015-10-15T14:39:47Z | [
"python",
"text-files"
]
|
Best Practices for Building a SSO System | 291,874 | <p>I am looking to build a Single-signon system for a couple web apps that used form based authentication. </p>
<p>They way that I envision it is that my sso system would handle authentication against active directory pass the verification through to the desired web app when ever the used clicked a link through my sso portal.</p>
<p>What might be the best way to build something like this?</p>
| 0 | 2008-11-15T00:34:15Z | 291,890 | <p>Check out <a href="http://www.ja-sig.org/products/cas/index.html" rel="nofollow">JA-SIG CAS</a>. Even if you build your own, you should look at their architecture for ideas on how to implement.</p>
| 0 | 2008-11-15T00:40:50Z | [
"python",
"web-services",
"web-applications",
"active-directory"
]
|
Best Practices for Building a SSO System | 291,874 | <p>I am looking to build a Single-signon system for a couple web apps that used form based authentication. </p>
<p>They way that I envision it is that my sso system would handle authentication against active directory pass the verification through to the desired web app when ever the used clicked a link through my sso portal.</p>
<p>What might be the best way to build something like this?</p>
| 0 | 2008-11-15T00:34:15Z | 291,894 | <p>When a user accesses an application URL without a session cookie, he is redirected to the SSO system. He then logs into the SSO form, which then redirects him back to your app with a ticket ID that you can look up in the SSO system to get cridentials.</p>
<p>Also, take a look at <a href="http://www.atlassian.com/software/crowd/" rel="nofollow">Crowd</a> and <a href="http://www.ja-sig.org/products/cas/" rel="nofollow">CAS</a>.</p>
| 1 | 2008-11-15T00:42:24Z | [
"python",
"web-services",
"web-applications",
"active-directory"
]
|
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | <p>Say I have the following in my <code>models.py</code>:</p>
<pre><code>class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
</code></pre>
<p>I.e. there are multiple <code>Companies</code>, each having a range of <code>Rates</code> and <code>Clients</code>. Each <code>Client</code> should have a base <code>Rate</code> that is chosen from it's parent <code>Company's Rates</code>, not another <code>Company's Rates</code>.</p>
<p>When creating a form for adding a <code>Client</code>, I would like to remove the <code>Company</code> choices (as that has already been selected via an "Add Client" button on the <code>Company</code> page) and limit the <code>Rate</code> choices to that <code>Company</code> as well.</p>
<p>How do I go about this in Django 1.0? </p>
<p>My current <code>forms.py</code> file is just boilerplate at the moment:</p>
<pre><code>from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
</code></pre>
<p>And the <code>views.py</code> is also basic:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
</code></pre>
<p>In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:</p>
<pre><code>manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to"><code>ForeignKey.limit_choices_to</code></a> seems promising but I don't know how to pass in <code>the_company.id</code> and I'm not clear if that will work outside the Admin interface anyway.</p>
<p>Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)</p>
| 152 | 2008-11-15T01:21:33Z | 291,968 | <p>ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield">ModelChoiceField</a>.</p>
<p>So, provide a QuerySet to the field's <code>queryset</code> attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly. </p>
<pre><code>form.rate.queryset = Rate.objects.filter(company_id=the_company.id)
</code></pre>
<p>If you take the default ModelForm object, <code>form.fields["rate"].queryset = ...</code></p>
<p>This is done explicitly in the view. No hacking around.</p>
| 164 | 2008-11-15T01:39:26Z | [
"python",
"django",
"django-forms"
]
|
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | <p>Say I have the following in my <code>models.py</code>:</p>
<pre><code>class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
</code></pre>
<p>I.e. there are multiple <code>Companies</code>, each having a range of <code>Rates</code> and <code>Clients</code>. Each <code>Client</code> should have a base <code>Rate</code> that is chosen from it's parent <code>Company's Rates</code>, not another <code>Company's Rates</code>.</p>
<p>When creating a form for adding a <code>Client</code>, I would like to remove the <code>Company</code> choices (as that has already been selected via an "Add Client" button on the <code>Company</code> page) and limit the <code>Rate</code> choices to that <code>Company</code> as well.</p>
<p>How do I go about this in Django 1.0? </p>
<p>My current <code>forms.py</code> file is just boilerplate at the moment:</p>
<pre><code>from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
</code></pre>
<p>And the <code>views.py</code> is also basic:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
</code></pre>
<p>In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:</p>
<pre><code>manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to"><code>ForeignKey.limit_choices_to</code></a> seems promising but I don't know how to pass in <code>the_company.id</code> and I'm not clear if that will work outside the Admin interface anyway.</p>
<p>Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)</p>
| 152 | 2008-11-15T01:21:33Z | 1,244,586 | <p>In addition to S.Lott's answer and as becomingGuru mentioned in comments, its possible to add the queryset filters by overriding the <code>ModelForm.__init__</code> function. (This could easily apply to regular forms) it can help with reuse and keeps the view function tidy. </p>
<pre><code>class ClientForm(forms.ModelForm):
def __init__(self,company,*args,**kwargs):
super (ClientForm,self ).__init__(*args,**kwargs) # populates the post
self.fields['rate'].queryset = Rate.objects.filter(company=company)
self.fields['client'].queryset = Client.objects.filter(company=company)
class Meta:
model = Client
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(the_company,request.POST) #<-- Note the extra arg
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm(the_company)
return render_to_response('addclient.html',
{'form': form, 'the_company':the_company})
</code></pre>
<p>This can be useful for reuse say if you have common filters needed on many models (normally I declare an abstract Form class). E.g.</p>
<pre><code>class UberClientForm(ClientForm):
class Meta:
model = UberClient
def view(request):
...
form = UberClientForm(company)
...
#or even extend the existing custom init
class PITAClient(ClientForm):
def __init__(company, *args, **args):
super (PITAClient,self ).__init__(company,*args,**kwargs)
self.fields['support_staff'].queryset = User.objects.exclude(user='michael')
</code></pre>
<p>Other than that I'm just restating Django blog material of which there are many good ones out there. </p>
| 100 | 2009-08-07T13:01:38Z | [
"python",
"django",
"django-forms"
]
|
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | <p>Say I have the following in my <code>models.py</code>:</p>
<pre><code>class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
</code></pre>
<p>I.e. there are multiple <code>Companies</code>, each having a range of <code>Rates</code> and <code>Clients</code>. Each <code>Client</code> should have a base <code>Rate</code> that is chosen from it's parent <code>Company's Rates</code>, not another <code>Company's Rates</code>.</p>
<p>When creating a form for adding a <code>Client</code>, I would like to remove the <code>Company</code> choices (as that has already been selected via an "Add Client" button on the <code>Company</code> page) and limit the <code>Rate</code> choices to that <code>Company</code> as well.</p>
<p>How do I go about this in Django 1.0? </p>
<p>My current <code>forms.py</code> file is just boilerplate at the moment:</p>
<pre><code>from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
</code></pre>
<p>And the <code>views.py</code> is also basic:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
</code></pre>
<p>In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:</p>
<pre><code>manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to"><code>ForeignKey.limit_choices_to</code></a> seems promising but I don't know how to pass in <code>the_company.id</code> and I'm not clear if that will work outside the Admin interface anyway.</p>
<p>Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)</p>
| 152 | 2008-11-15T01:21:33Z | 1,610,856 | <p>So, I've really tried to understand this, but it seems that Django still doesn't make this very straightforward. I'm not all that dumb, but I just can't see any (somewhat) simple solution.</p>
<p>I find it generally pretty ugly to have to override the Admin views for this sort of thing, and every example I find never fully applies to the Admin views.</p>
<p>This is such a common circumstance with the models I make that I find it appalling that there's no obvious solution to this...</p>
<p>I've got these classes:</p>
<pre><code># models.py
class Company(models.Model):
# ...
class Contract(models.Model):
company = models.ForeignKey(Company)
locations = models.ManyToManyField('Location')
class Location(models.Model):
company = models.ForeignKey(Company)
</code></pre>
<p>This creates a problem when setting up the Admin for Company, because it has inlines for both Contract and Location, and Contract's m2m options for Location are not properly filtered according to the Company that you're currently editing.</p>
<p>In short, I would need some admin option to do something like this:</p>
<pre><code># admin.py
class LocationInline(admin.TabularInline):
model = Location
class ContractInline(admin.TabularInline):
model = Contract
class CompanyAdmin(admin.ModelAdmin):
inlines = (ContractInline, LocationInline)
inline_filter = dict(Location__company='self')
</code></pre>
<p>Ultimately I wouldn't care if the filtering process was placed on the base CompanyAdmin, or if it was placed on the ContractInline. (Placing it on the inline makes more sense, but it makes it hard to reference the base Contract as 'self'.)</p>
<p>Is there anyone out there who knows of something as straightforward as this badly needed shortcut? Back when I made PHP admins for this sort of thing, this was considered basic functionality! In fact, it was always automatic, and had to be disabled if you really didn't want it!</p>
| 2 | 2009-10-23T00:45:59Z | [
"python",
"django",
"django-forms"
]
|
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | <p>Say I have the following in my <code>models.py</code>:</p>
<pre><code>class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
</code></pre>
<p>I.e. there are multiple <code>Companies</code>, each having a range of <code>Rates</code> and <code>Clients</code>. Each <code>Client</code> should have a base <code>Rate</code> that is chosen from it's parent <code>Company's Rates</code>, not another <code>Company's Rates</code>.</p>
<p>When creating a form for adding a <code>Client</code>, I would like to remove the <code>Company</code> choices (as that has already been selected via an "Add Client" button on the <code>Company</code> page) and limit the <code>Rate</code> choices to that <code>Company</code> as well.</p>
<p>How do I go about this in Django 1.0? </p>
<p>My current <code>forms.py</code> file is just boilerplate at the moment:</p>
<pre><code>from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
</code></pre>
<p>And the <code>views.py</code> is also basic:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
</code></pre>
<p>In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:</p>
<pre><code>manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to"><code>ForeignKey.limit_choices_to</code></a> seems promising but I don't know how to pass in <code>the_company.id</code> and I'm not clear if that will work outside the Admin interface anyway.</p>
<p>Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)</p>
| 152 | 2008-11-15T01:21:33Z | 6,989,226 | <p>If you haven't created the form and want to change the queryset you can do:</p>
<pre><code>formmodel.base_fields['myfield'].queryset = MyModel.objects.filter(...)
</code></pre>
<p>This is pretty useful when you are using generic views!</p>
| 2 | 2011-08-08T22:11:15Z | [
"python",
"django",
"django-forms"
]
|
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | <p>Say I have the following in my <code>models.py</code>:</p>
<pre><code>class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
</code></pre>
<p>I.e. there are multiple <code>Companies</code>, each having a range of <code>Rates</code> and <code>Clients</code>. Each <code>Client</code> should have a base <code>Rate</code> that is chosen from it's parent <code>Company's Rates</code>, not another <code>Company's Rates</code>.</p>
<p>When creating a form for adding a <code>Client</code>, I would like to remove the <code>Company</code> choices (as that has already been selected via an "Add Client" button on the <code>Company</code> page) and limit the <code>Rate</code> choices to that <code>Company</code> as well.</p>
<p>How do I go about this in Django 1.0? </p>
<p>My current <code>forms.py</code> file is just boilerplate at the moment:</p>
<pre><code>from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
</code></pre>
<p>And the <code>views.py</code> is also basic:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
</code></pre>
<p>In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:</p>
<pre><code>manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to"><code>ForeignKey.limit_choices_to</code></a> seems promising but I don't know how to pass in <code>the_company.id</code> and I'm not clear if that will work outside the Admin interface anyway.</p>
<p>Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)</p>
| 152 | 2008-11-15T01:21:33Z | 10,159,363 | <p>To do this with a generic view, like CreateView...</p>
<pre><code>class AddPhotoToProject(CreateView):
"""
a view where a user can associate a photo with a project
"""
model = Connection
form_class = CreateConnectionForm
def get_context_data(self, **kwargs):
context = super(AddPhotoToProject, self).get_context_data(**kwargs)
context['photo'] = self.kwargs['pk']
context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
return context
def form_valid(self, form):
pobj = Photo.objects.get(pk=self.kwargs['pk'])
obj = form.save(commit=False)
obj.photo = pobj
obj.save()
return_json = {'success': True}
if self.request.is_ajax():
final_response = json.dumps(return_json)
return HttpResponse(final_response)
else:
messages.success(self.request, 'photo was added to project!')
return HttpResponseRedirect(reverse('MyPhotos'))
</code></pre>
<p>the most important part of that...</p>
<pre><code> context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
</code></pre>
<p>, <a href="http://gravitymad.com/blog/2012/4/14/how-filter-django-forms-multiple-choice-or-foreign/">read my post here</a></p>
| 12 | 2012-04-15T03:53:42Z | [
"python",
"django",
"django-forms"
]
|
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | <p>Say I have the following in my <code>models.py</code>:</p>
<pre><code>class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
</code></pre>
<p>I.e. there are multiple <code>Companies</code>, each having a range of <code>Rates</code> and <code>Clients</code>. Each <code>Client</code> should have a base <code>Rate</code> that is chosen from it's parent <code>Company's Rates</code>, not another <code>Company's Rates</code>.</p>
<p>When creating a form for adding a <code>Client</code>, I would like to remove the <code>Company</code> choices (as that has already been selected via an "Add Client" button on the <code>Company</code> page) and limit the <code>Rate</code> choices to that <code>Company</code> as well.</p>
<p>How do I go about this in Django 1.0? </p>
<p>My current <code>forms.py</code> file is just boilerplate at the moment:</p>
<pre><code>from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
</code></pre>
<p>And the <code>views.py</code> is also basic:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
</code></pre>
<p>In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:</p>
<pre><code>manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to"><code>ForeignKey.limit_choices_to</code></a> seems promising but I don't know how to pass in <code>the_company.id</code> and I'm not clear if that will work outside the Admin interface anyway.</p>
<p>Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)</p>
| 152 | 2008-11-15T01:21:33Z | 15,667,564 | <p>This is simple, and works with Django 1.4:</p>
<pre><code>class ClientAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ClientAdminForm, self).__init__(*args, **kwargs)
# access object through self.instance...
self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)
class ClientAdmin(admin.ModelAdmin):
form = ClientAdminForm
....
</code></pre>
<p>You don't need to specify this in a form class, but can do it directly in the ModelAdmin, as Django already includes this built-in method on the ModelAdmin (from the docs):</p>
<pre><code>ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to
override the default formfield for a foreign keys field. For example,
to return a subset of objects for this foreign key field based on the
user:'''
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
</code></pre>
<p>An even niftier way to do this (for example in creating a front-end admin interface that users can access) is to subclass the ModelAdmin and then alter the methods below. The net result is a user interface that ONLY shows them content that is related to them, while allowing you (a super-user) to see everything.</p>
<p>I've overridden four methods, the first two make it impossible for a user to delete anything, and it also removes the delete buttons from the admin site. </p>
<p>The third override filters any query that contains a reference to (in the example 'user' or 'porcupine' (just as an illustration). </p>
<p>The last override filters any foreignkey field in the model to filter the choices available the same as the basic queryset. </p>
<p>In this way, you can present an easy to manage front-facing admin site that allows users to mess with their own objects, and you don't have to remember to type in the specific ModelAdmin filters we talked about above. </p>
<pre><code>class FrontEndAdmin(models.ModelAdmin):
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(FrontEndAdmin, self).__init__(model, admin_site)
</code></pre>
<p>remove 'delete' buttons:</p>
<pre><code> def get_actions(self, request):
actions = super(FrontEndAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
</code></pre>
<p>prevents delete permission</p>
<pre><code> def has_delete_permission(self, request, obj=None):
return False
</code></pre>
<p>filters objects that can be viewed on the admin site:</p>
<pre><code> def get_queryset(self, request):
if request.user.is_superuser:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
return qs
else:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
if hasattr(self.model, âuserâ):
return qs.filter(user=request.user)
if hasattr(self.model, âporcupineâ):
return qs.filter(porcupine=request.user.porcupine)
else:
return qs
</code></pre>
<p>filters choices for all foreignkey fields on the admin site:</p>
<pre><code> def formfield_for_foreignkey(self, db_field, request, **kwargs):
if request.employee.is_superuser:
return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
else:
if hasattr(db_field.rel.to, 'user'):
kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
if hasattr(db_field.rel.to, 'porcupine'):
kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)
</code></pre>
| 31 | 2013-03-27T19:18:52Z | [
"python",
"django",
"django-forms"
]
|
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | <p>Say I have the following in my <code>models.py</code>:</p>
<pre><code>class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
</code></pre>
<p>I.e. there are multiple <code>Companies</code>, each having a range of <code>Rates</code> and <code>Clients</code>. Each <code>Client</code> should have a base <code>Rate</code> that is chosen from it's parent <code>Company's Rates</code>, not another <code>Company's Rates</code>.</p>
<p>When creating a form for adding a <code>Client</code>, I would like to remove the <code>Company</code> choices (as that has already been selected via an "Add Client" button on the <code>Company</code> page) and limit the <code>Rate</code> choices to that <code>Company</code> as well.</p>
<p>How do I go about this in Django 1.0? </p>
<p>My current <code>forms.py</code> file is just boilerplate at the moment:</p>
<pre><code>from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
</code></pre>
<p>And the <code>views.py</code> is also basic:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
</code></pre>
<p>In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:</p>
<pre><code>manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to"><code>ForeignKey.limit_choices_to</code></a> seems promising but I don't know how to pass in <code>the_company.id</code> and I'm not clear if that will work outside the Admin interface anyway.</p>
<p>Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)</p>
| 152 | 2008-11-15T01:21:33Z | 38,988,875 | <p>A more public way is by calling get_form in Admin classes. It also works for non-database fields too. For example here i have a field called '_terminal_list' on the form that can be used in special cases for choosing several terminal items from get_list(request), then filtering based on request.user:</p>
<pre><code>class ChangeKeyValueForm(forms.ModelForm):
_terminal_list = forms.ModelMultipleChoiceField(
queryset=Terminal.objects.all() )
class Meta:
model = ChangeKeyValue
fields = ['_terminal_list', 'param_path', 'param_value', 'scheduled_time', ]
class ChangeKeyValueAdmin(admin.ModelAdmin):
form = ChangeKeyValueForm
list_display = ('terminal','task_list', 'plugin','last_update_time')
list_per_page =16
def get_form(self, request, obj = None, **kwargs):
form = super(ChangeKeyValueAdmin, self).get_form(request, **kwargs)
qs, filterargs = Terminal.get_list(request)
form.base_fields['_terminal_list'].queryset = qs
return form
</code></pre>
| 0 | 2016-08-17T05:42:37Z | [
"python",
"django",
"django-forms"
]
|
Short Description of Scoping Rules | 291,978 | <p>What <strong>exactly</strong> are the Python scoping rules?</p>
<p>If I have some code:</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>Where is <em>x</em> found? Some possible choices include the list above:</p>
<ol>
<li>In the enclosing source file</li>
<li>In the class namespace</li>
<li>In the function definition</li>
<li>In the for loop index variable</li>
<li>Inside the for loop</li>
</ol>
<p>Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?</p>
<p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
| 228 | 2008-11-15T01:48:37Z | 292,002 | <p>Python resolves your variables with -- generally -- three namespaces available. </p>
<blockquote>
<p>At any time during execution, there
are at least three nested scopes whose
namespaces are directly accessible:
the innermost scope, which is searched
first, contains the local names; the
namespaces of any enclosing functions,
which are searched starting with the
nearest enclosing scope; the middle
scope, searched next, contains the
current module's global names; and the
outermost scope (searched last) is the
namespace containing built-in names.</p>
</blockquote>
<p>There are two functions: <code>globals</code> and <code>locals</code> which show you the contents two of these namespaces.</p>
<p>Namespaces are created by packages, modules, classes, object construction and functions. There aren't any other flavors of namespaces. </p>
<p>In this case, the call to a function named <code>x</code> has to be resolved in the local name space or the global namespace.</p>
<p>Local in this case, is the body of the method function <code>Foo.spam</code>.</p>
<p>Global is -- well -- global. </p>
<p>The rule is to search the nested local spaces created by method functions (and nested function definitions), then search global. That's it.</p>
<p>There are no other scopes. The <code>for</code> statement (and other compound statements like <code>if</code> and <code>try</code>) don't create new nested scopes. Only definitions (packages, modules, functions, classes and object instances.)</p>
<p>Inside a class definition, the names are part of the class namespace. <code>code2</code>, for instance, must be qualified by the class name. Generally <code>Foo.code2</code>. However, <code>self.code2</code> will also work because Python objects look at the containing class as a fall-back.</p>
<p>An object (an instance of a class) has instance variables. These names are in the object's namespace. They must be qualified by the object. (<code>variable.instance</code>.) </p>
<p>From within a class method, you have locals and globals. You say <code>self.variable</code> to pick the instance as the namespace. You'll note that <code>self</code> is an argument to every class member function, making it part of the local namespace.</p>
<p>See <a href="http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html" rel="nofollow">Python Scope Rules</a>, <a href="http://stackoverflow.com/questions/146359/python-scope">Python Scope</a>, <a href="http://showmedo.com/videos/video?name=2800020&fromSeriesID=280" rel="nofollow">Variable Scope</a>.</p>
| 6 | 2008-11-15T02:03:38Z | [
"python",
"scope",
"dynamic-languages"
]
|
Short Description of Scoping Rules | 291,978 | <p>What <strong>exactly</strong> are the Python scoping rules?</p>
<p>If I have some code:</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>Where is <em>x</em> found? Some possible choices include the list above:</p>
<ol>
<li>In the enclosing source file</li>
<li>In the class namespace</li>
<li>In the function definition</li>
<li>In the for loop index variable</li>
<li>Inside the for loop</li>
</ol>
<p>Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?</p>
<p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
| 228 | 2008-11-15T01:48:37Z | 292,498 | <blockquote>
<p>Where is x found?</p>
</blockquote>
<p>x is not found as you haven't defined it. :-) It could be found in code1 (global) or code3 (local) if you put it there.</p>
<p>code2 (class members) aren't visible to code inside methods of the same classâââyou would usually access them using self. code4/code5 (loops) live in the same scope as code3, so if you wrote to x in there you would be changing the x instance defined in code3, not making a new x.</p>
<p>Python is statically scoped, so if you pass âspamâ to another function spam will still have access to globals in the module it came from (defined in code1), and any other containing scopes (see below). code2 members would again be accessed through self.</p>
<p>lambda is no different to def. If you have a lambda used inside a function, it's the same as defining a nested function. In Python 2.2 onwards, nested scopes are available. In this case you can bind x at any level of function nesting and Python will pick up the innermost instance:</p>
<pre><code>x= 0
def fun1():
x= 1
def fun2():
x= 2
def fun3():
return x
return fun3()
return fun2()
print fun1(), x
2 0
</code></pre>
<p>fun3 sees the instance x from the nearest containing scope, which is the function scope associated with fun2. But the other x instances, defined in fun1 and globally, are not affected.</p>
<p>Before nested_scopesâââin Python pre-2.1, and in 2.1 unless you specifically ask for the feature using a from-future-importâââfun1 and fun2's scopes are not visible to fun3, so S.Lott's answer holds and you would get the global x:</p>
<pre><code>0 0
</code></pre>
| 5 | 2008-11-15T12:44:59Z | [
"python",
"scope",
"dynamic-languages"
]
|
Short Description of Scoping Rules | 291,978 | <p>What <strong>exactly</strong> are the Python scoping rules?</p>
<p>If I have some code:</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>Where is <em>x</em> found? Some possible choices include the list above:</p>
<ol>
<li>In the enclosing source file</li>
<li>In the class namespace</li>
<li>In the function definition</li>
<li>In the for loop index variable</li>
<li>Inside the for loop</li>
</ol>
<p>Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?</p>
<p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
| 228 | 2008-11-15T01:48:37Z | 292,502 | <p>Actually, a concise rule for Python Scope resolution, from <a href="http://rads.stackoverflow.com/amzn/click/0596513984">Learning Python, 3rd. Ed.</a>. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply)</p>
<p>LEGB Rule.</p>
<p><strong>L</strong>, Local â Names assigned in any way within a function (<code>def</code> or <code>lambda</code>)), and not declared global in that function.</p>
<p><strong>E</strong>, Enclosing function locals â Name in the local scope of any and all enclosing functions (<code>def</code> or <code>lambda</code>), from inner to outer.</p>
<p><strong>G</strong>, Global (module) â Names assigned at the top-level of a module file, or declared global in a <code>def</code> within the file.</p>
<p><strong>B</strong>, Built-in (Python) â Names preassigned in the built-in names module : <code>open</code>,<code>range</code>,<code>SyntaxError</code>,...</p>
<p>So, in the case of</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>The for loop does not have its own namespace. In LEGB order, the scopes would be </p>
<p>L : local, in the current def.</p>
<p>E : Enclosed function, any enclosing functions (if def spam was in another def)</p>
<p>G : Global. Were there any declared globally in the module?</p>
<p>B : Any builtin x() in Python.</p>
| 212 | 2008-11-15T12:47:22Z | [
"python",
"scope",
"dynamic-languages"
]
|
Short Description of Scoping Rules | 291,978 | <p>What <strong>exactly</strong> are the Python scoping rules?</p>
<p>If I have some code:</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>Where is <em>x</em> found? Some possible choices include the list above:</p>
<ol>
<li>In the enclosing source file</li>
<li>In the class namespace</li>
<li>In the function definition</li>
<li>In the for loop index variable</li>
<li>Inside the for loop</li>
</ol>
<p>Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?</p>
<p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
| 228 | 2008-11-15T01:48:37Z | 292,907 | <p>The scoping rules for Python 2.x have been outlined already in other answers. The only thing I would add is that in Python 3.0, there is also the concept of a non-local scope (indicated by the 'nonlocal' keyword). This allows you to access outer scopes directly, and opens up the ability to do some neat tricks, including lexical closures (without ugly hacks involving mutable objects).</p>
<p>EDIT: Here's the <a href="http://www.python.org/dev/peps/pep-3104/">PEP</a> with more information on this.</p>
| 17 | 2008-11-15T18:52:49Z | [
"python",
"scope",
"dynamic-languages"
]
|
Short Description of Scoping Rules | 291,978 | <p>What <strong>exactly</strong> are the Python scoping rules?</p>
<p>If I have some code:</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>Where is <em>x</em> found? Some possible choices include the list above:</p>
<ol>
<li>In the enclosing source file</li>
<li>In the class namespace</li>
<li>In the function definition</li>
<li>In the for loop index variable</li>
<li>Inside the for loop</li>
</ol>
<p>Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?</p>
<p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
| 228 | 2008-11-15T01:48:37Z | 293,097 | <p>Essentially, the only thing in Python that introduces a new scope is a function definition. Classes are a bit of a special case in that anything defined directly in the body is placed in the class's namespace, but they are not directly accessible from within the methods (or nested classes) they contain.</p>
<p>In your example there are only 3 scopes where x will be searched in:</p>
<ul>
<li><p>spam's scope - containing everything defined in code3 and code5 (as well as code4, your loop variable)</p></li>
<li><p>The global scope - containing everything defined in code1, as well as Foo (and whatever changes after it)</p></li>
<li><p>The builtins namespace. A bit of a special case - this contains the various Python builtin functions and types such as len() and str(). Generally this shouldn't be modified by any user code, so expect it to contain the standard functions and nothing else.</p></li>
</ul>
<p>More scopes only appear when you introduce a nested function (or lambda) into the picture.
These will behave pretty much as you'd expect however. The nested function can access everything in the local scope, as well as anything in the enclosing function's scope. eg.</p>
<pre><code>def foo():
x=4
def bar():
print x # Accesses x from foo's scope
bar() # Prints 4
x=5
bar() # Prints 5
</code></pre>
<p><strong>Restrictions:</strong></p>
<p>Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new <strong>local</strong> variable instead of affecting the variable in the parent scope. For example:</p>
<pre><code>global_var1 = []
global_var2 = 1
def func():
# This is OK: It's just accessing, not rebinding
global_var1.append(4)
# This won't affect global_var2. Instead it creates a new variable
global_var2 = 2
local1 = 4
def embedded_func():
# Again, this doen't affect func's local1 variable. It creates a
# new local variable also called local1 instead.
local1 = 5
print local1
embedded_func() # Prints 5
print local1 # Prints 4
</code></pre>
<p>In order to actually modify the bindings of global variables from within a function scope, you need to specify that the variable is global with the global keyword. Eg:</p>
<pre><code>global_var = 4
def change_global():
global global_var
global_var = global_var + 1
</code></pre>
<p>Currently there is no way to do the same for variables in enclosing <em>function</em> scopes, but Python 3 introduces a new keyword, "<code>nonlocal</code>" which will act in a similar way to global, but for nested function scopes.</p>
| 96 | 2008-11-15T21:51:09Z | [
"python",
"scope",
"dynamic-languages"
]
|
Short Description of Scoping Rules | 291,978 | <p>What <strong>exactly</strong> are the Python scoping rules?</p>
<p>If I have some code:</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>Where is <em>x</em> found? Some possible choices include the list above:</p>
<ol>
<li>In the enclosing source file</li>
<li>In the class namespace</li>
<li>In the function definition</li>
<li>In the for loop index variable</li>
<li>Inside the for loop</li>
</ol>
<p>Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?</p>
<p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
| 228 | 2008-11-15T01:48:37Z | 23,471,004 | <p>There was no thorough answer concerning Python3 time, so I made an answer here.</p>
<p>As provided in other answers, there are 4 basic scopes, the LEGB, for Local, Enclosing, Global and Builtin. In addition to those, there is a special scope, the <strong>class body</strong>, which does not comprise an enclosing scope for methods defined within the class; any assignments within the class body make the variable from there on be bound in the class body.</p>
<p>Especially, <strong>no</strong> block statement, besides <code>def</code> and <code>class</code>, create a variable scope. In Python 2 the list comprehension does not create a variable scope, however in Python 3 the loop variable is created in a new scope.</p>
<p>To demonstrate the peculiarities of the class body</p>
<pre><code>x = 0
class X(object):
y = x
x = x + 1 # x is now a variable
z = x
def method(self):
print(self.x) # -> 1
print(x) # -> 0, the global x
print(y) # -> NameError: global name 'y' is not defined
inst = X()
print(inst.x, inst.y, inst.z, x) # -> (1, 0, 1, 0)
</code></pre>
<p>Thus unlike in function body, you can reassign the variable to the same name in class body, to get a class variable with the same name; further lookups on this name resolve
to the class variable instead.</p>
<hr>
<p>One of the greater surprises to many newcomers to Python is that a <code>for</code> loop does not create a variable scope. In Python 2 the list comprehensions do not create a scope either (while generators and dict comprehensions do!) Instead they leak the value in the function or the global scope:</p>
<pre><code>>>> [ i for i in range(5) ]
>>> i
4
</code></pre>
<p>The comprehensions can be used as a cunning (or awful if you will) way to make modifiable variables within lambda expressions in Python 2 - a lambda expression does create a variable scope, like the <code>def</code> statement would, but within lambda no statements are allowed. Assignment being a statement in Python means that no variable assignments in lambda are allowed, but a list comprehension is an expression...</p>
<p>This behaviour has been fixed in Python 3 - no comprehension expressions or generators leak variables.</p>
<hr>
<p>The global really means the module scope; the main python module is the <code>__main__</code>; all imported modules are accessible through the <code>sys.modules</code> variable; to get access to <code>__main__</code> one can use <code>sys.modules['__main__']</code>, or <code>import __main__</code>; it is perfectly acceptable to access and assign attributes there; they will show up as variables in the global scope of the main module.</p>
<hr>
<p>If a name is ever assigned to in the current scope (except in the class scope), it will be considered belonging to that scope, otherwise it will be considered to belonging to any enclosing scope that assigns to the variable (it might not be assigned yet, or not at all), or finally the global scope. If the variable is considered local, but it is not set yet, or has been deleted, reading the variable value will result in <code>UnboundLocalError</code>, which is a subclass of <code>NameError</code>.</p>
<pre><code>x = 5
def foobar()
print(x) # UnboundLocalError!
x += 1 # assignment here makes x a local variable!
</code></pre>
<p>The scope can declare that it explicitly wants to modify the global (module scope) variable, with the global keyword:</p>
<pre><code>x = 5
def foobar():
global x
print(x) # -> 5
x += 1
foobar()
print(x) # -> 6
</code></pre>
<p>This also is possible even if it was shadowed in enclosing scope:</p>
<pre><code>x = 5
y = 13
def make_closure():
x = 42
y = 911
def func():
global x # sees the global value
print(x, y)
x += 1
return func
func = make_closure()
func() # -> print 5 911
print(x, y) # -> 6 13
</code></pre>
<p>In python 2 there is no easy way to modify the value in the enclosing scope; usually this is simulated by having a mutable value, such as a list with length of 1:</p>
<pre><code>def make_closure():
value = [0]
def get_next_value():
value[0] += 1
return value[0]
return get_next_value
get_next = make_closure()
print(get_next()) # -> 1
print(get_next()) # -> 2
</code></pre>
<p>However in python 3, the <code>nonlocal</code> comes to rescue:</p>
<pre><code>def make_closure():
value = 0
def get_next_value():
nonlocal value
value += 1
return value
return get_next_value
get_next = make_closure() # identical behavior to the previous example.
</code></pre>
<hr>
<p>Any variable that is not deemed to be local to the current scope, or any enclosing scope, is a global variable. A global name is looked up in the module global dictionary; if not found, the global is then looked up from the builtins module; the name of the module was changed from python 2 to python 3; in python 2 it was <code>__builtin__</code> and in python 3 it is now called <code>builtins</code>. If you assign to an attribute of builtins module, it will be visible thereafter to any module as a readable global variable, unless that module shadows them with its own global variable with the same name.</p>
<hr>
<p>Reading the builtin module can also be useful; suppose that you want the python 3 style print function in some parts of file, but other parts of file still use the <code>print</code> statement, if your python version is >= 2.6, you can get the new style function as:</p>
<pre><code>import __builtin__
print3 = __builtin__.__dict__['print']
</code></pre>
<p>The <code>from __future__ import print_function</code> actually does not import the <code>print</code> function anywhere in Python 2 - instead it just disables the parsing rules for <code>print</code> statement in the current module, handling <code>print</code> like any other variable identifier, and thus allowing the <code>print</code> the function be looked up in the builtins.</p>
| 44 | 2014-05-05T11:08:54Z | [
"python",
"scope",
"dynamic-languages"
]
|
Short Description of Scoping Rules | 291,978 | <p>What <strong>exactly</strong> are the Python scoping rules?</p>
<p>If I have some code:</p>
<pre><code>code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
</code></pre>
<p>Where is <em>x</em> found? Some possible choices include the list above:</p>
<ol>
<li>In the enclosing source file</li>
<li>In the class namespace</li>
<li>In the function definition</li>
<li>In the for loop index variable</li>
<li>Inside the for loop</li>
</ol>
<p>Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?</p>
<p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
| 228 | 2008-11-15T01:48:37Z | 34,094,235 | <p>A slightly more complete example of scope:</p>
<pre><code>x = 100
print "1. Global x:", x
class Test(object):
y = x
print "2. Enclosed y:", y
x = x + 1
print "3. Enclosed x:", x
z = x
def method(self):
print "4. Enclosed self.x", self.x
print "5. Global x", x
try:
print y
except NameError, e:
print "6.", e
def method_local_ref(self):
try:
print x
except UnboundLocalError, e:
print "7.", e
x = 200
print "8. Local x", x
inst = Test()
inst.method()
inst.method_local_ref()
</code></pre>
<p>output:</p>
<blockquote>
<ol>
<li>Global x: 100</li>
<li>Enclosed y: 100</li>
<li>Enclosed x: 101</li>
<li>Enclosed self.x 101</li>
<li>Global x 100</li>
<li>global name 'y' is not defined</li>
<li>local variable 'x' referenced before assignment</li>
<li>Local x 200</li>
</ol>
</blockquote>
| 9 | 2015-12-04T17:38:37Z | [
"python",
"scope",
"dynamic-languages"
]
|
Polling the keyboard (detect a keypress) in python | 292,095 | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code> while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p>
| 43 | 2008-11-15T03:29:09Z | 292,119 | <p>You might look at how <a href="http://books.google.com/books?id=W8T2f7F_rs0C&pg=PA147&lpg=PA147&dq=pygame+keyboard+polling&source=web&ots=Chhw92jDrx&sig=lavBFmwAUzB06J5er8T-AHN4eWs&hl=en&sa=X&oi=book_result&resnum=1&ct=result" rel="nofollow">pygame</a> handles this to steal some ideas.</p>
| 5 | 2008-11-15T03:49:45Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
]
|
Polling the keyboard (detect a keypress) in python | 292,095 | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code> while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p>
| 43 | 2008-11-15T03:29:09Z | 292,770 | <p>The standard approach is to use the <a href="https://docs.python.org/2/library/select.html" rel="nofollow">select</a> module.</p>
<p>However, this doesn't work on Windows. For that, you can use the <a href="https://docs.python.org/2/library/msvcrt.html#console-i-o" rel="nofollow">msvcrt</a> module's keyboard polling.</p>
<p>Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.</p>
| 19 | 2008-11-15T17:09:00Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
]
|
Polling the keyboard (detect a keypress) in python | 292,095 | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code> while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p>
| 43 | 2008-11-15T03:29:09Z | 293,249 | <p>From the comments:</p>
<pre><code>import msvcrt # built-in module
def kbfunc():
return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
</code></pre>
<p><hr /></p>
<p>Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:</p>
<pre><code>#include <conio.h>
int kb_inkey () {
int rc;
int key;
key = _kbhit();
if (key == 0) {
rc = 0;
} else {
rc = _getch();
}
return rc;
}
</code></pre>
<p>And I access it in python using the ctypes module (built into python 2.5):</p>
<pre><code>import ctypes
import time
#
# first, load the DLL
#
try:
kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
raise ("Error Loading PyKeyboardAccess.dll")
#
# now, find our function
#
try:
kbfunc = kblib.kb_inkey
except:
raise ("Could not find the kb_inkey function in the dll!")
#
# Ok, now let's demo the capability
#
while 1:
x = kbfunc()
if x != 0:
print "Got key: %d" % x
else:
time.sleep(.01)
</code></pre>
| 4 | 2008-11-15T23:53:49Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
]
|
Polling the keyboard (detect a keypress) in python | 292,095 | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code> while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p>
| 43 | 2008-11-15T03:29:09Z | 303,976 | <p>Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:</p>
<pre><code>import msvcrt
def kbfunc():
x = msvcrt.kbhit()
if x:
ret = ord(msvcrt.getch())
else:
ret = 0
return ret
</code></pre>
| 10 | 2008-11-20T00:32:05Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
]
|
Polling the keyboard (detect a keypress) in python | 292,095 | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code> while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p>
| 43 | 2008-11-15T03:29:09Z | 1,450,063 | <pre><code>
import sys
import select
def heardEnter():
i,o,e = select.select([sys.stdin],[],[],0.0001)
for s in i:
if s == sys.stdin:
input = sys.stdin.readline()
return True
return False
</code></pre>
| 12 | 2009-09-20T01:47:23Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
]
|
Polling the keyboard (detect a keypress) in python | 292,095 | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code> while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p>
| 43 | 2008-11-15T03:29:09Z | 3,524,350 | <p>A solution using the curses module. Printing a numeric value corresponding to each key pressed:</p>
<pre><code>import curses
def main(stdscr):
# do not wait for input when calling getch
stdscr.nodelay(1)
while True:
# get keyboard input, returns -1 if none available
c = stdscr.getch()
if c != -1:
# print numeric value
stdscr.addstr(str(c) + ' ')
stdscr.refresh()
# return curser to start position
stdscr.move(0, 0)
if __name__ == '__main__':
curses.wrapper(main)
</code></pre>
| 7 | 2010-08-19T17:12:50Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
]
|
Polling the keyboard (detect a keypress) in python | 292,095 | <p>How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):</p>
<pre><code> while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
</code></pre>
<p>What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.</p>
| 43 | 2008-11-15T03:29:09Z | 31,754,526 | <p>If you combine time.sleep, threading.Thread, and sys.stdin.read you can easily wait for a specified amount of time for input and then continue,
also this should be cross-platform compatible.</p>
<pre><code>t = threading.Thread(target=sys.stdin.read(1) args=(1,))
t.start()
time.sleep(5)
t.join()
</code></pre>
<p>You could also place this into a function like so</p>
<pre><code>def timed_getch(self, bytes=1, timeout=1):
t = threading.Thread(target=sys.stdin.read, args=(bytes,))
t.start()
time.sleep(timeout)
t.join()
del t
</code></pre>
<p>Although this will not return anything so instead you should use the multiprocessing pool module you can find that here: <a href="http://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python">how to get the return value from a thread in python?</a></p>
| 0 | 2015-07-31T20:18:05Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
]
|
excluding characters in \S regex match | 292,167 | <p>I have the following regex expression to match html links:</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?</p>
<p><strong>EDIT:</strong> This would make it grab only up to the quotes instead of everything after the < a href btw</p>
| 1 | 2008-11-15T04:56:53Z | 292,192 | <p>Why are you trying to match HTML links with a regex?</p>
<p>Depending on what you're trying to do the appropriate thing to do would vary.</p>
<p>You could try using an HTML Parser. There are several available, there's even one in the Python Library: <a href="https://docs.python.org/library/htmlparser.html" rel="nofollow">https://docs.python.org/library/htmlparser.html</a></p>
<p>Hope this helps!</p>
| 1 | 2008-11-15T05:33:39Z | [
"python",
"html",
"regex"
]
|
excluding characters in \S regex match | 292,167 | <p>I have the following regex expression to match html links:</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?</p>
<p><strong>EDIT:</strong> This would make it grab only up to the quotes instead of everything after the < a href btw</p>
| 1 | 2008-11-15T04:56:53Z | 292,193 | <pre><code>>>> import re
>>> regex = '<a\s+href=["\'](http://(.*?))["\']>'
>>> string = '<a href="http://google.com/test/this">'
>>> match = re.search(regex, string)
>>> match.group(1)
'http://google.com/test/this'
>>> match.group(2)
'google.com/test/this'
</code></pre>
<p>explanations:</p>
<pre><code> \s+ = match at least one white space (<ahref) is a bad link
["\'] = character class, | has no meaning within square brackets
(it will match a literal pipe "|")
</code></pre>
| 1 | 2008-11-15T05:33:53Z | [
"python",
"html",
"regex"
]
|
excluding characters in \S regex match | 292,167 | <p>I have the following regex expression to match html links:</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?</p>
<p><strong>EDIT:</strong> This would make it grab only up to the quotes instead of everything after the < a href btw</p>
| 1 | 2008-11-15T04:56:53Z | 292,213 | <p>I don't think your regex is doing what you want.</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>This captures anything non-greedily from http:// up to the first non-space character before a quote, single quote, or pipe. For that matter, I'm not sure how it parses, as it doesn't seem to have enough close parens.</p>
<p>If you are trying to capture the href, you might try something like this:</p>
<pre><code><a .*?+href=['"](http:\/\/.*?)['"].*?>
</code></pre>
<p>This uses the .*? (non-greedy match anything) to allow for other attributes (target, title, etc.). It matches an href that begins and ends with either a single or double quote (it does not distinguish, and allows the href to open with one and close with the other).</p>
| 4 | 2008-11-15T05:54:24Z | [
"python",
"html",
"regex"
]
|
excluding characters in \S regex match | 292,167 | <p>I have the following regex expression to match html links:</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?</p>
<p><strong>EDIT:</strong> This would make it grab only up to the quotes instead of everything after the < a href btw</p>
| 1 | 2008-11-15T04:56:53Z | 292,282 | <p>\S matches any character that is not a whitespace character, just like [^\s]</p>
<p>Written like that, you can easily exclude quotes: [^\s"']</p>
<p>Note that you'll likely have to give the .*? in your regex the same treatment. The dot matches any character that is not a newline, just like [^\r\n]</p>
<p>Again, written like that, you can easily exclude quotes: [^\r\n'"]</p>
| 1 | 2008-11-15T07:50:13Z | [
"python",
"html",
"regex"
]
|
excluding characters in \S regex match | 292,167 | <p>I have the following regex expression to match html links:</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?</p>
<p><strong>EDIT:</strong> This would make it grab only up to the quotes instead of everything after the < a href btw</p>
| 1 | 2008-11-15T04:56:53Z | 292,749 | <p>Read Jeff Friedl's "Mastering Regular Expressions" book.</p>
<p>As written:</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>You have unbalanced parentheses in the expression. Maybe the trouble is that the first match is being treated as "read to end of regex". Also, why would you not want the last non-space character of the URL?</p>
<p>The .*? (lazy greedy) operator is interesting. I must say, though, that I'd be more inclined to write:</p>
<pre><code><a\s+href=['|"]http://([^'"><]+)\1>
</code></pre>
<p>This distinguishes between "<ahref" (a non-existent HTML tag) and "<a href" (a valid HTML tag). It doesn't capture the 'http://' prefix. I'm not certain whether you have to escape the slashes -- in Perl, where I mainly work, I wouldn't need to. The capturing part uses the greedy match, but only on characters that might semi-legitimately appear in the URL. Specifically, it excludes both quotes and the end-tag (and, for good measure, the begin-tag too). If you really want the 'http://' prefix, shift the capturing parenthesis appropriately.</p>
| 0 | 2008-11-15T16:48:37Z | [
"python",
"html",
"regex"
]
|
excluding characters in \S regex match | 292,167 | <p>I have the following regex expression to match html links:</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?</p>
<p><strong>EDIT:</strong> This would make it grab only up to the quotes instead of everything after the < a href btw</p>
| 1 | 2008-11-15T04:56:53Z | 500,235 | <p>I ran into on issue with single quotes in some urls such as this one from Fox Sports. I made a slight adjustment that I think should take care of it.</p>
<p><a href="http://msn.foxsports.com/mlb/story/9152594/Fehr" rel="nofollow">http://msn.foxsports.com/mlb/story/9152594/Fehr</a>:'Heightened'-concern-about-free-agent-market</p>
<p>/<a\s+href\s*=\s*["'](http:\/\/.*?)["'][>\s]/i</p>
<p>this requires that the closing quote be followed by a space or closing bracket.</p>
| 0 | 2009-02-01T05:00:47Z | [
"python",
"html",
"regex"
]
|
"Unknown column 'user_id' error in django view | 293,300 | <p>I'm having an error where I am not sure what caused it.</p>
<p>Here is the error:</p>
<pre><code>Exception Type: OperationalError
Exception Value:
(1054, "Unknown column 'user_id' in 'field list'")
</code></pre>
<p>Does anyone know why I am getting this error? I can't figure it out. Everything seems to be fine. </p>
<p>My view code is below:</p>
<pre><code>if "login" in request.session:
t = request.POST.get('title', '')
d = request.POST.get('description', '')
fid = request.session["login"]
fuser = User.objects.get(id=fid)
i = Idea(user=fuser, title=t, description=d, num_votes=1)
i.save()
return HttpResponse("true", mimetype="text/plain")
else:
return HttpResponse("false", mimetype="text/plain")
</code></pre>
<p>I appreciate any help! Thanks!</p>
<p>Edit: Also a side question. Do I use objects.get(id= or objects.get(pk= ? If I use a primary key, do I need to declare an id field or an index in the model?</p>
<p>Edit: Here are the relevant models:</p>
<pre><code>class User (models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
password = models.CharField(max_length=200)
class Idea (models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
description = models.CharField(max_length=255)
num_votes = models.IntegerField()
</code></pre>
| 5 | 2008-11-16T00:44:35Z | 293,333 | <p>You'll have to show your models to get real help, but it looks like your Idea table doesn't have a user_id column? Did you modify the SQL table structure?</p>
| 4 | 2008-11-16T01:22:46Z | [
"python",
"django",
"django-models",
"model",
"view"
]
|
"Unknown column 'user_id' error in django view | 293,300 | <p>I'm having an error where I am not sure what caused it.</p>
<p>Here is the error:</p>
<pre><code>Exception Type: OperationalError
Exception Value:
(1054, "Unknown column 'user_id' in 'field list'")
</code></pre>
<p>Does anyone know why I am getting this error? I can't figure it out. Everything seems to be fine. </p>
<p>My view code is below:</p>
<pre><code>if "login" in request.session:
t = request.POST.get('title', '')
d = request.POST.get('description', '')
fid = request.session["login"]
fuser = User.objects.get(id=fid)
i = Idea(user=fuser, title=t, description=d, num_votes=1)
i.save()
return HttpResponse("true", mimetype="text/plain")
else:
return HttpResponse("false", mimetype="text/plain")
</code></pre>
<p>I appreciate any help! Thanks!</p>
<p>Edit: Also a side question. Do I use objects.get(id= or objects.get(pk= ? If I use a primary key, do I need to declare an id field or an index in the model?</p>
<p>Edit: Here are the relevant models:</p>
<pre><code>class User (models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
password = models.CharField(max_length=200)
class Idea (models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
description = models.CharField(max_length=255)
num_votes = models.IntegerField()
</code></pre>
| 5 | 2008-11-16T00:44:35Z | 293,335 | <ol>
<li><p>The <code>user_id</code> field is the FK reference from <code>Idea</code> to <code>User</code>. It looks like you've changed your model, and not updated your database, then you'll have this kind of problem.</p>
<p>Drop the old table, rerun syncdb.</p></li>
<li><p>Your model tables get an <code>id</code> field by default. You can call it <code>id</code> in your queries. You can also use the synonym of <code>pk</code>.</p>
<p>If you define your own primary key field you, you don't get the automatic <code>id</code> field. But you can still use <code>pk</code> to refer to the Primary Key.</p></li>
</ol>
| 5 | 2008-11-16T01:25:48Z | [
"python",
"django",
"django-models",
"model",
"view"
]
|
"Unknown column 'user_id' error in django view | 293,300 | <p>I'm having an error where I am not sure what caused it.</p>
<p>Here is the error:</p>
<pre><code>Exception Type: OperationalError
Exception Value:
(1054, "Unknown column 'user_id' in 'field list'")
</code></pre>
<p>Does anyone know why I am getting this error? I can't figure it out. Everything seems to be fine. </p>
<p>My view code is below:</p>
<pre><code>if "login" in request.session:
t = request.POST.get('title', '')
d = request.POST.get('description', '')
fid = request.session["login"]
fuser = User.objects.get(id=fid)
i = Idea(user=fuser, title=t, description=d, num_votes=1)
i.save()
return HttpResponse("true", mimetype="text/plain")
else:
return HttpResponse("false", mimetype="text/plain")
</code></pre>
<p>I appreciate any help! Thanks!</p>
<p>Edit: Also a side question. Do I use objects.get(id= or objects.get(pk= ? If I use a primary key, do I need to declare an id field or an index in the model?</p>
<p>Edit: Here are the relevant models:</p>
<pre><code>class User (models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
password = models.CharField(max_length=200)
class Idea (models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
description = models.CharField(max_length=255)
num_votes = models.IntegerField()
</code></pre>
| 5 | 2008-11-16T00:44:35Z | 1,983,734 | <p>Yes, I dropped the tables and it all worked great. However, you have to actually go into the database and DROP them. "manage.py flush" or "manage.py reset appname" won't do it by themselves.</p>
<p>-Nick O</p>
| 0 | 2009-12-31T03:01:31Z | [
"python",
"django",
"django-models",
"model",
"view"
]
|
wxPython, Set value of StaticText() | 293,344 | <p>I am making a little GUI frontend for a app at the moment using wxPython.</p>
<p>I am using <code>wx.StaticText()</code> to create a place to hold some text, code below:</p>
<pre><code>content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE)
</code></pre>
<p>I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the <code>StaticText()</code> to the MySQL data or what else could I use the hold the data.</p>
<p>I have tried using the below method: </p>
<pre><code>contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL)
content.SetValue("New Text")
</code></pre>
<p>This displays the data fine but after the data is loaded you can edit the data and I do not want this.</p>
<p>Hope you guys understand what I am trying to do, I am new to Python :)</p>
<p>Cheers</p>
| 24 | 2008-11-16T01:52:15Z | 293,350 | <p><code>wx.TextCtrl</code> has a style called <code>wx.TE_READONLY</code> . Use that to make it read-only.</p>
<p>As a sidenode, you can use the <a href="http://docs.wxwidgets.org/stable/wx_contents.html">C++ wxWidgets Manual</a> for wxPython aswell. Where special handling for wxPython or other ports is required, the manual often points out the difference.</p>
| 18 | 2008-11-16T02:00:54Z | [
"python",
"wxpython"
]
|
wxPython, Set value of StaticText() | 293,344 | <p>I am making a little GUI frontend for a app at the moment using wxPython.</p>
<p>I am using <code>wx.StaticText()</code> to create a place to hold some text, code below:</p>
<pre><code>content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE)
</code></pre>
<p>I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the <code>StaticText()</code> to the MySQL data or what else could I use the hold the data.</p>
<p>I have tried using the below method: </p>
<pre><code>contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL)
content.SetValue("New Text")
</code></pre>
<p>This displays the data fine but after the data is loaded you can edit the data and I do not want this.</p>
<p>Hope you guys understand what I am trying to do, I am new to Python :)</p>
<p>Cheers</p>
| 24 | 2008-11-16T01:52:15Z | 294,100 | <p>If you are using a <a href="http://docs.wxwidgets.org/stable/wx_wxstatictext.html#wxstatictextsetlabel">wx.StaticText()</a> you can just:</p>
<pre><code>def __init__(self, parent, *args, **kwargs): #frame constructor, etc.
self.some_text = wx.StaticText(panel, wx.ID_ANY, label="Awaiting MySQL Data", style=wx.ALIGN_CENTER)
def someFunction(self):
mysql_data = databasemodel.returnData() #query your database to return a string
self.some_text.SetLabel(mysql_data)
</code></pre>
<p>As litb mentioned, the wxWidgets docs are often much easier to use than the <a href="http://wxpython.org/docs/api/wx.StaticText-class.html">wxPython docs</a>. In order to see that the SetLabel() function can be applied to a wx.StaticText instance, you have to travel up the namespace hierarchy in the wxPython docs to the <a href="http://wxpython.org/docs/api/wx.Window-class.html#SetLabel">wxWindow superclass</a>, from which wx.StaticText is subclassed. There are a few things different in wxPython from wxWidgets, and it can be challenging to find out what they are. Fortunately, a lot of the time, the differences are convenience functions that have been added to wxPython and are not found in wxWidgets.</p>
| 50 | 2008-11-16T16:55:03Z | [
"python",
"wxpython"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 293,447 | <p>'self' is only a reference to the object. 'del self' is deleting the 'self' reference from the local namespace of the kill function, instead of the actual object.</p>
<p>To see this for yourself, look at what happens when these two functions are executed:</p>
<pre><code>>>> class A():
... def kill_a(self):
... print self
... del self
... def kill_b(self):
... del self
... print self
...
>>> a = A()
>>> b = A()
>>> a.kill_a()
<__main__.A instance at 0xb771250c>
>>> b.kill_b()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in kill_b
UnboundLocalError: local variable 'self' referenced before assignment
</code></pre>
| 60 | 2008-11-16T03:41:12Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 293,454 | <p>You don't need to use del to delete instances in the first place. Once the last reference to an object is gone, the object will be garbage collected. Maybe you should tell us more about the full problem.</p>
| 36 | 2008-11-16T03:46:09Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 293,462 | <p>Indeed, Python does garbage collection through reference counting. As soon as the last reference to an object falls out of scope, it is deleted. In your example:</p>
<pre><code>a = A()
a.kill()
</code></pre>
<p>I don't believe there's any way for variable 'a' to implicitly set itself to None.</p>
| 1 | 2008-11-16T03:59:10Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 293,485 | <p>I'm curious as to why you would want to do such a thing. Chances are, you should just let garbage collection do its job. In python, garbage collection is pretty deterministic. So you don't really have to worry as much about just leaving objects laying around in memory like you would in other languages (not to say that refcounting doesn't have disadvantages).</p>
<p>Although one thing that you should consider is a wrapper around any objects or resources you may get rid of later.</p>
<pre><code>class foo(object):
def __init__(self):
self.some_big_object = some_resource
def killBigObject(self):
del some_big_object
</code></pre>
<p>In response to <a href="http://stackoverflow.com/questions/293431/python-object-deleting-itself#293497">Null's addendum</a>:</p>
<p>Unfortunately, I don't believe there's a way to do what you want to do the way you want to do it. Here's one way that you may wish to consider:</p>
<pre><code>>>> class manager(object):
... def __init__(self):
... self.lookup = {}
... def addItem(self, name, item):
... self.lookup[name] = item
... item.setLookup(self.lookup)
>>> class Item(object):
... def __init__(self, name):
... self.name = name
... def setLookup(self, lookup):
... self.lookup = lookup
... def deleteSelf(self):
... del self.lookup[self.name]
>>> man = manager()
>>> item = Item("foo")
>>> man.addItem("foo", item)
>>> man.lookup
{'foo': <__main__.Item object at 0x81b50>}
>>> item.deleteSelf()
>>> man.lookup
{}
</code></pre>
<p>It's a little bit messy, but that should give you the idea. Essentially, I don't think that tying an item's existence in the game to whether or not it's allocated in memory is a good idea. This is because the conditions for the item to be garbage collected are probably going to be different than what the conditions are for the item in the game. This way, you don't have to worry so much about that.</p>
| 0 | 2008-11-16T04:19:45Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 293,920 | <p>In this specific context, your example doesn't make a lot of sense.</p>
<p>When a Being picks up an Item, the item retains an individual existence. It doesn't disappear because it's been picked up. It still exists, but it's (a) in the same location as the Being, and (b) no longer eligible to be picked up. While it's had a state change, it still exists.</p>
<p>There is a two-way association between Being and Item. The Being has the Item in a collection. The Item is associated with a Being.</p>
<p>When an Item is picked up by a Being, two things have to happen.</p>
<ul>
<li><p>The Being how adds the Item in some <code>set</code> of items. Your <code>bag</code> attribute, for example, could be such a <code>set</code>. [A <code>list</code> is a poor choice -- does order matter in the bag?]</p></li>
<li><p>The Item's location changes from where it used to be to the Being's location. There are probably two classes os Items - those with an independent sense of location (because they move around by themselves) and items that have to delegate location to the Being or Place where they're sitting.</p></li>
</ul>
<p>Under no circumstances does any Python object ever need to get deleted. If an item is "destroyed", then it's not in a Being's bag. It's not in a location. </p>
<pre><code>player.bag.remove(cat)
</code></pre>
<p>Is all that's required to let the cat out of the bag. Since the cat is not used anywhere else, it will both exist as "used" memory and not exist because nothing in your program can access it. It will quietly vanish from memory when some quantum event occurs and memory references are garbage collected.</p>
<p>On the other hand,</p>
<pre><code>here.add( cat )
player.bag.remove(cat)
</code></pre>
<p>Will put the cat in the current location. The cat continues to exist, and will not be put out with the garbage.</p>
| 12 | 2008-11-16T14:26:51Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 3,435,323 | <p>I can't tell you how this is possible with classes, but functions can delete themselves. </p>
<pre><code>def kill_self(exit_msg = 'killed'):
global kill_self
del kill_self
return exit_msg
</code></pre>
<p>And see the output:</p>
<pre><code> >>> kill_self
<function kill_self at 0x02A2C780>
>>> kill_self()
'killed'
>>> kill_self
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
kill_self
NameError: name 'kill_self' is not defined
</code></pre>
<p>I don't think that deleting an individual instance of a class without knowing the name of it is possible. </p>
<p><strong>NOTE:</strong>
If you assign another name to the function, the other name will still reference the old one, but will cause errors once you attempt to run it:</p>
<pre><code>>>> x = kill_self
>>> kill_self()
>>> kill_self
NameError: name 'kill_self' is not defined
>>> x
<function kill_self at 0x...>
>>> x()
NameError: global name 'kill_self' is not defined
</code></pre>
| 2 | 2010-08-08T17:33:22Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 8,429,876 | <p>I am trying the same thing. I have a RPG battle system in which my Death(self) function has to kill the own object of the Fighter class. But it appeared it`s not possible. Maybe my class Game in which I collect all participants in the combat should delete units form the "fictional" map???</p>
<pre><code> def Death(self):
if self.stats["HP"] <= 0:
print("%s wounds were too much... Dead!"%(self.player["Name"]))
del self
else:
return True
def Damage(self, enemy):
todamage = self.stats["ATK"] + randint(1,6)
todamage -= enemy.stats["DEF"]
if todamage >=0:
enemy.stats["HP"] -= todamage
print("%s took %d damage from your attack!"%(enemy.player["Name"], todamage))
enemy.Death()
return True
else:
print("Ineffective...")
return True
def Attack(self, enemy):
tohit = self.stats["DEX"] + randint(1,6)
if tohit > enemy.stats["EVA"]:
print("You landed a successful attack on %s "%(enemy.player["Name"]))
self.Damage(enemy)
return True
else:
print("Miss!")
return True
def Action(self, enemylist):
for i in range(0, len(enemylist)):
print("No.%d, %r"%(i, enemylist[i]))
print("It`s your turn, %s. Take action!"%(self.player["Name"]))
choice = input("\n(A)ttack\n(D)efend\n(S)kill\n(I)tem\n(H)elp\n>")
if choice == 'a'or choice == 'A':
who = int(input("Who? "))
self.Attack(enemylist[who])
return True
else:
return self.Action()
</code></pre>
| 2 | 2011-12-08T10:58:14Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 12,634,203 | <p>Realistically you should not need to delete the object to do what you are trying to do. Instead you can change the state of the object.
An example of how this works without getting into the coding would be your player fighting a monster and killing the monster. The state of this monster is fighting. The monster will be accessing all methods needed for fighting. When the monster dies because his health drops to 0, the monsters state will change to dead and your character will stop attacking automatically. This methodology is very similar to using flags or even keywords.</p>
<p>Also apparently in python deleting classes is not required since they will be garbage collected automatically when they are not used anymore. </p>
| 4 | 2012-09-28T05:41:34Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 14,645,298 | <p>If you're using a single reference to the object, then the object can kill itself by resetting that outside reference to itself, as in:</p>
<pre><code>class Zero:
pOne = None
class One:
pTwo = None
def process(self):
self.pTwo = Two()
self.pTwo.dothing()
self.pTwo.kill()
# now this fails:
self.pTwo.dothing()
class Two:
def dothing(self):
print "two says: doing something"
def kill(self):
Zero.pOne.pTwo = None
def main():
Zero.pOne = One() # just a global
Zero.pOne.process()
if __name__=="__main__":
main()
</code></pre>
<p>You can of course do the logic control by checking for the object existence from outside the object (rather than object state), as for instance in:</p>
<pre><code>if object_exists:
use_existing_obj()
else:
obj = Obj()
</code></pre>
| 1 | 2013-02-01T11:27:57Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 29,254,550 | <p>what you could do is take the name with you in the class and make a dictionairy:</p>
<pre><code>class A:
def __init__(self, name):
self.name=name
def kill(self)
del dict[self.name]
dict={}
dict["a"]=A("a")
dict["a"].kill()
</code></pre>
| 0 | 2015-03-25T11:36:00Z | [
"python",
"memory-management",
"instance"
]
|
Python object deleting itself | 293,431 | <p>Why won't this work? I'm trying to make an instance of a class delete itself.</p>
<pre><code>>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
</code></pre>
| 45 | 2008-11-16T03:29:59Z | 38,932,457 | <p>I think I've finally got it!
Take a look a this code:</p>
<pre><code>import weakref
class InsaneClass():
_alive = []
def __new__(cls):
self = super().__new__(cls)
InsaneClass._alive.append(self)
return weakref.proxy(self)
def commit_suicide(self):
self._alive.remove(self)
instance = InsaneClass()
instance.commit_suicide()
print(instance)
# Raises Error: ReferenceError: weakly-referenced object no longer exists
</code></pre>
<p>When the object is created in the <code>__new__</code> method, the instance is replaced by a weak reference proxy and only one reference is kept in the _alive class attribute.</p>
<h3>What is a weak-reference?</h3>
<p>Weak-reference is a reference which does not count as a reference when garbage collector collects the object. Consider this example:</p>
<pre><code>>>> class Test(): pass
>>> a = Test()
>>> b = Test()
>>> c = a
>>> d = weakref.proxy(b)
>>> d
<weakproxy at 0x10671ae58 to Test at 0x10670f4e0>
# The weak reference points to the Test() object
>>> del a
>>> c
<__main__.Test object at 0x10670f390> # c still exists
>>> del b
>>> d
<weakproxy at 0x10671ab38 to NoneType at 0x1002050d0>
# d is now only a weak-reference to None. The Test() instance was garbage-collected
</code></pre>
<p>So the only strong reference to the instance is stored in the _alive class atribute. And when the commit_suicide() method removes the reference the instance is garbage-collected.</p>
| 0 | 2016-08-13T11:55:25Z | [
"python",
"memory-management",
"instance"
]
|
Python help - Parsing Packet Logs | 293,444 | <p>I'm writing a simple program that's going to parse a logfile of a packet dump from wireshark into a more readable form. I'm doing this with python.</p>
<p>Currently I'm stuck on this part:</p>
<pre><code>for i in range(len(linelist)):
if '### SERVER' in linelist[i]:
#do server parsing stuff
packet = linelist[i:find("\n\n", i, len(linelist))]
</code></pre>
<p>linelist is a list created using the readlines() method, so every line in the file is an element in the list. I'm iterating through it for all occurances of "### SERVER", then grabbing all lines after it until the next empty line(which signifies the end of the packet). I must be doing something wrong, because not only is find() not working, but I have a feeling there's a better way to grab everything between ### SERVER and the next occurance of a blank line.</p>
<p>Any ideas?</p>
| 3 | 2008-11-16T03:39:45Z | 293,568 | <p>Looking at the<a href="http://docs.python.org/library/stdtypes.html#file.readlines" rel="nofollow">file.readlines()</a> doc:</p>
<blockquote>
<p>file.readlines([sizehint])</p>
<p>Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.</p>
</blockquote>
<p>and the <a href="http://docs.python.org/library/stdtypes.html#file.readline" rel="nofollow">file.readline()</a> doc:</p>
<blockquote>
<p>file.readline([size])</p>
<p>Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.</p>
</blockquote>
<p><code> A trailing newline character is kept in the string</code> - means that each line in <code>linelist</code> will contain at most <strong>one</strong> newline. That is why you cannot find a <code>"\n\n"</code> substring in any of the lines - look for <strong>a whole blank line</strong> (or an empty one at EOF):</p>
<pre><code>if myline in ("\n", ""):
handle_empty_line()
</code></pre>
<p>Note: I tried to explain <code>find</code> behavior, but a pythonic solution looks very different from your code snippet.</p>
| 1 | 2008-11-16T06:24:05Z | [
"python",
"parsing"
]
|
Python help - Parsing Packet Logs | 293,444 | <p>I'm writing a simple program that's going to parse a logfile of a packet dump from wireshark into a more readable form. I'm doing this with python.</p>
<p>Currently I'm stuck on this part:</p>
<pre><code>for i in range(len(linelist)):
if '### SERVER' in linelist[i]:
#do server parsing stuff
packet = linelist[i:find("\n\n", i, len(linelist))]
</code></pre>
<p>linelist is a list created using the readlines() method, so every line in the file is an element in the list. I'm iterating through it for all occurances of "### SERVER", then grabbing all lines after it until the next empty line(which signifies the end of the packet). I must be doing something wrong, because not only is find() not working, but I have a feeling there's a better way to grab everything between ### SERVER and the next occurance of a blank line.</p>
<p>Any ideas?</p>
| 3 | 2008-11-16T03:39:45Z | 293,685 | <p>General idea is:</p>
<pre><code>inpacket = False
packets = []
for line in open("logfile"):
if inpacket:
content += line
if line in ("\n", ""): # empty line
inpacket = False
packets.append(content)
elif '### SERVER' in line:
inpacket = True
content = line
# put here packets.append on eof if needed
</code></pre>
| 0 | 2008-11-16T08:31:57Z | [
"python",
"parsing"
]
|
Python help - Parsing Packet Logs | 293,444 | <p>I'm writing a simple program that's going to parse a logfile of a packet dump from wireshark into a more readable form. I'm doing this with python.</p>
<p>Currently I'm stuck on this part:</p>
<pre><code>for i in range(len(linelist)):
if '### SERVER' in linelist[i]:
#do server parsing stuff
packet = linelist[i:find("\n\n", i, len(linelist))]
</code></pre>
<p>linelist is a list created using the readlines() method, so every line in the file is an element in the list. I'm iterating through it for all occurances of "### SERVER", then grabbing all lines after it until the next empty line(which signifies the end of the packet). I must be doing something wrong, because not only is find() not working, but I have a feeling there's a better way to grab everything between ### SERVER and the next occurance of a blank line.</p>
<p>Any ideas?</p>
| 3 | 2008-11-16T03:39:45Z | 293,827 | <p>This works well with an explicit iterator, also. That way, nested loops can update the iterator's state by consuming lines.</p>
<pre><code>fileIter= iter(theFile)
for x in fileIter:
if "### SERVER" in x:
block = [x]
for y in fileIter:
if len(y.strip()) == 0: # empty line
break
block.append(y)
print block # Or whatever
# elif some other pattern:
</code></pre>
<p>This has the pleasant property of finding blocks that are at the tail end of the file, and don't have a blank line terminating them.</p>
<p>Also, this is quite easy to generalize, since there's no explicit state-change variables, you just go into another loop to soak up lines in other kinds of blocks.</p>
| 0 | 2008-11-16T12:37:24Z | [
"python",
"parsing"
]
|
Python help - Parsing Packet Logs | 293,444 | <p>I'm writing a simple program that's going to parse a logfile of a packet dump from wireshark into a more readable form. I'm doing this with python.</p>
<p>Currently I'm stuck on this part:</p>
<pre><code>for i in range(len(linelist)):
if '### SERVER' in linelist[i]:
#do server parsing stuff
packet = linelist[i:find("\n\n", i, len(linelist))]
</code></pre>
<p>linelist is a list created using the readlines() method, so every line in the file is an element in the list. I'm iterating through it for all occurances of "### SERVER", then grabbing all lines after it until the next empty line(which signifies the end of the packet). I must be doing something wrong, because not only is find() not working, but I have a feeling there's a better way to grab everything between ### SERVER and the next occurance of a blank line.</p>
<p>Any ideas?</p>
| 3 | 2008-11-16T03:39:45Z | 293,828 | <p>best way - use generators
read presentation <a href="http://www.dabeaz.com/generators/" rel="nofollow">Generator Tricks for Systems Programmers</a>
This best that I saw about parsing log ;)</p>
| 0 | 2008-11-16T12:37:26Z | [
"python",
"parsing"
]
|
How do I fix wrongly nested / unclosed HTML tags? | 293,482 | <p>I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc.</p>
<p>For example, something like</p>
<pre><code><p>
<ul>
<li>Foo
</code></pre>
<p>becomes</p>
<pre><code><p>
<ul>
<li>Foo</li>
</ul>
</p>
</code></pre>
<p>Any help would be appreciated :)</p>
| 15 | 2008-11-16T04:14:57Z | 293,484 | <p>Run it through <a href="http://tidy.sourceforge.net/" rel="nofollow">Tidy</a> or one of its ported <a href="http://utidylib.berlios.de/" rel="nofollow">libraries</a>.</p>
<p>Try to code it by hand and you <em>will</em> want to gouge your eyes out.</p>
| 9 | 2008-11-16T04:17:52Z | [
"python",
"html",
"algorithm",
"xhtml"
]
|
How do I fix wrongly nested / unclosed HTML tags? | 293,482 | <p>I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc.</p>
<p>For example, something like</p>
<pre><code><p>
<ul>
<li>Foo
</code></pre>
<p>becomes</p>
<pre><code><p>
<ul>
<li>Foo</li>
</ul>
</p>
</code></pre>
<p>Any help would be appreciated :)</p>
| 15 | 2008-11-16T04:14:57Z | 293,486 | <p>Beautiful Soup works great for this.</p>
<p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a></p>
| 2 | 2008-11-16T04:19:58Z | [
"python",
"html",
"algorithm",
"xhtml"
]
|
How do I fix wrongly nested / unclosed HTML tags? | 293,482 | <p>I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc.</p>
<p>For example, something like</p>
<pre><code><p>
<ul>
<li>Foo
</code></pre>
<p>becomes</p>
<pre><code><p>
<ul>
<li>Foo</li>
</ul>
</p>
</code></pre>
<p>Any help would be appreciated :)</p>
| 15 | 2008-11-16T04:14:57Z | 293,558 | <p>using BeautifulSoup:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
html = "<p><ul><li>Foo"
soup = BeautifulSoup(html)
print soup.prettify()
</code></pre>
<p>gets you</p>
<pre><code><p>
<ul>
<li>
Foo
</li>
</ul>
</p>
</code></pre>
<p>As far as I know, you can't control putting the <li></li> tags on separate lines from Foo.</p>
<p>using Tidy:</p>
<pre><code>import tidy
html = "<p><ul><li>Foo"
print tidy.parseString(html, show_body_only=True)
</code></pre>
<p>gets you</p>
<pre><code><ul>
<li>Foo</li>
</ul>
</code></pre>
<p>Unfortunately, I know of no way to keep the <p> tag in the example. Tidy interprets it as an empty paragraph rather than an unclosed one, so doing</p>
<pre><code>print tidy.parseString(html, show_body_only=True, drop_empty_paras=False)
</code></pre>
<p>comes out as</p>
<pre><code><p></p>
<ul>
<li>Foo</li>
</ul>
</code></pre>
<p>Ultimately, of course, the <p> tag in your example is redundant, so you might be fine with losing it.</p>
<p>Finally, Tidy can also do indenting:</p>
<pre><code>print tidy.parseString(html, show_body_only=True, indent=True)
</code></pre>
<p>becomes</p>
<pre><code><ul>
<li>Foo
</li>
</ul>
</code></pre>
<p>All of these have their ups and downs, but hopefully one of them is close enough.</p>
| 24 | 2008-11-16T06:05:25Z | [
"python",
"html",
"algorithm",
"xhtml"
]
|
How do I fix wrongly nested / unclosed HTML tags? | 293,482 | <p>I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc.</p>
<p>For example, something like</p>
<pre><code><p>
<ul>
<li>Foo
</code></pre>
<p>becomes</p>
<pre><code><p>
<ul>
<li>Foo</li>
</ul>
</p>
</code></pre>
<p>Any help would be appreciated :)</p>
| 15 | 2008-11-16T04:14:57Z | 32,627,081 | <p>Just now, I got a html which lxml and pyquery didn't work good on , seems there are some errors in the html.
Since Tidy is not easy to install in windows, I choose <code>BeautifulSoup</code>.
But I found that:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
import lxml.html
soup = BeautifulSoup(page)
h = lxml.html(soup.prettify())
</code></pre>
<p>act same as <code>h = lxml.html(page)</code><br></p>
<p>Which real solve my problem is <code>soup = BeautifulSoup(page, 'html5lib')</code>.<br>
You should install <code>html5lib</code> first, then can use it as a parser in <code>BeautifulSoup</code>.
<code>html5lib</code> parser seems work much better than others.<br></p>
<p>Hope this can help someone.</p>
| 0 | 2015-09-17T09:38:25Z | [
"python",
"html",
"algorithm",
"xhtml"
]
|
Python for Autohotkey style key-combination sniffing, automation? | 294,285 | <p>I want to automate several tasks (eg. simulate eclipse style ctrl-shift-r open dialog for other editors). The general pattern is: the user will press some key combination, my program will detect it and potentially pop up a dialog to get user input, and then run a corresponding command, typically by running an executable.</p>
<p>My target environment is windows, although cross-platform would be nice. My program would be started once, read a configuration file, and sit in the background till triggered by a key combination or other event.</p>
<p>Basically autohotkey.</p>
<p>Why not just use autohotkey? I actually have quite a few autohotkey macros, but I'd prefer to use a saner language.</p>
<p>My question is: is there a good way to have a background python process detect key combinations?</p>
<p>Update: found the answer using pyHook and the win32 extensions:</p>
<pre><code>import pyHook
import pythoncom
def OnKeyboardEvent(event):
print event.Ascii
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
while True:
pythoncom.PumpMessages()
</code></pre>
| 10 | 2008-11-16T19:43:27Z | 294,461 | <p>You may want to look at <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a>. It does everything that AutoHotKey can do, but the language syntax doesn't make you want to pull your hair out. Additonally, it has COM bindings so you can use most of it's abilities easily in python if you so desired. I've posted about how to do it here <a href="http://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python#155587">before</a>.</p>
| 7 | 2008-11-16T22:05:51Z | [
"python",
"autohotkey"
]
|
Python for Autohotkey style key-combination sniffing, automation? | 294,285 | <p>I want to automate several tasks (eg. simulate eclipse style ctrl-shift-r open dialog for other editors). The general pattern is: the user will press some key combination, my program will detect it and potentially pop up a dialog to get user input, and then run a corresponding command, typically by running an executable.</p>
<p>My target environment is windows, although cross-platform would be nice. My program would be started once, read a configuration file, and sit in the background till triggered by a key combination or other event.</p>
<p>Basically autohotkey.</p>
<p>Why not just use autohotkey? I actually have quite a few autohotkey macros, but I'd prefer to use a saner language.</p>
<p>My question is: is there a good way to have a background python process detect key combinations?</p>
<p>Update: found the answer using pyHook and the win32 extensions:</p>
<pre><code>import pyHook
import pythoncom
def OnKeyboardEvent(event):
print event.Ascii
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
while True:
pythoncom.PumpMessages()
</code></pre>
| 10 | 2008-11-16T19:43:27Z | 557,543 | <p>Found the answer using pyHook and the win32 extensions:</p>
<pre><code>import pyHook
import pythoncom
def OnKeyboardEvent(event):
print event.Ascii
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
while True:
pythoncom.PumpMessages()
</code></pre>
| 5 | 2009-02-17T16:07:25Z | [
"python",
"autohotkey"
]
|
unpacking an array of arguments in php | 294,313 | <p>Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:</p>
<pre><code>args = [3, 6]
range(*args) # call with arguments unpacked from a list
</code></pre>
<p>This is equivalent to:</p>
<pre><code>range(3, 6)
</code></pre>
<p>Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?</p>
| 20 | 2008-11-16T20:05:42Z | 294,325 | <p>You can use <a href="http://www.php.net/call_user_func_array"><code>call_user_func_array()</code></a> to achieve that:</p>
<p><code>call_user_func_array("range", $args);</code> to use your example.</p>
| 20 | 2008-11-16T20:08:30Z | [
"php",
"python",
"arguments",
"iterable-unpacking"
]
|
unpacking an array of arguments in php | 294,313 | <p>Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:</p>
<pre><code>args = [3, 6]
range(*args) # call with arguments unpacked from a list
</code></pre>
<p>This is equivalent to:</p>
<pre><code>range(3, 6)
</code></pre>
<p>Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?</p>
| 20 | 2008-11-16T20:05:42Z | 294,335 | <p>You should use the call_user_func_array</p>
<pre><code>call_user_func_array(array(CLASS, METHOD), array(arg1, arg2, ....))
</code></pre>
<p><a href="http://www.php.net/call_user_func_array" rel="nofollow">http://www.php.net/call_user_func_array</a></p>
<p>or use the reflection api <a href="http://www.php.net/oop5.reflection" rel="nofollow">http://www.php.net/oop5.reflection</a></p>
| 4 | 2008-11-16T20:15:01Z | [
"php",
"python",
"arguments",
"iterable-unpacking"
]
|
unpacking an array of arguments in php | 294,313 | <p>Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:</p>
<pre><code>args = [3, 6]
range(*args) # call with arguments unpacked from a list
</code></pre>
<p>This is equivalent to:</p>
<pre><code>range(3, 6)
</code></pre>
<p>Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?</p>
| 20 | 2008-11-16T20:05:42Z | 23,164,267 | <p>In <code>php5.6</code> the <a href="http://docs.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat" rel="nofollow"><code>...</code> operator</a> has been added. Using it, you can get rid of <code>call_user_func_array()</code> for this simpler alternative. For example having a function </p>
<pre><code>function add($a, $b){
return $a + $b;
}
</code></pre>
<p>and your array <code>$list = [4, 6];</code> (after php5.5 you can declare arrays in this way).
You can call your function with <code>...</code>:</p>
<p><code>echo add(...$list);</code></p>
| 8 | 2014-04-19T00:14:26Z | [
"php",
"python",
"arguments",
"iterable-unpacking"
]
|
unpacking an array of arguments in php | 294,313 | <p>Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:</p>
<pre><code>args = [3, 6]
range(*args) # call with arguments unpacked from a list
</code></pre>
<p>This is equivalent to:</p>
<pre><code>range(3, 6)
</code></pre>
<p>Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?</p>
| 20 | 2008-11-16T20:05:42Z | 32,401,548 | <p>In certain scenarios, you might consider using <code>unpacking</code>, which is possible in php, is a similar way to python:</p>
<pre><code>list($min, $max) = [3, 6];
range($min, $max);
</code></pre>
<p>This is how I have arrived to this answer at least.
Google search: <code>PHP argument unpacking</code></p>
| 0 | 2015-09-04T15:22:57Z | [
"php",
"python",
"arguments",
"iterable-unpacking"
]
|
How do I find userid by login (Python under *NIX) | 294,470 | <p>I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find <code>uid</code> if I have <code>login</code>?</p>
<p>I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?</p>
| 11 | 2008-11-16T22:11:25Z | 294,480 | <p>You might want to have a look at the <a href="http://docs.python.org/library/pwd.html">pwd</a> module in the python stdlib, for example:</p>
<pre><code>import pwd
pw = pwd.getpwnam("nobody")
uid = pw.pw_uid
</code></pre>
<p>it uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually</p>
| 20 | 2008-11-16T22:19:52Z | [
"python",
"linux",
"unix",
"process-management"
]
|
How do I find userid by login (Python under *NIX) | 294,470 | <p>I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find <code>uid</code> if I have <code>login</code>?</p>
<p>I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?</p>
| 11 | 2008-11-16T22:11:25Z | 294,535 | <p>Never directly scan <code>/etc/passwd</code>.</p>
<p>For instance, on a Linux system I administer, the user accounts are not on <code>/etc/passwd</code>, but on a LDAP server.</p>
<p>The correct way is to use <code>getpwent</code>/<code>getgrent</code> and related C functions (as in @TFKyle's answer), which will get the information on the correct way for each system (on Linux glibc, it reads <code>/etc/nsswitch.conf</code> to know which NSS dynamic libraries to load to get the information).</p>
| 5 | 2008-11-16T23:10:39Z | [
"python",
"linux",
"unix",
"process-management"
]
|
Python UPnP/IGD Client Implementation? | 294,504 | <p>I am searching for an open-source implementation of an <a href="http://elinux.org/UPnP" rel="nofollow">UPnP</a> client in Python, and more specifically of its <a href="http://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol" rel="nofollow">Internet Gateway Device</a> (IGD) part.</p>
<p>For now, I have only been able to find UPnP Media Server implementations, in projects such as <a href="http://pymediaserver.sourceforge.net/" rel="nofollow">PyMediaServer</a>, <a href="http://resnet.uoregon.edu/~gurney_j/jmpc/pymeds.html" rel="nofollow">PyMedS</a>, <a href="http://brisa.garage.maemo.org/" rel="nofollow">BRisa</a> or <a href="https://coherence.beebits.net/" rel="nofollow">Coherence</a>.</p>
<p>I am sure I could use those code bases as a start, but the Media Server part will introduce unneeded complexity.</p>
<p>So can you recommend a client UPnP (and hopefully IGD) Python library? An alternative would be to dispatch calls to a C library such as <a href="http://miniupnp.free.fr/" rel="nofollow">MiniUPnP</a>, but I would much prefer a pure Python implementation.</p>
<p>Update: an interesting, kind of related discussion of SSDP and UPnP is available on <a href="http://stackoverflow.com/questions/22321/remoting-server-auto-discovery-broadcast-or-not">StackOverflow</a>.</p>
| 11 | 2008-11-16T22:38:41Z | 298,052 | <p>MiniUPnP source code contains a Python sample code using the C library as an extension module (see <code>testupnpigd.py</code>), which I consider as a proper solution to my problem.</p>
<p>Rationale: this is not the pure Python solution I was looking for, but:</p>
<ul>
<li>significant effort has already been invested in this library,</li>
<li>it is lightweight (it does not address Media Server issues),</li>
<li>IGD is typically only used at connection setup, so not integrating it tighter with the Python code does not seem like an issue,</li>
<li>as a bonus, it also provides a NAT-PNP implementation (the Apple concurrent of IGD, part of <a href="http://developer.apple.com/networking/bonjour/specs.html">Bonjour</a>).</li>
</ul>
| 7 | 2008-11-18T07:26:00Z | [
"python",
"networking",
"nat",
"upnp"
]
|
Python UPnP/IGD Client Implementation? | 294,504 | <p>I am searching for an open-source implementation of an <a href="http://elinux.org/UPnP" rel="nofollow">UPnP</a> client in Python, and more specifically of its <a href="http://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol" rel="nofollow">Internet Gateway Device</a> (IGD) part.</p>
<p>For now, I have only been able to find UPnP Media Server implementations, in projects such as <a href="http://pymediaserver.sourceforge.net/" rel="nofollow">PyMediaServer</a>, <a href="http://resnet.uoregon.edu/~gurney_j/jmpc/pymeds.html" rel="nofollow">PyMedS</a>, <a href="http://brisa.garage.maemo.org/" rel="nofollow">BRisa</a> or <a href="https://coherence.beebits.net/" rel="nofollow">Coherence</a>.</p>
<p>I am sure I could use those code bases as a start, but the Media Server part will introduce unneeded complexity.</p>
<p>So can you recommend a client UPnP (and hopefully IGD) Python library? An alternative would be to dispatch calls to a C library such as <a href="http://miniupnp.free.fr/" rel="nofollow">MiniUPnP</a>, but I would much prefer a pure Python implementation.</p>
<p>Update: an interesting, kind of related discussion of SSDP and UPnP is available on <a href="http://stackoverflow.com/questions/22321/remoting-server-auto-discovery-broadcast-or-not">StackOverflow</a>.</p>
| 11 | 2008-11-16T22:38:41Z | 331,739 | <p>I think you should really consider BRisa. It recently became a pure python UPnP Framework, not focused only on Media Server.</p>
<p>It provides lots of utilitary modules and functions for you to build and deploy your UPnP device.</p>
<p>The project also is lacking feedback :-). I suggest you to use the latest svn code, if you're willing to try BRisa.</p>
<p>You can also contact the developers on #brisa at irc.freenode.org, we're either online or idling.</p>
| 2 | 2008-12-01T18:30:28Z | [
"python",
"networking",
"nat",
"upnp"
]
|
What are some techniques for code generation? | 294,520 | <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
| 4 | 2008-11-16T22:58:22Z | 294,528 | <p>I wrote <a href="http://nedbatchelder.com/code/cog/index.html">Cog</a> partly to generate C++ code from an XML data schema. It lets you use Python code embedded in C++ source files to generate C++ source.</p>
| 8 | 2008-11-16T23:06:18Z | [
"c++",
"python",
"code-generation"
]
|
What are some techniques for code generation? | 294,520 | <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
| 4 | 2008-11-16T22:58:22Z | 294,542 | <p>One technique I've used for code generation is to not worry at all about formatting in the code generator. Then, as a next step after generating the code, run it through <a href="http://www.gnu.org/software/indent/"><code>indent</code></a> to format it reasonably so you can read (and more importantly, debug) it. </p>
| 7 | 2008-11-16T23:12:17Z | [
"c++",
"python",
"code-generation"
]
|
What are some techniques for code generation? | 294,520 | <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
| 4 | 2008-11-16T22:58:22Z | 294,550 | <p>See <a href="http://homepage.mac.com/s_lott/iblog/architecture/C20071019092637/E20080830091128/index.html" rel="nofollow">Tooling to Build Test Cases</a>.</p>
<p>It's not clear what your problem is.</p>
<p>If you question is "how do I handle all the special cases in my generating classes?" then here's some advice. If your question is something else, then update your question.</p>
<ol>
<li><p>Use a template generator. <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>, for example, will make your life simpler.</p>
<p>Write an example of your result. Replace parts with <code>${thing}</code> placeholders. Since you started with something that worked, turning it into a template is easy.</p></li>
<li><p>When generating code in another language, you need to have all of the class definitions in other other language designed for flexible assembly. You want to generate as little fresh, new code as possible. You want to tweak and customize a bit, but you don't want to generate a lot of stuff from scratch.</p></li>
<li><p>Special cases are best handled with ordinary polymorphism. Separate subclasses of a common superclass can implement the various exceptions and special cases. Really complex situations are handled well by the <strong>Strategy</strong> design pattern. </p>
<p>In essence, you have Python classes that represent the real-world objects. Those classes have attributes that can be fit into a C++ template to generate the C++ version of those objects. </p></li>
</ol>
| 4 | 2008-11-16T23:23:00Z | [
"c++",
"python",
"code-generation"
]
|
What are some techniques for code generation? | 294,520 | <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
| 4 | 2008-11-16T22:58:22Z | 294,557 | <p>I have a code generation system and one of the best choices I have taken with it is to put much of the resultant program in non generated code, e.g. a library/runtime. Using templates works well also. Complex template systems may be hard to work with by hand, but your not working with them by hand so leverage that. </p>
| 0 | 2008-11-16T23:25:26Z | [
"c++",
"python",
"code-generation"
]
|
What are some techniques for code generation? | 294,520 | <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
| 4 | 2008-11-16T22:58:22Z | 294,581 | <p>It would actually be just recursing straight down, except I need to pull all function declarations out and put them elsewhere, and the fact that for all function calls I need to build a vector of all of the arguments, and then pass that to the function, since C++ doesn't have a syntax for vectors.</p>
| 0 | 2008-11-16T23:41:31Z | [
"c++",
"python",
"code-generation"
]
|
What are some techniques for code generation? | 294,520 | <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
| 4 | 2008-11-16T22:58:22Z | 308,944 | <p>I agree with S.Lott, that you should write out an example of what you want to generate.</p>
<p>Solving a problem with code generation should be less complicated than without.</p>
<p>This is because your total program has to deal with a lot of input information, and if a subset of that information changes very seldom, like once a week, the code generator only has to condition on that subset. The generated code conditions on the remaining input that changes more frequently.
It's a divide-and-conquer strategy. Another name for it is "partial evaluation".</p>
<p>Generated code should also run a lot faster because it's less general.</p>
<p>In your specific case, there's no harm in doing the code generation in 2 (or more) passes. Like on pass 1 you generate declarations. On pass 2 you generate process code. Alternatively you could generate two output streams, and concatenate them at the end.</p>
<p>Hope that helps. Sorry if I'm just saying what's obvious.</p>
| 1 | 2008-11-21T14:32:36Z | [
"c++",
"python",
"code-generation"
]
|
What are some techniques for code generation? | 294,520 | <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
| 4 | 2008-11-16T22:58:22Z | 9,557,837 | <p>as Ned suggested, Cog is an excellent tool for writing boilerplate code. For instance, i've had to write a AOP-style event system support for certain classes that it would work like this:</p>
<ul>
<li>you declare a method for a class</li>
<li>for each method, an event needs to be triggered upon invocation, passing the arguments of the method as event parameters</li>
</ul>
<p>So i did a special python declarator function that i would invoke on a cog region which would generate the boilerplate declarations and definitions for each method and event. At the end of the cog region the user places a block of code for a function that hides the implementation and is invoked by the AOP wrapper, something roughly like this:</p>
<pre><code>class MyFoo
{
public:
/*[[[cog
import myAOPDeclarators
AOP = myAOPDeclarators.AOP
AOP.declareAOPInterceptorMethod( 'invokeSomeStuff' , '(int param1, std::string param2)' )
]]]*/
//AOP wrapper
void invokeSomeStuff_ImplementationAOP(int param1, std::string param2);
void invokeSomeStuff(int param1, std::string param2) {
sendAOPPreEvent( param1 , param2 , "invokeSomeStuff" );
invokeSomeStuff_ImplementationAOP( param1 , param2);
}
void invokeSomeStuff_ImplementationAOP(int param1, std::string param2)
//[[[end]]]
{
// ...invokeSomeStuff implementation, not automatically generated
}
</code></pre>
<p>The best guideline i can give you for code generation is; <strong>make your generated code as readable as your hand written one</strong>. It makes the usage of code-generation transparent (even more transparent than template code, buy YMMV), Of course, as Greg suggested, indent can be applied afterwards, so there is really no point in wasting time in mixing indentation tinkering with code generation if a tool can post-process the source files anyways</p>
| 1 | 2012-03-04T18:54:59Z | [
"c++",
"python",
"code-generation"
]
|
What are some techniques for code generation? | 294,520 | <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
| 4 | 2008-11-16T22:58:22Z | 12,981,278 | <p>I was also looking for something like this and found this question. I wasn't very satisfied with cog, so I ended up writing my own which is similar but adds some (imo) much needed features.</p>
<p><a href="https://github.com/icholy/swapm" rel="nofollow">https://github.com/icholy/swapm</a> </p>
| 0 | 2012-10-19T19:37:06Z | [
"c++",
"python",
"code-generation"
]
|
What is the regular expression for the "root" of a website in django? | 294,607 | <p>I'm using django and when users go to www.website.com/ I want to point them to the index view.</p>
<p>Right now I'm doing this:</p>
<pre><code>(r'^$', 'ideas.idea.views.index'),
</code></pre>
<p>However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me. </p>
| 4 | 2008-11-17T00:05:46Z | 294,612 | <p>What you have should work (it does for me). Make sure it's in the top <code>urls.py</code>, and it should also be at the top of the list.</p>
| 3 | 2008-11-17T00:09:37Z | [
"python",
"regex",
"django",
"django-urls"
]
|
What is the regular expression for the "root" of a website in django? | 294,607 | <p>I'm using django and when users go to www.website.com/ I want to point them to the index view.</p>
<p>Right now I'm doing this:</p>
<pre><code>(r'^$', 'ideas.idea.views.index'),
</code></pre>
<p>However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me. </p>
| 4 | 2008-11-17T00:05:46Z | 294,656 | <p>Is there any way you can just use a generic view and go straight to template for your index page?:</p>
<pre><code>urlpatterns += patterns('django.views.generic.simple',
(r'', 'direct_to_template', {'template': 'index.html'}),
)
</code></pre>
| 0 | 2008-11-17T00:45:17Z | [
"python",
"regex",
"django",
"django-urls"
]
|
What is the regular expression for the "root" of a website in django? | 294,607 | <p>I'm using django and when users go to www.website.com/ I want to point them to the index view.</p>
<p>Right now I'm doing this:</p>
<pre><code>(r'^$', 'ideas.idea.views.index'),
</code></pre>
<p>However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me. </p>
| 4 | 2008-11-17T00:05:46Z | 16,170,740 | <p>Just put an empty raw regular expression: r''</p>
<p>I tested here and it worked perfectly.</p>
<pre><code>urlpatterns = patterns('',
url(r'', include('homepage.urls')),
)
</code></pre>
<p>Hope it help!</p>
<p>EDIT:</p>
<p>You can also put:</p>
<pre><code>urlpatterns = patterns('',
url(r'\?', include('homepage.urls')),
)
</code></pre>
<p>The question mark makes the bar optional.</p>
| 2 | 2013-04-23T13:33:58Z | [
"python",
"regex",
"django",
"django-urls"
]
|
Flattening one-to-many relationship in Django | 294,712 | <p>I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients:</p>
<pre><code>class Book(models.Model):
name = models.CharField(max_length=64)
class Recipe(models.Model):
book = models.ForeignKey(Book)
name = models.CharField(max_length=64)
class Ingredient(models.Model):
text = models.CharField(max_length=128)
recipe = models.ForeignKey(Recipe)
</code></pre>
<p>I'd like a flat list of all ingredients in all recipes from a particular book. What's the best way to express this in Python?</p>
<p>If I was using LINQ, I might write something like this:</p>
<pre><code>var allIngredients = from recipe in book.Recipes
from ingredient in recipe.Ingredients
select ingredient;
</code></pre>
| 7 | 2008-11-17T01:47:51Z | 294,717 | <p>To print each recipe and its ingredients:</p>
<pre><code>mybook = Book.objects.get(name="Jason's Cookbook")
for recipe in mybook.recipe_set.all():
print recipe.name
for ingredient in recipe.ingredients:
print ingredient.text
</code></pre>
<p>And if you just want to get a list of all ingredient objects:</p>
<pre><code>mybook = Book.objects.get(name="Jason's Cookbook")
ingredient_list = []
for recipe in mybook.recipe_set.all():
for ingredient in recipe.ingredients:
ingredient_list.append(ingredient)
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects" rel="nofollow">Documentation</a>.</p>
| 2 | 2008-11-17T01:52:19Z | [
"python",
"django",
"list",
"flatten"
]
|
Flattening one-to-many relationship in Django | 294,712 | <p>I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients:</p>
<pre><code>class Book(models.Model):
name = models.CharField(max_length=64)
class Recipe(models.Model):
book = models.ForeignKey(Book)
name = models.CharField(max_length=64)
class Ingredient(models.Model):
text = models.CharField(max_length=128)
recipe = models.ForeignKey(Recipe)
</code></pre>
<p>I'd like a flat list of all ingredients in all recipes from a particular book. What's the best way to express this in Python?</p>
<p>If I was using LINQ, I might write something like this:</p>
<pre><code>var allIngredients = from recipe in book.Recipes
from ingredient in recipe.Ingredients
select ingredient;
</code></pre>
| 7 | 2008-11-17T01:47:51Z | 294,723 | <p>Actually, it looks like there's a better approach using filter:</p>
<pre><code>my_book = Book.objects.get(pk=1)
all_ingredients = Ingredient.objects.filter(recipe__book=my_book)
</code></pre>
| 10 | 2008-11-17T02:00:37Z | [
"python",
"django",
"list",
"flatten"
]
|
What is the best way to distribute a python program extended with custom c modules? | 294,766 | <p>I've explored python for several years, but now I'm slowly learning how to work with c. Using the <a href="http://www.python.org/doc/2.5.2/ext/intro.html" rel="nofollow">python documentation</a>, I learned how to extend my python programs with some c, since this seemed like the logical way to start playing with it. My question now is how to distribute a program like this.</p>
<p>I suppose the heart of my question is how to compile things. I can do this easily on my own machine (gentoo), but a binary distribution like Ubuntu probably doesn't have a compiler available by default. Plus, I have a few friends who are mac users. My instinct says that I can't just compile with my own machine and then run it on another. Anyone know what I can do, or some online resources for learning things like this?</p>
| 1 | 2008-11-17T02:43:21Z | 294,785 | <p>Please read up on distutils. Specifically, the section on <a href="http://www.python.org/doc/2.5.2/dist/describing-extensions.html" rel="nofollow">Extension Modules</a>.</p>
<p>Making assumptions about compilers is bad policy; your instinct may not have all the facts. You could do some marketplace survey -- ask what they can handle regarding source distribution of extension modules.</p>
<p>It's relatively easy to create the proper distutils <code>setup.py</code> and see who can run it and who can't.</p>
<p>Built binary distributions are pretty common. Perhaps you can sign up some users will help create binary distributions -- with OS-native installers -- for some considerations. </p>
| 6 | 2008-11-17T02:55:54Z | [
"python",
"c",
"linux",
"osx",
"software-distribution"
]
|
What is the best way to distribute a python program extended with custom c modules? | 294,766 | <p>I've explored python for several years, but now I'm slowly learning how to work with c. Using the <a href="http://www.python.org/doc/2.5.2/ext/intro.html" rel="nofollow">python documentation</a>, I learned how to extend my python programs with some c, since this seemed like the logical way to start playing with it. My question now is how to distribute a program like this.</p>
<p>I suppose the heart of my question is how to compile things. I can do this easily on my own machine (gentoo), but a binary distribution like Ubuntu probably doesn't have a compiler available by default. Plus, I have a few friends who are mac users. My instinct says that I can't just compile with my own machine and then run it on another. Anyone know what I can do, or some online resources for learning things like this?</p>
| 1 | 2008-11-17T02:43:21Z | 1,533,793 | <p>S. Lott is right. You should first look at distutils. After you've learned what you need from distutils, look at <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow">setuptools</a>. Setuptools is built on top of distutils and makes installation easy for your users. Have you ever used easy_install or Python Eggs? That's what's next.</p>
| 1 | 2009-10-07T19:49:15Z | [
"python",
"c",
"linux",
"osx",
"software-distribution"
]
|
Pycurl WRITEDATA WRITEFUNCTION collision/crash | 294,960 | <p>How do I turnoff WRITEFUNCTION and WRITEDATA?</p>
<p>Using pycurl I have a class call curlUtil. In it I have pageAsString (self, URL) which returns a string. </p>
<p>To do this I setopt WRITEFUNCTION. Now in downloadFile (self, URL, fn, overwrite=0) I do an open and self.c.Setopt (pycurl.WRITEFUNCTION, 0) which cause problems. Int is not a valid argument. </p>
<p>I then assumed WRITEDATA would overwrite the value or there would be a NOWRITEFUNCTION commend. NOWRITEFUNCTION didn't exist so I just used WRITEDATA and Python crashed. </p>
<p>I wrote a quick func called reboot() which closes curl, opens it again, and calls reset to put it in the default state. I call it in both pageAsString and downloadFile and there is no problem at all. But, I don't want to reinitialize curl. There might be some special options I set. </p>
<p>How do I turnoff WRITEFUNCTION and WRITEDATA?</p>
| 0 | 2008-11-17T05:42:14Z | 297,347 | <p>using the writefunction, instead of turning it off would save you a lot off trouble. you might want to rewrite your pageAsString by utilizing WRITEFUNCTION..</p>
<p>as an example: </p>
<pre><code>from cStringIO import StringIO
c = pycurl.Curl()
buffer = StringIO()
c.setopt(pycurl.WRITEFUNCTION, buffer.write)
c.setopt(pycurl.URL, "http://example.com")
c.perform()
...
buffer.getvalue() # will return the data fetched.
</code></pre>
| 1 | 2008-11-17T23:28:53Z | [
"python",
"crash",
"libcurl",
"pycurl"
]
|
How do I count bytecodes in Python so I can modify sys.setcheckinterval appropriately | 294,963 | <p>I have a port scanning application that uses work queues and threads.</p>
<p>It uses simple TCP connections and spends a lot of time waiting for packets to come back (up to half a second). Thus the threads don't need to fully execute (i.e. first half sends a packet, context switch, does stuff, comes back to thread which has network data waiting for it).</p>
<p>I suspect I can improve performance by modifying the <code>sys.setcheckinterval</code> from the default of 100 (which lets up to 100 bytecodes execute before switching to another thread).</p>
<p>But without knowing how many bytecodes are actually executing in a thread or function I'm flying blind and simply guessing values, testing and relying on the testing shows a measurable difference (which is difficult since the amount of code being executed is minimal; a simple socket connection, thus network jitter will likely affect any measurements more than changing sys.setcheckinterval).</p>
<p>Thus I would like to find out how many bytecodes are in certain code executions (i.e. total for a function or in execution of a thread) so I can make more intelligent guesses at what to set sys.setcheckinterval to.</p>
| 1 | 2008-11-17T05:44:44Z | 294,968 | <p>For higher level (method, class) wise, <a href="http://www.python.org/doc/2.5.2/lib/module-dis.html" rel="nofollow">dis module</a> should help.</p>
<p>But if one needs finer grain, <a href="http://www.python.org/doc/2.5.2/lib/debugger-hooks.html" rel="nofollow">tracing</a> will be unavoidable. Tracing does operate line by line basis but <a href="http://nedbatchelder.com/blog/200804/wicked_hack_python_bytecode_tracing.html" rel="nofollow">explained here</a> is a great hack to dive deeper at the bytecode level. Hats off to Ned Batchelder.</p>
| 3 | 2008-11-17T05:50:00Z | [
"python",
"performance",
"multithreading",
"internals"
]
|
How do I count bytecodes in Python so I can modify sys.setcheckinterval appropriately | 294,963 | <p>I have a port scanning application that uses work queues and threads.</p>
<p>It uses simple TCP connections and spends a lot of time waiting for packets to come back (up to half a second). Thus the threads don't need to fully execute (i.e. first half sends a packet, context switch, does stuff, comes back to thread which has network data waiting for it).</p>
<p>I suspect I can improve performance by modifying the <code>sys.setcheckinterval</code> from the default of 100 (which lets up to 100 bytecodes execute before switching to another thread).</p>
<p>But without knowing how many bytecodes are actually executing in a thread or function I'm flying blind and simply guessing values, testing and relying on the testing shows a measurable difference (which is difficult since the amount of code being executed is minimal; a simple socket connection, thus network jitter will likely affect any measurements more than changing sys.setcheckinterval).</p>
<p>Thus I would like to find out how many bytecodes are in certain code executions (i.e. total for a function or in execution of a thread) so I can make more intelligent guesses at what to set sys.setcheckinterval to.</p>
| 1 | 2008-11-17T05:44:44Z | 295,492 | <p>" I suspect I can improve performance by modifying the sys.setcheckinterval" </p>
<p>This rarely works. Correct behavior can't depend on timing -- you can't control timing. Slight changes on OS, hardware, patch level of Python or phase of the moon will change how your application behaves.</p>
<p>The <a href="http://www.python.org/doc/2.5.2/lib/module-select.html" rel="nofollow">select</a> module is what you use to wait for I/O's. Your application can be structured as a main loop that does the select and <a href="http://www.python.org/doc/2.5.2/lib/module-Queue.html" rel="nofollow">queues</a> up work for other threads. The other threads are waiting for an entries in their queue of requests to process.</p>
| 2 | 2008-11-17T12:37:11Z | [
"python",
"performance",
"multithreading",
"internals"
]
|
How do I count bytecodes in Python so I can modify sys.setcheckinterval appropriately | 294,963 | <p>I have a port scanning application that uses work queues and threads.</p>
<p>It uses simple TCP connections and spends a lot of time waiting for packets to come back (up to half a second). Thus the threads don't need to fully execute (i.e. first half sends a packet, context switch, does stuff, comes back to thread which has network data waiting for it).</p>
<p>I suspect I can improve performance by modifying the <code>sys.setcheckinterval</code> from the default of 100 (which lets up to 100 bytecodes execute before switching to another thread).</p>
<p>But without knowing how many bytecodes are actually executing in a thread or function I'm flying blind and simply guessing values, testing and relying on the testing shows a measurable difference (which is difficult since the amount of code being executed is minimal; a simple socket connection, thus network jitter will likely affect any measurements more than changing sys.setcheckinterval).</p>
<p>Thus I would like to find out how many bytecodes are in certain code executions (i.e. total for a function or in execution of a thread) so I can make more intelligent guesses at what to set sys.setcheckinterval to.</p>
| 1 | 2008-11-17T05:44:44Z | 297,747 | <p>Reasoning about a system of this complexity will rarely produce the right answer. Measure the results, and use the setting that runs the fastest. If as you say, testing can't measure the difference in various settings of setcheckinterval, then why bother changing it? Only measurable differences are interesting. If your test run is too short to provide meaningful data, then make the run longer until it does.</p>
| 2 | 2008-11-18T03:05:53Z | [
"python",
"performance",
"multithreading",
"internals"
]
|
Inplace substitution from ConfigParser | 295,028 | <p>I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from <a href="https://docs.python.org/2/library/configparser.html" rel="nofollow">ConfigParser</a>. For example, I need to read</p>
<pre><code>self.post.id
</code></pre>
<p>from a .cfg file and use it as a variable in the script. How do I achieve this?</p>
<p>I suppose I was unclear in my query. The .cfg file looks something like:</p>
<pre><code>[head]
test: me
some variable : self.post.id
</code></pre>
<p>This self.post.id is to be replaced at the run time, taking values from the script.</p>
| 0 | 2008-11-17T06:55:05Z | 295,038 | <p>test.ini:</p>
<pre><code>[head]
var: self.post.id
</code></pre>
<p>python:</p>
<pre><code>import ConfigParser
class Test:
def __init__(self):
self.post = TestPost(5)
def getPost(self):
config = ConfigParser.ConfigParser()
config.read('/path/to/test.ini')
newvar = config.get('head', 'var')
print eval(newvar)
class TestPost:
def __init__(self, id):
self.id = id
test = Test()
test.getPost() # prints 5
</code></pre>
| 3 | 2008-11-17T07:02:53Z | [
"python",
"configuration-files"
]
|
Inplace substitution from ConfigParser | 295,028 | <p>I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from <a href="https://docs.python.org/2/library/configparser.html" rel="nofollow">ConfigParser</a>. For example, I need to read</p>
<pre><code>self.post.id
</code></pre>
<p>from a .cfg file and use it as a variable in the script. How do I achieve this?</p>
<p>I suppose I was unclear in my query. The .cfg file looks something like:</p>
<pre><code>[head]
test: me
some variable : self.post.id
</code></pre>
<p>This self.post.id is to be replaced at the run time, taking values from the script.</p>
| 0 | 2008-11-17T06:55:05Z | 295,745 | <p>This is a bit silly.</p>
<p>You have a dynamic language, distributed in source form.</p>
<p>You're trying to make what amounts to a change to the source. Which is easy-to-read, plain text Python.</p>
<p>Why not just change the Python source and stop messing about with a configuration file?</p>
<p>It's a lot easier to have a block of code like this</p>
<pre><code># Change this for some reason or another
x = self.post.id # Standard Configuration
# x = self.post.somethingElse # Another Configuration
# x = self.post.yetAnotherCase # A third configuration
</code></pre>
<p>it's just as complex to change this as it is to change a configuration file. And your Python program is simpler and more clear.</p>
| 1 | 2008-11-17T14:53:43Z | [
"python",
"configuration-files"
]
|
Convert a string to preexisting variable names | 295,058 | <p>How do I convert a string to the variable name in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>For example, if the program contains a object named <code>self.post</code> that contains a variable named, I want to do something like:</p>
<pre><code>somefunction("self.post.id") = |Value of self.post.id|
</code></pre>
| 20 | 2008-11-17T07:32:09Z | 295,064 | <p>As referenced in Stack Overflow question <em><a href="http://stackoverflow.com/questions/295028/">Inplace substitution from ConfigParser</a></em>, you're looking for <code>eval()</code>:</p>
<pre><code>print eval('self.post.id') # Prints the value of self.post.id
</code></pre>
| 23 | 2008-11-17T07:37:00Z | [
"python"
]
|
Convert a string to preexisting variable names | 295,058 | <p>How do I convert a string to the variable name in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>For example, if the program contains a object named <code>self.post</code> that contains a variable named, I want to do something like:</p>
<pre><code>somefunction("self.post.id") = |Value of self.post.id|
</code></pre>
| 20 | 2008-11-17T07:32:09Z | 295,113 | <p>Also, there is the <strong><a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow">globals()</a></strong> function in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow">Python</a> which returns a dictionary with all the defined variables. You could also use something like this:</p>
<pre><code>print globals()["myvar"]
</code></pre>
| 10 | 2008-11-17T08:47:58Z | [
"python"
]
|
Convert a string to preexisting variable names | 295,058 | <p>How do I convert a string to the variable name in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>For example, if the program contains a object named <code>self.post</code> that contains a variable named, I want to do something like:</p>
<pre><code>somefunction("self.post.id") = |Value of self.post.id|
</code></pre>
| 20 | 2008-11-17T07:32:09Z | 296,060 | <p>Note: do <strong>not</strong> use eval in any case where you are getting the name to look up from user entered input. For example, if this comes from a web page, there is nothing preventing anyone from entering:</p>
<pre><code>__import__("os").system("Some nasty command like rm -rf /*")
</code></pre>
<p>as the argument. Better is to limit to well-defined lookup locations such as a dictionary or instance using <a href="https://docs.python.org/2/library/functions.html#getattr">getattr()</a>. For example, to find the "post" value on self, use:</p>
<pre><code>varname = "post"
value = getattr(self, varname) # Gets self.post
</code></pre>
<p>Similarly to set it, use setattr():</p>
<pre><code>value = setattr(self, varname, new_value)
</code></pre>
<p>To handle <a href="https://en.wikipedia.org/wiki/Fully_qualified_name">fully qualified names</a>, like "post.id", you could use something like the below functions in place of getattr() / <a href="https://docs.python.org/2/library/functions.html#setattr">setattr()</a>.</p>
<pre><code>def getattr_qualified(obj, name):
for attr in name.split("."):
obj = getattr(obj, attr)
return obj
def setattr_qualified(obj, name, value):
parts = name.split(".")
for attr in parts[:-1]:
obj = getattr(obj, attr)
setattr(obj, parts[-1], value)
</code></pre>
| 42 | 2008-11-17T16:26:46Z | [
"python"
]
|
Convert a string to preexisting variable names | 295,058 | <p>How do I convert a string to the variable name in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>For example, if the program contains a object named <code>self.post</code> that contains a variable named, I want to do something like:</p>
<pre><code>somefunction("self.post.id") = |Value of self.post.id|
</code></pre>
| 20 | 2008-11-17T07:32:09Z | 1,732,924 | <p>You could do something like what Geo recommended, or go with:</p>
<pre><code>>>> wine = 'pinot_noir'
>>> vars()[wine] = 'yum'
>>> pinot_noir
'yum'
</code></pre>
<p><strike>Note: vars() and globals() are the same, I'm just used to using vars()</strike>
I'm surprised nobody called me out on this! Anyway, it's <code>vars()</code> and <em><code>locals()</code></em> that are the same.</p>
| 13 | 2009-11-14T01:32:15Z | [
"python"
]
|
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,146 | <p>This whitelist approach (ie, allowing only the chars present in valid_chars) will work if there aren't limits on the formatting of the files or combination of valid chars that are illegal (like ".."), for example, what you say would allow a filename named " . txt" which I think is not valid on Windows. As this is the most simple approach I'd try to remove whitespace from the valid_chars and prepend a known valid string in case of error, any other approach will have to know about what is allowed where to cope with <a href="http://stackoverflow.com/questions/62771/how-check-if-given-string-is-legal-allowed-file-name-under-windows">Windows file naming limitations</a> and thus be a lot more complex. </p>
<pre><code>>>> import string
>>> valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
>>> valid_chars
'-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
>>> filename = "This Is a (valid) - filename%$&$ .txt"
>>> ''.join(c for c in filename if c in valid_chars)
'This Is a (valid) - filename .txt'
</code></pre>
| 77 | 2008-11-17T09:10:49Z | [
"python",
"filenames",
"slug",
"sanitize"
]
|
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,147 | <p>You could use the re.sub() method to replace anything not "filelike". But in effect, every character could be valid; so there are no prebuilt functions (I believe), to get it done.</p>
<pre><code>import re
str = "File!name?.txt"
f = open(os.path.join("/tmp", re.sub('[^-a-zA-Z0-9_.() ]+', '', str))
</code></pre>
<p>Would result in a filehandle to /tmp/filename.txt.</p>
| 4 | 2008-11-17T09:10:53Z | [
"python",
"filenames",
"slug",
"sanitize"
]
|
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,150 | <p>What is the reason to use the strings as file names? If human readability is not a factor I would go with base64 module which can produce file system safe strings. It won't be readable but you won't have to deal with collisions and it is reversible.</p>
<pre><code>import base64
file_name_string = base64.urlsafe_b64encode(your_string)
</code></pre>
<p><strong>Update</strong>: Changed based on Matthew comment.</p>
| 70 | 2008-11-17T09:12:02Z | [
"python",
"filenames",
"slug",
"sanitize"
]
|
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,152 | <p>You can use list comprehension together with the string methods.</p>
<pre><code>>>> s
'foo-bar#baz?qux@127/\\9]'
>>> "".join(x for x in s if x.isalnum())
'foobarbazqux1279'
</code></pre>
| 61 | 2008-11-17T09:12:49Z | [
"python",
"filenames",
"slug",
"sanitize"
]
|
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,206 | <p>Just to further complicate things, you are not guaranteed to get a valid filename just by removing invalid characters. Since allowed characters differ on different filenames, a conservative approach could end up turning a valid name into an invalid one. You may want to add special handling for the cases where:</p>
<ul>
<li><p>The string is all invalid characters (leaving you with an empty string)</p></li>
<li><p>You end up with a string with a special meaning, eg "." or ".."</p></li>
<li><p>On windows, <a href="http://msdn.microsoft.com/en-us/library/aa365247.aspx">certain device names</a> are reserved. For instance, you can't create a file named "nul", "nul.txt" (or nul.anything in fact) The reserved names are:</p>
<p>CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9</p></li>
</ul>
<p>You can probably work around these issues by prepending some string to the filenames that can never result in one of these cases, and stripping invalid characters.</p>
| 27 | 2008-11-17T09:57:40Z | [
"python",
"filenames",
"slug",
"sanitize"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.