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
sequence
Creating a list of objects in Python
348,196
<p>I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.</p> <p>I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...</p> <p>Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over. </p> <p>So how do you write objects to a list within a loop?</p> <p>Thanks,</p> <p>Bob J</p> <p>Here's my simplified code</p> <pre><code>class SimpleClass(object): pass x = SimpleClass # Then create an empty list simpleList = [] #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass for count in range(0,4): # each iteration creates a slightly different attribute value, and then prints it to # prove that step is working # but the problem is, I'm always updating a reference to 'x' and what I want to add to # simplelist is a new instance of x that contains the updated attribute x.attr1= '*Bob* '* count print "Loop Count: %s Attribute Value %s" % (count, x.attr1) simpleList.append(x) print '-'*20 # And here I print out each instance of the object stored in the list 'simpleList' # and the problem surfaces. Every element of 'simpleList' contains the same attribute value y = SimpleClass print "Reading the attributes from the objects in the list" for count in range(0,4): y = simpleList[count] print y.attr1 </code></pre> <p>So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?</p>
42
2008-12-07T22:15:46Z
352,505
<p>To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.</p> <pre><code>instancelist = [ MyClass() for i in range(29)] </code></pre> <p>and then access the instances through the index of the list.</p> <pre><code>instancelist[5].attr1 = 'whamma' </code></pre>
31
2008-12-09T11:50:39Z
[ "python", "list", "object", "loops" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
348,396
<p>Yes, you can do pretty much everything with the built-in libraries. Do a search here looking for the tags <code>[python]</code> and <code>[email]</code> and you'll see how it's done.</p>
2
2008-12-08T00:15:54Z
[ "python", "email" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
348,403
<p>poplib and smtplib will be your friends when developing your app.</p>
4
2008-12-08T00:21:53Z
[ "python", "email" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
348,423
<p>Python has an SMTPD module that will be helpful to you for writing a server. You'll probably also want the SMTP module to do the re-send. Both modules are in the standard library at least since version 2.3.</p>
6
2008-12-08T00:39:49Z
[ "python", "email" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
348,551
<p>Here is a very simple example:</p> <pre><code>import smtplib server = 'mail.server.com' user = '' password = '' recipients = ['[email protected]', '[email protected]'] sender = '[email protected]' message = 'Hello World' session = smtplib.SMTP(server) # if your SMTP server doesn't need authentications, # you don't need the following line: session.login(user, password) session.sendmail(sender, recipients, message) </code></pre> <p>For more options, error handling, etc, look at the <a href="http://www.python.org/doc/2.5.2/lib/module-smtplib.html">smtplib module documentation</a>.</p>
21
2008-12-08T02:36:49Z
[ "python", "email" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
348,579
<p>Depending on the amount of mail you are sending you might want to look into using a real mail server like postifx or sendmail (*nix systems) Both of those programs have the ability to send a received mail to a program based on the email address. </p>
2
2008-12-08T03:06:33Z
[ "python", "email" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
349,001
<p>The sending part has been covered, for the receiving you can use <a href="http://docs.python.org/library/poplib.html" rel="nofollow">pop</a> or <a href="http://docs.python.org/library/imaplib.html" rel="nofollow">imap</a></p>
3
2008-12-08T09:37:39Z
[ "python", "email" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
349,352
<p>I do not think it would be a good idea to write a real mail server in Python. This is certainly possible (see mcrute's and Manuel Ceron's posts to have details) but it is a lot of work when you think of everything that a real mail server must handle (queuing, retransmission, dealing with spam, etc).</p> <p>You should explain in more detail what you need. If you just want to react to incoming email, I would suggest to configure the mail server to call a program when it receives the email. This program could do what it wants (updating a database, creating a file, talking to another Python program).</p> <p>To call an arbitrary program from the mail server, you have several choices:</p> <ol> <li>For sendmail and Postfix, a <code>~/.forward</code> containing <code>"|/path/to/program"</code></li> <li>If you use procmail, a recipe action of <code>|path/to/program</code></li> <li>And certainly many others</li> </ol>
10
2008-12-08T12:23:21Z
[ "python", "email" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
26,783,166
<p>Found a helpful example for reading emails by connecting using IMAP: </p> <p><a href="http://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/">Python — imaplib IMAP example with Gmail</a></p> <pre><code>import imaplib mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('[email protected]', 'mypassword') mail.list() # Out: list of "folders" aka labels in gmail. mail.select("inbox") # connect to inbox. result, data = mail.search(None, "ALL") ids = data[0] # data is a list. id_list = ids.split() # ids is a space separated string latest_email_id = id_list[-1] # get the latest # fetch the email body (RFC822) for the given ID result, data = mail.fetch(latest_email_id, "(RFC822)") raw_email = data[0][1] # here's the body, which is raw text of the whole email # including headers and alternate payloads </code></pre>
6
2014-11-06T15:28:55Z
[ "python", "email" ]
Receive and send emails in python
348,392
<p>How can i receive and send email in python? A 'mail server' of sorts.</p> <p>I am looking into making an app that listens to see if it recieves an email addressed to [email protected], and sends an email to the sender.</p> <p>Now, am i able to do this all in python, would it be best to use 3rd party libraries? </p>
29
2008-12-08T00:12:25Z
30,649,434
<p>The best way to do this would be to create a windows service in python that receives the emails using imaplib2</p> <p>Below is a sample python script to do the same.You can install this script to run as a windows service by running the following command on the command line "python THENAMEOFYOURSCRIPTFILE.py install".</p> <pre><code>import win32service import win32event import servicemanager import socket import imaplib2, time from threading import * import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText import datetime import email class Idler(object): def __init__(self, conn): self.thread = Thread(target=self.idle) self.M = conn self.event = Event() def start(self): self.thread.start() def stop(self): self.event.set() def join(self): self.thread.join() def idle(self): while True: if self.event.isSet(): return self.needsync = False def callback(args): if not self.event.isSet(): self.needsync = True self.event.set() self.M.idle(callback=callback) self.event.wait() if self.needsync: self.event.clear() self.dosync() def dosync(self): #DO SOMETHING HERE WHEN YOU RECEIVE YOUR EMAIL class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "receiveemail" _svc_display_name_ = "receiveemail" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): M = imaplib2.IMAP4_SSL("imap.gmail.com", 993) M.login("YourID", "password") M.select("INBOX") idler = Idler(M) idler.start() while True: time.sleep(1*60) idler.stop() idler.join() M.close() M.logout() if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) </code></pre>
0
2015-06-04T16:35:48Z
[ "python", "email" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
348,649
<p>I'm not an expert on Perl, but what I do know is that GMail supports IMAP and POP3, 2 protocols that are completely standard and allow you to do just that. </p> <p>Maybe that helps you to get started. </p>
10
2008-12-08T04:17:37Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
348,696
<p>Within gmail, you can filter on "has:attachment", use it to identify the messages you should be getting when testing. Note this appears to give both messages with attached files (paperclip icon shown), as well as inline attached images (no paperclip shown).</p> <p>There is no Gmail API, so IMAP or POP are your only real options. The <a href="http://www.nakov.com/inetjava/lectures/part-1-sockets/InetJava-1.9-JavaMail-API.html" rel="nofollow">JavaMail API</a> may be of some assistance as well as this very terse article on <a href="http://www.perlmonks.org/?node_id=697321" rel="nofollow">downloading attachments from IMAP using Perl</a>. Some <a href="http://stackoverflow.com/questions/61176/getting-mail-from-gmail-into-java-application-using-imap">previous questions</a> here on SO may also help.</p> <p>This <a href="http://petewarden.typepad.com/searchbrowser/2008/03/how-to-use-imap.html" rel="nofollow">PHP example</a> may help too. Unfortunately from what I can see, there is no attachment information contained within the imap_header, so downloading the body is required to be able to see the X-Attachment-Id field. (someone please prove me wrong).</p>
4
2008-12-08T05:10:38Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
348,715
<p>Since Gmail supports the standard protocols POP and IMAP, any platform, tool, application, component, or API that provides the client side of either protocol should work.</p> <p>I suggest doing a Google search for your favorite language/platform (e.g., "python"), plus "pop", plus "imap", plus perhaps "open source", plus perhaps "download" or "review", and see what you get for options.</p> <p>There are numerous free applications and components, pick a few that seem worthy, check for reviews, then download and enjoy.</p>
1
2008-12-08T05:23:54Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
413,041
<p>You should be aware of the fact that you need SSL to connect to GMail (both for POP3 and IMAP - this is of course true also for their SMTP-servers apart from port 25 but that's another story).</p>
1
2009-01-05T13:07:02Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
641,409
<p>Have you taken a look at the <a href="http://en.wikipedia.org/wiki/Gmail#Gmail%5F3rd%5Fparty%5FAdd-Ins" rel="nofollow">GMail 3rd party add-ons</a> at wikipedia?</p> <p>In particular, <a href="http://en.wikipedia.org/wiki/PhpGmailDrive" rel="nofollow">PhpGmailDrive</a> is an open source add-on that you may be able to use as-is, or perhaps study for inspiration?</p>
0
2009-03-13T03:52:27Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
641,843
<pre><code>#!/usr/bin/env python """Save all attachments for given gmail account.""" import os, sys from libgmail import GmailAccount ga = GmailAccount("[email protected]", "pA$$w0Rd_") ga.login() # folders: inbox, starred, all, drafts, sent, spam for thread in ga.getMessagesByFolder('all', allPages=True): for msg in thread: sys.stdout.write('.') if msg.attachments: print "\n", msg.id, msg.number, msg.subject, msg.sender for att in msg.attachments: if att.filename and att.content: attdir = os.path.join(thread.id, msg.id) if not os.path.isdir(attdir): os.makedirs(attdir) with open(os.path.join(attdir, att.filename), 'wb') as f: f.write(att.content) </code></pre> <p>untested</p> <ol> <li>Make sure TOS allows such scripts otherwise you account will be suspended</li> <li>There might be better options: GMail offline mode, Thunderbird + ExtractExtensions, GmailFS, Gmail Drive, etc.</li> </ol>
7
2009-03-13T08:40:25Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
642,335
<p>For Java, you will find <a href="http://g4j.sourceforge.net/" rel="nofollow">G4J</a> of use. It's a set of APIs to communicate with Google Mail via Java (the screenshot on the homepage is a demonstration email client built around this)</p>
0
2009-03-13T11:56:17Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
642,988
<p>Hard one :-)</p> <pre><code>import email, getpass, imaplib, os detach_dir = '.' # directory where to save attachments (default: current) user = raw_input("Enter your GMail username:") pwd = getpass.getpass("Enter your password: ") # connecting to the gmail imap server m = imaplib.IMAP4_SSL("imap.gmail.com") m.login(user,pwd) m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead # use m.list() to get all the mailboxes resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp) items = items[0].split() # getting the mails id for emailid in items: resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object #Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue print "["+mail["From"]+"] :" + mail["Subject"] # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue # is this part an attachment ? if part.get('Content-Disposition') is None: continue filename = part.get_filename() counter = 1 # if there is no filename, we create one with a counter to avoid duplicates if not filename: filename = 'part-%03d%s' % (counter, 'bin') counter += 1 att_path = os.path.join(detach_dir, filename) #Check if its already there if not os.path.isfile(att_path) : # finally write the stuff fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() </code></pre> <p>Wowww! That was something. ;-) But try the same in Java, just for fun!</p> <p>By the way, I tested that in a shell, so some errors likely remain.</p> <p>Enjoy</p> <p><strong>EDIT:</strong></p> <p>Because mail-box names can change from one country to another, I recommend doing <code>m.list()</code> and picking an item in it before <code>m.select("the mailbox name")</code> to avoid this error:</p> <blockquote> <p>imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED</p> </blockquote>
141
2009-03-13T14:34:44Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
643,366
<p>Take a look at <a href="http://search.cpan.org/~mincus/Mail-Webmail-Gmail-1.09/lib/Mail/Webmail/Gmail.pm#GETTING%5FATTACHMENTS">Mail::Webmail::Gmail</a>:</p> <p><strong>GETTING ATTACHMENTS</strong></p> <p>There are two ways to get an attachment:</p> <p>1 -> By sending a reference to a specific attachment returned by <code>get_indv_email</code></p> <pre><code># Creates an array of references to every attachment in your account my $messages = $gmail-&gt;get_messages(); my @attachments; foreach ( @{ $messages } ) { my $email = $gmail-&gt;get_indv_email( msg =&gt; $_ ); if ( defined( $email-&gt;{ $_-&gt;{ 'id' } }-&gt;{ 'attachments' } ) ) { foreach ( @{ $email-&gt;{ $_-&gt;{ 'id' } }-&gt;{ 'attachments' } } ) { push( @attachments, $gmail-&gt;get_attachment( attachment =&gt; $_ ) ); if ( $gmail-&gt;error() ) { print $gmail-&gt;error_msg(); } } } } </code></pre> <p>2 -> Or by sending the attachment ID and message ID</p> <pre><code>#retrieve specific attachment my $msgid = 'F000000000'; my $attachid = '0.1'; my $attach_ref = $gmail-&gt;get_attachment( attid =&gt; $attachid, msgid =&gt; $msgid ); </code></pre> <p>( Returns a reference to a scalar that holds the data from the attachment. )</p>
7
2009-03-13T15:52:00Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
4,172,062
<p>Here's something I wrote to download my bank statements in <a href="http://groovy.codehaus.org/" rel="nofollow">Groovy</a> (dynamic language for the Java Platform).</p> <pre><code>import javax.mail.* import java.util.Properties String gmailServer int gmailPort def user, password, LIMIT def inboxFolder, root, StartDate, EndDate // Downloads all attachments from a gmail mail box as per some criteria // to a specific folder // Based on code from // http://agileice.blogspot.com/2008/10/using-groovy-to-connect-to-gmail.html // http://stackoverflow.com/questions/155504/download-mail-attachment-with-java // // Requires: // java mail jars in the class path (mail.jar and activation.jar) // openssl, with gmail certificate added to java keystore (see agileice blog) // // further improvement: maybe findAll could be used to filter messages // subject could be added as another criteria ////////////////////// &lt;CONFIGURATION&gt; ////////////////////// // Maximm number of emails to access in case parameter range is too high LIMIT = 10000 // gmail credentials gmailServer = "imap.gmail.com" gmailPort = 993 user = "[email protected]" password = "gmailpassword" // gmail label, or "INBOX" for inbox inboxFolder = "finance" // local file system where the attachment files need to be stored root = "D:\\AttachmentStore" // date range dd-mm-yyyy StartDate= "31-12-2009" EndDate = "1-6-2010" ////////////////////// &lt;/CONFIGURATION&gt; ////////////////////// StartDate = Date.parse("dd-MM-yyyy", StartDate) EndDate = Date.parse("dd-MM-yyyy", EndDate) Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imaps.host", gmailServer); props.setProperty("mail.imaps.port", gmailPort.toString()); props.setProperty("mail.imaps.partialfetch", "false"); def session = javax.mail.Session.getDefaultInstance(props,null) def store = session.getStore("imaps") store.connect(gmailServer, user, password) int i = 0; def folder = store.getFolder(inboxFolder) folder.open(Folder.READ_ONLY) for(def msg : folder.messages) { //if (msg.subject?.contains("bank Statement")) println "[$i] From: ${msg.from} Subject: ${msg.subject} -- Received: ${msg.receivedDate}" if (msg.receivedDate &lt; StartDate || msg.receivedDate &gt; EndDate) { println "Ignoring due to date range" continue } if (msg.content instanceof Multipart) { Multipart mp = (Multipart)msg.content; for (int j=0; j &lt; mp.count; j++) { Part part = mp.getBodyPart(j); println " ---- ${part.fileName} ---- ${part.disposition}" if (part.disposition?.equalsIgnoreCase(Part.ATTACHMENT)) { if (part.content) { def name = msg.receivedDate.format("yyyy_MM_dd") + " " + part.fileName println "Saving file to $name" def f = new File(root, name) //f &lt;&lt; part.content try { if (!f.exists()) f &lt;&lt; part.content } catch (Exception e) { println "*** Error *** $e" } } else { println "NO Content Found!!" } } } } if (i++ &gt; LIMIT) break; } </code></pre>
1
2010-11-13T10:32:33Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
18,259,764
<p>If any of you have updated to python 3.3 I took the 2.7 script from <a href="https://gist.github.com/baali/2633554" rel="nofollow">HERE</a> and updated it to 3.3. Also fixed some issues with the way gmail was returning the information.</p> <pre><code># Something in lines of http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail # Make sure you have IMAP enabled in your gmail settings. # Right now it won't download same file name twice even if their contents are different. # Gmail as of now returns in bytes but just in case they go back to string this line is left here. import email import getpass, imaplib import os import sys import time detach_dir = '.' if 'attachments' not in os.listdir(detach_dir): os.mkdir('attachments') userName = input('Enter your GMail username:\n') passwd = getpass.getpass('Enter your password:\n') try: imapSession = imaplib.IMAP4_SSL('imap.gmail.com',993) typ, accountDetails = imapSession.login(userName, passwd) if typ != 'OK': print ('Not able to sign in!') raise imapSession.select('Inbox') typ, data = imapSession.search(None, 'ALL') if typ != 'OK': print ('Error searching Inbox.') raise # Iterating over all emails for msgId in data[0].split(): typ, messageParts = imapSession.fetch(msgId, '(RFC822)') if typ != 'OK': print ('Error fetching mail.') raise #print(type(emailBody)) emailBody = messageParts[0][1] #mail = email.message_from_string(emailBody) mail = email.message_from_bytes(emailBody) for part in mail.walk(): #print (part) if part.get_content_maintype() == 'multipart': # print part.as_string() continue if part.get('Content-Disposition') is None: # print part.as_string() continue fileName = part.get_filename() if bool(fileName): filePath = os.path.join(detach_dir, 'attachments', fileName) if not os.path.isfile(filePath) : print (fileName) fp = open(filePath, 'wb') fp.write(part.get_payload(decode=True)) fp.close() imapSession.close() imapSession.logout() except : print ('Not able to download all attachments.') time.sleep(3) </code></pre>
2
2013-08-15T19:02:05Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
26,009,465
<pre><code>/*based on http://www.codejava.net/java-ee/javamail/using-javamail-for-searching-e-mail-messages*/ package getMailsWithAtt; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.NoSuchProviderException; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeBodyPart; import javax.mail.search.AndTerm; import javax.mail.search.SearchTerm; import javax.mail.search.ReceivedDateTerm; import javax.mail.search.ComparisonTerm; public class EmailReader { private String saveDirectory; /** * Sets the directory where attached files will be stored. * * @param dir * absolute path of the directory */ public void setSaveDirectory(String dir) { this.saveDirectory = dir; } /** * Downloads new messages and saves attachments to disk if any. * * @param host * @param port * @param userName * @param password * @throws IOException */ public void downloadEmailAttachments(String host, String port, String userName, String password, Date startDate, Date endDate) { Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", userName, password); // ... Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); SearchTerm olderThan = new ReceivedDateTerm (ComparisonTerm.LT, startDate); SearchTerm newerThan = new ReceivedDateTerm (ComparisonTerm.GT, endDate); SearchTerm andTerm = new AndTerm(olderThan, newerThan); //Message[] arrayMessages = inbox.getMessages(); &lt;--get all messages Message[] arrayMessages = inbox.search(andTerm); for (int i = arrayMessages.length; i &gt; 0; i--) { //from newer to older Message msg = arrayMessages[i-1]; Address[] fromAddress = msg.getFrom(); String from = fromAddress[0].toString(); String subject = msg.getSubject(); String sentDate = msg.getSentDate().toString(); String receivedDate = msg.getReceivedDate().toString(); String contentType = msg.getContentType(); String messageContent = ""; // store attachment file name, separated by comma String attachFiles = ""; if (contentType.contains("multipart")) { // content may contain attachments Multipart multiPart = (Multipart) msg.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount &lt; numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart .getBodyPart(partCount); if (Part.ATTACHMENT.equalsIgnoreCase(part .getDisposition())) { // this part is attachment String fileName = part.getFileName(); attachFiles += fileName + ", "; part.saveFile(saveDirectory + File.separator + fileName); } else { // this part may be the message content messageContent = part.getContent().toString(); } } if (attachFiles.length() &gt; 1) { attachFiles = attachFiles.substring(0, attachFiles.length() - 2); } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } // print out details of each message System.out.println("Message #" + (i + 1) + ":"); System.out.println("\t From: " + from); System.out.println("\t Subject: " + subject); System.out.println("\t Received: " + sentDate); System.out.println("\t Message: " + messageContent); System.out.println("\t Attachments: " + attachFiles); } // disconnect inbox.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); System.exit(1); } catch (MessagingException e) { e.printStackTrace(); System.exit(2); } catch (IOException ex) { ex.printStackTrace(); } } /** * Runs this program with Gmail POP3 server * @throws ParseException */ public static void main(String[] args) throws ParseException { String host = "pop.gmail.com"; String port = "995"; String userName = "[email protected]"; String password = "pass"; Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse("2014-06-30"); Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse("2014-06-01"); String saveDirectory = "C:\\Temp"; EmailReader receiver = new EmailReader(); receiver.setSaveDirectory(saveDirectory); receiver.downloadEmailAttachments(host, port, userName, password,startDate,endDate); } } </code></pre> <p>Maven Dependency:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.sun.mail&lt;/groupId&gt; &lt;artifactId&gt;javax.mail&lt;/artifactId&gt; &lt;version&gt;1.5.1&lt;/version&gt; &lt;/dependency&gt; </code></pre>
1
2014-09-24T05:48:52Z
[ "java", "python", "perl", "gmail" ]
How can I download all emails with attachments from Gmail?
348,630
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
80
2008-12-08T03:57:49Z
37,088,611
<p>The question is quite old and at that time Gmail API was not available. But now Google provides Gmail API to access IMAP. Please see Google's Gmail API <a href="https://developers.google.com/gmail/api/quickstart/python" rel="nofollow">here</a>.</p>
1
2016-05-07T12:35:30Z
[ "java", "python", "perl", "gmail" ]
Adding a mimetype in python
348,999
<p>On my Centos server Python's mimetypes.guess_type("mobile.3gp") returns (None, None), instead of ('video/3gpp', None).</p> <p>Where does Python get the list of mimetypes from, and is it possible to add a missing type to the list?</p>
6
2008-12-08T09:33:04Z
349,020
<p>On my system (Debian lenny) its in /usr/lib/python2.5/mimetypes.py in the list <code>knownfiles</code> you can supply your own files for the <code>init()</code> function.</p>
5
2008-12-08T09:45:31Z
[ "python", "mime-types" ]
Adding a mimetype in python
348,999
<p>On my Centos server Python's mimetypes.guess_type("mobile.3gp") returns (None, None), instead of ('video/3gpp', None).</p> <p>Where does Python get the list of mimetypes from, and is it possible to add a missing type to the list?</p>
6
2008-12-08T09:33:04Z
349,024
<p>The mimetypes module uses mime.types files as they are common on Linux/Unix systems. If you look in mimetypes.knownfiles you will find a list of files that Python tries to access to load the data. You can also specify your own file to add new types by adding it to that list.</p>
2
2008-12-08T09:46:40Z
[ "python", "mime-types" ]
Formatting a data structure into a comma-separated list of arguments
349,175
<p>I need to convert a list (or a dict) into a comma-separated list for passing to another language.</p> <p>Is there a nicer way of doing this than:</p> <pre><code> result = '' args = ['a', 'b', 'c', 'd'] i = 0 for arg in args: if i != 0: result += arg else: result += arg + ', ' i += 1 result = 'function (' + result + ') </code></pre> <p>Thanks, Dan</p>
6
2008-12-08T11:00:39Z
349,182
<p><code>', '.join(args)</code> will do the trick.</p>
12
2008-12-08T11:03:54Z
[ "python", "refactoring", "list" ]
Formatting a data structure into a comma-separated list of arguments
349,175
<p>I need to convert a list (or a dict) into a comma-separated list for passing to another language.</p> <p>Is there a nicer way of doing this than:</p> <pre><code> result = '' args = ['a', 'b', 'c', 'd'] i = 0 for arg in args: if i != 0: result += arg else: result += arg + ', ' i += 1 result = 'function (' + result + ') </code></pre> <p>Thanks, Dan</p>
6
2008-12-08T11:00:39Z
349,197
<pre><code>'function(%s)' % ', '.join(args) </code></pre> <p>produces</p> <pre><code>'function(a, b, c, d)' </code></pre>
11
2008-12-08T11:09:37Z
[ "python", "refactoring", "list" ]
Formatting a data structure into a comma-separated list of arguments
349,175
<p>I need to convert a list (or a dict) into a comma-separated list for passing to another language.</p> <p>Is there a nicer way of doing this than:</p> <pre><code> result = '' args = ['a', 'b', 'c', 'd'] i = 0 for arg in args: if i != 0: result += arg else: result += arg + ', ' i += 1 result = 'function (' + result + ') </code></pre> <p>Thanks, Dan</p>
6
2008-12-08T11:00:39Z
349,229
<p>Why not use a standard that both languages can parse, like JSON, XML, or YAML? <a href="http://pypi.python.org/pypi/simplejson" rel="nofollow">simplejson</a> is handy, and included as json in python 2.6.</p>
0
2008-12-08T11:21:52Z
[ "python", "refactoring", "list" ]
Formatting a data structure into a comma-separated list of arguments
349,175
<p>I need to convert a list (or a dict) into a comma-separated list for passing to another language.</p> <p>Is there a nicer way of doing this than:</p> <pre><code> result = '' args = ['a', 'b', 'c', 'd'] i = 0 for arg in args: if i != 0: result += arg else: result += arg + ', ' i += 1 result = 'function (' + result + ') </code></pre> <p>Thanks, Dan</p>
6
2008-12-08T11:00:39Z
351,629
<pre><code>result = 'function (%s)' % ', '.join(map(str,args)) </code></pre> <p>I recommend the map(str, args) instead of just args because some of your arguments could potentially not be strings and would cause a TypeError, for example, with an int argument in your list:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: sequence item 0: expected string, int found </code></pre> <p>When you get into dict objects you will probably want to comma-separate the values of the dict (presumably because the values are what you want to pass into this function). If you do the join method on the dict object itself, you will get the keys separated, like so:</p> <pre><code>&gt;&gt;&gt; d = {'d':5, 'f':6.0, 'r':"BOB"} &gt;&gt;&gt; ','.join(d) 'r,d,f' </code></pre> <p>What you want is the following:</p> <pre><code>&gt;&gt;&gt; d = {'d':5, 'f':6.0, 'r':"BOB"} &gt;&gt;&gt; result = 'function (%s)' % ', '.join(map(str, d.values())) &gt;&gt;&gt; result 'function (BOB, 5, 6.0)' </code></pre> <p>Note the new problem you encounter, however. When you pass a string argument through the join function, it loses its quoting. So if you planned to pass strings through, you have lost the quotes that usually would surround the string when passed into a function (strings are quoted in many general-purpose languages). If you're only passing numbers, however, this isn't a problem for you.</p> <p>There is probably a nicer way of solving the problem I just described, but here's one method that could work for you.</p> <pre><code>&gt;&gt;&gt; l = list() &gt;&gt;&gt; for val in d.values(): ... try: ... v = float(val) #half-decent way of checking if something is an int, float, boolean ... l.append(val) #if it was, then append the original type to the list ... except: ... #wasn't a number, assume it's a string and surround with quotes ... l.append("\"" + val + "\"") ... &gt;&gt;&gt; result = 'function (%s)' % ', '.join(map(str, l)) &gt;&gt;&gt; result 'function ("BOB", 5, 6.0)' </code></pre> <p>Now the string has quotes surrounding itself. If you are passing more complex types than numeric primitives and strings then you probably need a new question :)</p> <p>One last note: I have been using d.values() to show how to extract the values from a dictionary, but in fact that will return the values from the dictionary in pretty much arbitrary order. Since your function most likely requires the arguments in a particular order, you should manually construct your list of values instead of calling d.values().</p>
1
2008-12-09T02:39:34Z
[ "python", "refactoring", "list" ]
How do I find the "concrete class" of a django model baseclass
349,206
<p>I'm trying to find the actual class of a django-model object, when using model-inheritance.</p> <p>Some code to describe the problem:</p> <pre><code>class Base(models.model): def basemethod(self): ... class Child_1(Base): pass class Child_2(Base): pass </code></pre> <p>If I create various objects of the two Child classes and the create a queryset containing them all:</p> <pre><code>Child_1().save() Child_2().save() (o1, o2) = Base.objects.all() </code></pre> <p>I want to determine if the object is of type Child_1 or Child_2 in basemethod, I can get to the child object via o1.child_1 and o2.child_2 but that reconquers knowledge about the childclasses in the baseclass.</p> <p>I have come up with the following code:</p> <pre><code>def concrete_instance(self): instance = None for subclass in self._meta.get_all_related_objects(): acc_name = subclass.get_accessor_name() try: instance = self.__getattribute__(acc_name) return instance except Exception, e: pass </code></pre> <p>But it feels brittle and I'm not sure of what happens when if I inherit in more levels.</p>
10
2008-12-08T11:11:45Z
349,235
<p>It feels brittle because it is. (This is a reprint of an answer in a different context. <a href="http://stackoverflow.com/questions/243082/c-casting-programmatically-can-it-be-done">See C++ casting programmatically : can it be done ?</a>)</p> <p>Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented.</p> <p>Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses.</p> <p>You left out the most important part of your example. The useful, polymorphic work.</p> <p>When you said "I want to determine if the object is of type Child_1 or Child_2..." you left out the "so I can make the object do <code>aMethod()</code> in a way that's unique to each subclass". That method is the useful work, and it should simply be a method of both subclasses.</p> <pre><code>class Base(models.model): def aMethod(self): # base class implementation. class Child_1(Base): def aMethod(self): # Child_1 override of base class behavior. class Child_2(Base): def aMethod(self): supert( Child_2, self ).aMethod() # Invoke the base class version # Child_2 extension to base class behavior. </code></pre> <p>Same method, multiple implementations. Never a need to "run-time type identification" or determining the concrete class.</p>
-2
2008-12-08T11:23:59Z
[ "python", "django", "inheritance", "django-models" ]
How do I find the "concrete class" of a django model baseclass
349,206
<p>I'm trying to find the actual class of a django-model object, when using model-inheritance.</p> <p>Some code to describe the problem:</p> <pre><code>class Base(models.model): def basemethod(self): ... class Child_1(Base): pass class Child_2(Base): pass </code></pre> <p>If I create various objects of the two Child classes and the create a queryset containing them all:</p> <pre><code>Child_1().save() Child_2().save() (o1, o2) = Base.objects.all() </code></pre> <p>I want to determine if the object is of type Child_1 or Child_2 in basemethod, I can get to the child object via o1.child_1 and o2.child_2 but that reconquers knowledge about the childclasses in the baseclass.</p> <p>I have come up with the following code:</p> <pre><code>def concrete_instance(self): instance = None for subclass in self._meta.get_all_related_objects(): acc_name = subclass.get_accessor_name() try: instance = self.__getattribute__(acc_name) return instance except Exception, e: pass </code></pre> <p>But it feels brittle and I'm not sure of what happens when if I inherit in more levels.</p>
10
2008-12-08T11:11:45Z
349,494
<p>Django implements model inheritance with a OneToOneField between the parent model's table and the child model's table. When you do <code>Base.object.all()</code>, Django is querying just the Base table, and so has no way of knowing what the child table is. Therefore, unfortunately, it's not possible to go directly to the child model instance without additional queries.</p> <p>This <a href="http://www.djangosnippets.org/snippets/1031/" rel="nofollow">snippet</a> shows a common method of adding a ContentType field to the base model:</p> <pre><code>from django.contrib.contenttypes.models import ContentType class Base(models.Model): content_type = models.ForeignKey(ContentType,editable=False,null=True) def save(self): if(not self.content_type): self.content_type = ContentType.objects.get_for_model(self.__class__) self.save_base() def as_leaf_class(self): content_type = self.content_type model = content_type.model_class() if(model == Base): return self return model.objects.get(id=self.id) </code></pre> <p>You can then say <code>if Base.content_type.model_class()</code> to determine the type.</p> <p><a href="http://www.djangosnippets.org/snippets/1034/" rel="nofollow">Here</a> is another snippet that adds a custom manager into the mix.</p> <p>As you can see, both of these solutions have the potential to be extremely expensive. If you have a large number of instances, using the as_leaf_class() method will require one query on each item.</p> <p>Instead, if you have a known set of child models, simply query each model separately and aggregate the instances into one list.</p>
12
2008-12-08T13:05:59Z
[ "python", "django", "inheritance", "django-models" ]
How do I find the "concrete class" of a django model baseclass
349,206
<p>I'm trying to find the actual class of a django-model object, when using model-inheritance.</p> <p>Some code to describe the problem:</p> <pre><code>class Base(models.model): def basemethod(self): ... class Child_1(Base): pass class Child_2(Base): pass </code></pre> <p>If I create various objects of the two Child classes and the create a queryset containing them all:</p> <pre><code>Child_1().save() Child_2().save() (o1, o2) = Base.objects.all() </code></pre> <p>I want to determine if the object is of type Child_1 or Child_2 in basemethod, I can get to the child object via o1.child_1 and o2.child_2 but that reconquers knowledge about the childclasses in the baseclass.</p> <p>I have come up with the following code:</p> <pre><code>def concrete_instance(self): instance = None for subclass in self._meta.get_all_related_objects(): acc_name = subclass.get_accessor_name() try: instance = self.__getattribute__(acc_name) return instance except Exception, e: pass </code></pre> <p>But it feels brittle and I'm not sure of what happens when if I inherit in more levels.</p>
10
2008-12-08T11:11:45Z
2,936,296
<p>Well... My problem was. In a view, I had this principal model, lets say "Big_Model" and there were some "Small_Model" related to "Big_Model". So when I wanted to retrieve all "Small_Model" related to a certain instance of "Big_Model" I did that **_set.all() stuff. But the point is that Small_Model has Child Classes and I wanted, in views.py, to get which child class was each of the Small_Model instances related to. My trick was to define boolean methods in model Small_Model like is_child_1() and is_child_2(). And when it is true, you apply the actual child pointer instead of the Small_Model pointer.</p> <p>Ok... Thats not clear enough, still I dont have much time to write a good example, so i'll just copy-paste my case here:</p> <pre><code>class Cache(models.Model): valor = models.DecimalField(max_digits=9, decimal_places=2, blank= True, null= True) evento=models.ForeignKey(Evento) def __unicode__(self): return u'%s: %s' % (self.evento, self.valor) class Meta: verbose_name='Cachê' verbose_name_plural='Cachês' def is_cb(self): try: self.cache_bilheteria return True except self.DoesNotExist: return False def is_co(self): try: self.cache_outro return True except self.DoesNotExist: return False </code></pre>
0
2010-05-29T19:19:48Z
[ "python", "django", "inheritance", "django-models" ]
How do I find the "concrete class" of a django model baseclass
349,206
<p>I'm trying to find the actual class of a django-model object, when using model-inheritance.</p> <p>Some code to describe the problem:</p> <pre><code>class Base(models.model): def basemethod(self): ... class Child_1(Base): pass class Child_2(Base): pass </code></pre> <p>If I create various objects of the two Child classes and the create a queryset containing them all:</p> <pre><code>Child_1().save() Child_2().save() (o1, o2) = Base.objects.all() </code></pre> <p>I want to determine if the object is of type Child_1 or Child_2 in basemethod, I can get to the child object via o1.child_1 and o2.child_2 but that reconquers knowledge about the childclasses in the baseclass.</p> <p>I have come up with the following code:</p> <pre><code>def concrete_instance(self): instance = None for subclass in self._meta.get_all_related_objects(): acc_name = subclass.get_accessor_name() try: instance = self.__getattribute__(acc_name) return instance except Exception, e: pass </code></pre> <p>But it feels brittle and I'm not sure of what happens when if I inherit in more levels.</p>
10
2008-12-08T11:11:45Z
8,478,666
<p>Have a look at InheritanceManager in <a href="https://github.com/carljm/django-model-utils/">django-model-utils</a> – attaching it to a model gives you the concrete child classes (at least at the first level):</p> <pre><code>from model_utils.managers import InheritanceManager class Base(models.Model): objects = InheritanceManager() # ... Base.objects.all().select_subclasses() # returns instances of child classes </code></pre> <p>model-utils requires Django 1.2 or higher.</p>
5
2011-12-12T17:59:21Z
[ "python", "django", "inheritance", "django-models" ]
How do I find the "concrete class" of a django model baseclass
349,206
<p>I'm trying to find the actual class of a django-model object, when using model-inheritance.</p> <p>Some code to describe the problem:</p> <pre><code>class Base(models.model): def basemethod(self): ... class Child_1(Base): pass class Child_2(Base): pass </code></pre> <p>If I create various objects of the two Child classes and the create a queryset containing them all:</p> <pre><code>Child_1().save() Child_2().save() (o1, o2) = Base.objects.all() </code></pre> <p>I want to determine if the object is of type Child_1 or Child_2 in basemethod, I can get to the child object via o1.child_1 and o2.child_2 but that reconquers knowledge about the childclasses in the baseclass.</p> <p>I have come up with the following code:</p> <pre><code>def concrete_instance(self): instance = None for subclass in self._meta.get_all_related_objects(): acc_name = subclass.get_accessor_name() try: instance = self.__getattribute__(acc_name) return instance except Exception, e: pass </code></pre> <p>But it feels brittle and I'm not sure of what happens when if I inherit in more levels.</p>
10
2008-12-08T11:11:45Z
17,443,716
<p>Slightly modified version of <a href="http://stackoverflow.com/a/349494/1042635">what Daniel Naab proposed</a>:</p> <pre><code>from django.contrib.contenttypes.models import ContentType from django.db import models def ParentClass(models.Model): superclass = models.CharField(max_length = 255, blank = True) def save(self, *args, **kwargs): if not self.superclass: self.superclass = ContentType.objects.get_for_model(self.__class__) super(ParentClass, self).save(*args, **kwargs) def getChild(self): s = getattr(self, self.superclass) if hasattr(s, 'pk'): return s else: return None class Child1(ParentClass): pass class Child2(ParentClass): pass </code></pre>
0
2013-07-03T08:56:44Z
[ "python", "django", "inheritance", "django-models" ]
How do I pass a python list in the post query?
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
7
2008-12-08T12:28:28Z
349,384
<p>There's no such thing as a "list of strings" in a URL (or in practically anything in HTTP - if you specify multiple values for the same header, they come out as a single delimited value in most web app frameworks IME). It's just a single string. I suggest you delimit the strings in some way (e.g. comma-separated) and then parse them out again at the other end.</p>
8
2008-12-08T12:35:54Z
[ "python", "web-services" ]
How do I pass a python list in the post query?
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
7
2008-12-08T12:28:28Z
349,386
<p>If the big string you're receiving is merely delimited then you could try splitting it. See <a href="http://www.java2s.com/Code/Python/String/Splittingstrings.htm" rel="nofollow">Splitting strings</a>.</p> <p>To clarify, you get the delimited list of the strings, split that list into a python list, and voila!, you have a python list...</p>
2
2008-12-08T12:36:52Z
[ "python", "web-services" ]
How do I pass a python list in the post query?
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
7
2008-12-08T12:28:28Z
349,389
<p>Are you talking about this?</p> <pre><code>post_data= ",".join( list_of_strings ) </code></pre>
1
2008-12-08T12:38:23Z
[ "python", "web-services" ]
How do I pass a python list in the post query?
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
7
2008-12-08T12:28:28Z
349,515
<p>TRY JSON(JavaScript Object Notation) it's available in the python package. Find out here: <a href="http://docs.python.org/library/json.html" rel="nofollow">http://docs.python.org/library/json.html</a></p> <p>You can Encode your list to an array represented in JSON and append to the post argument. Later decode it back to list...</p>
4
2008-12-08T13:13:35Z
[ "python", "web-services" ]
How do I pass a python list in the post query?
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
7
2008-12-08T12:28:28Z
349,522
<p>It depends on your server to format the incoming arguments. for example, when zope gets a request like this: <a href="http://www.zope.org?ids:list=1&amp;ids:list=2" rel="nofollow">http://www.zope.org?ids:list=1&amp;ids:list=2</a></p> <p>you can get the the ids as a list. But this feature depends on the server. If your server does not support some kind of parsing and validating your input, you have to implement it by yourself. Or you use zope.</p>
2
2008-12-08T13:15:32Z
[ "python", "web-services" ]
How do I pass a python list in the post query?
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
7
2008-12-08T12:28:28Z
349,776
<p>Data passed to a POST statement is (as far as I understood) encoded as key-value pairs, using the application/x-www-form-urlencoded encoding.</p> <p>So, I'll assume that you represent your list of string as the following dictionnary :</p> <pre><code>&gt;&gt;&gt; my_string_list= { 's1': 'I', ... 's2': 'love', ... 's3': 'python' ... } </code></pre> <p>Then, passing it as argument to POST is as difficult as reading the documentation of urllib.</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; print urllib.urlopen( 'http://www.google.fr/search', urllib.urlencode( my_string_list ) ).read() </code></pre> <p>Note that google does not use POST for its search queries, but you will see the error reported by google.</p> <p>If you run WireShark while typing the code above, you will see the data of the POST being passed as : </p> <pre><code> s3=python&amp;s2=love&amp;s1=I </code></pre>
1
2008-12-08T14:55:56Z
[ "python", "web-services" ]
How do I pass a python list in the post query?
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
7
2008-12-08T12:28:28Z
351,047
<p>A data structure like <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py" rel="nofollow"><code>django.utils.datastructures.MultiValueDict</code></a> is a clean way to represent such data. AFAIK it preserves order.</p> <pre><code>&gt;&gt;&gt; d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) &gt;&gt;&gt; d['name'] 'Simon' &gt;&gt;&gt; d.getlist('name') ['Adrian', 'Simon'] &gt;&gt;&gt; d.get('lastname', 'nonexistent') 'nonexistent' &gt;&gt;&gt; d.setlist('lastname', ['Holovaty', 'Willison']) </code></pre> <p>Django is using <a href="http://code.djangoproject.com/browser/django/trunk/django/http/__init__.py" rel="nofollow"><code>django.http.QueryDict</code></a> (subclass of <code>MultiValueDict</code>) to turn a query string into python primitives and back.</p> <pre><code>from django.http import QueryDict qs = 'post_data=a&amp;post_data=b&amp;post_data=c' query_dict = QueryDict(qs) assert query_dict['post_data'] == 'c' assert query_dict.getlist('post_data') == ['a', 'b', 'c'] assert query_dict.urlencode() == qs </code></pre> <p>You should be able to copy these classes and use them in your project. (I haven't checked all dependencies though)</p>
0
2008-12-08T21:47:47Z
[ "python", "web-services" ]
How do I pass a python list in the post query?
349,369
<p>I want to send some strings in a list in a POST call. eg:</p> <pre><code> www.example.com/?post_data = A list of strings </code></pre> <p>The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?</p>
7
2008-12-08T12:28:28Z
2,071,413
<p>If you can't or don't want to simply separate them with a comma and you want to send them in a more list-ish way. I have a list of numbers that I want to pass and I use a PHP webservice on the other end, I don't want to rebuild my webservice since I'v used a common multiselect element that Zend Framework provided.</p> <p>This example works fine for me and my little integers and it would with your strings, I actualy don't perform the urllib.quote(s), I just do a str(s).</p> <p>Import urllib</p> <pre><code>import urllib </code></pre> <p>Your list of stings:</p> <pre><code>string_list = ['A', 'list', 'of', 'strings', 'and', 'öthér', '.&amp;st,u?ff,'] </code></pre> <p>Join together the list of strings with 'post_data[]=', also urlencode the string</p> <pre><code>post_data = '&amp;'.join('post_data[]='+urllib.quote(s) for s in string_list) </code></pre> <p>Posts to <a href="http://example.com/" rel="nofollow">http://example.com/</a></p> <pre><code>urllib.urlopen('http://example.com/',post_data) </code></pre>
2
2010-01-15T12:33:24Z
[ "python", "web-services" ]
Run a shortcut under windows
349,653
<p>The following doesn't work, because it doesn't wait until the process is finished:</p> <pre><code>import subprocess p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True) p.wait() </code></pre> <p>Any idea how to run a shortcut and wait that the subprocess returns ?</p> <p><strong>Edit:</strong> originally I was trying this without the <strong>shell</strong> option in my post, which caused Popen to fail. In effect, <code>start</code> is not an executable but a shell command. This was fixed thanks to Jim.</p>
1
2008-12-08T14:09:25Z
349,697
<p>You will need to invoke a shell to get the subprocess option to work:</p> <pre><code>p = subprocess.Popen('start /B MOZILL~1.LNK', shell=True) p.wait() </code></pre> <p>This however will still exit immediately (see @R. Bemrose).</p> <p>If <code>p.pid</code> contains the correct pid (I'm not sure on windows), then you could use <a href="http://docs.python.org/library/os.html#os.waitpid" rel="nofollow"><code>os.waitpid()</code></a> to wait for the program to exit. Otherwise you may need to use some win32 com magic.</p>
4
2008-12-08T14:21:50Z
[ "python", "windows" ]
Run a shortcut under windows
349,653
<p>The following doesn't work, because it doesn't wait until the process is finished:</p> <pre><code>import subprocess p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True) p.wait() </code></pre> <p>Any idea how to run a shortcut and wait that the subprocess returns ?</p> <p><strong>Edit:</strong> originally I was trying this without the <strong>shell</strong> option in my post, which caused Popen to fail. In effect, <code>start</code> is not an executable but a shell command. This was fixed thanks to Jim.</p>
1
2008-12-08T14:09:25Z
349,793
<p>Note: I am simply adding on Jim's reply, with a small trick. What about using 'WAIT' option for start?</p> <pre><code>p = subprocess.Popen('start /B MOZILL~1.LNK /WAIT', shell=True) p.wait() </code></pre> <p>This should work.</p>
0
2008-12-08T15:01:43Z
[ "python", "windows" ]
Run a shortcut under windows
349,653
<p>The following doesn't work, because it doesn't wait until the process is finished:</p> <pre><code>import subprocess p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True) p.wait() </code></pre> <p>Any idea how to run a shortcut and wait that the subprocess returns ?</p> <p><strong>Edit:</strong> originally I was trying this without the <strong>shell</strong> option in my post, which caused Popen to fail. In effect, <code>start</code> is not an executable but a shell command. This was fixed thanks to Jim.</p>
1
2008-12-08T14:09:25Z
349,851
<p>cmd.exe is terminating as soon as start launches the program. This behavior is documented (in start /? ):</p> <blockquote> <p>If Command Extensions are enabled, external command invocation through the command line or the START command changes as follows:</p> </blockquote> <p>...</p> <blockquote> <p>When executing an application that is a 32-bit GUI application, CMD.EXE does not wait for the application to terminate before returning to the command prompt. This new behavior does NOT occur if executing within a command script.</p> </blockquote> <p>How this is affected by the /wait flag, I'm not sure.</p>
3
2008-12-08T15:24:43Z
[ "python", "windows" ]
Getting the lesser n elements of a list in Python
350,519
<p>I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.</p> <p>n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. Sorting can't be made in place.</p> <p>Initially, I have written this function:</p> <pre><code>def mins(items, n): mins = [float('inf')]*n for item in items: for i, min in enumerate(mins): if item &lt; min: mins.insert(i, item) mins.pop() break return mins </code></pre> <p>But this function can't beat a simple sorted(items)[:n] which sort the entire list. Here is my test:</p> <pre><code>from random import randint, random import time test_data = [randint(10, 50) + random() for i in range(20000)] init = time.time() mins = mins(test_data, 8) print 'mins(items, n):', time.time() - init init = time.time() mins = sorted(test_data)[:8] print 'sorted(items)[:n]:', time.time() - init </code></pre> <p>Results:</p> <pre><code>mins(items, n): 0.0632939338684 sorted(items)[:n]: 0.0231449604034 </code></pre> <p>sorted()[:n] is three times faster. I believe this is because:</p> <ol> <li>insert() operation is costly because Python lists are not linked lists.</li> <li>sorted() is an optimized c function and mine is pure python.</li> </ol> <p>Is there any way to beat sorted()[:n] ? Should I use a C extension, or Pyrex or Psyco or something like that?</p> <p>Thanks in advance for your answers.</p>
8
2008-12-08T19:10:10Z
350,568
<p>You actually want a sorted sequence of mins.</p> <pre><code>mins = items[:n] mins.sort() for i in items[n:]: if i &lt; mins[-1]: mins.append(i) mins.sort() mins= mins[:n] </code></pre> <p>This runs <em>much</em> faster because you aren't even looking at mins unless it's provably got a value larger than the given item. About 1/10th the time of the original algorithm.</p> <p>This ran in zero time on my Dell. I had to run it 10 times to get a measurable run time.</p> <pre><code>mins(items, n): 0.297000169754 sorted(items)[:n]: 0.109999895096 mins2(items)[:n]: 0.0309998989105 </code></pre> <p>Using <code>bisect.insort</code> instead of append and sort may speed this up a hair further.</p>
13
2008-12-08T19:27:39Z
[ "python", "algorithm", "sorting" ]
Getting the lesser n elements of a list in Python
350,519
<p>I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.</p> <p>n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. Sorting can't be made in place.</p> <p>Initially, I have written this function:</p> <pre><code>def mins(items, n): mins = [float('inf')]*n for item in items: for i, min in enumerate(mins): if item &lt; min: mins.insert(i, item) mins.pop() break return mins </code></pre> <p>But this function can't beat a simple sorted(items)[:n] which sort the entire list. Here is my test:</p> <pre><code>from random import randint, random import time test_data = [randint(10, 50) + random() for i in range(20000)] init = time.time() mins = mins(test_data, 8) print 'mins(items, n):', time.time() - init init = time.time() mins = sorted(test_data)[:8] print 'sorted(items)[:n]:', time.time() - init </code></pre> <p>Results:</p> <pre><code>mins(items, n): 0.0632939338684 sorted(items)[:n]: 0.0231449604034 </code></pre> <p>sorted()[:n] is three times faster. I believe this is because:</p> <ol> <li>insert() operation is costly because Python lists are not linked lists.</li> <li>sorted() is an optimized c function and mine is pure python.</li> </ol> <p>Is there any way to beat sorted()[:n] ? Should I use a C extension, or Pyrex or Psyco or something like that?</p> <p>Thanks in advance for your answers.</p>
8
2008-12-08T19:10:10Z
350,578
<p>A possibility is to use the <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect</a> module:</p> <pre><code>import bisect def mins(items, n): mins = [float('inf')]*n for item in items: bisect.insort(mins, item) mins.pop() return mins </code></pre> <p>However, it's just a bit faster for me:</p> <pre><code>mins(items, n): 0.0892250537872 sorted(items)[:n]: 0.0990262031555 </code></pre> <p>Using psyco does speed it up a bit more:</p> <pre><code>import bisect import psyco psyco.full() def mins(items, n): mins = [float('inf')]*n for item in items: bisect.insort(mins, item) mins.pop() return mins </code></pre> <p>Result:</p> <pre><code>mins(items, n): 0.0431621074677 sorted(items)[:n]: 0.0859830379486 </code></pre>
2
2008-12-08T19:32:09Z
[ "python", "algorithm", "sorting" ]
Getting the lesser n elements of a list in Python
350,519
<p>I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.</p> <p>n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. Sorting can't be made in place.</p> <p>Initially, I have written this function:</p> <pre><code>def mins(items, n): mins = [float('inf')]*n for item in items: for i, min in enumerate(mins): if item &lt; min: mins.insert(i, item) mins.pop() break return mins </code></pre> <p>But this function can't beat a simple sorted(items)[:n] which sort the entire list. Here is my test:</p> <pre><code>from random import randint, random import time test_data = [randint(10, 50) + random() for i in range(20000)] init = time.time() mins = mins(test_data, 8) print 'mins(items, n):', time.time() - init init = time.time() mins = sorted(test_data)[:8] print 'sorted(items)[:n]:', time.time() - init </code></pre> <p>Results:</p> <pre><code>mins(items, n): 0.0632939338684 sorted(items)[:n]: 0.0231449604034 </code></pre> <p>sorted()[:n] is three times faster. I believe this is because:</p> <ol> <li>insert() operation is costly because Python lists are not linked lists.</li> <li>sorted() is an optimized c function and mine is pure python.</li> </ol> <p>Is there any way to beat sorted()[:n] ? Should I use a C extension, or Pyrex or Psyco or something like that?</p> <p>Thanks in advance for your answers.</p>
8
2008-12-08T19:10:10Z
350,597
<p>If speed is of utmost concern, the fastest method is going to be with c. Psyco has an upfront cost, but may prove to be pretty fast. I would recommend Cython for python -> c compilation (a more up to date for pf Pyrex).</p> <p>Hand coding it in c would be the best, and allow you to use data structures specific to your problem domain.</p> <p>But note:</p> <blockquote> <p>"Compiling the wrong algorithm in C may not be any faster than the right algorithm in Python" @S.Lott</p> </blockquote> <p>I wanted to add S.Lott's comment so it gets noticed. Python make an excellent prototype language, where you can iron out an algorithm that you intend to later translate to a lower level language.</p>
2
2008-12-08T19:37:25Z
[ "python", "algorithm", "sorting" ]
Getting the lesser n elements of a list in Python
350,519
<p>I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.</p> <p>n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. Sorting can't be made in place.</p> <p>Initially, I have written this function:</p> <pre><code>def mins(items, n): mins = [float('inf')]*n for item in items: for i, min in enumerate(mins): if item &lt; min: mins.insert(i, item) mins.pop() break return mins </code></pre> <p>But this function can't beat a simple sorted(items)[:n] which sort the entire list. Here is my test:</p> <pre><code>from random import randint, random import time test_data = [randint(10, 50) + random() for i in range(20000)] init = time.time() mins = mins(test_data, 8) print 'mins(items, n):', time.time() - init init = time.time() mins = sorted(test_data)[:8] print 'sorted(items)[:n]:', time.time() - init </code></pre> <p>Results:</p> <pre><code>mins(items, n): 0.0632939338684 sorted(items)[:n]: 0.0231449604034 </code></pre> <p>sorted()[:n] is three times faster. I believe this is because:</p> <ol> <li>insert() operation is costly because Python lists are not linked lists.</li> <li>sorted() is an optimized c function and mine is pure python.</li> </ol> <p>Is there any way to beat sorted()[:n] ? Should I use a C extension, or Pyrex or Psyco or something like that?</p> <p>Thanks in advance for your answers.</p>
8
2008-12-08T19:10:10Z
350,683
<p>I like erickson's heap idea. I don't know Python either, but there appears to be a canned solution here: <a href="http://docs.python.org/library/heapq.html" rel="nofollow">heapq — Heap queue algorithm</a></p>
3
2008-12-08T20:00:39Z
[ "python", "algorithm", "sorting" ]
Getting the lesser n elements of a list in Python
350,519
<p>I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.</p> <p>n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. Sorting can't be made in place.</p> <p>Initially, I have written this function:</p> <pre><code>def mins(items, n): mins = [float('inf')]*n for item in items: for i, min in enumerate(mins): if item &lt; min: mins.insert(i, item) mins.pop() break return mins </code></pre> <p>But this function can't beat a simple sorted(items)[:n] which sort the entire list. Here is my test:</p> <pre><code>from random import randint, random import time test_data = [randint(10, 50) + random() for i in range(20000)] init = time.time() mins = mins(test_data, 8) print 'mins(items, n):', time.time() - init init = time.time() mins = sorted(test_data)[:8] print 'sorted(items)[:n]:', time.time() - init </code></pre> <p>Results:</p> <pre><code>mins(items, n): 0.0632939338684 sorted(items)[:n]: 0.0231449604034 </code></pre> <p>sorted()[:n] is three times faster. I believe this is because:</p> <ol> <li>insert() operation is costly because Python lists are not linked lists.</li> <li>sorted() is an optimized c function and mine is pure python.</li> </ol> <p>Is there any way to beat sorted()[:n] ? Should I use a C extension, or Pyrex or Psyco or something like that?</p> <p>Thanks in advance for your answers.</p>
8
2008-12-08T19:10:10Z
350,685
<pre><code>import heapq nlesser_items = heapq.nsmallest(n, items) </code></pre> <p>Here's a correct version of <a href="http://stackoverflow.com/questions/350519/getting-the-lesser-n-elements-of-a-list-in-python#350568">S.Lott's algorithm</a>:</p> <pre><code>from bisect import insort from itertools import islice def nsmallest_slott_bisect(n, iterable, insort=insort): it = iter(iterable) mins = sorted(islice(it, n)) for el in it: if el &lt;= mins[-1]: #NOTE: equal sign is to preserve duplicates insort(mins, el) mins.pop() return mins </code></pre> <p>Performance:</p> <pre><code>$ python -mtimeit -s "import marshal; from nsmallest import nsmallest$label as nsmallest; items = marshal.load(open('items.marshal','rb')); n = 10"\ "nsmallest(n, items)" </code></pre> <pre> nsmallest_heapq 100 loops, best of 3: 12.9 msec per loop nsmallest_slott_list 100 loops, best of 3: 4.37 msec per loop nsmallest_slott_bisect 100 loops, best of 3: 3.95 msec per loop </pre> <p><code>nsmallest_slott_bisect</code> is <strong>3 times faster</strong> than <code>heapq</code>'s <code>nsmallest</code> (for n=10, len(items)=20000). <code>nsmallest_slott_list</code> is only marginally slower. It is unclear why heapq's nsmallest is so slow; its algorithm is almost identical to the presented above (for small n).</p>
10
2008-12-08T20:01:12Z
[ "python", "algorithm", "sorting" ]
Getting the lesser n elements of a list in Python
350,519
<p>I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.</p> <p>n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. Sorting can't be made in place.</p> <p>Initially, I have written this function:</p> <pre><code>def mins(items, n): mins = [float('inf')]*n for item in items: for i, min in enumerate(mins): if item &lt; min: mins.insert(i, item) mins.pop() break return mins </code></pre> <p>But this function can't beat a simple sorted(items)[:n] which sort the entire list. Here is my test:</p> <pre><code>from random import randint, random import time test_data = [randint(10, 50) + random() for i in range(20000)] init = time.time() mins = mins(test_data, 8) print 'mins(items, n):', time.time() - init init = time.time() mins = sorted(test_data)[:8] print 'sorted(items)[:n]:', time.time() - init </code></pre> <p>Results:</p> <pre><code>mins(items, n): 0.0632939338684 sorted(items)[:n]: 0.0231449604034 </code></pre> <p>sorted()[:n] is three times faster. I believe this is because:</p> <ol> <li>insert() operation is costly because Python lists are not linked lists.</li> <li>sorted() is an optimized c function and mine is pure python.</li> </ol> <p>Is there any way to beat sorted()[:n] ? Should I use a C extension, or Pyrex or Psyco or something like that?</p> <p>Thanks in advance for your answers.</p>
8
2008-12-08T19:10:10Z
22,357,180
<p>why not just call the select_n_th element in O(N) time and then divide the array into two parts by the n_th element, this should be the fastest one.</p> <p>ps: This O(N) algorithm works if you don't specify the order of the n-smallest elements The link below seems to do the selection algorithm. <a href="http://code.activestate.com/recipes/269554-select-the-nth-smallest-element/" rel="nofollow">http://code.activestate.com/recipes/269554-select-the-nth-smallest-element/</a></p> <p>Assuming the array doesn't have duplicate elements, the code works for me. The efficiency still depends on the problem scale, if n&lt;10, probably an O(logn*N) algorithm is enough. </p> <pre><code>import random import numpy as np def select(data, n): "Find the nth rank ordered element (the least value has rank 0)." data = list(data) if not 0 &lt;= n &lt; len(data): raise ValueError('not enough elements for the given rank') while True: pivot = random.choice(data) pcount = 0 under, over = [], [] uappend, oappend = under.append, over.append for elem in data: if elem &lt; pivot: uappend(elem) elif elem &gt; pivot: oappend(elem) else: pcount += 1 if n &lt; len(under): data = under elif n &lt; len(under) + pcount: return pivot else: data = over n -= len(under) + pcount def n_lesser(data,n): data_nth = select(data,n) ind = np.where(data&lt;data_nth) return data[ind] </code></pre>
0
2014-03-12T16:02:43Z
[ "python", "algorithm", "sorting" ]
Why is my Python C Extension leaking memory?
350,647
<p>The function below takes a python file handle, reads in packed binary data from the file, creates a Python dictionary and returns it. If I loop it endlessly, it'll continually consume RAM. What's wrong with my RefCounting?</p> <pre><code>static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){ PyObject *o; //generic object PyObject* pyDB = NULL; //this has to be a py file object if (!PyArg_ParseTuple(args, "O", &amp;pyDB)){ return NULL; } else { Py_INCREF(pyDB); if (!PyFile_Check(pyDB)){ Py_DECREF(pyDB); PyErr_SetString(PyExc_IOError, "argument 1 must be open file handle"); return NULL; } } FILE *fhDB = PyFile_AsFile(pyDB); long offset = 0; DB_HEADER *pdbHeader = malloc(sizeof(DB_HEADER)); fseek(fhDB,offset,SEEK_SET); //at the beginning fread(pdbHeader, 1, sizeof(DB_HEADER), fhDB ); if (ferror(fhDB)){ fclose(fhDB); Py_DECREF(pyDB); PyErr_SetString(PyExc_IOError, "failed reading database header"); return NULL; } Py_DECREF(pyDB); PyObject *pyDBHeader = PyDict_New(); Py_INCREF(pyDBHeader); o=PyInt_FromLong(pdbHeader-&gt;version_number); PyDict_SetItemString(pyDBHeader, "version", o); Py_DECREF(o); PyObject *pyTimeList = PyList_New(0); Py_INCREF(pyTimeList); int i; for (i=0; i&lt;NUM_DRAWERS; i++){ //epochs o=PyInt_FromLong(pdbHeader-&gt;last_good_test[i]); PyList_Append(pyTimeList, o); Py_DECREF(o); } PyDict_SetItemString(pyDBHeader, "lastTest", pyTimeList); Py_DECREF(pyTimeList); o=PyInt_FromLong(pdbHeader-&gt;temp); PyDict_SetItemString(pyDBHeader, "temp", o); Py_DECREF(o); free(pdbHeader); return (pyDBHeader); } </code></pre> <p>Thanks for taking a look,</p> <p>LarsenMTL</p>
5
2008-12-08T19:51:04Z
350,695
<p><code>PyDict_New()</code> returns a new reference, check the <a href="http://docs.python.org/c-api/dict.html">docs</a> for <code>PyDict</code>. So if you increase the refcount immediately after creating it, you have two references to it. One is transferred to the caller when you return it as a result value, but the other one never goes aways.</p> <p>You also don't need to incref <code>pyTimeList</code>. It's yours when you create it. However, you need to decref it, but you only decref it once, so it's leaked as well.</p> <p>You also don't need to call <code>Py_INCREF</code> on <code>pyDB</code>. It's a borrowed reference and it won't go away as long as your function does not return, because it's still referenced in a lower stack frame. </p> <p>Only if you want to keep the reference in another structure somewhere, you need to increse the refcount.</p> <p>Cf. the <a href="http://docs.python.org/c-api/arg.html">API docs</a></p>
16
2008-12-08T20:04:32Z
[ "python", "c", "refcounting" ]
Why is my Python C Extension leaking memory?
350,647
<p>The function below takes a python file handle, reads in packed binary data from the file, creates a Python dictionary and returns it. If I loop it endlessly, it'll continually consume RAM. What's wrong with my RefCounting?</p> <pre><code>static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){ PyObject *o; //generic object PyObject* pyDB = NULL; //this has to be a py file object if (!PyArg_ParseTuple(args, "O", &amp;pyDB)){ return NULL; } else { Py_INCREF(pyDB); if (!PyFile_Check(pyDB)){ Py_DECREF(pyDB); PyErr_SetString(PyExc_IOError, "argument 1 must be open file handle"); return NULL; } } FILE *fhDB = PyFile_AsFile(pyDB); long offset = 0; DB_HEADER *pdbHeader = malloc(sizeof(DB_HEADER)); fseek(fhDB,offset,SEEK_SET); //at the beginning fread(pdbHeader, 1, sizeof(DB_HEADER), fhDB ); if (ferror(fhDB)){ fclose(fhDB); Py_DECREF(pyDB); PyErr_SetString(PyExc_IOError, "failed reading database header"); return NULL; } Py_DECREF(pyDB); PyObject *pyDBHeader = PyDict_New(); Py_INCREF(pyDBHeader); o=PyInt_FromLong(pdbHeader-&gt;version_number); PyDict_SetItemString(pyDBHeader, "version", o); Py_DECREF(o); PyObject *pyTimeList = PyList_New(0); Py_INCREF(pyTimeList); int i; for (i=0; i&lt;NUM_DRAWERS; i++){ //epochs o=PyInt_FromLong(pdbHeader-&gt;last_good_test[i]); PyList_Append(pyTimeList, o); Py_DECREF(o); } PyDict_SetItemString(pyDBHeader, "lastTest", pyTimeList); Py_DECREF(pyTimeList); o=PyInt_FromLong(pdbHeader-&gt;temp); PyDict_SetItemString(pyDBHeader, "temp", o); Py_DECREF(o); free(pdbHeader); return (pyDBHeader); } </code></pre> <p>Thanks for taking a look,</p> <p>LarsenMTL</p>
5
2008-12-08T19:51:04Z
350,719
<p>OT: Using successive calls to <code>PyList_Append</code> is a performance issue. Since you know how many results you'll get in advance, you can use:</p> <pre><code>PyObject *pyTimeList = PyList_New(NUM_DRAWERS); int i; for (i=0; i&lt;NUM_DRAWERS; i++){ o = PyInt_FromLong(pdbHeader-&gt;last_good_test[i]); PyList_SET_ITEM(pyTimeList, i, o); } </code></pre> <p>Observe that you may not decrease the refcount of <code>o</code> after calling <code>PyList_SET_ITEM</code>, because it "steals" a reference. Check the <a href="http://docs.python.org/c-api/list.html">docs</a>.</p>
5
2008-12-08T20:12:44Z
[ "python", "c", "refcounting" ]
Why is my Python C Extension leaking memory?
350,647
<p>The function below takes a python file handle, reads in packed binary data from the file, creates a Python dictionary and returns it. If I loop it endlessly, it'll continually consume RAM. What's wrong with my RefCounting?</p> <pre><code>static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){ PyObject *o; //generic object PyObject* pyDB = NULL; //this has to be a py file object if (!PyArg_ParseTuple(args, "O", &amp;pyDB)){ return NULL; } else { Py_INCREF(pyDB); if (!PyFile_Check(pyDB)){ Py_DECREF(pyDB); PyErr_SetString(PyExc_IOError, "argument 1 must be open file handle"); return NULL; } } FILE *fhDB = PyFile_AsFile(pyDB); long offset = 0; DB_HEADER *pdbHeader = malloc(sizeof(DB_HEADER)); fseek(fhDB,offset,SEEK_SET); //at the beginning fread(pdbHeader, 1, sizeof(DB_HEADER), fhDB ); if (ferror(fhDB)){ fclose(fhDB); Py_DECREF(pyDB); PyErr_SetString(PyExc_IOError, "failed reading database header"); return NULL; } Py_DECREF(pyDB); PyObject *pyDBHeader = PyDict_New(); Py_INCREF(pyDBHeader); o=PyInt_FromLong(pdbHeader-&gt;version_number); PyDict_SetItemString(pyDBHeader, "version", o); Py_DECREF(o); PyObject *pyTimeList = PyList_New(0); Py_INCREF(pyTimeList); int i; for (i=0; i&lt;NUM_DRAWERS; i++){ //epochs o=PyInt_FromLong(pdbHeader-&gt;last_good_test[i]); PyList_Append(pyTimeList, o); Py_DECREF(o); } PyDict_SetItemString(pyDBHeader, "lastTest", pyTimeList); Py_DECREF(pyTimeList); o=PyInt_FromLong(pdbHeader-&gt;temp); PyDict_SetItemString(pyDBHeader, "temp", o); Py_DECREF(o); free(pdbHeader); return (pyDBHeader); } </code></pre> <p>Thanks for taking a look,</p> <p>LarsenMTL</p>
5
2008-12-08T19:51:04Z
350,743
<p>I don't know about Python-C. However, My experience with COM reference counting says that a newly created reference-counted object has a reference count of <strong>1</strong>. So your Py_INCREF(pyDB) after PyArg_ParseTuple(args, "O", &amp;pyDB) and PyObject *pyDBHeader = PyDict_New(); are the culprit. Their reference counts are already 2.</p>
2
2008-12-08T20:18:09Z
[ "python", "c", "refcounting" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
350,817
<p>It has to do with the meta class that is used in defining the form class. I think it keeps an internal list of the fields and if you insert into the middle of the list it might work. It has been a while since I looked at that code.</p>
0
2008-12-08T20:41:55Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
350,851
<p>Form fields have an attribute for creation order, called <code>creation_counter</code>. <code>.fields</code> attribute is a dictionary, so simple adding to dictionary and changing <code>creation_counter</code> attributes in all fields to reflect new ordering should suffice (never tried this, though).</p>
5
2008-12-08T20:52:25Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
350,913
<p>I went ahead and answered my own question. Here's the answer for future reference:</p> <p>In Django <code>form.py</code> does some dark magic using the <code>__new__</code> method to load your class variables ultimately into <code>self.fields</code> in the order defined in the class. <code>self.fields</code> is a Django <code>SortedDict</code> instance (defined in <code>datastructures.py</code>).</p> <p>So to override this, say in my example you wanted sender to come first but needed to add it in an <strong>init</strong> method, you would do:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() def __init__(self,*args,**kwargs): forms.Form.__init__(self,*args,**kwargs) #first argument, index is the position of the field you want it to come before self.fields.insert(0,'sender',forms.EmailField(initial=str(time.time()))) </code></pre>
38
2008-12-08T21:12:56Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
871,048
<p>Use a counter in the Field class. Sort by that counter:</p> <pre><code>import operator import itertools class Field(object): _counter = itertools.count() def __init__(self): self.count = Field._counter.next() self.name = '' def __repr__(self): return "Field(%r)" % self.name class MyForm(object): b = Field() a = Field() c = Field() def __init__(self): self.fields = [] for field_name in dir(self): field = getattr(self, field_name) if isinstance(field, Field): field.name = field_name self.fields.append(field) self.fields.sort(key=operator.attrgetter('count')) m = MyForm() print m.fields # in defined order </code></pre> <p>Output:</p> <pre><code>[Field('b'), Field('a'), Field('c')] </code></pre> <p><hr /></p>
4
2009-05-15T22:03:32Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
1,191,310
<p><strong>[NOTE: this answer is now somewhat outdated - please see the discussion below it].</strong></p> <p>If f is a form, its fields are f.fields, which is a <code>django.utils.datastructures.SortedDict</code> (it presents the items in the order they are added). After form construction f.fields has a keyOrder attribute, which is a list containing the field names in the order they should be presented. You can set this to the correct ordering (though you need to exercise care to ensure you don't omit items or add extras).</p> <p>Here's an example I just created in my current project:</p> <pre><code>class PrivEdit(ModelForm): def __init__(self, *args, **kw): super(ModelForm, self).__init__(*args, **kw) self.fields.keyOrder = [ 'super_user', 'all_districts', 'multi_district', 'all_schools', 'manage_users', 'direct_login', 'student_detail', 'license'] class Meta: model = Privilege </code></pre>
86
2009-07-28T00:12:20Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
2,551,889
<p>For future reference: things have changed a bit since newforms. This is one way of reordering fields from base formclasses you have no control over:</p> <pre><code>def move_field_before(form, field, before_field): content = form.base_fields[field] del(form.base_fields[field]) insert_at = list(form.base_fields).index(before_field) form.base_fields.insert(insert_at, field, content) return form </code></pre> <p>Also, there's a little bit of documentation about the SortedDict that <code>base_fields</code> uses here: <a href="http://code.djangoproject.com/wiki/SortedDict" rel="nofollow">http://code.djangoproject.com/wiki/SortedDict</a></p>
3
2010-03-31T09:53:37Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
5,747,259
<p>Fields are listed in the order they are defined in ModelClass._meta.fields. But if you want to change order in Form, you can do by using keyOrder function. For example : </p> <pre><code>class ContestForm(ModelForm): class Meta: model = Contest exclude=('create_date', 'company') def __init__(self, *args, **kwargs): super(ContestForm, self).__init__(*args, **kwargs) self.fields.keyOrder = [ 'name', 'description', 'image', 'video_link', 'category'] </code></pre>
11
2011-04-21T16:53:43Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
25,449,079
<p>Using <code>fields</code> in inner <code>Meta</code> class is what worked for me on <code>Django==1.6.5</code>:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Example form declaration with custom field order. """ from django import forms from app.models import AppModel class ExampleModelForm(forms.ModelForm): """ An example model form for ``AppModel``. """ field1 = forms.CharField() field2 = forms.CharField() class Meta: model = AppModel fields = ['field2', 'field1'] </code></pre> <p>As simple as that.</p>
0
2014-08-22T14:14:27Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
27,315,534
<p>I've used this to move fields about:</p> <pre><code>def move_field_before(frm, field_name, before_name): fld = frm.fields.pop(field_name) pos = frm.fields.keys().index(before_name) frm.fields.insert(pos, field_name, fld) </code></pre> <p>This works in 1.5 and I'm reasonably sure it still works in more recent versions.</p>
0
2014-12-05T12:05:19Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
27,322,256
<p>If either <code>fields = '__all__'</code>:</p> <pre><code>class AuthorForm(ModelForm): class Meta: model = Author fields = '__all__' </code></pre> <p>or <code>exclude</code> are used:</p> <pre><code>class PartialAuthorForm(ModelForm): class Meta: model = Author exclude = ['title'] </code></pre> <p>Then Django references the order of fields <strong>as defined in the model</strong>. This just caught me out, so I thought I'd mention it. It's referenced in the <a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/" rel="nofollow">ModelForm docs</a>:</p> <blockquote> <p>If either of these are used, the order the fields appear in the form will be the order the fields are defined in the model, with ManyToManyField instances appearing last.</p> </blockquote>
2
2014-12-05T18:19:05Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
27,595,191
<p>With Django >= 1.7 your must modify <code>ContactForm.base_fields</code> as below:</p> <pre><code>from collections import OrderedDict ... class ContactForm(forms.Form): ... ContactForm.base_fields = OrderedDict( (k, ContactForm.base_fields[k]) for k in ['your', 'field', 'in', 'order'] ) </code></pre> <p>This trick is used in Django Admin <code>PasswordChangeForm</code>: <a href="https://github.com/django/django/blob/1.7/django/contrib/auth/forms.py#L338" rel="nofollow">Source on Github</a></p>
4
2014-12-22T00:13:52Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
28,843,066
<p>As of Django 1.7 forms use OrderedDict which does not support the append operator. So you have to rebuild the dictionary from scratch...</p> <pre><code>class ChecklistForm(forms.ModelForm): class Meta: model = Checklist fields = ['name', 'email', 'website'] def __init__(self, guide, *args, **kwargs): self.guide = guide super(ChecklistForm, self).__init__(*args, **kwargs) new_fields = OrderedDict() for tier, tasks in guide.tiers().items(): questions = [(t['task'], t['question']) for t in tasks if 'question' in t] new_fields[tier.lower()] = forms.MultipleChoiceField( label=tier, widget=forms.CheckboxSelectMultiple(), choices=questions, help_text='desired set of site features' ) new_fields['name'] = self.fields['name'] new_fields['email'] = self.fields['email'] new_fields['website'] = self.fields['website'] self.fields = new_fields </code></pre>
4
2015-03-03T22:18:34Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
34,502,078
<p>New to Django 1.9 is <strong><a href="https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.field_order">Form.field_order</a></strong> and <strong><a href="https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.order_fields">Form.order_fields()</a></strong>.</p>
7
2015-12-28T23:05:23Z
[ "python", "django", "class", "django-forms", "contacts" ]
How does Django Know the Order to Render Form Fields?
350,799
<p>If I have a Django form such as:</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() </code></pre> <p>And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.</p> <p>My question is how does Django know the order that class variables where defined? </p> <p>(Also how do I override this order, for example when I want to add a field from the classe's <strong>init</strong> method?)</p>
70
2008-12-08T20:37:44Z
39,412,472
<p>The easiest way to order fields in django 1.9 forms is to use <code>field_order</code> in your form <a href="https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.field_order" rel="nofollow">Form.field_order</a></p> <p>Here is a small example</p> <pre><code>class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() field_order = ['sender','message','subject'] </code></pre> <p>This will show everything in the order you specified in <code>field_order</code> dict.</p>
0
2016-09-09T13:17:11Z
[ "python", "django", "class", "django-forms", "contacts" ]
What does the function set use to check if two objects are different?
351,271
<p>Simple code:</p> <pre><code>&gt;&gt;&gt; set([2,2,1,2,2,2,3,3,5,1]) set([1, 2, 3, 5]) </code></pre> <p>Ok, in the resulting sets there are no duplicates. What if the object in the list are not int but are some defined by me? What method does it check to understand if they are different? I implemented __eq__ and __cmp__ with some objects but <strong>set</strong> doesn't seems to use them :\</p> <p>Does anyone know how to solve this?</p>
6
2008-12-08T23:02:23Z
351,287
<p>According to the <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="nofollow">set documentation</a>, the elements must be <a href="http://docs.python.org/glossary.html#term-hashable" rel="nofollow">hashable</a>. </p> <p>An object is hashable if it has a hash value which never changes during its lifetime (it needs a <code>__hash__()</code> method), and can be compared to other objects (it needs an <code>__eq__()</code> or <code>__cmp__()</code> method). Hashable objects which compare equal must have the same hash value.</p> <p><strong>EDIT</strong>: added proper Hashable definition thanks to Roberto</p>
13
2008-12-08T23:08:24Z
[ "python", "methods", "set" ]
Determine record in multi record html form
351,440
<p>In a html form, I'm displaying multiple records from a table, ready for update.</p> <p>Right now I use: <code>name=&lt;column-name&gt;_&lt;pk-id&gt; value=&lt;value&gt;</code> for the fields. Then in my python-script I go for:</p> <pre><code>for key in form.keys(): if key.startswith('&lt;name-A&gt;_'): update &lt;table&gt; set &lt;name-A&gt; = &lt;value&gt; where pk=&lt;pk-id&gt; if key.startswith('&lt;name-B&gt;_'): update &lt;table&gt; set &lt;name-B&gt; = &lt;value&gt; where pk=&lt;pk-id&gt; </code></pre> <p>Is there a more 'organic' way to handle multi-record forms?</p>
1
2008-12-09T00:33:01Z
351,457
<p>In java apps, it's common to JSONify the name.</p> <pre><code>&lt;input name="records[pk].fieldName"/&gt; </code></pre> <p><code>pk</code> being the primary key of the row and <code>fieldName</code> the field. Of course most frameworks handle this transparently. Each record ends up as a instance of a class with a property for each field, all of which are put into a list called "records". You may have to write some sort of interpreter, but that shouldn't be too hard.</p>
1
2008-12-09T00:48:36Z
[ "python", "html", "cgi" ]
How do I get data from stdin using os.system()
351,456
<p>The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call <code>os.system()</code>. Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(<code>0</code>). Alternately somebody could show be how to properly use <code>urllib</code>.</p>
0
2008-12-09T00:48:28Z
351,469
<p>Answering the question, Python has a subprocess module which allows you to interact with spawned processes.<a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="nofollow">http://docs.python.org/library/subprocess.html#subprocess.Popen</a></p> <p>It allows you to read the stdout for the invoked process, and even send items to the stdin.</p> <p>however as you said urllib is a much better option. if you <a href="http://stackoverflow.com/search?q=urllib">search</a> stackoverflow i am sure you will find at least 10 other related questions...</p>
2
2008-12-09T00:55:36Z
[ "python", "shell", "curl", "urllib", "os.system" ]
How do I get data from stdin using os.system()
351,456
<p>The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call <code>os.system()</code>. Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(<code>0</code>). Alternately somebody could show be how to properly use <code>urllib</code>.</p>
0
2008-12-09T00:48:28Z
351,472
<p>As an alternetive to urllib, you could use the libCurl <a href="http://curl.haxx.se/libcurl/python/" rel="nofollow">Python bindings</a>.</p>
0
2008-12-09T01:00:21Z
[ "python", "shell", "curl", "urllib", "os.system" ]
How do I get data from stdin using os.system()
351,456
<p>The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call <code>os.system()</code>. Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(<code>0</code>). Alternately somebody could show be how to properly use <code>urllib</code>.</p>
0
2008-12-09T00:48:28Z
351,475
<p>From <a href="http://diveintopython.net/html_processing/extracting_data.html" rel="nofollow">Dive into Python:</a> </p> <pre><code>import urllib sock = urllib.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)") htmlsource = sock.read() sock.close() print htmlsource </code></pre> <p>That will print out the source code for the Python Wikipedia article. I suggest you take a look at Dive into Python for more details.</p> <p>Example using urllib2 from the <a href="http://www.python.org/doc/2.5.2/lib/urllib2-examples.html" rel="nofollow">Python Library Reference:</a> </p> <pre><code>import urllib2 f = urllib2.urlopen('http://www.python.org/') print f.read(100) </code></pre> <p>Edit: Also you might want to take a look at <a href="http://en.wikipedia.org/wiki/Wget#Using_Wget" rel="nofollow">wget.</a><br> Edit2: Added urllib2 example based on S.Lott's advice</p>
7
2008-12-09T01:01:28Z
[ "python", "shell", "curl", "urllib", "os.system" ]
How do I mock an IMAP server in Python, despite extreme laziness?
351,656
<p>I'm curious to know if there is an easy way to mock an IMAP server (a la the <code>imaplib</code> module) in Python, <em>without</em> doing a lot of work.</p> <p>Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure.</p> <p>Some background into the laziness: I have a nasty feeling that this small script I'm writing will grow over time and would <em>like</em> to create a proper testing environment, but given that it might <em>not</em> grow over time, I don't want to do much work to get the mock server running.</p>
9
2008-12-09T02:57:49Z
351,675
<p>I found it quite easy to write an IMAP server in twisted last time I tried. It comes with support for writing IMAP servers and you have a huge amount of flexibility.</p>
8
2008-12-09T03:14:39Z
[ "python", "testing", "imap", "mocking" ]
How do I mock an IMAP server in Python, despite extreme laziness?
351,656
<p>I'm curious to know if there is an easy way to mock an IMAP server (a la the <code>imaplib</code> module) in Python, <em>without</em> doing a lot of work.</p> <p>Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure.</p> <p>Some background into the laziness: I have a nasty feeling that this small script I'm writing will grow over time and would <em>like</em> to create a proper testing environment, but given that it might <em>not</em> grow over time, I don't want to do much work to get the mock server running.</p>
9
2008-12-09T02:57:49Z
352,194
<p>I never tried but, if I had to, I would start with the existing SMTP server.</p>
1
2008-12-09T09:12:17Z
[ "python", "testing", "imap", "mocking" ]
How do I mock an IMAP server in Python, despite extreme laziness?
351,656
<p>I'm curious to know if there is an easy way to mock an IMAP server (a la the <code>imaplib</code> module) in Python, <em>without</em> doing a lot of work.</p> <p>Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure.</p> <p>Some background into the laziness: I have a nasty feeling that this small script I'm writing will grow over time and would <em>like</em> to create a proper testing environment, but given that it might <em>not</em> grow over time, I don't want to do much work to get the mock server running.</p>
9
2008-12-09T02:57:49Z
353,175
<p>How much of it do you really need for any one test? If you start to build something on the order of complexity of a real server so that you can use it on all your tests, you've already gone wrong. Just mock the bits any one tests needs. </p> <p>Don't bother trying so hard to share a mock implementation. They're not supposed to be assets, but discardable bits-n-pieces.</p>
6
2008-12-09T15:41:57Z
[ "python", "testing", "imap", "mocking" ]
How do I mock an IMAP server in Python, despite extreme laziness?
351,656
<p>I'm curious to know if there is an easy way to mock an IMAP server (a la the <code>imaplib</code> module) in Python, <em>without</em> doing a lot of work.</p> <p>Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure.</p> <p>Some background into the laziness: I have a nasty feeling that this small script I'm writing will grow over time and would <em>like</em> to create a proper testing environment, but given that it might <em>not</em> grow over time, I don't want to do much work to get the mock server running.</p>
9
2008-12-09T02:57:49Z
35,488,764
<p>As I didn't find something convenient in python 3 for my needs (mail part of twisted is not running in python 3), I did a small mock with asyncio that you can improve if you'd like :</p> <p>I defined an ImapProtocol which extends asyncio.Protocol. Then launch a server like this :</p> <pre><code>factory = loop.create_server(lambda: ImapProtocol(mailbox_map), 'localhost', 1143) server = loop.run_until_complete(factory) </code></pre> <p>The mailbox_map is a map of map : email -> map of mailboxes -> set of messages. So all the messages/mailboxes are in memory.</p> <p>Each time a client connects, a new instance of ImapProtocol is created. Then, the ImapProtocol executes and answers for each client, implementing capability/login/fetch/select/search/store : </p> <pre><code>class ImapHandler(object): def __init__(self, mailbox_map): self.mailbox_map = mailbox_map self.user_login = None # ... def connection_made(self, transport): self.transport = transport transport.write('* OK IMAP4rev1 MockIMAP Server ready\r\n'.encode()) def data_received(self, data): command_array = data.decode().rstrip().split() tag = command_array[0] self.by_uid = False self.exec_command(tag, command_array[1:]) def connection_lost(self, error): if error: log.error(error) else: log.debug('closing') self.transport.close() super().connection_lost(error) def exec_command(self, tag, command_array): command = command_array[0].lower() if not hasattr(self, command): return self.error(tag, 'Command "%s" not implemented' % command) getattr(self, command)(tag, *command_array[1:]) def capability(self, tag, *args): # code for it... def login(self, tag, *args): # code for it... </code></pre> <p>Then in my tests, I start the server during setup with :</p> <pre><code>self.loop = asyncio.get_event_loop() self.server = self.loop.run_until_complete(self.loop.create_server(create_imap_protocol, 'localhost', 12345)) </code></pre> <p>When I want to simulate a new message : </p> <pre><code>imap_receive(Mail(to='[email protected]', mail_from='[email protected]', subject='hello')) </code></pre> <p>And stop it at teardown :</p> <pre><code>self.server.close() asyncio.wait_for(self.server.wait_closed(), 1) </code></pre> <p>cf <a href="https://github.com/bamthomas/mockimapserver" rel="nofollow">https://github.com/bamthomas/mockimapserver</a></p> <hr> <p><strong><em>EDIT</em></strong>: I had a buggy stop of the server, I rewrote it with asyncio.Protocol and modify the answer to reflect the changes</p>
0
2016-02-18T17:48:13Z
[ "python", "testing", "imap", "mocking" ]
Python method arguments with spaces
351,760
<p>I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing. Syntax like this for defining a data element seems quite convenient.</p> <pre><code>Allocation(Param1 = Val1, Param2 = Val2 ) </code></pre> <p>However, it does not support param names with spaces.</p> <pre><code>Allocation(Param 1 = Val1, Param 2 = Val2 ) </code></pre> <p>Python parser friendly versions can look as follows, but not very user friendly.</p> <pre><code>Allocation(("Param 1",Val1), ("Param 2",Val1) ) Allocation(**{"Param 1":Val1, "Param 2":Val1} ) </code></pre> <p>Is there a way to make this more readable in python?</p>
1
2008-12-09T04:14:45Z
351,776
<p>You can do this:</p> <pre><code>def Allocation(**kwargs): print kwargs myargs = {"Param 1":Val1, "Param 2":Val1} Allocation(**myargs) </code></pre> <p><strong>Edit:</strong> Your edit now includes my answer so no, there is no easier way to have spaces in keyword arguments.</p>
0
2008-12-09T04:22:03Z
[ "python", "dsl" ]
Python method arguments with spaces
351,760
<p>I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing. Syntax like this for defining a data element seems quite convenient.</p> <pre><code>Allocation(Param1 = Val1, Param2 = Val2 ) </code></pre> <p>However, it does not support param names with spaces.</p> <pre><code>Allocation(Param 1 = Val1, Param 2 = Val2 ) </code></pre> <p>Python parser friendly versions can look as follows, but not very user friendly.</p> <pre><code>Allocation(("Param 1",Val1), ("Param 2",Val1) ) Allocation(**{"Param 1":Val1, "Param 2":Val1} ) </code></pre> <p>Is there a way to make this more readable in python?</p>
1
2008-12-09T04:14:45Z
351,795
<p>Unless I am mistaking your basic premise here, there's nothing to stop you from writing a class that parses your own custom syntax, and then using that custom syntax as a single-argument string:</p> <pre><code>Allocation("Param 1=Check Up; Param 2=Mean Value Theorem;") </code></pre> <p>In this example, semicolons act as the name-value-pair separators, and equals represents the name-value separator. Moreover, you can easily configure your parser to accept custom delimiters as part of the object constructor.</p> <p>If it seems too daunting to write a parser, consider that (for a syntax such as this) you could obtain your values by simply splitting the string on </p> <pre><code>/\s*;\s*/ </code></pre> <p>and then on</p> <pre><code>/\s*=\s*/ </code></pre> <p>to quickly obtain the name-value pairs. You also have the option to choose from any of several argument parsers already written for Python.</p> <p>Admittedly, this does not use Python as the argument parser, which is a consideration you will have to balance against the simplicity of an approach such as this.</p>
1
2008-12-09T04:40:19Z
[ "python", "dsl" ]
Python method arguments with spaces
351,760
<p>I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing. Syntax like this for defining a data element seems quite convenient.</p> <pre><code>Allocation(Param1 = Val1, Param2 = Val2 ) </code></pre> <p>However, it does not support param names with spaces.</p> <pre><code>Allocation(Param 1 = Val1, Param 2 = Val2 ) </code></pre> <p>Python parser friendly versions can look as follows, but not very user friendly.</p> <pre><code>Allocation(("Param 1",Val1), ("Param 2",Val1) ) Allocation(**{"Param 1":Val1, "Param 2":Val1} ) </code></pre> <p>Is there a way to make this more readable in python?</p>
1
2008-12-09T04:14:45Z
351,802
<p>I'd imagine that there would be some way to do it. But I feel compelled to ask, is there really a big enough difference in readability from this</p> <pre><code>Allocation(Param1 = Val1, Param2 = Val2 ) </code></pre> <p>To this:</p> <pre><code>Allocation(Param 1 = Val1, Param 2 = Val2 ) </code></pre> <p>to make that big a difference? I'm sure there's a way to do what you want to do, but my first concern is if the effort involved would be worth the result.</p> <blockquote> <p>my goal is to provide a DSL which can be used for data entry into the system. In the above scenario, params would be people names and values would be percentages.</p> </blockquote> <p>I have a better understanding of what you want to do now, but I still think that you might end up having to sacrifice some readability to get what you want. Personally, I would go with something like:</p> <pre><code>Allocation( { 'name1' : value1, 'name1' : value2, } ) </code></pre> <p>If that's not something you can go with, then you might want to reconsider whether you want to use Python for your DSL or go with something home-grown. Allowing whitespace allows too many ambiguities for most programming languages to allow it.</p> <p>If you still want to pursue this with using python, you might want to consider posting to the C-API SIG (<a href="http://www.python.org/community/sigs/" rel="nofollow">SIGS</a>) or maybe the <a href="http://mail.python.org/mailman/listinfo/python-dev" rel="nofollow">python-dev list</a> (as a last resort). The only way that I can see to do this would be to embed the python interpreter into a C/C++ program and do some kind of hacking with it (which can be difficult!).</p>
3
2008-12-09T04:42:47Z
[ "python", "dsl" ]
Python method arguments with spaces
351,760
<p>I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing. Syntax like this for defining a data element seems quite convenient.</p> <pre><code>Allocation(Param1 = Val1, Param2 = Val2 ) </code></pre> <p>However, it does not support param names with spaces.</p> <pre><code>Allocation(Param 1 = Val1, Param 2 = Val2 ) </code></pre> <p>Python parser friendly versions can look as follows, but not very user friendly.</p> <pre><code>Allocation(("Param 1",Val1), ("Param 2",Val1) ) Allocation(**{"Param 1":Val1, "Param 2":Val1} ) </code></pre> <p>Is there a way to make this more readable in python?</p>
1
2008-12-09T04:14:45Z
353,389
<p>Here's my preference.</p> <pre><code>AllocationSet( Alloc( name="some name", value=1.23 ), Alloc( name="another name", value=2.34 ), Alloc( name="yet another name", value=4.56 ), ) </code></pre> <p>These are relatively easy class declarations to create. The resulting structure is pleasant to process, too.</p>
1
2008-12-09T16:36:00Z
[ "python", "dsl" ]
destroying a Toplevel tk window in python
351,821
<p>I was trying to write code that would auto-close a Toplevel Tk window in Python.</p> <p>I ended up getting it to work, but ran into a little problem along the way that I wasn't able to figure out.</p> <p>The second two buttons work, but the first one doesn't and I don't understand why...</p> <p>Any ideas?</p> <pre><code>from Tkinter import * root = Tk() def doDestroy (): TL.destroy() TL = Toplevel() TL.b = Button (TL, text="lambda destroy", command=lambda: TL.destroy) TL.b.pack() TL.b2 = Button (TL, text="callback destroy", command=doDestroy) TL.b2.pack() de = lambda: TL.destroy() TL.b3 = Button (TL, text="lambda that works", command=de) TL.b3.pack() root.mainloop() </code></pre>
1
2008-12-09T04:53:58Z
351,832
<p>Because it returns a function and not its result.</p> <p>You should put:</p> <pre><code>command=TL.destroy </code></pre> <p>or if you used lambda:</p> <pre><code>command=lambda: TL.destroy() </code></pre>
8
2008-12-09T04:59:40Z
[ "python", "tkinter" ]
Python imaplib Gmail authenticate failure
351,927
<p>I just ran into an issue with Python's imaplib and Gmail's authentication mechanism:</p> <pre><code>&gt;&gt;&gt; import imaplib &gt;&gt;&gt; imap = imaplib.IMAP4_SSL('imap.gmail.com', 993) &gt;&gt;&gt; imap.authenticate('[email protected]', 'Bob Dole likes your style!') Traceback (most recent call last): ... imaplib.error: AUTHENTICATE command error: BAD ['TODO (not supported yet) 31if3458825wff.5'] </code></pre> <p>If authentication is unsupported, how does one log in?</p>
7
2008-12-09T06:07:50Z
351,930
<p>I found the solution on <a href="http://codeclimber.blogspot.com/2008/06/using-ruby-for-imap-with-gmail.html" rel="nofollow">this helpful blog post</a>. Although Gmail doesn't support AUTHENTICATE, it does support the LOGIN capability, like so:</p> <pre><code>&gt;&gt;&gt; imap.login('[email protected]', 'Bob Dole likes your style!') ('OK', ['[email protected] authenticated (Success)']) </code></pre>
0
2008-12-09T06:10:14Z
[ "python", "gmail", "imap" ]
Python imaplib Gmail authenticate failure
351,927
<p>I just ran into an issue with Python's imaplib and Gmail's authentication mechanism:</p> <pre><code>&gt;&gt;&gt; import imaplib &gt;&gt;&gt; imap = imaplib.IMAP4_SSL('imap.gmail.com', 993) &gt;&gt;&gt; imap.authenticate('[email protected]', 'Bob Dole likes your style!') Traceback (most recent call last): ... imaplib.error: AUTHENTICATE command error: BAD ['TODO (not supported yet) 31if3458825wff.5'] </code></pre> <p>If authentication is unsupported, how does one log in?</p>
7
2008-12-09T06:07:50Z
351,933
<p>The following works for me:</p> <pre><code>srv = imaplib.IMAP4_SSL("imap.gmail.com") srv.login(account, password) </code></pre> <p>I think using <code>login()</code> is required.</p>
2
2008-12-09T06:10:34Z
[ "python", "gmail", "imap" ]
Python imaplib Gmail authenticate failure
351,927
<p>I just ran into an issue with Python's imaplib and Gmail's authentication mechanism:</p> <pre><code>&gt;&gt;&gt; import imaplib &gt;&gt;&gt; imap = imaplib.IMAP4_SSL('imap.gmail.com', 993) &gt;&gt;&gt; imap.authenticate('[email protected]', 'Bob Dole likes your style!') Traceback (most recent call last): ... imaplib.error: AUTHENTICATE command error: BAD ['TODO (not supported yet) 31if3458825wff.5'] </code></pre> <p>If authentication is unsupported, how does one log in?</p>
7
2008-12-09T06:07:50Z
351,934
<p>Instead of</p> <pre><code>&gt;&gt;&gt; imap.authenticate('[email protected]', 'Bob Dole likes your style!') </code></pre> <p>use</p> <pre><code>&gt;&gt;&gt; imap.login('[email protected]', 'Bob Dole likes your style!') </code></pre>
8
2008-12-09T06:10:52Z
[ "python", "gmail", "imap" ]
Most pythonic form for mapping a series of statements?
352,076
<p>This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here):</p> <pre><code>result = [ f(x) for x in list ] </code></pre> <p>In many cases though, we want to execute more than a single statement on x, say:</p> <pre><code>result = [ f(g(h(x))) for x in list ] </code></pre> <p>This very quickly gets clunky, and difficult to read.</p> <p>My normal solution to this is to expand this back into a for loop:</p> <pre><code>result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) </code></pre> <p>One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] </code></pre> <p>Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?</p>
0
2008-12-09T08:06:41Z
352,105
<p>There are cases where it's best to go back to the for-loop, yes, but more often I prefer one of these approaches:</p> <p>Use appropriate line breaks and indentation to keep it readable:</p> <pre><code>result = [blah(blah(blah(x))) for x in list] </code></pre> <p>Or extract (enough of) the logic into another function, as you mention. But not necessarily local; Python programmers prefer flat to nested structure, if you can see a reasonable way of factoring the functionality out.</p> <p>I came to Python from the functional-programming world, too, and share your prejudice.</p>
0
2008-12-09T08:26:04Z
[ "python", "coding-style", "idioms" ]
Most pythonic form for mapping a series of statements?
352,076
<p>This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here):</p> <pre><code>result = [ f(x) for x in list ] </code></pre> <p>In many cases though, we want to execute more than a single statement on x, say:</p> <pre><code>result = [ f(g(h(x))) for x in list ] </code></pre> <p>This very quickly gets clunky, and difficult to read.</p> <p>My normal solution to this is to expand this back into a for loop:</p> <pre><code>result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) </code></pre> <p>One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] </code></pre> <p>Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?</p>
0
2008-12-09T08:06:41Z
352,121
<p>If your only concerned with the last result, your last answer is the best. It's clear for anyone looking at it what your doing. </p> <p>I often take any code that starts to get complex and move it to a function. This basically serves as a comment for that block of code. (any complex code probably needs a re-write anyway, and putting it in a function I can go back and work on it later)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list] </code></pre>
1
2008-12-09T08:34:29Z
[ "python", "coding-style", "idioms" ]
Most pythonic form for mapping a series of statements?
352,076
<p>This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here):</p> <pre><code>result = [ f(x) for x in list ] </code></pre> <p>In many cases though, we want to execute more than a single statement on x, say:</p> <pre><code>result = [ f(g(h(x))) for x in list ] </code></pre> <p>This very quickly gets clunky, and difficult to read.</p> <p>My normal solution to this is to expand this back into a for loop:</p> <pre><code>result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) </code></pre> <p>One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] </code></pre> <p>Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?</p>
0
2008-12-09T08:06:41Z
352,219
<p>Follow the style that most matches your tastes.<br> I would not worry about performance; only in case you really see some issue you can try to move to a different style.</p> <p>Here some other possible suggestions, in addition to your proposals:</p> <pre><code>result = [f( g( h(x) ) ) for x in list] </code></pre> <p>Use progressive list comprehensions:</p> <pre><code>result = [h(x) for x in list] result = [g(x) for x in result] result = [f(x) for x in result] </code></pre> <p>Again, that's only a matter of style and taste. Pick the one you prefer most, and stick with it :-)</p>
3
2008-12-09T09:25:04Z
[ "python", "coding-style", "idioms" ]
Most pythonic form for mapping a series of statements?
352,076
<p>This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here):</p> <pre><code>result = [ f(x) for x in list ] </code></pre> <p>In many cases though, we want to execute more than a single statement on x, say:</p> <pre><code>result = [ f(g(h(x))) for x in list ] </code></pre> <p>This very quickly gets clunky, and difficult to read.</p> <p>My normal solution to this is to expand this back into a for loop:</p> <pre><code>result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) </code></pre> <p>One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] </code></pre> <p>Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?</p>
0
2008-12-09T08:06:41Z
353,060
<p>You can easily do function composition in Python. </p> <p>Here's a demonstrates of a way to create a new function which is a composition of existing functions.</p> <pre><code>&gt;&gt;&gt; def comp( a, b ): def compose( args ): return a( b( args ) ) return compose &gt;&gt;&gt; def times2(x): return x*2 &gt;&gt;&gt; def plus1(x): return x+1 &gt;&gt;&gt; comp( times2, plus1 )(32) 66 </code></pre> <p>Here's a more complete recipe for <a href="http://code.activestate.com/recipes/52902/" rel="nofollow">function composition</a>. This should make it look less clunky.</p>
5
2008-12-09T15:11:15Z
[ "python", "coding-style", "idioms" ]
Most pythonic form for mapping a series of statements?
352,076
<p>This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here):</p> <pre><code>result = [ f(x) for x in list ] </code></pre> <p>In many cases though, we want to execute more than a single statement on x, say:</p> <pre><code>result = [ f(g(h(x))) for x in list ] </code></pre> <p>This very quickly gets clunky, and difficult to read.</p> <p>My normal solution to this is to expand this back into a for loop:</p> <pre><code>result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) </code></pre> <p>One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] </code></pre> <p>Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?</p>
0
2008-12-09T08:06:41Z
353,147
<p>If this is something you're doing often and with several different statements you could write something like</p> <pre><code>def seriesoffncs(fncs,x): for f in fncs[::-1]: x=f(x) return x </code></pre> <p>where fncs is a list of functions. so seriesoffncs((f,g,h),x) would return f(g(h(x))). This way if you later in your code need to workout h(q(g(f(x)))) you would simply do seriesoffncs((h,q,g,f),x) rather than make a new operations function for each combination of functions.</p>
2
2008-12-09T15:35:13Z
[ "python", "coding-style", "idioms" ]
Most pythonic form for mapping a series of statements?
352,076
<p>This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here):</p> <pre><code>result = [ f(x) for x in list ] </code></pre> <p>In many cases though, we want to execute more than a single statement on x, say:</p> <pre><code>result = [ f(g(h(x))) for x in list ] </code></pre> <p>This very quickly gets clunky, and difficult to read.</p> <p>My normal solution to this is to expand this back into a for loop:</p> <pre><code>result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) </code></pre> <p>One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] </code></pre> <p>Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?</p>
0
2008-12-09T08:06:41Z
353,729
<p>A variation of <a href="http://stackoverflow.com/questions/352076/most-pythonic-form-for-mapping-a-series-of-statements#353147">dagw.myopenid.com</a>'s function:</p> <pre><code>def chained_apply(*args): val = args[-1] for f in fncs[:-1:-1]: val=f(val) return val </code></pre> <p>Instead of seriesoffncs((h,q,g,f),x) now you can call:</p> <pre><code>result = chained_apply(foo, bar, baz, x) </code></pre>
1
2008-12-09T18:20:06Z
[ "python", "coding-style", "idioms" ]
Most pythonic form for mapping a series of statements?
352,076
<p>This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here):</p> <pre><code>result = [ f(x) for x in list ] </code></pre> <p>In many cases though, we want to execute more than a single statement on x, say:</p> <pre><code>result = [ f(g(h(x))) for x in list ] </code></pre> <p>This very quickly gets clunky, and difficult to read.</p> <p>My normal solution to this is to expand this back into a for loop:</p> <pre><code>result = [] for x in list: x0 = h(x) x1 = g(x0) x2 = f(x1) result.append(x2) </code></pre> <p>One thing about this that bothers me no end is having to initialize the empty list 'result'. It's a triviality, but it makes me unhappy. I was wondering if there were any alternative equivalent forms. One way may be to use a local function(is that what they're called in Python?)</p> <pre><code>def operation(x): x0 = h(x) x1 = g(x0) x2 = f(x1) return x2 result = [ operation(x) for x in list ] </code></pre> <p>Are there any particular advantages/disadvantages to either of the two forms above? Or is there perhaps a more elegant way?</p>
0
2008-12-09T08:06:41Z
406,944
<p>As far as I know there's no built-in/native syntax for composition in Python, but you can write your own function to compose stuff without too much trouble.</p> <pre><code>def compose(*f): return f[0] if len(f) == 1 else lambda *args: f[0](compose(*f[1:])(*args)) def f(x): return 'o ' + str(x) def g(x): return 'hai ' + str(x) def h(x, y): return 'there ' + str(x) + str(y) + '\n' action = compose(f, g, h) print [action("Test ", item) for item in [1, 2, 3]] </code></pre> <p>Composing outside the comprehension isn't required, of course.</p> <pre><code>print [compose(f, g, h)("Test ", item) for item in [1, 2, 3]] </code></pre> <p>This way of composing will work for any number of functions (well, up to the recursion limit) with any number of parameters for the inner function.</p>
1
2009-01-02T14:41:29Z
[ "python", "coding-style", "idioms" ]
How to adding middleware to Appengine's webapp framework?
352,079
<p>Im using the appengine webapp framework (<a href="http://code.google.com/appengine/docs/webapp/" rel="nofollow">link</a>). Is it possible to add Django middleware? I cant find any examples. Im currently trying to get the firepython middleware to work (<a href="http://github.com/woid/firepython/tree/master" rel="nofollow">link</a>).</p>
3
2008-12-09T08:09:07Z
436,831
<p>Could you provide any details on your failure?</p> <p>AFAIK Google App Engine lets you use django middleware as long as it does not use django models/ORM.</p> <p>BTW. Thanks for pointing out Firepython, looks sweet :)</p>
1
2009-01-12T20:12:04Z
[ "python", "django", "google-app-engine", "middleware", "django-middleware" ]
How to adding middleware to Appengine's webapp framework?
352,079
<p>Im using the appengine webapp framework (<a href="http://code.google.com/appengine/docs/webapp/" rel="nofollow">link</a>). Is it possible to add Django middleware? I cant find any examples. Im currently trying to get the firepython middleware to work (<a href="http://github.com/woid/firepython/tree/master" rel="nofollow">link</a>).</p>
3
2008-12-09T08:09:07Z
442,831
<p>It's easy: You create the WSGI application as per normal, then wrap that application in your WSGI middleware before executing it.</p> <p>See <a href="http://github.com/Arachnid/bloog/blob/bb777426376d298765d5dee5b88f53964cc6b5f3/main.py#L71">this code</a> from Bloog to see how firepython is added as middleware.</p>
5
2009-01-14T12:49:37Z
[ "python", "django", "google-app-engine", "middleware", "django-middleware" ]
How to adding middleware to Appengine's webapp framework?
352,079
<p>Im using the appengine webapp framework (<a href="http://code.google.com/appengine/docs/webapp/" rel="nofollow">link</a>). Is it possible to add Django middleware? I cant find any examples. Im currently trying to get the firepython middleware to work (<a href="http://github.com/woid/firepython/tree/master" rel="nofollow">link</a>).</p>
3
2008-12-09T08:09:07Z
455,888
<p>The GAE webapp framework does not map one to one to the Django framework. It would be hard to do what you want without implementing some kind of adapter yourself, I do not know of any third party handler adapters to do this.</p> <p>That said, I generally use the app-engine-patch so I can use the latest 1.0.2 Django release with AppEngine, and then you can just include the Django middleware the normal way with the setup.py file. If you needed to, you could probably look through the app-engine-patch's adapter to see how they do it, and start with that as a framework.</p>
0
2009-01-18T21:04:44Z
[ "python", "django", "google-app-engine", "middleware", "django-middleware" ]
How to adding middleware to Appengine's webapp framework?
352,079
<p>Im using the appengine webapp framework (<a href="http://code.google.com/appengine/docs/webapp/" rel="nofollow">link</a>). Is it possible to add Django middleware? I cant find any examples. Im currently trying to get the firepython middleware to work (<a href="http://github.com/woid/firepython/tree/master" rel="nofollow">link</a>).</p>
3
2008-12-09T08:09:07Z
548,865
<p>"Middleware" as understood by Django is a kind of request/response processor, quite different from what WSGI calls "middleware". Think: django-like middleware will add <code>session</code> attribute to request object basing on what Beaker (WSGI middleware) has put in <code>environ['beaker.session']</code>. While adding WSGI middleware to the stack should be straightforward (you already work on WSGI level in your <code>main.py</code>), adding request/response processor depends on how request and response are abstracted from WSGI.</p> <p>How this can be done using <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> (which is basic WSGI toolset) is described in <a href="http://dev.pocoo.org/projects/werkzeug/wiki/RequestResponseProcessor" rel="nofollow">Werkzeug's wiki</a> and in one of its <a href="http://dev.pocoo.org/projects/werkzeug/browser/werkzeug/contrib/kickstart.py#L89" rel="nofollow">contrib modules</a>.</p>
0
2009-02-14T10:04:13Z
[ "python", "django", "google-app-engine", "middleware", "django-middleware" ]
Return file from python module
352,340
<p>Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV</p>
1
2008-12-09T10:34:14Z
352,385
<p>You can either pass back a reference to the file itself i.e. the full path to the file. Then you can open the file or otherwise manipulate it.</p> <p>Or, the more normal case is to pass back the file handle, and, use the standard read/write operations on the file handle.</p> <p>It is not recommended to pass the actual data as files can be arbiterally large and the program could run out of memory.</p> <p>In your case, you probably want to return a tuple containing the open file handle, the file name and any other meta data you are interested in.</p>
2
2008-12-09T10:56:37Z
[ "python", "file", "mime-types", "download" ]
Return file from python module
352,340
<p>Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV</p>
1
2008-12-09T10:34:14Z
352,399
<p>For information on MIME types (which are how downloads happen), start here: <a href="https://developer.mozilla.org/en/Properly_Configuring_Server_MIME_Types" rel="nofollow">Properly Configure Server MIME Types</a>.</p> <p>For information on CherryPy, look at the attributes of a <a href="http://www.cherrypy.org/wiki/ResponseObject" rel="nofollow">Response</a> object. You can set the <a href="http://www.cherrypy.org/wiki/ResponseObject#headers" rel="nofollow">content type</a> of the response. Also, you can use <a href="http://www.cherrypy.org/wiki/BuiltinTools#tools.response_headers" rel="nofollow">tools.response_headers</a> to set the content type.</p> <p>And, of course, there's an example of <a href="http://www.cherrypy.org/wiki/FileDownload" rel="nofollow">File Download</a>.</p>
0
2008-12-09T11:06:04Z
[ "python", "file", "mime-types", "download" ]
Return file from python module
352,340
<p>Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV</p>
1
2008-12-09T10:34:14Z
352,497
<p>Fully supported in CherryPy using</p> <pre><code>from cherrypy.lib.static import serve_file </code></pre> <p>As documented in the <a href="http://www.cherrypy.org/wiki/FileDownload" rel="nofollow">CherryPy docs - FileDownload</a>:</p> <pre><code>import glob import os.path import cherrypy from cherrypy.lib.static import serve_file class Root: def index(self, directory="."): html = """&lt;html&gt;&lt;body&gt;&lt;h2&gt;Here are the files in the selected directory:&lt;/h2&gt; &lt;a href="index?directory=%s"&gt;Up&lt;/a&gt;&lt;br /&gt; """ % os.path.dirname(os.path.abspath(directory)) for filename in glob.glob(directory + '/*'): absPath = os.path.abspath(filename) if os.path.isdir(absPath): html += '&lt;a href="/index?directory=' + absPath + '"&gt;' + os.path.basename(filename) + "&lt;/a&gt; &lt;br /&gt;" else: html += '&lt;a href="/download/?filepath=' + absPath + '"&gt;' + os.path.basename(filename) + "&lt;/a&gt; &lt;br /&gt;" html += """&lt;/body&gt;&lt;/html&gt;""" return html index.exposed = True class Download: def index(self, filepath): return serve_file(filepath, "application/x-download", "attachment") index.exposed = True if __name__ == '__main__': root = Root() root.download = Download() cherrypy.quickstart(root) </code></pre>
1
2008-12-09T11:48:15Z
[ "python", "file", "mime-types", "download" ]
Capitalize a string
352,478
<p>Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?</p> <p>For example:</p> <pre><code>asimpletest -&gt; Asimpletest aSimpleTest -&gt; ASimpleTest </code></pre> <p>I would like to be able to do all string lengths as well.</p>
25
2008-12-09T11:42:47Z
352,494
<pre><code>str = str[0].upper() + str[1:] </code></pre> <p>This should work with every string, except for the empty string (<code>""</code>).</p>
7
2008-12-09T11:47:59Z
[ "python", "string" ]