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
listlengths
1
5
XML Parsing with Python and minidom
1,596,829
<p>I'm using Python (minidom) to parse an XML file that prints a hierarchical structure that looks something like this (indentation is used here to show the significant hierarchical relationship):</p> <pre><code>My Document Overview Basic Features About This Software Platforms Supported </code></pre> ...
12
2009-10-20T19:36:07Z
14,255,287
<p>Recusive function:</p> <pre><code>import xml.dom.minidom def traverseTree(document, depth=0): tag = document.tagName for child in document.childNodes: if child.nodeType == child.TEXT_NODE: if document.tagName == 'Title': print depth*' ', child.data if child.nodeType == xml.dom.Node.ELE...
1
2013-01-10T10:08:00Z
[ "python", "xml", "minidom" ]
XML Parsing with Python and minidom
1,596,829
<p>I'm using Python (minidom) to parse an XML file that prints a hierarchical structure that looks something like this (indentation is used here to show the significant hierarchical relationship):</p> <pre><code>My Document Overview Basic Features About This Software Platforms Supported </code></pre> ...
12
2009-10-20T19:36:07Z
21,410,794
<p>I think that can help</p> <pre><code>import os import sys import subprocess import base64,xml.dom.minidom from xml.dom.minidom import Node f = open("file.xml",'r') data = f.read() i = 0 doc = xml.dom.minidom.parseString(data) for topic in doc.getElementsByTagName('Topic'): title= doc.getElementsByTagName('Title'...
1
2014-01-28T16:07:43Z
[ "python", "xml", "minidom" ]
Read a file from server with ssh using python
1,596,963
<p>I am trying to read a file from a server using ssh from python. I am using paramiko to connect. I can connect to the server and run a command like 'cat filename' and get the data back from the server but some files I am trying to read are around 1 GB or more in size.</p> <p>How can I read the file on the server lin...
18
2009-10-20T20:04:00Z
1,597,006
<p>What do you mean by "line by line" - there are lots of data buffers between network hosts, and none of them are line-oriented. </p> <p>So you can read a bunch of data, then split it into lines at the near end.</p> <pre><code>ssh otherhost cat somefile | python process_standard_input.py | do_process_locally </code>...
4
2009-10-20T20:11:21Z
[ "python", "file-io" ]
Read a file from server with ssh using python
1,596,963
<p>I am trying to read a file from a server using ssh from python. I am using paramiko to connect. I can connect to the server and run a command like 'cat filename' and get the data back from the server but some files I am trying to read are around 1 GB or more in size.</p> <p>How can I read the file on the server lin...
18
2009-10-20T20:04:00Z
1,597,009
<pre><code>#!/usr/bin/env python import paramiko import select client = paramiko.SSHClient() client.load_system_host_keys() client.connect('yourhost.com') transport = client.get_transport() channel = transport.open_session() channel.exec_command("cat /path/to/your/file") while True: rl, wl, xl = select.select([channe...
3
2009-10-20T20:12:03Z
[ "python", "file-io" ]
Read a file from server with ssh using python
1,596,963
<p>I am trying to read a file from a server using ssh from python. I am using paramiko to connect. I can connect to the server and run a command like 'cat filename' and get the data back from the server but some files I am trying to read are around 1 GB or more in size.</p> <p>How can I read the file on the server lin...
18
2009-10-20T20:04:00Z
1,597,750
<p><a href="https://github.com/paramiko/paramiko">Paramiko's</a> <code>SFTPClient</code> class allows you to get a file-like object to read data from a remote file in a Pythonic way.</p> <p>Assuming you have an open <code>SSHClient</code>:</p> <pre><code>sftp_client = ssh_client.open_sftp() remote_file = sftp_client....
32
2009-10-20T22:53:20Z
[ "python", "file-io" ]
Read a file from server with ssh using python
1,596,963
<p>I am trying to read a file from a server using ssh from python. I am using paramiko to connect. I can connect to the server and run a command like 'cat filename' and get the data back from the server but some files I am trying to read are around 1 GB or more in size.</p> <p>How can I read the file on the server lin...
18
2009-10-20T20:04:00Z
1,598,554
<p>Here's an extension to <a href="http://stackoverflow.com/questions/1596963/read-a-file-from-server-with-ssh-using-python/1597750#1597750">@Matt Good's answer</a>:</p> <pre><code>from contextlib import closing from fabric.network import connect with closing(connect(user, host, port)) as ssh, \ closing(ssh....
7
2009-10-21T03:15:19Z
[ "python", "file-io" ]
Multithreaded Downloading Through Proxies In Python
1,597,093
<p>What would be the best library for multithreaded harvesting/downloading with multiple proxy support? I've looked at Tkinter, it looks good but there are so many, does anyone have a specific recommendation? Many thanks!</p>
0
2009-10-20T20:27:51Z
1,597,104
<p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a></p>
1
2009-10-20T20:28:57Z
[ "python", "proxy", "download", "multithreading", "harvest" ]
Multithreaded Downloading Through Proxies In Python
1,597,093
<p>What would be the best library for multithreaded harvesting/downloading with multiple proxy support? I've looked at Tkinter, it looks good but there are so many, does anyone have a specific recommendation? Many thanks!</p>
0
2009-10-20T20:27:51Z
1,597,142
<p>Is this something you can't just do by passing a URL to newly spawned threads and calling urllib2.urlopen in each one, or is there a more specific requirement?</p>
0
2009-10-20T20:36:02Z
[ "python", "proxy", "download", "multithreading", "harvest" ]
Multithreaded Downloading Through Proxies In Python
1,597,093
<p>What would be the best library for multithreaded harvesting/downloading with multiple proxy support? I've looked at Tkinter, it looks good but there are so many, does anyone have a specific recommendation? Many thanks!</p>
0
2009-10-20T20:27:51Z
1,597,402
<p>Also take a look at <a href="http://scrapy.org/" rel="nofollow">http://scrapy.org/</a>, which is a scraping framework built on top of twisted. </p>
0
2009-10-20T21:24:04Z
[ "python", "proxy", "download", "multithreading", "harvest" ]
Python graceful fail on int() call?
1,597,114
<p>I have to make a rudimentary FSM in a class, and am writing it in Python. The assignment requires we read the transitions for the machine from a text file. So for example, a FSM with 3 states, each of which have 2 possible transitions, with possible inputs 'a' and 'b', wolud have a text file that looks like this:<...
1
2009-10-20T20:30:26Z
1,597,148
<p>You should really only be trying to parse the tokens that you expect to be integers</p> <pre><code>for line in f: tokens = line.split(" ") current_state, input_val, next_state = int(tokens[0]), tokens[1], int(tokens[2]) </code></pre> <p>Arguably more-readable:</p> <pre><code>for line in f: current_sta...
12
2009-10-20T20:37:19Z
[ "python", "fsm" ]
Python graceful fail on int() call?
1,597,114
<p>I have to make a rudimentary FSM in a class, and am writing it in Python. The assignment requires we read the transitions for the machine from a text file. So for example, a FSM with 3 states, each of which have 2 possible transitions, with possible inputs 'a' and 'b', wolud have a text file that looks like this:<...
1
2009-10-20T20:30:26Z
1,597,155
<p>This is something very functional, but I'm not sure if it's "pythonic"... And it may cause some people to scratch their heads. You should really have a "lazy" zip() to do it this way if you have a large number of values:</p> <pre><code>types = [int, str, int] for line in f: current_state, input_val, next_state =...
5
2009-10-20T20:38:03Z
[ "python", "fsm" ]
Python graceful fail on int() call?
1,597,114
<p>I have to make a rudimentary FSM in a class, and am writing it in Python. The assignment requires we read the transitions for the machine from a text file. So for example, a FSM with 3 states, each of which have 2 possible transitions, with possible inputs 'a' and 'b', wolud have a text file that looks like this:<...
1
2009-10-20T20:30:26Z
1,597,785
<pre><code>self.finalStates = [int(state) for state in f.readline().split()] for line in f: words = line.split() current_state, input_val, next_state = int(words[0]), words[1], int(words[2]) # now do something with values </code></pre> <p>Note that you can shorten <code>line.strip("\n").split(" ")</code> ...
0
2009-10-20T23:03:33Z
[ "python", "fsm" ]
Python graceful fail on int() call?
1,597,114
<p>I have to make a rudimentary FSM in a class, and am writing it in Python. The assignment requires we read the transitions for the machine from a text file. So for example, a FSM with 3 states, each of which have 2 possible transitions, with possible inputs 'a' and 'b', wolud have a text file that looks like this:<...
1
2009-10-20T20:30:26Z
1,598,326
<p>You got excellent answers that match your problem well. However, in other cases, there may indeed be situations where you want to convert some fields to <code>int</code> if feasible (i.e. if they're all digits) and leave them as <code>str</code> otherwise (as the title of your question suggests) <em>without</em> kn...
1
2009-10-21T01:44:49Z
[ "python", "fsm" ]
cElementTree invalid encoding problem
1,597,604
<p>I'm encoding challenged, so this is probably simple, but I'm stuck.</p> <p>I'm trying to parse an XML file emailed to the <a href="http://en.wikipedia.org/wiki/Google_App_Engine" rel="nofollow">App Engine</a>'s new receive mail functionality. First, I just pasted the XML into the body of the message, and it parsed ...
0
2009-10-20T22:07:19Z
1,598,839
<p>Ah, nevermind. There's a bug in App Engine that is calling lower() on all attachments when you decode them. This made the CDATA string invalid. </p> <p>Here's a link to the bug report: <a href="http://code.google.com/p/googleappengine/issues/detail?id=2289#c2" rel="nofollow">http://code.google.com/p/googleappengine...
0
2009-10-21T05:10:42Z
[ "python", "xml" ]
Replace strings in files by Python
1,597,649
<p><strong>How can you replace the match with the given replacement recursively in a given directory and its subdirectories?</strong></p> <h2>Pseudo-code</h2> <pre><code>import os import re from os.path import walk for root, dirs, files in os.walk("/home/noa/Desktop/codes"): for name in dirs: ...
10
2009-10-20T22:17:55Z
1,597,739
<p>Do you really need regular expressions?</p> <pre><code>import os def recursive_replace( root, pattern, replace ) for dir, subdirs, names in os.walk( root ): for name in names: path = os.path.join( dir, name ) text = open( path ).read() if pattern in text: ...
9
2009-10-20T22:49:27Z
[ "python", "regex", "search", "replace", "operating-system" ]
Replace strings in files by Python
1,597,649
<p><strong>How can you replace the match with the given replacement recursively in a given directory and its subdirectories?</strong></p> <h2>Pseudo-code</h2> <pre><code>import os import re from os.path import walk for root, dirs, files in os.walk("/home/noa/Desktop/codes"): for name in dirs: ...
10
2009-10-20T22:17:55Z
1,597,755
<p>Put all this code into a file called <code>mass_replace</code>. Under Linux or Mac OS X, you can do <code>chmod +x mass_replace</code> and then just run this. Under Windows, you can run it with <code>python mass_replace</code> followed by the appropriate arguments.</p> <pre><code>#!/usr/bin/python import os impo...
19
2009-10-20T22:54:46Z
[ "python", "regex", "search", "replace", "operating-system" ]
Replace strings in files by Python
1,597,649
<p><strong>How can you replace the match with the given replacement recursively in a given directory and its subdirectories?</strong></p> <h2>Pseudo-code</h2> <pre><code>import os import re from os.path import walk for root, dirs, files in os.walk("/home/noa/Desktop/codes"): for name in dirs: ...
10
2009-10-20T22:17:55Z
1,598,317
<p>Of course, if you just want to get it done without coding it up, use find and xargs:</p> <pre><code>find /home/noa/Desktop/codes -type f -print0 | \ xargs -0 sed --in-place "s/dbname=noa user=noa/dbname=masi user=masi" </code></pre> <p>(And you could likely do this with find's -exec or something as well, but I pre...
3
2009-10-21T01:39:08Z
[ "python", "regex", "search", "replace", "operating-system" ]
Replace strings in files by Python
1,597,649
<p><strong>How can you replace the match with the given replacement recursively in a given directory and its subdirectories?</strong></p> <h2>Pseudo-code</h2> <pre><code>import os import re from os.path import walk for root, dirs, files in os.walk("/home/noa/Desktop/codes"): for name in dirs: ...
10
2009-10-20T22:17:55Z
6,258,249
<p>This is how I would find and replace strings in files using python. This is a simple little function that will recursively search a directories for a string and replace it with a string. You can also limit files with a certain file extension like the example below.</p> <pre><code>import os, fnmatch def findReplace(...
2
2011-06-06T21:30:17Z
[ "python", "regex", "search", "replace", "operating-system" ]
Replace strings in files by Python
1,597,649
<p><strong>How can you replace the match with the given replacement recursively in a given directory and its subdirectories?</strong></p> <h2>Pseudo-code</h2> <pre><code>import os import re from os.path import walk for root, dirs, files in os.walk("/home/noa/Desktop/codes"): for name in dirs: ...
10
2009-10-20T22:17:55Z
35,413,705
<p>this should work:</p> <pre><code>import re, os import fnmatch for path, dirs, files in os.walk(os.path.abspath(directory)): for filename in fnmatch.filter(files, filePattern): filepath = os.path.join(path, filename) with open("namelist.wps", 'a') as out: with open("nameli...
1
2016-02-15T15:57:07Z
[ "python", "regex", "search", "replace", "operating-system" ]
Is there a better, pythonic way to do this?
1,597,764
<p>This is my first python program - </p> <p>Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds.</p> <p>Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way?</p> <p>CODE ...
10
2009-10-20T22:58:28Z
1,597,795
<p>You could shorten the for-loop to this:</p> <pre><code>for row in reader: adDict.setdefault(row[0], set()).add(row[1]) </code></pre>
7
2009-10-20T23:06:58Z
[ "dictionary", "set", "python" ]
Is there a better, pythonic way to do this?
1,597,764
<p>This is my first python program - </p> <p>Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds.</p> <p>Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way?</p> <p>CODE ...
10
2009-10-20T22:58:28Z
1,597,796
<p>The only changes I'd make are extracting multiple elements from the reader at once, and using string formatting for print statements.</p> <pre><code>import csv adDict = {} reader = csv.reader(open("some.csv"), delimiter=' ') # Can extract multiple elements from a list in the iteration statement: for adId, userId i...
1
2009-10-20T23:07:59Z
[ "dictionary", "set", "python" ]
Is there a better, pythonic way to do this?
1,597,764
<p>This is my first python program - </p> <p>Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds.</p> <p>Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way?</p> <p>CODE ...
10
2009-10-20T22:58:28Z
1,597,800
<p>Congratulations, your code is very nice. There are a few little tricks you could use to make it shorter/simpler.</p> <p>There is a nifty object type called defaultdict which is provided by the collections module. Instead of having to check if adDict has an adId key, you can set up a defaultdict which acts like a r...
18
2009-10-20T23:08:26Z
[ "dictionary", "set", "python" ]
Is there a better, pythonic way to do this?
1,597,764
<p>This is my first python program - </p> <p>Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds.</p> <p>Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way?</p> <p>CODE ...
10
2009-10-20T22:58:28Z
1,597,803
<p>Just a few bits and pieces:</p> <p>For extracting the row list into variables:</p> <pre><code>adId, userId = row </code></pre> <p>The if statement does not need braces:</p> <pre><code>if adId in adDict: </code></pre> <p>You <em>could</em> use exceptions to handle a missing Key in the dict, but both ways work we...
1
2009-10-20T23:09:01Z
[ "dictionary", "set", "python" ]
Is there a better, pythonic way to do this?
1,597,764
<p>This is my first python program - </p> <p>Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds.</p> <p>Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way?</p> <p>CODE ...
10
2009-10-20T22:58:28Z
1,597,809
<p>Instead of:</p> <pre><code>for row in reader: adId = row[0] userId = row[1] </code></pre> <p>Use automatic sequence unpacking:</p> <pre><code>for (adId, userId) in reader: </code></pre> <p>In:</p> <pre><code>if ( adId in adDict ): </code></pre> <p>You don't need parentheses.</p> <p>Instead of:</p> <p...
3
2009-10-20T23:10:51Z
[ "dictionary", "set", "python" ]
Is there a better, pythonic way to do this?
1,597,764
<p>This is my first python program - </p> <p>Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds.</p> <p>Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way?</p> <p>CODE ...
10
2009-10-20T22:58:28Z
1,597,838
<p>Since you only have a space-delimited file, I'd do:</p> <pre><code>from __future__ import with_statement from collections import defaultdict ads = defaultdict(set) with open("some.csv") as f: for ad, user in (line.split(" ") for line in f): ads[ad].add(user) for ad in ads: print "%s, %s" % (ad, le...
3
2009-10-20T23:18:40Z
[ "dictionary", "set", "python" ]
Is there a better, pythonic way to do this?
1,597,764
<p>This is my first python program - </p> <p>Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds.</p> <p>Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way?</p> <p>CODE ...
10
2009-10-20T22:58:28Z
1,598,247
<p>the line of code:</p> <pre><code>adDict[adId] = set(userId) </code></pre> <p>is unlikely to do what you want -- it will treat string <code>userId</code> as a sequence of letters, so for example if <code>userId</code> was <code>aleax</code> you'd get a set with four items, just like, say, <code>set(['a', 'l', 'e', ...
10
2009-10-21T01:13:15Z
[ "dictionary", "set", "python" ]
Is there a better, pythonic way to do this?
1,597,764
<p>This is my first python program - </p> <p>Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds.</p> <p>Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way?</p> <p>CODE ...
10
2009-10-20T22:58:28Z
1,598,266
<p>There are some great answers in here.</p> <p>One trick I particularly like is to make my code easier to reuse in future like so </p> <pre><code>import csv def parse_my_file(file_name): # some existing code goes here return aDict if __name__ == "__main__": #this gets executed if this .py file is ru...
3
2009-10-21T01:21:36Z
[ "dictionary", "set", "python" ]
How to store dynamically generated HTML form elements from Javascript in Python?
1,597,766
<p>I have an HTML form that a user can add an arbitrary amount of input fields to through jQuery. The user is also able to remove any input field from any position. My current implementation is that each new input box has an id of "field[i]" so when the form is posted it is processed in Python as field1, field2 field3,...
2
2009-10-20T22:58:39Z
1,597,786
<p>You could serialize the data with javascript and pass it in as json. Then you would just have a dictionary to work with in python. You would need something like <a href="http://code.google.com/p/simplejson/" rel="nofollow">simplejson</a>, of course</p>
1
2009-10-20T23:03:38Z
[ "javascript", "jquery", "python", "google-app-engine", "dhtml" ]
Printing basenames by Python
1,598,013
<p><strong>How can you print the basenames of files by Python in the main folder and subfolders?</strong></p> <p><strong>My attempt</strong> </p> <pre><code>#!/usr/bin/python import os import sys def dir_basename (dir_name): for dirpath, dirnames, filenames in os.walk(dir_name): ...
1
2009-10-21T00:03:11Z
1,598,036
<pre><code>if len(sys.argv) != 1: </code></pre> <p>I think you mean <code>2</code>. <code>argv[0]</code> is the name of the script; <code>argv[1]</code> is the first argument, etc.</p>
3
2009-10-21T00:09:06Z
[ "python", "path" ]
Printing basenames by Python
1,598,013
<p><strong>How can you print the basenames of files by Python in the main folder and subfolders?</strong></p> <p><strong>My attempt</strong> </p> <pre><code>#!/usr/bin/python import os import sys def dir_basename (dir_name): for dirpath, dirnames, filenames in os.walk(dir_name): ...
1
2009-10-21T00:03:11Z
1,598,038
<p>The length of <code>sys.argv</code> is 2 because you have an item at index 0 (the program name) and an item at index 1 (the first argument to the program).</p> <p>Changing your program to compare against 2 appears to give the correct results, without making any other changes.</p>
1
2009-10-21T00:09:18Z
[ "python", "path" ]
Printing basenames by Python
1,598,013
<p><strong>How can you print the basenames of files by Python in the main folder and subfolders?</strong></p> <p><strong>My attempt</strong> </p> <pre><code>#!/usr/bin/python import os import sys def dir_basename (dir_name): for dirpath, dirnames, filenames in os.walk(dir_name): ...
1
2009-10-21T00:03:11Z
1,598,039
<p><code>argv</code> typically includes the name of the program/script invokved as the first element, and thus the length when passing it a single argument is actually 2, not 1.</p>
1
2009-10-21T00:09:23Z
[ "python", "path" ]
Printing basenames by Python
1,598,013
<p><strong>How can you print the basenames of files by Python in the main folder and subfolders?</strong></p> <p><strong>My attempt</strong> </p> <pre><code>#!/usr/bin/python import os import sys def dir_basename (dir_name): for dirpath, dirnames, filenames in os.walk(dir_name): ...
1
2009-10-21T00:03:11Z
1,598,065
<p>Let me explain the debugging methodology a little bit.</p> <p>As you've encountered the situation in which <code>len(sys.argv) != 1</code>, you should ask youself: "What is the actual value of <code>len(sys.argv)</code>? Why it is so?". The answers are:</p> <pre><code>&gt;&gt;&gt; len(sys.argv) 2 &gt;&gt;&gt; sys....
8
2009-10-21T00:17:23Z
[ "python", "path" ]
Printing basenames by Python
1,598,013
<p><strong>How can you print the basenames of files by Python in the main folder and subfolders?</strong></p> <p><strong>My attempt</strong> </p> <pre><code>#!/usr/bin/python import os import sys def dir_basename (dir_name): for dirpath, dirnames, filenames in os.walk(dir_name): ...
1
2009-10-21T00:03:11Z
1,598,299
<p>As others have noted, the first element of sys.argv is the program::</p> <pre><code># argv.py import sys for index, arg in enumerate(sys.argv): print '%(index)s: %(arg)s' % locals() </code></pre> <p>If I run this without parameters::</p> <pre><code>$ python argv.py 0: argv.py </code></pre> <p>I see that th...
2
2009-10-21T01:34:03Z
[ "python", "path" ]
Pythonic way to only do work first time a variable is called
1,598,174
<p>my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value.</p> <p>I don't want to waste time doing this work unless they are actually needed by the user. So is there a clean Pythonic way to implement this use case?</p>...
6
2009-10-21T00:51:30Z
1,598,204
<pre><code>class myclass(object): def __init__(self): self.__age=None @property def age(self): if self.__age is None: self.__age=21 #This can be a long computation return self.__age </code></pre> <p>Alex mentioned you can use <code>__getattr__</code>, this is how it wor...
13
2009-10-21T01:01:54Z
[ "class", "variables", "python", "precompute" ]
Pythonic way to only do work first time a variable is called
1,598,174
<p>my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value.</p> <p>I don't want to waste time doing this work unless they are actually needed by the user. So is there a clean Pythonic way to implement this use case?</p>...
6
2009-10-21T00:51:30Z
1,598,205
<p>Yes you can use properties, though lazy evaluation is also often accomplished using descriptors, see e.g:</p> <p><a href="http://blog.pythonisito.com/2008/08/lazy-descriptors.html" rel="nofollow">http://blog.pythonisito.com/2008/08/lazy-descriptors.html</a></p>
2
2009-10-21T01:02:05Z
[ "class", "variables", "python", "precompute" ]
Pythonic way to only do work first time a variable is called
1,598,174
<p>my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value.</p> <p>I don't want to waste time doing this work unless they are actually needed by the user. So is there a clean Pythonic way to implement this use case?</p>...
6
2009-10-21T00:51:30Z
1,598,215
<p><code>property</code>, as you've seen, will not let you override it. You need to use a slightly different approach, such as:</p> <pre><code>class myclass(object): @property def age(self): if not hasattr(self, '_age'): self._age = self._big_long_computation() return self._age </code></p...
6
2009-10-21T01:04:03Z
[ "class", "variables", "python", "precompute" ]
Pythonic way to only do work first time a variable is called
1,598,174
<p>my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value.</p> <p>I don't want to waste time doing this work unless they are actually needed by the user. So is there a clean Pythonic way to implement this use case?</p>...
6
2009-10-21T00:51:30Z
1,599,584
<p><a href="http://my.safaribooksonline.com/0596007973/pythoncook2-CHP-20-SECT-4" rel="nofollow">Here</a> is decorator from <a href="http://oreilly.com/catalog/9780596007973/" rel="nofollow">Python Cookbook</a> for this problem:</p> <pre><code>class CachedAttribute(object): ''' Computes attribute value and caches ...
4
2009-10-21T09:05:04Z
[ "class", "variables", "python", "precompute" ]
Specific use case for Django admin
1,598,248
<p>I have a couple special use cases for Django admin, and I'm curious about other peoples' opinions:</p> <ol> <li><p>I'd like to use a customized version the admin to allow users to edit certain objects on the site (customized to look more like the rest of the site). At this point users can only edit objects they own...
2
2009-10-21T01:13:45Z
1,598,288
<p>You are free to do whatever you want. If you want to customize the Django admin, go for it, but you will likely not be as well supported by the mailing list and IRC once you deviate from the typical admin modifications path.</p> <p>While customizing the admin might seem like the easy solution right now, more than ...
4
2009-10-21T01:30:13Z
[ "python", "django", "django-admin", "django-views" ]
Specific use case for Django admin
1,598,248
<p>I have a couple special use cases for Django admin, and I'm curious about other peoples' opinions:</p> <ol> <li><p>I'd like to use a customized version the admin to allow users to edit certain objects on the site (customized to look more like the rest of the site). At this point users can only edit objects they own...
2
2009-10-21T01:13:45Z
1,598,787
<p>I've previously made a django app do precisely this without modifying the actual admin code. Rather by creating a subclass of admin.ModelAdmin with several of it's methods extended with queryset filters. This will display only records that are owned by the user (in this case business is the AUTH_PROFILE_MODEL). Ther...
2
2009-10-21T04:55:46Z
[ "python", "django", "django-admin", "django-views" ]
Specific use case for Django admin
1,598,248
<p>I have a couple special use cases for Django admin, and I'm curious about other peoples' opinions:</p> <ol> <li><p>I'd like to use a customized version the admin to allow users to edit certain objects on the site (customized to look more like the rest of the site). At this point users can only edit objects they own...
2
2009-10-21T01:13:45Z
1,599,907
<p>We limit the Django Admin -- unmodified -- for "back-office" access by our admins and support people. Not by users or customers. Some stylesheet changes to make the colors consistent with the rest of the site, but that's it.</p> <p>For the users (our customers), we provide proper view functions to do the various ...
1
2009-10-21T10:19:55Z
[ "python", "django", "django-admin", "django-views" ]
Adding row to numpy recarray
1,598,251
<p>Is there an easy way to add a record/row to a numpy recarray without creating a new recarray? Let's say I have a recarray that takes 1Gb in memory, I want to be able to add a row to it without having python take up 2Gb of memory temporarily.</p>
6
2009-10-21T01:14:57Z
1,598,295
<p>You can call <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.resize.html#numpy.recarray.resize"><code>yourrecarray.resize</code></a> with a shape which has one more row, then assign to that new row. Of course. <code>numpy</code> <em>might</em> still have to allocate completely new memory...
9
2009-10-21T01:32:54Z
[ "python", "numpy" ]
How to read continous HTTP streaming data in Python?
1,598,331
<p>How to read binary streams from a HTTP streamer server in python. I did a search and someone said urllib2 can do the job but had blocking issues. Someone suggested Twisted framework.</p> <p>My questions are:</p> <ol> <li><p>If it's just a streaming client reads data on background, can I ignore the blocking issues ...
3
2009-10-21T01:46:38Z
1,598,371
<p>To defeat urllib2's intrinsic buffering, you could do:</p> <pre><code>import socket socket._fileobject.default_bufsize = 0 </code></pre> <p>because it's actualy <code>socket._fileobject</code> that buffers underneath. No data will be lost anyway, but with the default buffering (8192 bytes at a time) data may end ...
6
2009-10-21T01:59:14Z
[ "python", "streaming", "client", "stream" ]
Encoding of arguments to subprocess.Popen
1,598,334
<p>I have a Python extension to the Nautilus file browser (AFAIK this runs exclusively on GNU/Linux/Unix/etc environments). I decided to split out an expensive computation and run it as a subprocess, pickle the result and send it back over a pipe. My question concerns the arguments <em>to</em> the script. Since the com...
1
2009-10-21T01:47:31Z
1,598,375
<p>It does not matter: as long as your script knows to expect a utf-8 encoding for the argument, it can decode it properly. utf-8 is the correct choice because it will let you encode ANY Unicode string -- not just those for some languages but not others, as choices such as Latin-1 would entail!</p>
4
2009-10-21T02:01:31Z
[ "python", "localization", "subprocess" ]
Encoding of arguments to subprocess.Popen
1,598,334
<p>I have a Python extension to the Nautilus file browser (AFAIK this runs exclusively on GNU/Linux/Unix/etc environments). I decided to split out an expensive computation and run it as a subprocess, pickle the result and send it back over a pipe. My question concerns the arguments <em>to</em> the script. Since the com...
1
2009-10-21T01:47:31Z
1,599,509
<p>Use <code>sys.getfilesystemencoding()</code> if file names should be readable by user. However this can cause problems when there are characters not supported by the system encoding. To avoid this you can substitute missing characters with some character sequences (e.g. by registering you own error handling function...
2
2009-10-21T08:45:15Z
[ "python", "localization", "subprocess" ]
How to use tabs-as-spaces in Python in Visual Studio 2008?
1,598,445
<p>I have some IronPython scripts that are embedded in a C# project, and it would be convenient to be able to edit them in the VS editor. VS evidently knows about Python because it provides syntax coloring for it. Unfortunately however the editor uses tab characters for indentation, whereas I want spaces. Is there a se...
3
2009-10-21T02:32:57Z
1,598,460
<p>Tools -> Options -> Text Editor -> Choose Language ( you might need to choose All Languages )</p> <p>Click on Tabs and set it how you want it.</p> <p>Edit: Looks like you can add your own file types in the same area and set Tab setting specifically for them.</p>
0
2009-10-21T02:37:46Z
[ "python", "visual-studio", "visual-studio-2008", "ironpython" ]
How to use tabs-as-spaces in Python in Visual Studio 2008?
1,598,445
<p>I have some IronPython scripts that are embedded in a C# project, and it would be convenient to be able to edit them in the VS editor. VS evidently knows about Python because it provides syntax coloring for it. Unfortunately however the editor uses tab characters for indentation, whereas I want spaces. Is there a se...
3
2009-10-21T02:32:57Z
1,598,477
<p>Here is one way to do it, probably not the best. On the Tools -> Text Editor -> File extension part of the Options menu add a .py extension, and set an type of editor. You don't get a python editor type, but you can pick one of the ones you use less often (for me this would be VB.net), and then make sure that the ta...
4
2009-10-21T02:44:17Z
[ "python", "visual-studio", "visual-studio-2008", "ironpython" ]
How to use tabs-as-spaces in Python in Visual Studio 2008?
1,598,445
<p>I have some IronPython scripts that are embedded in a C# project, and it would be convenient to be able to edit them in the VS editor. VS evidently knows about Python because it provides syntax coloring for it. Unfortunately however the editor uses tab characters for indentation, whereas I want spaces. Is there a se...
3
2009-10-21T02:32:57Z
39,940,667
<p>Only the print command is able to read such functions properly in python . so, a tab command can be used along with the print command. To get a space when one uses a tab function.</p>
0
2016-10-09T06:25:05Z
[ "python", "visual-studio", "visual-studio-2008", "ironpython" ]
Rounding decimals with new Python format function
1,598,579
<p>How do I round a decimal to a particular number of decimal places using the Python 3.0 <code>format</code> function?</p>
25
2009-10-21T03:27:10Z
1,598,583
<p>To round x to n decimal places use:</p> <pre><code>"{0:.{1}f}".format(x,n) </code></pre> <p>where 0 and 1 stand for the first and second arguments of the str.format() method, respectively.</p>
1
2009-10-21T03:27:57Z
[ "python", "string", "python-3.x" ]
Rounding decimals with new Python format function
1,598,579
<p>How do I round a decimal to a particular number of decimal places using the Python 3.0 <code>format</code> function?</p>
25
2009-10-21T03:27:10Z
1,598,650
<p>Here's a typical, useful example...:</p> <pre><code>&gt;&gt;&gt; n = 4 &gt;&gt;&gt; p = math.pi &gt;&gt;&gt; '{0:.{1}f}'.format(p, n) '3.1416' </code></pre> <p>the nested <code>{1}</code> takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format -- ...
49
2009-10-21T03:56:46Z
[ "python", "string", "python-3.x" ]
Rounding decimals with new Python format function
1,598,579
<p>How do I round a decimal to a particular number of decimal places using the Python 3.0 <code>format</code> function?</p>
25
2009-10-21T03:27:10Z
1,598,663
<p>In Python 3.x a format string contains replacement fields indicated by braces thus::</p> <pre><code>".... {0: format_spec} ....".format(value) </code></pre> <p>The format spec has the general layout:</p> <pre><code>[[fill]align][sign][pad][width][,][.precision][type] </code></pre> <p>So, for example leaving out ...
6
2009-10-21T04:04:41Z
[ "python", "string", "python-3.x" ]
Rounding decimals with new Python format function
1,598,579
<p>How do I round a decimal to a particular number of decimal places using the Python 3.0 <code>format</code> function?</p>
25
2009-10-21T03:27:10Z
38,629,025
<p>I just found out that it is possible to combine both the <code>{0}</code> and the <code>{digits}</code> notation. This is especially useful when you want to round all variables to a pre-specified number of decimals <em>with 1 declaration</em>:</p> <pre><code>sName = 'Nander' fFirstFloat = 1.12345 fSecondFloat = 2.3...
0
2016-07-28T06:51:37Z
[ "python", "string", "python-3.x" ]
Pure python solution to convert XHTML to PDF
1,598,715
<p>I am after a pure Python solution (for the GAE) to convert webpages to pdf.</p> <p>I had a look at <a href="http://www.reportlab.org/rl%5Ftoolkit.html">reportlab</a> but the documentation focuses on generating pdfs from scratch, rather than converting from HTML.</p> <p>What do you recommend? - <a href="http://www....
16
2009-10-21T04:26:37Z
1,598,943
<p>Have you considered <a href="http://pybrary.net/pyPdf/" rel="nofollow">pyPdf</a>? I doubt it has anywhere like the functional richness you require, but, it IS a start, and is in pure Python. The <a href="http://pybrary.net/pyPdf/pythondoc-pyPdf.pdf.html#pyPdf.pdf.PdfFileWriter-class" rel="nofollow">PdfFileWriter</...
4
2009-10-21T05:51:58Z
[ "python", "google-app-engine", "pdf" ]
Pure python solution to convert XHTML to PDF
1,598,715
<p>I am after a pure Python solution (for the GAE) to convert webpages to pdf.</p> <p>I had a look at <a href="http://www.reportlab.org/rl%5Ftoolkit.html">reportlab</a> but the documentation focuses on generating pdfs from scratch, rather than converting from HTML.</p> <p>What do you recommend? - <a href="http://www....
16
2009-10-21T04:26:37Z
1,599,390
<p>What you're asking for is a pure Python HTML renderer, which is a big task to say the least ('real' renderers like webkit are the product of thousands of hours of work). As far as I'm aware, there aren't any.</p> <p>Instead of looking for an HTML to PDF converter, what I'd suggest is building your report in a forma...
4
2009-10-21T08:10:38Z
[ "python", "google-app-engine", "pdf" ]
Pure python solution to convert XHTML to PDF
1,598,715
<p>I am after a pure Python solution (for the GAE) to convert webpages to pdf.</p> <p>I had a look at <a href="http://www.reportlab.org/rl%5Ftoolkit.html">reportlab</a> but the documentation focuses on generating pdfs from scratch, rather than converting from HTML.</p> <p>What do you recommend? - <a href="http://www....
16
2009-10-21T04:26:37Z
1,605,075
<p><a href="http://www.xhtml2pdf.com/">Pisa</a> claims to support what I want to do:</p> <blockquote> <p>pisa is a html2pdf converter using the ReportLab Toolkit, the HTML5lib and pyPdf. It supports HTML 5 and CSS 2.1 (and some of CSS 3). It is completely written in pure Python so it is platform independen...
8
2009-10-22T04:51:45Z
[ "python", "google-app-engine", "pdf" ]
Python Console Website
1,598,733
<p>I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?</p>
14
2009-10-21T04:38:56Z
1,598,755
<p>This is one I know of:</p> <blockquote> <p><a href="http://shell.appspot.com/" rel="nofollow">http://shell.appspot.com/</a></p> </blockquote> <p>There's also Lord of the REPL's:</p> <blockquote> <p><a href="http://lotrepls.appspot.com/" rel="nofollow">http://lotrepls.appspot.com/</a></p> </blockquote> <p>Pyt...
12
2009-10-21T04:44:44Z
[ "python" ]
Python Console Website
1,598,733
<p>I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?</p>
14
2009-10-21T04:38:56Z
1,598,764
<p>While not really a "console", <a href="http://www.skulpt.org/">skulpt.org</a> runs python code client-side with no plugins or anything, which makes it a lot faster than a server-side prompt. For server side and a more traditional shell I found this: <a href="http://shell.appspot.com/">http://shell.appspot.com/</a>.<...
11
2009-10-21T04:46:53Z
[ "python" ]
Python Console Website
1,598,733
<p>I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?</p>
14
2009-10-21T04:38:56Z
1,599,340
<p>IronPython (using Silverlight or Moonlight 2): <a href="http://www.trypython.org/" rel="nofollow">http://www.trypython.org/</a></p>
4
2009-10-21T07:55:12Z
[ "python" ]
Python Console Website
1,598,733
<p>I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?</p>
14
2009-10-21T04:38:56Z
1,599,804
<p>I'm just find this one <a href="http://con.appspot.com/console/" rel="nofollow">http://con.appspot.com/console/</a></p>
3
2009-10-21T09:55:53Z
[ "python" ]
Python Console Website
1,598,733
<p>I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?</p>
14
2009-10-21T04:38:56Z
5,280,029
<p>This one is very interesting, it has an interactive shell AND a script editing area:</p> <blockquote> <p><a href="http://py-ide-online.appspot.com/" rel="nofollow">Py I/O</a></p> </blockquote>
4
2011-03-12T00:54:31Z
[ "python" ]
Python Console Website
1,598,733
<p>I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?</p>
14
2009-10-21T04:38:56Z
5,602,707
<p>An online python editor: <a href="http://doc.pyschools.com/console" rel="nofollow">http://doc.pyschools.com/console</a>.</p>
2
2011-04-09T03:37:49Z
[ "python" ]
Elegant setup of Python logging in Django
1,598,823
<p>I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple:</p> <ul> <li>Different log handlers for different events - that is, I want to be able to log to different files</li> <li>Easy access to loggers in my modules. The module should be able to find i...
74
2009-10-21T05:07:01Z
1,598,894
<p>I am currently using a logging system, which I created myself. It uses CSV format for logging.</p> <p><a href="http://bitbucket.org/oduvan/django-csvlog/" rel="nofollow">django-csvlog</a></p> <p>This project still doesn't have full documentation, but I am working on it.</p>
6
2009-10-21T05:33:39Z
[ "python", "django", "logging" ]
Elegant setup of Python logging in Django
1,598,823
<p>I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple:</p> <ul> <li>Different log handlers for different events - that is, I want to be able to log to different files</li> <li>Easy access to loggers in my modules. The module should be able to find i...
74
2009-10-21T05:07:01Z
1,598,979
<p>The best way I've found so far is to initialize logging setup in settings.py - nowhere else. You can either use a configuration file or do it programmatically step-by-step - it just depends on your requirements. The key thing is that I usually add the handlers I want to the root logger, using levels and sometimes lo...
44
2009-10-21T06:03:38Z
[ "python", "django", "logging" ]
Elegant setup of Python logging in Django
1,598,823
<p>I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple:</p> <ul> <li>Different log handlers for different events - that is, I want to be able to log to different files</li> <li>Easy access to loggers in my modules. The module should be able to find i...
74
2009-10-21T05:07:01Z
1,599,881
<p>We initialize logging in the top-level <code>urls.py</code> by using a <code>logging.ini</code> file.</p> <p>The location of the <code>logging.ini</code> is provided in <code>settings.py</code>, but that's all.</p> <p>Each module then does</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> <p>To d...
6
2009-10-21T10:12:47Z
[ "python", "django", "logging" ]
Elegant setup of Python logging in Django
1,598,823
<p>I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple:</p> <ul> <li>Different log handlers for different events - that is, I want to be able to log to different files</li> <li>Easy access to loggers in my modules. The module should be able to find i...
74
2009-10-21T05:07:01Z
5,806,903
<p>I know this is a solved answer already, but as per django >= 1.3 there's a new logging setting.</p> <p>Moving from old to new is not automatic, so I thought i'll write it down here.</p> <p>And of course checkout <a href="http://docs.djangoproject.com/en/dev/topics/logging" rel="nofollow" title="Django Logging Doc"...
102
2011-04-27T15:50:04Z
[ "python", "django", "logging" ]
Atomic increment of a counter in django
1,598,932
<p>I'm trying to atomically increment a simple counter in Django. My code looks like this:</p> <pre><code>from models import Counter from django.db import transaction @transaction.commit_on_success def increment_counter(name): counter = Counter.objects.get_or_create(name = name)[0] counter.count += 1 coun...
33
2009-10-21T05:49:08Z
1,599,090
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#query-expressions">New in Django 1.1</a></p> <pre><code>Counter.objects.get_or_create(name = name) Counter.objects.filter(name = name).update(count = F('count')+1) </code></pre> <p>or using <a href="https://docs.djangoproject.com/en/dev/ref/models/ex...
51
2009-10-21T06:43:45Z
[ "python", "django", "transactions", "race-condition" ]
Atomic increment of a counter in django
1,598,932
<p>I'm trying to atomically increment a simple counter in Django. My code looks like this:</p> <pre><code>from models import Counter from django.db import transaction @transaction.commit_on_success def increment_counter(name): counter = Counter.objects.get_or_create(name = name)[0] counter.count += 1 coun...
33
2009-10-21T05:49:08Z
3,572,943
<p>Or if you just want a counter and not a persistent object you can use itertools counter which is implemented in C. The GIL will provide the safety needed.</p> <p>--Sai</p>
-4
2010-08-26T07:33:45Z
[ "python", "django", "transactions", "race-condition" ]
Atomic increment of a counter in django
1,598,932
<p>I'm trying to atomically increment a simple counter in Django. My code looks like this:</p> <pre><code>from models import Counter from django.db import transaction @transaction.commit_on_success def increment_counter(name): counter = Counter.objects.get_or_create(name = name)[0] counter.count += 1 coun...
33
2009-10-21T05:49:08Z
8,901,941
<p>In Django 1.4 there is <a href="https://docs.djangoproject.com/en/dev/releases/1.4/#select-for-update-support">support for SELECT ... FOR UPDATE</a> clauses, using database locks to make sure no data is accesses concurrently by mistake. </p>
11
2012-01-17T21:26:25Z
[ "python", "django", "transactions", "race-condition" ]
Atomic increment of a counter in django
1,598,932
<p>I'm trying to atomically increment a simple counter in Django. My code looks like this:</p> <pre><code>from models import Counter from django.db import transaction @transaction.commit_on_success def increment_counter(name): counter = Counter.objects.get_or_create(name = name)[0] counter.count += 1 coun...
33
2009-10-21T05:49:08Z
18,937,431
<p>Keeping it simple and building on @Oduvan's answer:</p> <pre><code>counter, created = Counter.objects.get_or_create(name = name, defaults={'count':1}) if not created: counter.count = F('count') +1 counter.save() </code></pre> <p>The advantage here is that i...
3
2013-09-21T20:44:27Z
[ "python", "django", "transactions", "race-condition" ]
Atomic increment of a counter in django
1,598,932
<p>I'm trying to atomically increment a simple counter in Django. My code looks like this:</p> <pre><code>from models import Counter from django.db import transaction @transaction.commit_on_success def increment_counter(name): counter = Counter.objects.get_or_create(name = name)[0] counter.count += 1 coun...
33
2009-10-21T05:49:08Z
28,228,959
<p>Django 1.7</p> <pre><code>from django.db.models import F counter, created = Counter.objects.get_or_create(name = name) counter.count = F('count') +1 counter.save() </code></pre>
4
2015-01-30T03:53:05Z
[ "python", "django", "transactions", "race-condition" ]
How can I get an accurate UTC time with Python?
1,599,060
<p>I wrote a desktop application and was using <code>datetime.datetime.utcnow()</code> for timestamping, however I've recently noticed that some people using the application get wildly different results than I do when we run the program at the same time. Is there any way to get the UTC time locally without using urlli...
8
2009-10-21T06:34:31Z
1,599,094
<p>Python depends on the underlying operating system to provide an accurate time-of-day clock. If it isn't doing that, you don't have much choice other than to bypass the o/s. There's a pure-Python implementation of an NTP client <a href="http://pypi.python.org/pypi/ntplib/" rel="nofollow">here</a>. A very simple-mi...
19
2009-10-21T06:45:09Z
[ "python", "datetime", "timestamp", "utc" ]
How can I get an accurate UTC time with Python?
1,599,060
<p>I wrote a desktop application and was using <code>datetime.datetime.utcnow()</code> for timestamping, however I've recently noticed that some people using the application get wildly different results than I do when we run the program at the same time. Is there any way to get the UTC time locally without using urlli...
8
2009-10-21T06:34:31Z
1,715,510
<p>Actually, ntplib computes this offset accounting for round-trip delay. It's available through the "offset" attribute of the NTP response. Therefore the result should not very wildly.</p>
7
2009-11-11T14:29:05Z
[ "python", "datetime", "timestamp", "utc" ]
Python (Django) Shopify API Client -- For a Beginner
1,599,067
<p>I have a requirement to build a client for Shopify's API, building it in Python &amp; Django.</p> <p>I've never done it before and so I'm wondering if someone might advise on a good starting point for the kinds of patterns and techniques needed to get a job like this done.</p> <p>Here's a link to the <a href="http...
4
2009-10-21T06:36:13Z
1,600,386
<p>I think you can find some inspiration by taking a look at this:</p> <p><a href="http://bitbucket.org/jespern/django-piston/wiki/Home" rel="nofollow">http://bitbucket.org/jespern/django-piston/wiki/Home</a></p> <p>Although it is directly opposite what you want to do (Piston is for building APIs, and what you want i...
0
2009-10-21T12:00:18Z
[ "python", "django", "shopify" ]
Python (Django) Shopify API Client -- For a Beginner
1,599,067
<p>I have a requirement to build a client for Shopify's API, building it in Python &amp; Django.</p> <p>I've never done it before and so I'm wondering if someone might advise on a good starting point for the kinds of patterns and techniques needed to get a job like this done.</p> <p>Here's a link to the <a href="http...
4
2009-10-21T06:36:13Z
1,603,971
<p>Your question is somewhat open-ended, but if you're new to Python or API programming, then you should get a feel for how to do network programming in Python, using either the urllib2 or httplib modules that come with more recent versions of Python. Learn how to initiate a request for a page and read the response int...
2
2009-10-21T22:13:23Z
[ "python", "django", "shopify" ]
Python (Django) Shopify API Client -- For a Beginner
1,599,067
<p>I have a requirement to build a client for Shopify's API, building it in Python &amp; Django.</p> <p>I've never done it before and so I'm wondering if someone might advise on a good starting point for the kinds of patterns and techniques needed to get a job like this done.</p> <p>Here's a link to the <a href="http...
4
2009-10-21T06:36:13Z
6,636,469
<p>Shopify has now released a Python API client: <a href="https://github.com/Shopify/shopify_python_api" rel="nofollow">https://github.com/Shopify/shopify_python_api</a></p>
1
2011-07-09T17:57:50Z
[ "python", "django", "shopify" ]
Python (Django) Shopify API Client -- For a Beginner
1,599,067
<p>I have a requirement to build a client for Shopify's API, building it in Python &amp; Django.</p> <p>I've never done it before and so I'm wondering if someone might advise on a good starting point for the kinds of patterns and techniques needed to get a job like this done.</p> <p>Here's a link to the <a href="http...
4
2009-10-21T06:36:13Z
14,005,547
<p>I have been working on a project for the last few months using Python and Django integrating with Shopify, built on Google App Engine. </p> <p>Shopify has a valuable wiki resource, <a href="http://wiki.shopify.com/Using_the_shopify_python_api" rel="nofollow">http://wiki.shopify.com/Using_the_shopify_python_api</a>...
1
2012-12-22T18:47:16Z
[ "python", "django", "shopify" ]
Asynchronous Stream Processing in Python
1,599,540
<p>Let's start with a simple example. A HTTP data stream comes in the following format:</p> <pre><code>MESSAGE_LENGTH, 2 bytes MESSAGE_BODY, REPEAT... </code></pre> <p>Currently, I use urllib2 to retrieve and process streaming data as below:</p> <pre><code>length = response.read(2) while True: data = response.r...
3
2009-10-21T08:54:21Z
1,599,681
<p>Yes, of course, and there are many different techniques to do so. You'll typically end up having a set of processes that only retrieves data, and increase the number of processes in that pool until you run out of bandwith, more or less. Those processes store the data somewhere, and then you have other processes or t...
0
2009-10-21T09:22:56Z
[ "python", "streaming", "stream" ]
Asynchronous Stream Processing in Python
1,599,540
<p>Let's start with a simple example. A HTTP data stream comes in the following format:</p> <pre><code>MESSAGE_LENGTH, 2 bytes MESSAGE_BODY, REPEAT... </code></pre> <p>Currently, I use urllib2 to retrieve and process streaming data as below:</p> <pre><code>length = response.read(2) while True: data = response.r...
3
2009-10-21T08:54:21Z
1,602,013
<p>Yes, can be done and is not that hard, if your format is essentially fixed.</p> <p>I used it with httplib in Python 2.2.3 and found it had some abysmal performance in the way we hacked it together (basically monkey patching a select() based socket layer into httplib).</p> <p>The trick is to get the socket and do t...
1
2009-10-21T16:33:54Z
[ "python", "streaming", "stream" ]
Is there easy way in python to extrapolate data points to the future?
1,599,754
<p>I have a simple numpy array, for every date there is a data point. Something like this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; x = np.array( [(date(2008,3,5), 4800 ), (date(2008,3,15), 4000 ), (date(2008,3, 20), 3500 ...
8
2009-10-21T09:42:52Z
1,599,772
<p>The mathematical models are the way to go in this case. For instance, if you have only three data points, you can have absolutely no indication on how the trend will unfold (could be any of two parabola.)</p> <p>Get some statistics courses and try to implement the algorithms. Try <a href="http://en.wikibooks.org/wi...
3
2009-10-21T09:47:42Z
[ "python", "numpy", "interpolation", "spline", "burndowncharts" ]
Is there easy way in python to extrapolate data points to the future?
1,599,754
<p>I have a simple numpy array, for every date there is a data point. Something like this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; x = np.array( [(date(2008,3,5), 4800 ), (date(2008,3,15), 4000 ), (date(2008,3, 20), 3500 ...
8
2009-10-21T09:42:52Z
1,600,008
<p>You have to swpecify over which function you need extrapolation. Than you can use regression <a href="http://en.wikipedia.org/wiki/Regression%5Fanalysis" rel="nofollow">http://en.wikipedia.org/wiki/Regression%5Fanalysis</a> to find paratmeters of function. And extrapolate this in future.</p> <p>For instance: trans...
1
2009-10-21T10:39:00Z
[ "python", "numpy", "interpolation", "spline", "burndowncharts" ]
Is there easy way in python to extrapolate data points to the future?
1,599,754
<p>I have a simple numpy array, for every date there is a data point. Something like this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; x = np.array( [(date(2008,3,5), 4800 ), (date(2008,3,15), 4000 ), (date(2008,3, 20), 3500 ...
8
2009-10-21T09:42:52Z
1,600,707
<p>A simple way of doing extrapolations is to use interpolating polynomials or splines: there are many routines for this in <a href="http://docs.scipy.org/doc/scipy/reference/interpolate.html" rel="nofollow">scipy.interpolate</a>, and there are quite easy to use (just give the (x, y) points, and you get a function [a c...
4
2009-10-21T13:04:11Z
[ "python", "numpy", "interpolation", "spline", "burndowncharts" ]
Is there easy way in python to extrapolate data points to the future?
1,599,754
<p>I have a simple numpy array, for every date there is a data point. Something like this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; from datetime import date &gt;&gt;&gt; x = np.array( [(date(2008,3,5), 4800 ), (date(2008,3,15), 4000 ), (date(2008,3, 20), 3500 ...
8
2009-10-21T09:42:52Z
1,614,148
<p>It's all too easy for extrapolation to generate garbage; try this. Many different extrapolations are of course possible; some produce obvious garbage, some non-obvious garbage, many are ill-defined.</p> <p><img src="http://i39.tinypic.com/am62wp.png" alt="alt text"></p> <pre><code>""" extrapolate y,m,d data with ...
15
2009-10-23T15:15:12Z
[ "python", "numpy", "interpolation", "spline", "burndowncharts" ]
Daemon dies unexpectedly
1,599,798
<p>I have a python script, which I daemonise using this code</p> <pre><code> def daemonise(): from os import fork, setsid, umask, dup2 from sys import stdin, stdout, stderr if fork(): exit(0) umask(0) setsid() if fork(): exit(0) ...
1
2009-10-21T09:53:35Z
1,599,964
<p>What I've used in my clients is <a href="http://cr.yp.to/daemontools.html" rel="nofollow">daemontools</a>. It is a proven, well tested tool to run anything daemonized.</p> <p>You just write your application without any daemonization, to run on foreground; Then create a daemontools service folder for it, and it will...
0
2009-10-21T10:30:29Z
[ "python", "daemon" ]
Daemon dies unexpectedly
1,599,798
<p>I have a python script, which I daemonise using this code</p> <pre><code> def daemonise(): from os import fork, setsid, umask, dup2 from sys import stdin, stdout, stderr if fork(): exit(0) umask(0) setsid() if fork(): exit(0) ...
1
2009-10-21T09:53:35Z
1,602,145
<p>Why are you silently swallowing all exceptions? Try to see what exceptions are being caught by this:</p> <pre><code>while True: try: funny_code() sleep(10) except BaseException, e: print e.__class__, e.message pass </code></pre> <p>Something unexpected might be happening whi...
1
2009-10-21T16:55:25Z
[ "python", "daemon" ]
Daemon dies unexpectedly
1,599,798
<p>I have a python script, which I daemonise using this code</p> <pre><code> def daemonise(): from os import fork, setsid, umask, dup2 from sys import stdin, stdout, stderr if fork(): exit(0) umask(0) setsid() if fork(): exit(0) ...
1
2009-10-21T09:53:35Z
1,613,834
<p>You really should use <a href="http://pypi.python.org/pypi/python-daemon/1.5.1" rel="nofollow">python-daemon</a> for this which is a library that implements <a href="http://www.python.org/dev/peps/pep-3143/" rel="nofollow">PEP 3141</a> for a standard daemon process library. This way you will ensure that your applic...
3
2009-10-23T14:27:30Z
[ "python", "daemon" ]
Configuring Python's default exception handling
1,599,962
<p>For an uncaught exception, Python by default prints a stack trace, the exception itself, and terminates. Is anybody aware of a way to tailor this behaviour on the program level (other than establishing my own global, catch-all exception handler), so that the stack trace is omitted? I would like to toggle in my app w...
14
2009-10-21T10:29:55Z
1,599,973
<p>You are looking for sys.excepthook:</p> <p><strong>sys.excepthook(type, value, traceback)</strong> </p> <p>This function prints out a given traceback and exception to sys.stderr.</p> <p>When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, except...
20
2009-10-21T10:31:41Z
[ "python" ]
Using south to refactor a Django model with inheritance
1,600,129
<p>I was wondering if the following migration is possible with Django <a href="http://south.aeracode.org/">south</a> and still retain data.</p> <h2>Before:</h2> <p>I currently have two apps, one called tv, one called movies, each with a VideoFile model (simplified here):</p> <p><strong>tv/models.py:</strong></p> <p...
32
2009-10-21T11:05:57Z
1,600,165
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes" rel="nofollow">Abstract Model</a></p> <pre><code>class VideoFile(models.Model): name = models.CharField(max_length=1024, blank=True) size = models.IntegerField(blank=True, null=True) ctime = models.DateTimeField(blank...
3
2009-10-21T11:12:57Z
[ "python", "django", "migration", "django-south" ]
Using south to refactor a Django model with inheritance
1,600,129
<p>I was wondering if the following migration is possible with Django <a href="http://south.aeracode.org/">south</a> and still retain data.</p> <h2>Before:</h2> <p>I currently have two apps, one called tv, one called movies, each with a VideoFile model (simplified here):</p> <p><strong>tv/models.py:</strong></p> <p...
32
2009-10-21T11:05:57Z
1,600,832
<p>I did a similar migration and I chose to do it in multiple steps. In addition to creating the multiple migrations, I also created the backward migration to provide a fallback if things went wrong. Then, I grabbed some test data and migrated it forward and backwards until I was sure it was coming out correctly when...
1
2009-10-21T13:25:09Z
[ "python", "django", "migration", "django-south" ]
Using south to refactor a Django model with inheritance
1,600,129
<p>I was wondering if the following migration is possible with Django <a href="http://south.aeracode.org/">south</a> and still retain data.</p> <h2>Before:</h2> <p>I currently have two apps, one called tv, one called movies, each with a VideoFile model (simplified here):</p> <p><strong>tv/models.py:</strong></p> <p...
32
2009-10-21T11:05:57Z
1,603,570
<p><strong>Check out response below by Paul for some notes on compatibility with newer versions of Django/South.</strong></p> <hr> <p>This seemed like an interesting problem, and I'm becoming a big fan of South, so I decided to look into this a bit. I built a test project on the abstract of what you've described abo...
49
2009-10-21T20:56:57Z
[ "python", "django", "migration", "django-south" ]
Using south to refactor a Django model with inheritance
1,600,129
<p>I was wondering if the following migration is possible with Django <a href="http://south.aeracode.org/">south</a> and still retain data.</p> <h2>Before:</h2> <p>I currently have two apps, one called tv, one called movies, each with a VideoFile model (simplified here):</p> <p><strong>tv/models.py:</strong></p> <p...
32
2009-10-21T11:05:57Z
4,805,806
<p>I did try to walk through the solution outlined by T Stone and while I think it's a superb starter and explains how things should be done I ran into a few problems. </p> <p>I think mostly you <strong>don't</strong> need to create the table entry for the parent class anymore, i.e. you don't need</p> <pre><code>new_...
9
2011-01-26T14:42:52Z
[ "python", "django", "migration", "django-south" ]
Using a Python Dictionary as a Key (Non-nested)
1,600,591
<p>Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? </p> <p>The general problem with more complicated non-hashable objects and my specific use case has been <a href="http://stackoverflow.com/questions/1611797/using-non-hashable...
10
2009-10-21T12:47:53Z
1,600,700
<p>I don't see why you'd ever want to do this, but if you really really do need to, you could try pickling the dictionary:</p> <pre><code>mydict = {"a":1, "b":{"c":10}} import pickle key = pickle.dumps(mydict) d[key] = value </code></pre>
1
2009-10-21T13:03:12Z
[ "python", "data-structures", "dictionary" ]
Using a Python Dictionary as a Key (Non-nested)
1,600,591
<p>Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? </p> <p>The general problem with more complicated non-hashable objects and my specific use case has been <a href="http://stackoverflow.com/questions/1611797/using-non-hashable...
10
2009-10-21T12:47:53Z
1,600,717
<p>I don't know whether I understand your question correctly, but i'll give it a try</p> <pre><code> d[repr(a)]=value </code></pre> <p>You can interate over the dictionary like this</p> <pre><code>for el1 in d: for el2 in eval(el1): print el2,eval(el1)[el2] </code></pre>
-1
2009-10-21T13:06:43Z
[ "python", "data-structures", "dictionary" ]
Using a Python Dictionary as a Key (Non-nested)
1,600,591
<p>Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? </p> <p>The general problem with more complicated non-hashable objects and my specific use case has been <a href="http://stackoverflow.com/questions/1611797/using-non-hashable...
10
2009-10-21T12:47:53Z
1,600,806
<p>If you have a really immutable dictionary (although it isn't clear to me why you don't just use a list of pairs: e.g. <code>[('content-type', 'text/plain'), ('host', 'example.com')]</code>), then you may convert your <code>dict</code> into:</p> <ol> <li><p>A tuple of pairs. You've already done that in your question...
30
2009-10-21T13:21:19Z
[ "python", "data-structures", "dictionary" ]
Using a Python Dictionary as a Key (Non-nested)
1,600,591
<p>Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? </p> <p>The general problem with more complicated non-hashable objects and my specific use case has been <a href="http://stackoverflow.com/questions/1611797/using-non-hashable...
10
2009-10-21T12:47:53Z
1,600,851
<p>One way to do this would be to subclass the dict and provide a hash method. ie:</p> <pre><code>class HashableDict(dict): def __hash__(self): return hash(tuple(sorted(self.iteritems()))) &gt;&gt;&gt; d = HashableDict(a=1, b=2) &gt;&gt;&gt; d2 = { d : "foo"} &gt;&gt;&gt; d2[HashableDict(a=1, b=2)] "foo"...
3
2009-10-21T13:28:25Z
[ "python", "data-structures", "dictionary" ]
Using a Python Dictionary as a Key (Non-nested)
1,600,591
<p>Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? </p> <p>The general problem with more complicated non-hashable objects and my specific use case has been <a href="http://stackoverflow.com/questions/1611797/using-non-hashable...
10
2009-10-21T12:47:53Z
1,600,859
<p>If I needed to use dictionaries as keys, I would flatten the dictionary into a tuple of tuples.</p> <p>You might find this SO question useful: <a href="http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python">http://stackoverflow.com/questions/635483/what-is-the-bes...
8
2009-10-21T13:29:38Z
[ "python", "data-structures", "dictionary" ]
Using a Python Dictionary as a Key (Non-nested)
1,600,591
<p>Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? </p> <p>The general problem with more complicated non-hashable objects and my specific use case has been <a href="http://stackoverflow.com/questions/1611797/using-non-hashable...
10
2009-10-21T12:47:53Z
1,600,916
<p>Hmm, isn't your use case just memoizing function calls? Using a decorator, you will have easy support for arbitrary functions. And yes, they often pickle the arguments, and using circular reasoning, this works for non-standard types as long as they can be pickled.</p> <p>See e.g. <a href="http://www.finalcog.com/py...
3
2009-10-21T13:42:27Z
[ "python", "data-structures", "dictionary" ]
Using a Python Dictionary as a Key (Non-nested)
1,600,591
<p>Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? </p> <p>The general problem with more complicated non-hashable objects and my specific use case has been <a href="http://stackoverflow.com/questions/1611797/using-non-hashable...
10
2009-10-21T12:47:53Z
1,601,087
<p>To turn a someDictionary into a key, do this</p> <pre><code>key = tuple(sorted(someDictionary .items()) </code></pre> <p>You can easily reverse this with <code>dict( key )</code></p>
2
2009-10-21T14:13:16Z
[ "python", "data-structures", "dictionary" ]
setTrace() in Python
1,600,726
<p>Is there a way to use the setTrace() function in a script that has no method definitions? i.e.</p> <pre><code>for i in range(1, 100): print i def traceit(frame, event, arg): if event == "line": lineno = frame.f_lineno print "line", lineno return traceit sys.settrace(traceit) </code></pre>...
5
2009-10-21T13:07:44Z
1,600,902
<p>settrace() is really only intended for implementing debuggers. If you are using it to debug this program, you may be better off using PDB</p> <p>According to the documentation, settrace() will not do what you want.</p> <p>If you really want to do this line by line tracing, have a look at the compiler package which...
2
2009-10-21T13:39:15Z
[ "python", "trace" ]
setTrace() in Python
1,600,726
<p>Is there a way to use the setTrace() function in a script that has no method definitions? i.e.</p> <pre><code>for i in range(1, 100): print i def traceit(frame, event, arg): if event == "line": lineno = frame.f_lineno print "line", lineno return traceit sys.settrace(traceit) </code></pre>...
5
2009-10-21T13:07:44Z
1,600,992
<p>I only use one simple syntax line to rule them all:</p> <pre><code>import pdb; pdb.set_trace() </code></pre> <p>Put it wherever you want to break execution and start debugging. Use pdb commands (n for next, l for list, etc).</p> <p>Cheers,</p> <p>H.</p>
2
2009-10-21T13:57:24Z
[ "python", "trace" ]
setTrace() in Python (redux)
1,601,217
<p>Apologies for reposting but I had to edit this question when I got to work and realized I needed to have an account to do so. So here it goes again (with a little more context).</p> <p>I'm trying to time how long a script takes to execute, and I am thinking of doing that by checking the elapsed time after every lin...
1
2009-10-21T14:31:24Z
1,601,276
<p>No, as <a href="http://docs.python.org/library/sys.html?highlight=settrace#sys.settrace" rel="nofollow">the docs</a> say, "The trace function is invoked (with event set to 'call') whenever a new local scope is entered" -- if you never enter a local scope (and only execute in global scope), the trace function will ne...
2
2009-10-21T14:39:16Z
[ "python", "trace" ]
How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
1,601,269
<p>Have a look at this Python code:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] </code></pre> <p>Notice how modifying one element of <code>c</code> modifies that every...
5
2009-10-21T14:38:27Z
1,601,298
<p>Use <code>[:]</code>:</p> <pre><code>&gt;&gt;&gt; a = [1, 2] &gt;&gt;&gt; b = a[:] &gt;&gt;&gt; b.append(9) &gt;&gt;&gt; a [1, 2] </code></pre> <p>Alteratively, use <a href="http://docs.python.org/library/copy.html" rel="nofollow"><code>copy</code> or <code>deepcopy</code></a>:</p> <pre><code>&gt;&gt;&gt; import ...
4
2009-10-21T14:41:57Z
[ "python", "list", "copy" ]