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
How can I tokenize this with a regex?
1,389,062
<p>Suppose I have strings like the following :</p> <pre><code>OneTwo ThreeFour AnotherString DVDPlayer CDPlayer </code></pre> <p>I know how to tokenize the camel-case ones, except the "DVDPlayer" and "CDPlayer". I know I could tokenize them manually, but maybe you can show me a regex that can handle all the cases?</p> <p>EDIT: the expected tokens are :</p> <pre><code>OneTwo -&gt; One Two ... CDPlayer -&gt; CD Player DVDPlayer -&gt; DVD Player </code></pre>
1
2009-09-07T12:02:18Z
1,389,118
<p>Try this regular expression:</p> <pre><code>[A-Z](?:[a-z]+|[A-Z]*?(?=[A-Z][a-z]|\b)) </code></pre>
4
2009-09-07T12:14:21Z
[ "python", "ruby", "regex", "tokenize", "lexical-analysis" ]
How can I tokenize this with a regex?
1,389,062
<p>Suppose I have strings like the following :</p> <pre><code>OneTwo ThreeFour AnotherString DVDPlayer CDPlayer </code></pre> <p>I know how to tokenize the camel-case ones, except the "DVDPlayer" and "CDPlayer". I know I could tokenize them manually, but maybe you can show me a regex that can handle all the cases?</p> <p>EDIT: the expected tokens are :</p> <pre><code>OneTwo -&gt; One Two ... CDPlayer -&gt; CD Player DVDPlayer -&gt; DVD Player </code></pre>
1
2009-09-07T12:02:18Z
1,389,124
<p>The regex</p> <pre><code>([A-Z]+[a-z]*)([A-Z][a-z]*) </code></pre> <p>would do what you want assuming that all your strings are 2 words long and the second word is not like DVD.</p> <p>I.e. it would work for your examples but maybe not for what you are actually trying to do.</p>
1
2009-09-07T12:15:36Z
[ "python", "ruby", "regex", "tokenize", "lexical-analysis" ]
How can I tokenize this with a regex?
1,389,062
<p>Suppose I have strings like the following :</p> <pre><code>OneTwo ThreeFour AnotherString DVDPlayer CDPlayer </code></pre> <p>I know how to tokenize the camel-case ones, except the "DVDPlayer" and "CDPlayer". I know I could tokenize them manually, but maybe you can show me a regex that can handle all the cases?</p> <p>EDIT: the expected tokens are :</p> <pre><code>OneTwo -&gt; One Two ... CDPlayer -&gt; CD Player DVDPlayer -&gt; DVD Player </code></pre>
1
2009-09-07T12:02:18Z
1,389,146
<p>Here's my attempt: </p> <pre><code>([A-Z][a-z]+)|([A-Z]+(?=[A-Z][a-z]+)) </code></pre>
1
2009-09-07T12:20:22Z
[ "python", "ruby", "regex", "tokenize", "lexical-analysis" ]
how to create an excel file in google app engine (python)?
1,389,076
<p>I want to create an excel sheet using Google App Engine in python.</p> <p>my application datastore contains the data of company details like </p> <pre><code>name, business, website,..etc.,. </code></pre> <p>i want to put those details in an excel sheet, is it possible to generate excel file in Google App Engine using python.</p> <p>can anybody help me!</p>
4
2009-09-07T12:05:48Z
1,389,129
<p>You can use <a href="http://sourceforge.net/projects/pyexcelerator/" rel="nofollow">pyexcelerator</a> to generate excel files </p>
0
2009-09-07T12:16:47Z
[ "python", "google-app-engine" ]
how to create an excel file in google app engine (python)?
1,389,076
<p>I want to create an excel sheet using Google App Engine in python.</p> <p>my application datastore contains the data of company details like </p> <pre><code>name, business, website,..etc.,. </code></pre> <p>i want to put those details in an excel sheet, is it possible to generate excel file in Google App Engine using python.</p> <p>can anybody help me!</p>
4
2009-09-07T12:05:48Z
1,391,790
<p>You can't write to the filesystem in App Engine, so pyexcelerator's save function obviously won't work. </p> <p>You'll want to take the data pyexcelerator's generating, and instead of writing it to a file either save it as a blob in the Datastore or return it directly to the user's browser.</p>
4
2009-09-08T03:20:03Z
[ "python", "google-app-engine" ]
how to create an excel file in google app engine (python)?
1,389,076
<p>I want to create an excel sheet using Google App Engine in python.</p> <p>my application datastore contains the data of company details like </p> <pre><code>name, business, website,..etc.,. </code></pre> <p>i want to put those details in an excel sheet, is it possible to generate excel file in Google App Engine using python.</p> <p>can anybody help me!</p>
4
2009-09-07T12:05:48Z
1,394,024
<p>You may like to consider <code>xlwt</code>, a fork of <code>pyExcelerator</code> with bug-fixes and on-going enhancements. See <code>http://pypi.python.org/pypi/xlwt</code> ... disclosure: I'm the maintainer of xlwt.</p>
4
2009-09-08T13:25:05Z
[ "python", "google-app-engine" ]
how to create an excel file in google app engine (python)?
1,389,076
<p>I want to create an excel sheet using Google App Engine in python.</p> <p>my application datastore contains the data of company details like </p> <pre><code>name, business, website,..etc.,. </code></pre> <p>i want to put those details in an excel sheet, is it possible to generate excel file in Google App Engine using python.</p> <p>can anybody help me!</p>
4
2009-09-07T12:05:48Z
7,239,490
<p>Another simple suggestion is to create tab seperated files (.tsv) or comma seperated files (.csv), which is very easy to do. Just use "\t".join(row) and save as .xls/.tsv or ",".join(row) and save as .csv. Excel will know how to handle this. I suggest tab seperated files since tab is a rare character and using it probably means you won't need escaping in your code.</p> <p>Creating real excel files is an overhead that I think you should avoid.</p>
0
2011-08-30T06:32:34Z
[ "python", "google-app-engine" ]
how to add json library
1,389,141
<p>i am new to python, on my Mac, when i issue command</p> <pre><code>User:ihasfriendz user$ python main.py Traceback (most recent call last): File "main.py", line 2, in &lt;module&gt; import json ImportError: No module named json </code></pre> <p>I get error on json. how to add this library? i'm using 2.5 (the default came with leopard)</p>
9
2009-09-07T12:19:02Z
1,389,191
<p>AFAIK the json module was added in version 2.6, see <a href="http://docs.python.org/library/json.html" rel="nofollow">here</a>. I'm guessing you can update your python installation to the latest stable 2.6 from <a href="http://www.python.org/download/" rel="nofollow">this page</a>.</p>
4
2009-09-07T12:31:54Z
[ "python", "json", "osx", "python-2.5" ]
how to add json library
1,389,141
<p>i am new to python, on my Mac, when i issue command</p> <pre><code>User:ihasfriendz user$ python main.py Traceback (most recent call last): File "main.py", line 2, in &lt;module&gt; import json ImportError: No module named json </code></pre> <p>I get error on json. how to add this library? i'm using 2.5 (the default came with leopard)</p>
9
2009-09-07T12:19:02Z
1,389,203
<p>You can also install json-py from here <a href="http://sourceforge.net/projects/json-py/" rel="nofollow">http://sourceforge.net/projects/json-py/</a></p>
2
2009-09-07T12:34:40Z
[ "python", "json", "osx", "python-2.5" ]
how to add json library
1,389,141
<p>i am new to python, on my Mac, when i issue command</p> <pre><code>User:ihasfriendz user$ python main.py Traceback (most recent call last): File "main.py", line 2, in &lt;module&gt; import json ImportError: No module named json </code></pre> <p>I get error on json. how to add this library? i'm using 2.5 (the default came with leopard)</p>
9
2009-09-07T12:19:02Z
1,389,269
<p>You can also install simplejson.</p> <p>If you have pip (see <a href="https://pypi.python.org/pypi/pip" rel="nofollow">https://pypi.python.org/pypi/pip</a>) as your Python package manager you can install simplejson with:</p> <pre><code> pip install simplejson </code></pre> <p>This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".</p>
12
2009-09-07T12:47:24Z
[ "python", "json", "osx", "python-2.5" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
1,389,202
<p>You could do it easily with the keyword arguments, e.g. like this:</p> <pre><code>&gt;&gt;&gt; class D: def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) &gt;&gt;&gt; D(test='d').test 'd' </code></pre> <p>similar implementation for the positional arguments would be:</p> <pre><code>&gt;&gt; class C: def __init__(self, *args): self.t, self.d = args &gt;&gt;&gt; C('abc', 'def').t 'abc' &gt;&gt;&gt; C('abc', 'def').d 'def' </code></pre> <p>which to me doesn't seem to solve your problem.</p>
11
2009-09-07T12:34:37Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
1,389,216
<p><strong>Edit: extended the solution to honor default arguments also</strong></p> <p>Here is the complete solution:</p> <pre><code>from functools import wraps import inspect def initializer(func): """ Automatically assigns the parameters. &gt;&gt;&gt; class process: ... @initializer ... def __init__(self, cmd, reachable=False, user='root'): ... pass &gt;&gt;&gt; p = process('halt', True) &gt;&gt;&gt; p.cmd, p.reachable, p.user ('halt', True, 'root') """ names, varargs, keywords, defaults = inspect.getargspec(func) @wraps(func) def wrapper(self, *args, **kargs): for name, arg in list(zip(names[1:], args)) + list(kargs.items()): setattr(self, name, arg) for name, default in zip(reversed(names), reversed(defaults)): if not hasattr(self, name): setattr(self, name, default) func(self, *args, **kargs) return wrapper </code></pre> <hr> <p><strong>Edit: Adam asked me to extend the solution to support keyword arguments</strong></p> <pre><code>from functools import wraps import inspect def initializer(fun): names, varargs, keywords, defaults = inspect.getargspec(fun) @wraps(fun) def wrapper(self, *args, **kargs): for name, arg in zip(names[1:], args) + kargs.items(): setattr(self, name, arg) fun(self, *args, **kargs) return wrapper </code></pre> <hr> <p>You can use a decorator:</p> <pre><code>from functools import wraps import inspect def initializer(fun): names, varargs, keywords, defaults = inspect.getargspec(fun) @wraps(fun) def wrapper(self, *args): for name, arg in zip(names[1:], args): setattr(self, name, arg) fun(self, *args) return wrapper class process: @initializer def __init__(self, PID, PPID, cmd, FDs, reachable, user): pass </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; c = process(1, 2, 3, 4, 5, 6) &gt;&gt;&gt; c.PID 1 &gt;&gt;&gt; dir(c) ['FDs', 'PID', 'PPID', '__doc__', '__init__', '__module__', 'cmd', 'reachable', 'user' </code></pre>
56
2009-09-07T12:37:39Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
1,389,224
<p>Quoting the <a href="http://www.python.org/dev/peps/pep-0020/">Zen of Python</a>,</p> <blockquote> <p>Explicit is better than implicit.</p> </blockquote>
21
2009-09-07T12:38:59Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
1,389,232
<p>If you're using Python 2.6 or higher, you can use <a href="http://docs.python.org/library/collections.html#collections.namedtuple">collections.namedtuple</a>:</p> <pre><code>&gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; Process = namedtuple('Process', 'PID PPID cmd') &gt;&gt;&gt; proc = Process(1, 2, 3) &gt;&gt;&gt; proc.PID 1 &gt;&gt;&gt; proc.PPID 2 </code></pre> <p>This is appropriate especially when your class is really just a big bag of values.</p>
25
2009-09-07T12:40:02Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
1,389,304
<p>Another thing you can do:</p> <pre><code>class X(object): def __init__(self, a,b,c,d): vars = locals() # dict of local names self.__dict__.update(vars) # __dict__ holds and object's attributes del self.__dict__["self"] # don't need `self` </code></pre> <p>But the only solution I would recommend, besides just spelling it out, is "make a macro in your editor" ;-p</p>
12
2009-09-07T12:54:44Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
1,837,379
<p>Nadia's solution is better and more powerful, but I think this is also interesting:</p> <pre><code>def constructor(*arg_names): def __init__(self, *args): for name, val in zip(arg_names, args): self.__setattr__(name, val) return __init__ class MyClass(object): __init__ = constructor("var1", "var2", "var3") &gt;&gt;&gt; c = MyClass("fish", "cheese", "beans") &gt;&gt;&gt; c.var2 "cheese" </code></pre>
5
2009-12-03T03:08:01Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
15,028,395
<p><a href="https://github.com/nu11ptr" rel="nofollow">nu11ptr</a> has made a small module, <a href="https://github.com/nu11ptr/PyInstanceVars" rel="nofollow">PyInstanceVars</a>, which includes this functionality as a function decorator. In the module's README is states that the "<em>[...] performance is now only 30-40% worse than explicit initialization under CPython</em>".</p> <p>Usage example, lifted straight from the module's <a href="https://github.com/nu11ptr/PyInstanceVars#basic-usage" rel="nofollow">documentation</a>:</p> <pre><code>&gt;&gt;&gt; from instancevars import * &gt;&gt;&gt; class TestMe(object): ... @instancevars(omit=['arg2_']) ... def __init__(self, _arg1, arg2_, arg3='test'): ... self.arg2 = arg2_ + 1 ... &gt;&gt;&gt; testme = TestMe(1, 2) &gt;&gt;&gt; testme._arg1 1 &gt;&gt;&gt; testme.arg2_ Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'TestMe' object has no attribute 'arg2_' &gt;&gt;&gt; testme.arg2 3 &gt;&gt;&gt; testme.arg3 'test' </code></pre>
0
2013-02-22T16:09:41Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
21,242,547
<p>There may not be a need to initialize variables, as locals() already contains the values!</p> <p>class Dummy(object):</p> <pre><code>def __init__(self, a, b, default='Fred'): self.params = {k:v for k,v in locals().items() if k != 'self'} </code></pre> <p>d = Dummy(2, 3)</p> <p>d.params</p> <p>{'a': 2, 'b': 3, 'default': 'Fred'}</p> <p>d.params['b']</p> <p>3</p> <p>Of course, within a class one could use self.params</p>
2
2014-01-20T19:31:47Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
32,073,190
<p>Maybe this is a closed question, but I would like to propose my solution in order to know what you think about it. I have used a metaclass which applies a decorator to <strong>init</strong> method</p> <pre><code>import inspect class AutoInit(type): def __new__(meta, classname, supers, classdict): classdict['__init__'] = wrapper(classdict['__init__']) return type.__new__(meta, classname, supers, classdict) def wrapper(old_init): def autoinit(*args): formals = inspect.getfullargspec(old_init).args for name, value in zip(formals[1:], args[1:]): setattr(args[0], name, value) return autoinit </code></pre>
0
2015-08-18T13:00:55Z
[ "python", "class", "initialization-list" ]
Python: Automatically initialize instance variables?
1,389,180
<p>I have a python class that looks like this:</p> <pre><code>class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): </code></pre> <p>followed by:</p> <pre><code> self.PID=PID self.PPID=PPID self.cmd=cmd ... </code></pre> <p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p>
35
2009-09-07T12:28:28Z
35,542,235
<p>As soon as <code>getargspec</code> is deprecated since Python 3.5, here's solution using <code>inspect.signature</code>:</p> <pre><code>from inspect import signature, Parameter import functools def auto_assign(func): # Signature: sig = signature(func) for name, param in sig.parameters.items(): if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): raise RuntimeError('Unable to auto assign if *args or **kwargs in signature.') # Wrapper: @functools.wraps(func) def wrapper(self, *args, **kwargs): for i, (name, param) in enumerate(sig.parameters.items()): # Skip 'self' param: if i == 0: continue # Search value in args, kwargs or defaults: if i - 1 &lt; len(args): val = args[i - 1] elif name in kwargs: val = kwargs[name] else: val = param.default setattr(self, name, val) func(self, *args, **kwargs) return wrapper </code></pre> <p>Check if works:</p> <pre><code>class Foo(object): @auto_assign def __init__(self, a, b, c=None, d=None, e=3): pass f = Foo(1, 2, d="a") assert f.a == 1 assert f.b == 2 assert f.c is None assert f.d == "a" assert f.e == 3 print("Ok") </code></pre>
2
2016-02-21T21:21:28Z
[ "python", "class", "initialization-list" ]
what's wrong with my simple HTTP proxy script? (python socket based)
1,389,278
<p>i wrote a smple python script for a proxy functionality. It works. However, if the requested webpage has many other http requests, e.g. Google map, the page was rendered quite slow. </p> <p>Could you guys give some hints, what would be the bottleneck in my code? how to improve?</p> <p>Thanks in advance.</p> <pre><code>#!/usr/bin/python import socket,select,re from threading import Thread class ProxyServer(): def __init__(self, host, port): self.host=host self.port=port self.sk1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def startServer(self): self.sk1.bind((self.host,self.port)) self.sk1.listen(256) print "proxy is ready for connections..." while(1): conn,clientAddr = self.sk1.accept() # print "new request coming in from " + str(clientAddr) handler = RequestHandler(conn) handler.start() class RequestHandler(Thread): def __init__(self, sk1): Thread.__init__(self) self.clientSK = sk1 self.buffer = '' self.header = {} def run(self): sk1 = self.clientSK sk2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while 1: self.buffer += sk1.recv(8192) if self.buffer.find('\n') != -1: break; self.header = self.processHeader(self.buffer) if len(self.header)&gt;0: #header got processed hostString = self.header['Host'] host=port='' if hostString.__contains__(':'): # with port number host,port = hostString.split(':') else: host,port = hostString,"80" sk2.connect((host,int(port))) else: sk1.send('bad request') sk1.close(); return inputs=[sk1,sk2] sk2.send(self.buffer) #counter count = 0 while 1: count+=1 rl, wl, xl = select.select(inputs, [], [], 3) if xl: break if rl: for x in rl: data = x.recv(8192) if x is sk1: output = sk2 else: output = sk1 if data: output.send(data) count = 0 if count == 20: break sk1.close() sk2.close() def processHeader(self,header): header = header.replace("\r\n","\n") lines = header.split('\n') result = {} uLine = lines[0] # url line if len(uLine) == 0: return result # if url line empty return empty dict vl = uLine.split(' ') result['method'] = vl[0] result['url'] = vl[1] result['protocol'] = vl[2] for line in lines[1: - 1]: if len(line)&gt;3: # if line is not empty exp = re.compile(': ') nvp = exp.split(line, 1) if(len(nvp)&gt;1): result[nvp[0]] = nvp[1] return result if __name__ == "__main__": HOST, PORT = "0.0.0.0", 8088 proxy = ProxyServer(HOST,PORT) proxy.startServer() </code></pre>
0
2009-09-07T12:48:40Z
1,389,624
<p>I'm not sure what your speed problems are, but here are some other nits I found to pick:</p> <pre><code>result['protocal'] = vl[2] </code></pre> <p>should be</p> <pre><code>result['protocol'] = vl[2] </code></pre> <p>This code is indented one level too deep:</p> <pre><code>sk2.connect((host,int(port))) </code></pre> <p>You can use <a href="http://mg.pov.lt/blog/profiling.html" rel="nofollow" title="@profile decorator">this</a> decorator to profile your individual methods by line.</p>
0
2009-09-07T14:16:57Z
[ "python" ]
what's wrong with my simple HTTP proxy script? (python socket based)
1,389,278
<p>i wrote a smple python script for a proxy functionality. It works. However, if the requested webpage has many other http requests, e.g. Google map, the page was rendered quite slow. </p> <p>Could you guys give some hints, what would be the bottleneck in my code? how to improve?</p> <p>Thanks in advance.</p> <pre><code>#!/usr/bin/python import socket,select,re from threading import Thread class ProxyServer(): def __init__(self, host, port): self.host=host self.port=port self.sk1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def startServer(self): self.sk1.bind((self.host,self.port)) self.sk1.listen(256) print "proxy is ready for connections..." while(1): conn,clientAddr = self.sk1.accept() # print "new request coming in from " + str(clientAddr) handler = RequestHandler(conn) handler.start() class RequestHandler(Thread): def __init__(self, sk1): Thread.__init__(self) self.clientSK = sk1 self.buffer = '' self.header = {} def run(self): sk1 = self.clientSK sk2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while 1: self.buffer += sk1.recv(8192) if self.buffer.find('\n') != -1: break; self.header = self.processHeader(self.buffer) if len(self.header)&gt;0: #header got processed hostString = self.header['Host'] host=port='' if hostString.__contains__(':'): # with port number host,port = hostString.split(':') else: host,port = hostString,"80" sk2.connect((host,int(port))) else: sk1.send('bad request') sk1.close(); return inputs=[sk1,sk2] sk2.send(self.buffer) #counter count = 0 while 1: count+=1 rl, wl, xl = select.select(inputs, [], [], 3) if xl: break if rl: for x in rl: data = x.recv(8192) if x is sk1: output = sk2 else: output = sk1 if data: output.send(data) count = 0 if count == 20: break sk1.close() sk2.close() def processHeader(self,header): header = header.replace("\r\n","\n") lines = header.split('\n') result = {} uLine = lines[0] # url line if len(uLine) == 0: return result # if url line empty return empty dict vl = uLine.split(' ') result['method'] = vl[0] result['url'] = vl[1] result['protocol'] = vl[2] for line in lines[1: - 1]: if len(line)&gt;3: # if line is not empty exp = re.compile(': ') nvp = exp.split(line, 1) if(len(nvp)&gt;1): result[nvp[0]] = nvp[1] return result if __name__ == "__main__": HOST, PORT = "0.0.0.0", 8088 proxy = ProxyServer(HOST,PORT) proxy.startServer() </code></pre>
0
2009-09-07T12:48:40Z
1,397,939
<p>Er, well first of all you're assuming that all the subsequent requests on a connection are going to be for the same host...</p>
0
2009-09-09T06:54:19Z
[ "python" ]
How to process UDP data in Appengine
1,389,385
<p>I have a service provider who is transmitting data thro' UDP. I want to establish a connection to them, receive &amp; process data (will be with in the 30 sec limit/request)</p> <p>Is it possible to get &amp; process UDP data in appengine. I am looking for some simple example.</p>
1
2009-09-07T13:14:39Z
1,389,493
<p>Unfortunately I don't believe it's possible. The <a href="http://code.google.com/appengine/docs/python/runtime.html">docs</a> on the GAE python runtime say this:</p> <blockquote> <p>An App Engine application cannot:</p> <ul> <li>open a socket or access another host directly. An application can use the App Engine URL fetch service to make HTTP and HTTPS requests to other hosts on ports 80 and 443, respectively.</li> </ul> </blockquote> <p>You would most likely use the <code>socket</code> module for UDP communication, which you can import on GAE, but does not contain any socket functionality (the module is empty).</p>
6
2009-09-07T13:41:19Z
[ "python", "google-app-engine", "udp" ]
How to process UDP data in Appengine
1,389,385
<p>I have a service provider who is transmitting data thro' UDP. I want to establish a connection to them, receive &amp; process data (will be with in the 30 sec limit/request)</p> <p>Is it possible to get &amp; process UDP data in appengine. I am looking for some simple example.</p>
1
2009-09-07T13:14:39Z
16,725,489
<p><a href="http://googleappengine.blogspot.co.il/2013/04/app-engine-177-released.html" rel="nofollow">Update</a> for GAE 1.7.7:</p> <blockquote> <p><strong>Outbound sockets moved to Preview</strong></p> <p>Outbound sockets is now in preview in this release for <a href="https://developers.google.com/appengine/docs/java/sockets/overview" rel="nofollow">Java</a> and <a href="https://developers.google.com/appengine/docs/python/sockets/overview" rel="nofollow">Python</a>. With outbound sockets, billing-enabled App Engine applications can now make outbound connections with TCP or UDP sockets.</p> </blockquote> <p>Note the word "<em>outbound</em>" above -- you still <a href="https://developers.google.com/appengine/docs/python/sockets/overview#limitations-and-restrictions" rel="nofollow">cannot create a listen socket</a>.</p>
2
2013-05-23T23:24:03Z
[ "python", "google-app-engine", "udp" ]
How to process UDP data in Appengine
1,389,385
<p>I have a service provider who is transmitting data thro' UDP. I want to establish a connection to them, receive &amp; process data (will be with in the 30 sec limit/request)</p> <p>Is it possible to get &amp; process UDP data in appengine. I am looking for some simple example.</p>
1
2009-09-07T13:14:39Z
17,618,253
<p>You could run a separate agent on a cloud host like DigitalOcean or Amazon EC2 that proxies this protocol and makes itself available to Google App Engine via ordinary HTTP or web sockets.</p>
0
2013-07-12T15:14:59Z
[ "python", "google-app-engine", "udp" ]
AN error about "User.add_to_class" to extend my user?I do not know why
1,389,627
<p>In my models.py, I user these code to extent two fields:</p> <pre><code>User.add_to_class('bio', models.TextField(blank=True)) User.add_to_class('about', models.TextField(blank=True)) </code></pre> <p>But when I creat a User :</p> <pre><code>user = User.objects.create_user(username=self.cleaned_data['username'], \ email=self.cleaned_data['email'],password=self.cleaned_data['password1']) </code></pre> <p>There is an error like this :</p> <pre><code>ProgrammingError at /account/register/ (1110, "Column 'about' specified twice") Request Method: POST Request URL: http://127.0.0.1:8000/account/register/ Exception Type: ProgrammingError Exception Value: (1110, "Column 'about' specified twice") </code></pre> <p>An I check the sql that django creats,I find it is very weird:</p> <pre><code>'INSERT INTO `auth_user` (`username`, `first_name`, `last_name`, `email`, `password`, `is_staff`, `is_active`, `is_superuser`, `last_login`, `date_joined`, `about`,'bio','about','bio') VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' </code></pre> <p>There are two about and bio .But in Mysql table there is only one 'about' and 'bio'. On the another hand,in which case the models.py will be run twice, I`ve no idea.</p> <p>I do not know why.Please help me!</p>
1
2009-09-07T14:17:05Z
1,389,778
<p>This is <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/a35d94ce1a7893b0" rel="nofollow">not a good way to store additional user information</a>, for a number of reasons, as James Bennett points out in the linked thread. It's no surprise that you're getting weird SQL output and struggling to debug it. Keep things easy for yourself by using a related profile model instead.</p>
2
2009-09-07T14:57:08Z
[ "python", "mysql", "django" ]
How to write a large amount of data in a tarfile in python without using temporary file
1,389,681
<p>I've wrote a small cryptographic module in python whose task is to cipher a file and put the result in a tarfile. The original file to encrypt can be quit large, but that's not a problem because my program only need to work with a small block of data at a time, that can be encrypted on the fly and stored.</p> <p>I'm looking for a way to avoid doing it in two passes, first writing all the data in a temporary file then inserting result in a tarfile.</p> <p>Basically I do the following (where generator_encryptor is a simple generator that yield chunks of data read from sourcefile). :</p> <pre><code>t = tarfile.open("target.tar", "w") tmp = file('content', 'wb') for chunk in generator_encryptor("sourcefile"): tmp.write(chunks) tmp.close() t.add(content) t.close() </code></pre> <p>I'm a bit annoyed having to use a temporary file as I file it should be easy to write blocs directly in the tar file, but collecting every chunks in a single string and using something like t.addfile('content', StringIO(bigcipheredstring) seems excluded because I can't guarantee that I have memory enough to old bigcipheredstring.</p> <p>Any hint of how to do that ?</p>
3
2009-09-07T14:33:56Z
1,389,697
<p>I guess you need to understand how the tar format works, and handle the tar writing yourself. Maybe this can be helpful?</p> <p><a href="http://mail.python.org/pipermail/python-list/2001-August/100796.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2001-August/100796.html</a></p>
0
2009-09-07T14:39:04Z
[ "python", "tar" ]
How to write a large amount of data in a tarfile in python without using temporary file
1,389,681
<p>I've wrote a small cryptographic module in python whose task is to cipher a file and put the result in a tarfile. The original file to encrypt can be quit large, but that's not a problem because my program only need to work with a small block of data at a time, that can be encrypted on the fly and stored.</p> <p>I'm looking for a way to avoid doing it in two passes, first writing all the data in a temporary file then inserting result in a tarfile.</p> <p>Basically I do the following (where generator_encryptor is a simple generator that yield chunks of data read from sourcefile). :</p> <pre><code>t = tarfile.open("target.tar", "w") tmp = file('content', 'wb') for chunk in generator_encryptor("sourcefile"): tmp.write(chunks) tmp.close() t.add(content) t.close() </code></pre> <p>I'm a bit annoyed having to use a temporary file as I file it should be easy to write blocs directly in the tar file, but collecting every chunks in a single string and using something like t.addfile('content', StringIO(bigcipheredstring) seems excluded because I can't guarantee that I have memory enough to old bigcipheredstring.</p> <p>Any hint of how to do that ?</p>
3
2009-09-07T14:33:56Z
1,389,707
<p>You can create an own file-like object and pass to TarFile.addfile. Your file-like object will generate the encrypted contents on the fly in the fileobj.read() method.</p>
4
2009-09-07T14:41:10Z
[ "python", "tar" ]
How to write a large amount of data in a tarfile in python without using temporary file
1,389,681
<p>I've wrote a small cryptographic module in python whose task is to cipher a file and put the result in a tarfile. The original file to encrypt can be quit large, but that's not a problem because my program only need to work with a small block of data at a time, that can be encrypted on the fly and stored.</p> <p>I'm looking for a way to avoid doing it in two passes, first writing all the data in a temporary file then inserting result in a tarfile.</p> <p>Basically I do the following (where generator_encryptor is a simple generator that yield chunks of data read from sourcefile). :</p> <pre><code>t = tarfile.open("target.tar", "w") tmp = file('content', 'wb') for chunk in generator_encryptor("sourcefile"): tmp.write(chunks) tmp.close() t.add(content) t.close() </code></pre> <p>I'm a bit annoyed having to use a temporary file as I file it should be easy to write blocs directly in the tar file, but collecting every chunks in a single string and using something like t.addfile('content', StringIO(bigcipheredstring) seems excluded because I can't guarantee that I have memory enough to old bigcipheredstring.</p> <p>Any hint of how to do that ?</p>
3
2009-09-07T14:33:56Z
1,389,710
<p>Huh? Can't you just use the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to run a pipe through to tar? That way, no temporary file should be needed. Of course, this won't work if you can't generate your data in small enough chunks to fit in RAM, but if you have that problem, then tar isn't the issue.</p>
2
2009-09-07T14:41:20Z
[ "python", "tar" ]
How to write a large amount of data in a tarfile in python without using temporary file
1,389,681
<p>I've wrote a small cryptographic module in python whose task is to cipher a file and put the result in a tarfile. The original file to encrypt can be quit large, but that's not a problem because my program only need to work with a small block of data at a time, that can be encrypted on the fly and stored.</p> <p>I'm looking for a way to avoid doing it in two passes, first writing all the data in a temporary file then inserting result in a tarfile.</p> <p>Basically I do the following (where generator_encryptor is a simple generator that yield chunks of data read from sourcefile). :</p> <pre><code>t = tarfile.open("target.tar", "w") tmp = file('content', 'wb') for chunk in generator_encryptor("sourcefile"): tmp.write(chunks) tmp.close() t.add(content) t.close() </code></pre> <p>I'm a bit annoyed having to use a temporary file as I file it should be easy to write blocs directly in the tar file, but collecting every chunks in a single string and using something like t.addfile('content', StringIO(bigcipheredstring) seems excluded because I can't guarantee that I have memory enough to old bigcipheredstring.</p> <p>Any hint of how to do that ?</p>
3
2009-09-07T14:33:56Z
1,452,363
<p>Basically using a file-like object and passing it to TarFile.addfile do the trick, but there is still some issues open.</p> <ul> <li>I need to known the full encrypted file size at the beginning</li> <li>the way tarfile access to read method is such that the custom file-like object must always return full read buffers, or tarfile suppose it's end of file. It leads to some really inefficient buffer copying in the code of read method, but it's either that or change tarfile module.</li> </ul> <p>The resulting code is below, basically I had to write a wrapper class that transform my existing generator into a file-like object. I also added the GeneratorEncrypto class in my example to make code compleat. You can notice it has a len method that returns the length of the written file (but understand it's just a dummy placeholder that does nothing usefull).</p> <pre><code>import tarfile class GeneratorEncryptor(object): """Dummy class for testing purpose The real one perform on the fly encryption of source file """ def __init__(self, source): self.source = source self.BLOCKSIZE = 1024 self.NBBLOCKS = 1000 def __call__(self): for c in range(0, self.NBBLOCKS): yield self.BLOCKSIZE * str(c%10) def __len__(self): return self.BLOCKSIZE * self.NBBLOCKS class GeneratorToFile(object): """Transform a data generator into a conventional file handle """ def __init__(self, generator): self.buf = '' self.generator = generator() def read(self, size): chunk = self.buf while len(chunk) &lt; size: try: chunk = chunk + self.generator.next() except StopIteration: self.buf = '' return chunk self.buf = chunk[size:] return chunk[:size] t = tarfile.open("target.tar", "w") tmp = file('content', 'wb') generator = GeneratorEncryptor("source") ti = t.gettarinfo(name = "content") ti.size = len(generator) t.addfile(ti, fileobj = GeneratorToFile(generator)) t.close() </code></pre>
2
2009-09-20T23:53:26Z
[ "python", "tar" ]
How to save data with Python?
1,389,738
<p>I am working on a program in Python and want users to be able to save data they are working on. I have looked into cPickle; it seems like it would be a fast and easy way to save data, it seems insecure. Since entire functions, classes, etc can be pickled, I am worried that a rogue save file could inject harmful code into the program. Is there a way I can prevent that, or should I look into other methods of saving data, such as directly converting to a string (which also seems insecure,) or creating an XML hierarchy, and putting data in that.</p> <p>I am new to python, so please bear with me.</p> <p>Thanks in advance!</p> <p>EDIT: As for the type of data I am storing, it is mainly dictionaries and lists. Information such as names, speeds, etc. It is fairly simple right now, but may get more complex in the future.</p>
12
2009-09-07T14:49:22Z
1,389,757
<p>You need to give us more context before we can answer: what type of data are you saving, how much is there, how do you want to access it?</p> <p>As for pickles: they do not store code. When you pickle a function or class, it is the name that is stored, not the actual code itself.</p>
1
2009-09-07T14:53:33Z
[ "python", "data-structures", "save" ]
How to save data with Python?
1,389,738
<p>I am working on a program in Python and want users to be able to save data they are working on. I have looked into cPickle; it seems like it would be a fast and easy way to save data, it seems insecure. Since entire functions, classes, etc can be pickled, I am worried that a rogue save file could inject harmful code into the program. Is there a way I can prevent that, or should I look into other methods of saving data, such as directly converting to a string (which also seems insecure,) or creating an XML hierarchy, and putting data in that.</p> <p>I am new to python, so please bear with me.</p> <p>Thanks in advance!</p> <p>EDIT: As for the type of data I am storing, it is mainly dictionaries and lists. Information such as names, speeds, etc. It is fairly simple right now, but may get more complex in the future.</p>
12
2009-09-07T14:49:22Z
1,389,790
<p>You could do something like:</p> <p>to write</p> <ul> <li>Pickle</li> <li>Sign pickled file</li> <li>Done</li> </ul> <p>to read</p> <ul> <li>Check pickled file's signature</li> <li>Unpickle</li> <li>Use</li> </ul> <p>I wonder though what makes you think that the data files are going to be tampered but your application is not going to be?</p>
3
2009-09-07T14:59:33Z
[ "python", "data-structures", "save" ]
How to save data with Python?
1,389,738
<p>I am working on a program in Python and want users to be able to save data they are working on. I have looked into cPickle; it seems like it would be a fast and easy way to save data, it seems insecure. Since entire functions, classes, etc can be pickled, I am worried that a rogue save file could inject harmful code into the program. Is there a way I can prevent that, or should I look into other methods of saving data, such as directly converting to a string (which also seems insecure,) or creating an XML hierarchy, and putting data in that.</p> <p>I am new to python, so please bear with me.</p> <p>Thanks in advance!</p> <p>EDIT: As for the type of data I am storing, it is mainly dictionaries and lists. Information such as names, speeds, etc. It is fairly simple right now, but may get more complex in the future.</p>
12
2009-09-07T14:49:22Z
1,389,792
<p>From your description JSON encoding is the secure and fast solution. There is a json module in python2.6, you can use it like this:</p> <pre><code>import json obj = {'key1': 'value1', 'key2': [1, 2, 3, 4], 'key3': 1322} encoded = json.dumps(obj) obj = json.loads(encoded) </code></pre> <p>JSON format is human readable and is very similar to the dictionary string representation in python. And doesn't have any security issues like pickle. If you don't have python2.6 you can install cjson or <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a></p> <p>You can't use JSON to save python objects like Pickle. But you can use it to save: strings, dictionaries, lists, ... It can be enough for most cases.</p> <p><strong>To explain why pickle is insecure.</strong> From python <a href="http://www.python.org/doc/2.2.3/lib/pickle-sec.html">docs</a>:</p> <blockquote> <p>Most of the security issues surrounding the pickle and cPickle module involve unpickling. There are no known security vulnerabilities related to pickling because you (the programmer) control the objects that pickle will interact with, and all it produces is a string.</p> <p>However, for unpickling, it is <strong>never</strong> a good idea to unpickle an untrusted string whose origins are dubious, for example, strings read from a socket. This is because unpickling can create unexpected objects and even potentially run methods of those objects, such as their class constructor or destructor ... <strong>The moral of the story is that you should be really careful about the source of the strings your application unpickles.</strong></p> </blockquote> <p>There are some ways to defend yourself but it is much easier to use JSON in your case.</p>
21
2009-09-07T15:00:30Z
[ "python", "data-structures", "save" ]
How to save data with Python?
1,389,738
<p>I am working on a program in Python and want users to be able to save data they are working on. I have looked into cPickle; it seems like it would be a fast and easy way to save data, it seems insecure. Since entire functions, classes, etc can be pickled, I am worried that a rogue save file could inject harmful code into the program. Is there a way I can prevent that, or should I look into other methods of saving data, such as directly converting to a string (which also seems insecure,) or creating an XML hierarchy, and putting data in that.</p> <p>I am new to python, so please bear with me.</p> <p>Thanks in advance!</p> <p>EDIT: As for the type of data I am storing, it is mainly dictionaries and lists. Information such as names, speeds, etc. It is fairly simple right now, but may get more complex in the future.</p>
12
2009-09-07T14:49:22Z
1,389,803
<p><strong><em></strong>In this answer, I'm only concerned about <strong>accidental</strong> corruption of the application's integrity.<strong></em></strong></p> <p>Pickle is "secure". What might be insecure is accessing code you didn't write, for example in plugins; that is not relevant to pickles though.</p> <p>When you pickle an object, all its data is saved, but code and implementation is not. This means when unpickled, an updated object might find it has "old-style" data inside (if you update the implementation). This is something you must know and handle, if applicable.</p> <p>Pickling strings, lists, numbers, dicts is very easy and works perfectly, and comparably to JSON. The Pickle magic is that -- sometimes without adjustment -- even complex python objects can be pickled. But only data is pickled; the instances are reconstructed simply by the saved module name and type name of the object.</p>
1
2009-09-07T15:04:53Z
[ "python", "data-structures", "save" ]
How to save data with Python?
1,389,738
<p>I am working on a program in Python and want users to be able to save data they are working on. I have looked into cPickle; it seems like it would be a fast and easy way to save data, it seems insecure. Since entire functions, classes, etc can be pickled, I am worried that a rogue save file could inject harmful code into the program. Is there a way I can prevent that, or should I look into other methods of saving data, such as directly converting to a string (which also seems insecure,) or creating an XML hierarchy, and putting data in that.</p> <p>I am new to python, so please bear with me.</p> <p>Thanks in advance!</p> <p>EDIT: As for the type of data I am storing, it is mainly dictionaries and lists. Information such as names, speeds, etc. It is fairly simple right now, but may get more complex in the future.</p>
12
2009-09-07T14:49:22Z
1,390,025
<p>You should use a database of some kind. Storing in pickle format isn't a good idea (in most cases). You may consider:</p> <ul> <li><strong>SQLite</strong> - (included in Python 2.5+) fast and simple, but requires knowledge of SQL and DB-API</li> <li><a href="http://buzhug.sourceforge.net/" rel="nofollow"><strong>buzhug</strong></a> - non-SQL, file based database with pythonic syntax</li> <li>SQL database - you may use interface to some of DBMS (like MySQL, PostreSQL etc.), but it's only good for larger amount of data (thousands of records).</li> </ul> <p>You may find some other solutions <a href="http://wiki.python.org/moin/DatabaseInterfaces#Non-RelationalDatabases" rel="nofollow">here</a>.</p>
1
2009-09-07T16:09:03Z
[ "python", "data-structures", "save" ]
How to save data with Python?
1,389,738
<p>I am working on a program in Python and want users to be able to save data they are working on. I have looked into cPickle; it seems like it would be a fast and easy way to save data, it seems insecure. Since entire functions, classes, etc can be pickled, I am worried that a rogue save file could inject harmful code into the program. Is there a way I can prevent that, or should I look into other methods of saving data, such as directly converting to a string (which also seems insecure,) or creating an XML hierarchy, and putting data in that.</p> <p>I am new to python, so please bear with me.</p> <p>Thanks in advance!</p> <p>EDIT: As for the type of data I am storing, it is mainly dictionaries and lists. Information such as names, speeds, etc. It is fairly simple right now, but may get more complex in the future.</p>
12
2009-09-07T14:49:22Z
1,391,437
<p>Who -- specifically -- is the sociopath who's going through the effort to break a program by hacking the pickled file?</p> <p>It's Python. The sociopath has your source. They don't need to fool around hacking your pickle file. They can just edit your source and do all the "damage" they want.</p> <p>Don't worry about "insecurity" unless you're involved in litigation with organized crime syndicates.</p> <p>Don't worry about "a rogue save file could inject harmful code into the program". No one will bother with a rogue save file when they have the source.</p>
1
2009-09-08T00:40:10Z
[ "python", "data-structures", "save" ]
How to save data with Python?
1,389,738
<p>I am working on a program in Python and want users to be able to save data they are working on. I have looked into cPickle; it seems like it would be a fast and easy way to save data, it seems insecure. Since entire functions, classes, etc can be pickled, I am worried that a rogue save file could inject harmful code into the program. Is there a way I can prevent that, or should I look into other methods of saving data, such as directly converting to a string (which also seems insecure,) or creating an XML hierarchy, and putting data in that.</p> <p>I am new to python, so please bear with me.</p> <p>Thanks in advance!</p> <p>EDIT: As for the type of data I am storing, it is mainly dictionaries and lists. Information such as names, speeds, etc. It is fairly simple right now, but may get more complex in the future.</p>
12
2009-09-07T14:49:22Z
1,512,645
<p>You might enjoy working with the y_serial module over at <a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a> </p> <p>which reads like a tutorial but operationally offers working code for serialization and persistance. The commentary discusses some of the pros and cons relevant to issues raised here.</p> <p>It's designed to be a general solution to warehousing compressed Python objects with SQLite (with almost no SQL fuss ;-)</p> <p>Hope this helps.</p>
1
2009-10-03T02:45:42Z
[ "python", "data-structures", "save" ]
How to run django shell from Emacs?
1,389,835
<p>I'd like to be able to run <code>./manage.py shell</code> in an Emacs buffer, with all the nice stuff that you get from ipython, like magic commands and autocompletion. Ideally I would also like to be able evaluate code from a buffer to the django shell.</p> <p>Is this possible?</p>
9
2009-09-07T15:16:28Z
1,390,399
<p>It won't work in <code>shell</code>? I managed to get a django shell session going in emacs just now. </p> <p>Hit <code>M-x shell</code> and then start your python shell inside that bash shell session, like so:</p> <pre><code> M-x shell </code></pre> <p>the shell spawns</p> <pre><code>prompt&gt; cd path/to/my/django/directory prompt&gt; python manage.py shell Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) &gt;&gt;&gt; </code></pre> <p>and it should bring up a django shell just as if you are working in a bare terminal, but it is another buffer in Emacs.</p> <p>As far as the integration (sending code to the shell to be evaluated, etc) it seems like you may be able find what you're looking for at the bottom of the page <a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode" rel="nofollow">here (Emacs Wiki for python.el)</a>. There's plenty of info there about getting iPython working with python.el, and you may be able to get that to run your django shell by modifying the code there or in python.el.</p>
0
2009-09-07T17:57:53Z
[ "python", "django", "emacs", "ipython" ]
How to run django shell from Emacs?
1,389,835
<p>I'd like to be able to run <code>./manage.py shell</code> in an Emacs buffer, with all the nice stuff that you get from ipython, like magic commands and autocompletion. Ideally I would also like to be able evaluate code from a buffer to the django shell.</p> <p>Is this possible?</p>
9
2009-09-07T15:16:28Z
1,390,919
<p>Using <a href="http://www.emacswiki.org/emacs/AnsiTerm" rel="nofollow"><code>ansi-term</code></a> will make ipython's tab-completion work, however note that this will remap all <code>C-x [...]</code> keybindings to <code>C-c [...]</code>.</p> <p>If you like it, you can easily create a keybinding for it by putting this to your .emacs:</p> <pre><code>(defun start-my-ipython-term () (interactive) (ansi-term "/usr/bin/ipython")) (global-set-key (kbd "&lt;your keybinding here&gt;") 'start-my-ipython-term) </code></pre>
1
2009-09-07T20:53:51Z
[ "python", "django", "emacs", "ipython" ]
How to run django shell from Emacs?
1,389,835
<p>I'd like to be able to run <code>./manage.py shell</code> in an Emacs buffer, with all the nice stuff that you get from ipython, like magic commands and autocompletion. Ideally I would also like to be able evaluate code from a buffer to the django shell.</p> <p>Is this possible?</p>
9
2009-09-07T15:16:28Z
1,392,730
<p>OK, so I hacked this by myself today. A major part of it is copy-and-paste from <code>py-shell</code> from <code>python-mode.el</code>.</p> <pre class="lang-lisp prettyprint-override"><code>(defun django-shell (&amp;optional argprompt) (interactive "P") ;; Set the default shell if not already set (labels ((read-django-project-dir (prompt dir) (let* ((dir (read-directory-name prompt dir)) (manage (expand-file-name (concat dir "manage.py")))) (if (file-exists-p manage) (expand-file-name dir) (progn (message "%s is not a Django project directory" manage) (sleep-for .5) (read-django-project-dir prompt dir)))))) (let* ((dir (read-django-project-dir "project directory: " default-directory)) (project-name (first (remove-if (lambda (s) (or (string= "src" s) (string= "" s))) (reverse (split-string dir "/"))))) (buffer-name (format "django-%s" project-name)) (manage (concat dir "manage.py"))) (cd dir) (if (not (equal (buffer-name) buffer-name)) (switch-to-buffer-other-window (apply 'make-comint buffer-name manage nil '("shell"))) (apply 'make-comint buffer-name manage nil '("shell"))) (make-local-variable 'comint-prompt-regexp) (setq comint-prompt-regexp (concat py-shell-input-prompt-1-regexp "\\|" py-shell-input-prompt-2-regexp "\\|" "^([Pp]db) ")) (add-hook 'comint-output-filter-functions 'py-comint-output-filter-function) ;; pdbtrack (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file) (setq py-pdbtrack-do-tracking-p t) (set-syntax-table py-mode-syntax-table) (use-local-map py-shell-map) (run-hooks 'py-shell-hook)))) </code></pre>
8
2009-09-08T08:33:27Z
[ "python", "django", "emacs", "ipython" ]
How to run django shell from Emacs?
1,389,835
<p>I'd like to be able to run <code>./manage.py shell</code> in an Emacs buffer, with all the nice stuff that you get from ipython, like magic commands and autocompletion. Ideally I would also like to be able evaluate code from a buffer to the django shell.</p> <p>Is this possible?</p>
9
2009-09-07T15:16:28Z
1,392,773
<p>I did simply create a replacement ipython shell script.</p> <p>I use python-mode.el and ipython.el; related .emacs.el fragment goes like this:</p> <pre> (setq ipython-command "/Users/japhy/bin/smart_ipython") (require 'ipython) ;; fix completion for ipython 0.10 (setq ipython-completion-command-string "print(';'.join(__IP.Completer.all_completions('%s'))) #PYTHON-MODE SILENT\n") </pre> <p>where smart_ipython script looks like this:</p> <pre><code>#!/bin/sh set -e /bin/echo -n "Select Django project/dir, or press enter for plain ipython: " read selection case $selection in '') exec ipython ;; project) cd /Users/japhy/Projekty/some/project/dir ;; # other often used projects go here *) cd $selection ;; esac exec python manage.py shell </code></pre>
1
2009-09-08T08:47:13Z
[ "python", "django", "emacs", "ipython" ]
How to run django shell from Emacs?
1,389,835
<p>I'd like to be able to run <code>./manage.py shell</code> in an Emacs buffer, with all the nice stuff that you get from ipython, like magic commands and autocompletion. Ideally I would also like to be able evaluate code from a buffer to the django shell.</p> <p>Is this possible?</p>
9
2009-09-07T15:16:28Z
32,867,813
<p>This is a pretty old question, but it's probably still useful for someone. I've found the easiest way of doing this is by adding the following to my .emacs</p> <pre><code>(setq python-shell-interpreter "python" python-shell-interpreter-args "-i /absolute/path/to/manage.py shell_plus") </code></pre> <p>You can then use any of the python-shell-interpreter commands, and everything will run in the django shell instead of with the regular python interpreter.</p> <p>I wrote a blog post about it <a href="https://faridrener.com/2015/09/30/shell-plus-emacs.html" rel="nofollow">here</a>.</p>
1
2015-09-30T13:48:14Z
[ "python", "django", "emacs", "ipython" ]
How to run django shell from Emacs?
1,389,835
<p>I'd like to be able to run <code>./manage.py shell</code> in an Emacs buffer, with all the nice stuff that you get from ipython, like magic commands and autocompletion. Ideally I would also like to be able evaluate code from a buffer to the django shell.</p> <p>Is this possible?</p>
9
2009-09-07T15:16:28Z
38,608,305
<p>After researching this question I think the best solution that will work for multiple django projects without changing your config each time you swap is <code>python-django.el</code> plus correct configuration of <em>directory-local variables</em>.</p> <p>python-django is a great addition to python.el for django users, with many small quality of life improvements, like running commands etc.</p> <p>To get it to always launch the django shell when in a project, you need to set the proper directory-local variables, by creating a <code>.dir-locals.el</code> file in the root of your project. You can use this config for the <code>.dir-locals.el</code> file. The critical part is setting your python-shell-interpreter args to <code>manage.py shell</code> for your project.</p> <pre><code>((python-mode (python-shell-interpreter . "python") (python-shell-interpreter-args . "/home/youruser/code/yourproject/manage.py shell") (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ") (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ") (python-shell-completion-setup-code . "from IPython.core.completerlib import module_completion") (python-shell-completion-module-string-code . "';'.join(module_completion('''%s'''))\n") (python-shell-completion-string-code . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n") (python-shell-extra-pythonpaths "/home/youruser/code/yourproject/apps/") (python-shell-virtualenv-path . "/home/youruser/.virtualenvs/yourproject"))) </code></pre> <p>```</p> <p>The config is taken <a href="http://web.archive.org/web/20131010005338/http://from-the-cloud.com/en/emacs/2013/01/28_emacs-as-a-django-ide-with-python-djangoel.html" rel="nofollow">from this blogpost</a> by the author of the project.</p>
0
2016-07-27T08:57:31Z
[ "python", "django", "emacs", "ipython" ]
Mechanize and Google App Engine
1,389,893
<p>Has someone managed to use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> with Google App Engine application?</p>
4
2009-09-07T15:30:49Z
1,398,104
<p>I found that someone created this project: <a href="http://code.google.com/p/gaemechanize/" rel="nofollow">gaemechanize</a>. But no code at the time of writing.</p>
2
2009-09-09T07:34:35Z
[ "python", "google-app-engine", "mechanize" ]
Mechanize and Google App Engine
1,389,893
<p>Has someone managed to use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> with Google App Engine application?</p>
4
2009-09-07T15:30:49Z
2,056,566
<p>I have solved this problem, please see: <a href="http://stackoverflow.com/questions/1902079/python-mechanize-gaepython-code/2056543#2056543">http://stackoverflow.com/questions/1902079/python-mechanize-gaepython-code/2056543#2056543</a></p>
3
2010-01-13T12:27:41Z
[ "python", "google-app-engine", "mechanize" ]
OpenGL in Python with Snow Leopard?
1,389,928
<p>I'm interested in playing around with OpenGL in Python. I've used OpenGL in C++ and Objective-C, but I don't have much experience in Python. I'm wondering if there's a good tutorial that works in Snow Leopard. I'd prefer to stay in 64-bit mode if possible, since I've heard 32-bit programs require loading a lot of extra 32-bit libraries.</p> <p>I've already tried a <a href="http://www.siafoo.net/snippet/97" rel="nofollow">PyOpenGL/wxPython tutorial</a>. When I ran the code, it crashed with this message:</p> <pre><code>ImportError: /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/_core_.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode) </code></pre> <p>It looks like there's a <a href="http://trac.wxwidgets.org/ticket/11160" rel="nofollow">bug</a> in wxPython that prevents it from working on a 64-bit system.</p> <p>I also looked at Pyglet, but they have a <a href="http://code.google.com/p/pyglet/issues/detail?id=438" rel="nofollow">similar issue</a>. They provide a work-around (setting Python to 32-bit mode), but it doesn't look like they're going to fix it.</p> <p>Finally, I looked at PyGLUT, but I think it's only for Windows.</p> <p>Are there any other libraries that would let me access OpenGL and draw on the screen? Again, I'd prefer to stay in 64-bit mode, but if nothing works, I'll switch to 32-bit and try wxPython or Pyglet again.</p> <p><hr/></p> <p><strong>Edit:</strong> I've also tried PyGame. It depends on SDL which is <a href="http://bugzilla.libsdl.org/show_bug.cgi?id=581" rel="nofollow">broken</a> in SL. I thought about trying to use Cocoa through PyObjc, but the Xcode Python application templates <a href="http://stackoverflow.com/questions/1382252/xcode-3-2-ruby-and-python-templates">have been removed</a>.</p>
4
2009-09-07T15:42:48Z
1,390,205
<p>You could try pygame. Pygame is a python wrapper around SDL. According to their website they have Max OS X binaries. Here is a <a href="http://www.willmcgugan.com/blog/tech/2007/6/4/opengl-sample-code-for-pygame/" rel="nofollow">simple example</a> of using pygame with OpenGL. Once you are able to create the window and handle events most OpenGL programming is just like it would be in C or C++, but with some added python goodness. For OpenGL a great tutorial is NeHe.</p>
0
2009-09-07T17:01:35Z
[ "python", "opengl", "osx-snow-leopard" ]
OpenGL in Python with Snow Leopard?
1,389,928
<p>I'm interested in playing around with OpenGL in Python. I've used OpenGL in C++ and Objective-C, but I don't have much experience in Python. I'm wondering if there's a good tutorial that works in Snow Leopard. I'd prefer to stay in 64-bit mode if possible, since I've heard 32-bit programs require loading a lot of extra 32-bit libraries.</p> <p>I've already tried a <a href="http://www.siafoo.net/snippet/97" rel="nofollow">PyOpenGL/wxPython tutorial</a>. When I ran the code, it crashed with this message:</p> <pre><code>ImportError: /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/_core_.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode) </code></pre> <p>It looks like there's a <a href="http://trac.wxwidgets.org/ticket/11160" rel="nofollow">bug</a> in wxPython that prevents it from working on a 64-bit system.</p> <p>I also looked at Pyglet, but they have a <a href="http://code.google.com/p/pyglet/issues/detail?id=438" rel="nofollow">similar issue</a>. They provide a work-around (setting Python to 32-bit mode), but it doesn't look like they're going to fix it.</p> <p>Finally, I looked at PyGLUT, but I think it's only for Windows.</p> <p>Are there any other libraries that would let me access OpenGL and draw on the screen? Again, I'd prefer to stay in 64-bit mode, but if nothing works, I'll switch to 32-bit and try wxPython or Pyglet again.</p> <p><hr/></p> <p><strong>Edit:</strong> I've also tried PyGame. It depends on SDL which is <a href="http://bugzilla.libsdl.org/show_bug.cgi?id=581" rel="nofollow">broken</a> in SL. I thought about trying to use Cocoa through PyObjc, but the Xcode Python application templates <a href="http://stackoverflow.com/questions/1382252/xcode-3-2-ruby-and-python-templates">have been removed</a>.</p>
4
2009-09-07T15:42:48Z
1,390,246
<p>There's probably no good reason to avoid 32-bit mode. Unless your Python programs need to larger address space, of course.</p>
2
2009-09-07T17:13:13Z
[ "python", "opengl", "osx-snow-leopard" ]
OpenGL in Python with Snow Leopard?
1,389,928
<p>I'm interested in playing around with OpenGL in Python. I've used OpenGL in C++ and Objective-C, but I don't have much experience in Python. I'm wondering if there's a good tutorial that works in Snow Leopard. I'd prefer to stay in 64-bit mode if possible, since I've heard 32-bit programs require loading a lot of extra 32-bit libraries.</p> <p>I've already tried a <a href="http://www.siafoo.net/snippet/97" rel="nofollow">PyOpenGL/wxPython tutorial</a>. When I ran the code, it crashed with this message:</p> <pre><code>ImportError: /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/_core_.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode) </code></pre> <p>It looks like there's a <a href="http://trac.wxwidgets.org/ticket/11160" rel="nofollow">bug</a> in wxPython that prevents it from working on a 64-bit system.</p> <p>I also looked at Pyglet, but they have a <a href="http://code.google.com/p/pyglet/issues/detail?id=438" rel="nofollow">similar issue</a>. They provide a work-around (setting Python to 32-bit mode), but it doesn't look like they're going to fix it.</p> <p>Finally, I looked at PyGLUT, but I think it's only for Windows.</p> <p>Are there any other libraries that would let me access OpenGL and draw on the screen? Again, I'd prefer to stay in 64-bit mode, but if nothing works, I'll switch to 32-bit and try wxPython or Pyglet again.</p> <p><hr/></p> <p><strong>Edit:</strong> I've also tried PyGame. It depends on SDL which is <a href="http://bugzilla.libsdl.org/show_bug.cgi?id=581" rel="nofollow">broken</a> in SL. I thought about trying to use Cocoa through PyObjc, but the Xcode Python application templates <a href="http://stackoverflow.com/questions/1382252/xcode-3-2-ruby-and-python-templates">have been removed</a>.</p>
4
2009-09-07T15:42:48Z
1,390,287
<p>Also when programing with OpenGL in python remember that Python datastructures can be rather slow when it comes to requirements for 3D graphics. PyGL developers for example recommend using ctypes for operations that concern graphics, since that way you can get enough performance for some complicated geometry with bareable FPS.</p>
0
2009-09-07T17:24:21Z
[ "python", "opengl", "osx-snow-leopard" ]
OpenGL in Python with Snow Leopard?
1,389,928
<p>I'm interested in playing around with OpenGL in Python. I've used OpenGL in C++ and Objective-C, but I don't have much experience in Python. I'm wondering if there's a good tutorial that works in Snow Leopard. I'd prefer to stay in 64-bit mode if possible, since I've heard 32-bit programs require loading a lot of extra 32-bit libraries.</p> <p>I've already tried a <a href="http://www.siafoo.net/snippet/97" rel="nofollow">PyOpenGL/wxPython tutorial</a>. When I ran the code, it crashed with this message:</p> <pre><code>ImportError: /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode/wx/_core_.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode) </code></pre> <p>It looks like there's a <a href="http://trac.wxwidgets.org/ticket/11160" rel="nofollow">bug</a> in wxPython that prevents it from working on a 64-bit system.</p> <p>I also looked at Pyglet, but they have a <a href="http://code.google.com/p/pyglet/issues/detail?id=438" rel="nofollow">similar issue</a>. They provide a work-around (setting Python to 32-bit mode), but it doesn't look like they're going to fix it.</p> <p>Finally, I looked at PyGLUT, but I think it's only for Windows.</p> <p>Are there any other libraries that would let me access OpenGL and draw on the screen? Again, I'd prefer to stay in 64-bit mode, but if nothing works, I'll switch to 32-bit and try wxPython or Pyglet again.</p> <p><hr/></p> <p><strong>Edit:</strong> I've also tried PyGame. It depends on SDL which is <a href="http://bugzilla.libsdl.org/show_bug.cgi?id=581" rel="nofollow">broken</a> in SL. I thought about trying to use Cocoa through PyObjc, but the Xcode Python application templates <a href="http://stackoverflow.com/questions/1382252/xcode-3-2-ruby-and-python-templates">have been removed</a>.</p>
4
2009-09-07T15:42:48Z
1,390,361
<p>I've used <a href="http://pyopengl.sourceforge.net/index.html" rel="nofollow">PyOpenGL</a> 3.0.0 quite successfully on Snow Leopard. It uses ctypes, so it should be making 64-bit calls if those libraries are available (and Snow Leopard's Python includes a 64-bit version). I haven't used the wxPython stuff with PyOpenGL so that's where you might be running into problems, but PyOpenGL also includes GLUT, which both run fine.</p>
4
2009-09-07T17:47:23Z
[ "python", "opengl", "osx-snow-leopard" ]
How do I use StandardAnalyzer with TermQuery?
1,390,088
<p>I'm trying to produce something similar to what QueryParser in lucene does, but without the parser, i.e. run a string through StandardAnalyzer, tokenize this and use TermQuery:s in a BooleanQuery to produce a query. My problem is that I only get Token:s from StandardAnalyzer, and not Term:s. I can convert a Token to a term by just extracting the string from it with Token.term(), but this is 2.4.x-only and it seems backwards, because I need to add the field a second time. What is the proper way of producing a TermQuery with StandardAnalyzer?</p> <p>I'm using pylucene, but I guess the answer is the same for Java etc. Here is the code I've come up with:</p> <pre><code>from lucene import * def term_match(self, phrase): query = BooleanQuery() sa = StandardAnalyzer() for token in sa.tokenStream("contents", StringReader(phrase)): term_query = TermQuery(Term("contents", token.term()) query.add(term_query), BooleanClause.Occur.SHOULD) </code></pre>
3
2009-09-07T16:26:23Z
1,390,495
<p>The established way to get the token text is with <code>token.termText()</code> - that API's been there forever.</p> <p>And yes, you'll need to specify a field name to both the <code>Analyzer</code> and the <code>Term</code>; I think that's considered normal. 8-)</p>
2
2009-09-07T18:28:22Z
[ "python", "lucene", "pylucene" ]
How do I use StandardAnalyzer with TermQuery?
1,390,088
<p>I'm trying to produce something similar to what QueryParser in lucene does, but without the parser, i.e. run a string through StandardAnalyzer, tokenize this and use TermQuery:s in a BooleanQuery to produce a query. My problem is that I only get Token:s from StandardAnalyzer, and not Term:s. I can convert a Token to a term by just extracting the string from it with Token.term(), but this is 2.4.x-only and it seems backwards, because I need to add the field a second time. What is the proper way of producing a TermQuery with StandardAnalyzer?</p> <p>I'm using pylucene, but I guess the answer is the same for Java etc. Here is the code I've come up with:</p> <pre><code>from lucene import * def term_match(self, phrase): query = BooleanQuery() sa = StandardAnalyzer() for token in sa.tokenStream("contents", StringReader(phrase)): term_query = TermQuery(Term("contents", token.term()) query.add(term_query), BooleanClause.Occur.SHOULD) </code></pre>
3
2009-09-07T16:26:23Z
4,268,451
<p>I've come across the same problem, and, using Lucene 2.9 API and Java, my code snippet looks like this:</p> <pre><code>final TokenStream tokenStream = new StandardAnalyzer(Version.LUCENE_29) .tokenStream( fieldName , new StringReader( value ) ); final List&lt; String &gt; result = new ArrayList&lt; String &gt;(); try { while ( tokenStream.incrementToken() ) { final TermAttribute term = ( TermAttribute ) tokenStream.getAttribute( TermAttribute.class ); result.add( term.term() ); } </code></pre>
0
2010-11-24T15:26:27Z
[ "python", "lucene", "pylucene" ]
What are the different options for processing uploaded PDF files in a Django application?
1,390,371
<p>Our Django application needs to do a few things with uploaded PDF files:</p> <ol> <li>Verify that the file is a PDF and isn't corrupted</li> <li>Check that the file isn't encrypted</li> <li>Count the number of pages</li> </ol> <p>We run into problems with one unfortunately popular application that's idea of an unencrypted PDF export is actually an encrypted PDF file, just with a blank password. We've been working with PyPDF to date, which is unable to read those files because the encryption is non-standard. The application exporting these files is quite popular among our users, which is a pain.</p> <p>Another application exported files with a bad MIME type (something other than <code>application/pdf</code>), so whatever we end up using needs to be able to cope with silly choking points like that.</p> <p>Is there an actively maintained, robust PDF library anywhere that we could utilize? Even PDFtk, a CLI utility that a couple people have been recommending, was last updated in 2006.</p> <p>Any help is appreciated.</p> <p><strong>Update:</strong> To clarify, it can be free or paid-for. Suggest whatever you think is the best option.</p>
1
2009-09-07T17:49:43Z
1,390,392
<p><a href="http://pdflib.com" rel="nofollow">PDFlib</a> is excellent, but costs money. You didn't say it had to be free, though implicitly somehow I assume you want it to be! :)</p>
1
2009-09-07T17:55:45Z
[ "python", "django", "pdf" ]
Removing redundant symbols from string
1,390,657
<p>Let's say I have a string like that: <code>'12,423,343.93'</code>. How to convert it to <code>float</code> in simple, effective and yet elegant way?</p> <p>It seems I need to remove redundant commas from the string and then call <code>float()</code>, but I have no good solution for that.</p> <p>Thanks</p>
2
2009-09-07T19:14:06Z
1,390,666
<pre><code>s = "12,423,343.93" f = float(s.replace(",", "")) </code></pre>
9
2009-09-07T19:17:02Z
[ "python", "floating-point" ]
Removing redundant symbols from string
1,390,657
<p>Let's say I have a string like that: <code>'12,423,343.93'</code>. How to convert it to <code>float</code> in simple, effective and yet elegant way?</p> <p>It seems I need to remove redundant commas from the string and then call <code>float()</code>, but I have no good solution for that.</p> <p>Thanks</p>
2
2009-09-07T19:14:06Z
1,391,175
<p>Note that the seperator symbols used vary from country to country. In some cultures, "." is used to seperate groups, and "," indicates a decimal point for instance. If you're parsing user-entered strings like this, it may be better to use the locale module instead. For example:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.atof('12,423,343.93') # No locale set yet, so this will refuse to parse ValueError: invalid literal for float(): 12,423,343.93 &gt;&gt;&gt; locale.setlocale(locale.LC_NUMERIC, "en_GB") # Use a UK locale. &gt;&gt;&gt; locale.atof('12,423,343.93') 12423343.93 </code></pre>
6
2009-09-07T22:26:04Z
[ "python", "floating-point" ]
Python: how do I implement 'pop' in this class?
1,390,966
<p>I'd like this class to act like a list. It's data resides in the attribute self.data. If I have an instance, pp = population, does defining <code>__getitem__</code> mean I can refer to pp instead of pp.data? Or is it the defining of <code>__repr__</code> that does that? Would deriving this class from list instead of object provide me with 'pop'. Right now I need to implement 'pop'method. Thanks</p> <pre><code>class population (object): def __init__ (self): self.data = [] def append(self, item): self.data.append(item) def extend(self, item): self.data.extend(item) def sort(self): self.data.sort(cmp=fitnesscompare) def __getitem__(self, index): return self.data[index] def __setitem__(self, index, item): self.data[index] = item def __len__(self): return len(self.data) def __repr__(self): return repr(self.data) def copy(self): return copy.deepcopy(self) </code></pre>
1
2009-09-07T21:09:20Z
1,390,988
<p>Why not just extend the list class? Then you have all of that functionality built in.</p> <pre><code>class population(list): # custom methods here </code></pre> <p>Just remember, instead of referencing <code>self.data</code> for the list, just reference <code>self</code>.</p>
7
2009-09-07T21:17:11Z
[ "python" ]
Python: how do I implement 'pop' in this class?
1,390,966
<p>I'd like this class to act like a list. It's data resides in the attribute self.data. If I have an instance, pp = population, does defining <code>__getitem__</code> mean I can refer to pp instead of pp.data? Or is it the defining of <code>__repr__</code> that does that? Would deriving this class from list instead of object provide me with 'pop'. Right now I need to implement 'pop'method. Thanks</p> <pre><code>class population (object): def __init__ (self): self.data = [] def append(self, item): self.data.append(item) def extend(self, item): self.data.extend(item) def sort(self): self.data.sort(cmp=fitnesscompare) def __getitem__(self, index): return self.data[index] def __setitem__(self, index, item): self.data[index] = item def __len__(self): return len(self.data) def __repr__(self): return repr(self.data) def copy(self): return copy.deepcopy(self) </code></pre>
1
2009-09-07T21:09:20Z
1,391,010
<pre><code>def pop(self, index=-1) : return self.data.pop(index) </code></pre> <p>This will implement the expected behavior :</p> <ul> <li>return the last item if no index is passed;</li> <li>return the item at "index" if passed;</li> <li>will use the type check of the underlying pop();</li> <li>will raise the same exceptions as the underlying pop().</li> </ul> <p>I would have sub classed List as Evan Fosmark suggested before, but I can see good reasons for not doing so. Composition can ease low coupling, and you have full control over it. But you have to write bridges for all the methods you want to delegate, it can be a pain...</p>
2
2009-09-07T21:25:36Z
[ "python" ]
Python: how do I implement 'pop' in this class?
1,390,966
<p>I'd like this class to act like a list. It's data resides in the attribute self.data. If I have an instance, pp = population, does defining <code>__getitem__</code> mean I can refer to pp instead of pp.data? Or is it the defining of <code>__repr__</code> that does that? Would deriving this class from list instead of object provide me with 'pop'. Right now I need to implement 'pop'method. Thanks</p> <pre><code>class population (object): def __init__ (self): self.data = [] def append(self, item): self.data.append(item) def extend(self, item): self.data.extend(item) def sort(self): self.data.sort(cmp=fitnesscompare) def __getitem__(self, index): return self.data[index] def __setitem__(self, index, item): self.data[index] = item def __len__(self): return len(self.data) def __repr__(self): return repr(self.data) def copy(self): return copy.deepcopy(self) </code></pre>
1
2009-09-07T21:09:20Z
1,391,053
<blockquote> <p>If I have an instance, pp = population, does defining <code>__getitem__</code> mean I can refer to pp instead of pp.data?</p> </blockquote> <p>Essentially, yes. Adding a <code>__getitem__</code> method is equivalent to overloading the [] operator in some other languages. Thus the following two would be equivalent:</p> <pre><code>pp.data[0] pp[0] </code></pre> <blockquote> <p>Or is it the defining of <code>__repr__</code> that does that?</p> </blockquote> <p>Defining <code>__repr__</code> will give you a string representation of the object. Thus these two calls would be equivalent:</p> <pre><code>repr(pp.data) repr(pp) </code></pre> <blockquote> <p>Would deriving this class from list instead of object provide me with 'pop'.</p> </blockquote> <p>From what I see right now, inheriting from list is probably the way to go. Unless I'm missing something, the only thing that's different is the sort method and copy. Just about everything else is the same.</p>
1
2009-09-07T21:41:38Z
[ "python" ]
Python: how do I implement 'pop' in this class?
1,390,966
<p>I'd like this class to act like a list. It's data resides in the attribute self.data. If I have an instance, pp = population, does defining <code>__getitem__</code> mean I can refer to pp instead of pp.data? Or is it the defining of <code>__repr__</code> that does that? Would deriving this class from list instead of object provide me with 'pop'. Right now I need to implement 'pop'method. Thanks</p> <pre><code>class population (object): def __init__ (self): self.data = [] def append(self, item): self.data.append(item) def extend(self, item): self.data.extend(item) def sort(self): self.data.sort(cmp=fitnesscompare) def __getitem__(self, index): return self.data[index] def __setitem__(self, index, item): self.data[index] = item def __len__(self): return len(self.data) def __repr__(self): return repr(self.data) def copy(self): return copy.deepcopy(self) </code></pre>
1
2009-09-07T21:09:20Z
1,391,450
<p>Is this really a <strong>list</strong> of things, or are you using a list to store a bunch of things? Before you inherit from list, why not just use a list?</p> <p>I try to save inheritance for things that are true is-a relationships. A Form is-a Window, a Dialog is-a Form, etc. If you are just modeling is-implemented-using-a, then just use the base class, or use containment and delegation.</p> <p>What is it about a population that is more than just a list?</p>
1
2009-09-08T00:43:07Z
[ "python" ]
Google App Engine - Request class query_string
1,391,026
<p>In Python and GAE, I would like to ask how to get the parameters of a query string in the url. As I know, the query_string part returns all the part after the "?" in the url. So what I have to do is to split the query string with "&amp;", and use the variables. Is there any other convinient way to manage the query string? How do you normally do it? </p> <pre><code>str_query = self.request.query_string m = str_query.split('&amp;') a = m[0] b = m[1] c = m[2] </code></pre> <p>Doing this way, in case, the query_string does not have any values, it threw an error:</p> <pre><code>IndexError: list index out of range </code></pre>
6
2009-09-07T21:31:07Z
1,391,032
<p>You don't need to complicate. You can retrieve all GET parameters with:</p> <pre><code>self.request.get('var_name') </code></pre> <p>Or if you want to retrieve them all in one list you can use:</p> <pre><code>self.request.get_all() </code></pre> <p>You can find more info on the Request class <a href="http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request%5Fget%5Fall">here</a>.</p>
17
2009-09-07T21:34:38Z
[ "python", "google-app-engine" ]
Google App Engine - Request class query_string
1,391,026
<p>In Python and GAE, I would like to ask how to get the parameters of a query string in the url. As I know, the query_string part returns all the part after the "?" in the url. So what I have to do is to split the query string with "&amp;", and use the variables. Is there any other convinient way to manage the query string? How do you normally do it? </p> <pre><code>str_query = self.request.query_string m = str_query.split('&amp;') a = m[0] b = m[1] c = m[2] </code></pre> <p>Doing this way, in case, the query_string does not have any values, it threw an error:</p> <pre><code>IndexError: list index out of range </code></pre>
6
2009-09-07T21:31:07Z
28,768,234
<p>If you want to iterate over all the parameters of your request, you should do something like this:</p> <pre><code>for argument in self.request.arguments(): values = self.request.get_all(argument) # do something with values (which is a list) </code></pre> <p>Or, you could build your own <code>dict</code> containing all the data:</p> <pre><code>params = {arg: self.request.get_all(arg) for arg in self.request.arguments()} </code></pre>
0
2015-02-27T15:10:26Z
[ "python", "google-app-engine" ]
function decorators in c#
1,391,157
<p>Is there a C# analog for Python's function decorators? It feels like it's doable with attributes and the reflection framework, but I don't see a way to replace functions at runtime.</p> <p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808">Python decorators</a> generally work this way:</p> <pre><code>class decorator(obj): def __init__(self, f): self.f = f def __call__(self, *args, **kwargs): print "Before" self.f() print "After" @decorator def func1(): print "Function 1" @decorator def func2(): print "Function 2" </code></pre> <p>Calling func1 and func2 would then result in</p> <pre> Before Function 1 After Before Function 2 After </pre> <p>The idea is that decorators will let me easily add common tasks at the entry and exit points of multiple functions.</p>
21
2009-09-07T22:19:37Z
1,391,176
<p>You can do that using <a href="http://www.postsharp.org/">Post Sharp</a>. Check out the demo video for instructions.</p>
8
2009-09-07T22:26:29Z
[ "c#", "python", "reflection", "decorator" ]
function decorators in c#
1,391,157
<p>Is there a C# analog for Python's function decorators? It feels like it's doable with attributes and the reflection framework, but I don't see a way to replace functions at runtime.</p> <p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808">Python decorators</a> generally work this way:</p> <pre><code>class decorator(obj): def __init__(self, f): self.f = f def __call__(self, *args, **kwargs): print "Before" self.f() print "After" @decorator def func1(): print "Function 1" @decorator def func2(): print "Function 2" </code></pre> <p>Calling func1 and func2 would then result in</p> <pre> Before Function 1 After Before Function 2 After </pre> <p>The idea is that decorators will let me easily add common tasks at the entry and exit points of multiple functions.</p>
21
2009-09-07T22:19:37Z
1,391,202
<p>The way I achieve this is through <a href="http://en.wikipedia.org/wiki/Aspect-oriented%5Fprogramming">AOP frameworks</a> like <a href="http://www.castleproject.org/dynamicproxy/index.html">Castle Dynamic Proxy</a>, <a href="http://www.springframework.net/doc/reference/html/aop-quickstart.html">Spring.NET</a> or even the <a href="http://msdn.microsoft.com/en-us/library/cc309507.aspx">Policy Injection Application Block</a>.</p>
12
2009-09-07T22:37:40Z
[ "c#", "python", "reflection", "decorator" ]
function decorators in c#
1,391,157
<p>Is there a C# analog for Python's function decorators? It feels like it's doable with attributes and the reflection framework, but I don't see a way to replace functions at runtime.</p> <p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808">Python decorators</a> generally work this way:</p> <pre><code>class decorator(obj): def __init__(self, f): self.f = f def __call__(self, *args, **kwargs): print "Before" self.f() print "After" @decorator def func1(): print "Function 1" @decorator def func2(): print "Function 2" </code></pre> <p>Calling func1 and func2 would then result in</p> <pre> Before Function 1 After Before Function 2 After </pre> <p>The idea is that decorators will let me easily add common tasks at the entry and exit points of multiple functions.</p>
21
2009-09-07T22:19:37Z
1,391,302
<p>you can sort of achieve that by "ContextBoundObject" in the .NET framework. but it's a bit convoluted because it basically uses .net remoting infrastructure to intercept method calls. (the runtime overhead is minimum if your calls are within the same app domain but just across different "context"). so the better approaches would be the ones mentioned above by the other posters. </p>
4
2009-09-07T23:28:12Z
[ "c#", "python", "reflection", "decorator" ]
Pyqt GroupBox parenting
1,391,174
<p>In Python and Pyqt - I've got a simple class which instantiates a Label class and a GroupBox class. </p> <p>According to docs, passing the Groupbox to the Label upon creation should make the Groupbox the parent of Label. However, I must be missing something simple here. When I create the GroupBox it's fine, when I create the Label however - it appears distorted (or perhaps behind the GroupBox?)</p> <p>Cheers -</p> <pre><code>from PyQt4.QtCore import * from PyQt4.QtGui import * import sys class FileBrowser(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setGeometry(0, 0, 920, 780) self.initClasses() def initClasses(self): # GroupBox self.groupBox1 = GroupBox(self, QRect(20, 10, 191, 131), 'Shot Info') # Label self.labelGroup1_ShotInfo = Label(self, QRect(10, 26, 52, 15), 'Film') class GroupBox(QWidget): def __init__(self, parent, geo, title): QWidget.__init__(self, parent) obj = QGroupBox(parent) obj.setGeometry(geo) obj.setTitle(title) class Label(QWidget): def __init__(self, parent, geo, text): QWidget.__init__(self, parent) obj = QLabel(parent) obj.setGeometry(geo) obj.setText(text) def main(): app = QApplication(sys.argv) w = FileBrowser() w.show() sys.exit(app.exec_()) if __name__ == "__main__": main() </code></pre>
1
2009-09-07T22:26:04Z
1,403,724
<p>The problem is that you are not using a layout. Because you are not using one, both widgets are being rendered one on top of the other one. It of course depends on what you are trying to do, but the following should be a good example: <code></p> <pre><code>class FileBrowser(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setGeometry(0, 0, 920, 780) self.initClasses() # changes layout = QVBoxLayout(self) # create layout out layout.addWidget(self.groupBox1) # add widget layout.addWidget(self.labelGroup1_ShotInfo) # add widget # set my layout to make sure contents are correctly rendered self.setLayout(layout) def initClasses(self): # GroupBox self.groupBox1 = GroupBox(self, QRect(20, 10, 191, 131), 'Shot Info') # Label self.labelGroup1_ShotInfo = Label(self, QRect(10, 26, 52, 15), 'Film') </code></pre> <p></code></p> <p>The above example uses a vertical layout and solves the problem. </p>
2
2009-09-10T06:54:57Z
[ "python", "qt", "oop", "pyqt" ]
Application Structure for GUI & Functions
1,391,190
<p>I'm starting a basic application using Python and PyQt and could use some experienced insight. Here's the structure I was thinking. This is understandably subjective, but is there a better way?</p> <pre><code>myApp/GUI/__init__.py mainWindow.py subWindow1.py subWindow2.py myApp/Logic/__init__.py setOfMethods1.py setOfMethods2.py mainWindow imports subWindows mainWindow imports Logic module </code></pre>
1
2009-09-07T22:31:51Z
1,391,252
<h2>MVC</h2> <p>It looks like you have been reading about model-view-controller.</p> <p>Separating the UI from the back end is a good idea. It will make runnings tests and debugging just the logic side easier, and the internal structure will be more modular.</p> <p>I'm not certain it makes as much sense to split the UI into the currently anticipated windows, though. I might just let the UI part grow and factor for common code.</p>
1
2009-09-07T22:58:53Z
[ "python", "user-interface", "structure" ]
similar function to php's str_replace in python?
1,391,429
<p>is there a similar function in python that takes search(array) and replace(array) as a parameter? Then takes a value from each array and uses them to do search and replace on subject(string).</p> <p>I know I can achieve this using for loops, but just looking more elegant way.</p>
2
2009-09-08T00:37:49Z
1,391,466
<p>I believe the answer is no.</p> <p>I would specify your search/replace strings in a list, and the iterate over it:</p> <pre><code>edits = [(search0, replace0), (search1, replace1), (search2, replace2)] # etc. for search, replace in edits: s = s.replace(search, replace) </code></pre> <p>Even if python did have a <code>str_replace</code>-style function, I think I would still separate out my search/replace strings as a list, so really this is only taking one extra line of code.</p> <p>Finally, this is a programming language after all. If it doesn't supply the function you want, you can always define it yourself.</p>
11
2009-09-08T00:48:01Z
[ "python" ]
similar function to php's str_replace in python?
1,391,429
<p>is there a similar function in python that takes search(array) and replace(array) as a parameter? Then takes a value from each array and uses them to do search and replace on subject(string).</p> <p>I know I can achieve this using for loops, but just looking more elegant way.</p>
2
2009-09-08T00:37:49Z
1,391,574
<p>Do it with regexps:</p> <pre><code>import re def replace_from_list(replacements, str): def escape_string_to_regex(str): return re.sub(r"([\\.^$*+?{}[\]|\(\)])", r"\\\1", str) def get_replacement(match): return replacements[match.group(0)] replacements = dict(replacements) replace_from = [escape_string_to_regex(r) for r in replacements.keys()] regex = "|".join(["(%s)" % r for r in replace_from]) repl = re.compile(regex) return repl.sub(get_replacement, str) # Simple replacement: assert replace_from_list([("in1", "out1")], "in1") == "out1" # Replacements are never themselves replaced, even if later search strings match # earlier destination strings: assert replace_from_list([("1", "2"), ("2", "3")], "123") == "233" # These are plain strings, not regexps: assert replace_from_list([("...", "out")], "abc ...") == "abc out" </code></pre> <p>Using regexps for this makes the searching fast. This won't iteratively replace replacements with further replacements, which is <em>usually</em> what's wanted.</p>
1
2009-09-08T01:44:53Z
[ "python" ]
similar function to php's str_replace in python?
1,391,429
<p>is there a similar function in python that takes search(array) and replace(array) as a parameter? Then takes a value from each array and uses them to do search and replace on subject(string).</p> <p>I know I can achieve this using for loops, but just looking more elegant way.</p>
2
2009-09-08T00:37:49Z
1,391,771
<p>Heh - you could use the one-liner below whose elegance is second only to its convenience :-P</p> <p>(Acts like PHP when search is longer than replace, too, if I read that correctly in the PHP docs.):</p> <p><strong>** Edit: This new version works for all sized substrings to replace. **</strong></p> <pre><code>&gt;&gt;&gt; subject = "Coming up with these convoluted things can be very addictive." &gt;&gt;&gt; search = ['Coming', 'with', 'things', 'addictive.', ' up', ' these', 'convoluted ', ' very'] &gt;&gt;&gt; replace = ['Making', 'Python', 'one-liners', 'fun!'] &gt;&gt;&gt; reduce(lambda s, p: s.replace(p[0],p[1]),[subject]+zip(search, replace+['']*(len(search)-len(replace)))) 'Making Python one-liners can be fun!' </code></pre>
2
2009-09-08T03:11:40Z
[ "python" ]
easy way of installing python apps without using PYTHON path or muli symlink in site-package
1,391,584
<p>I didn't want to install python modules using easy install, symlinks in site-packages or PYTHONPATH.<br> So, I am trying something that I do wants system wide, then any application installation is done locally. Note, the root password is required only once here.</p> <p>First create a symblink of.../pythonX.Y/site-packages/mymodules -> /home/me/lib/python_related</p> <p>So, I create a directory called </p> <pre><code>/home/me/lib/python_related/ </code></pre> <p>In there:</p> <pre><code>/home/me/lib/python_related /home/me/lib/python_related/__init__.py /home/me/lib/python_related/django_related/ /home/me/lib/python_related/django_related/core /home/me/lib/python_related/django_related/core/Django1.0 /home/me/lib/python_related/django_related/core/Django1.1 /home/me/lib/python_related/django_related/core/mycurrent_django -&gt; Django1.1/django /home/me/lib/python_related/django_related/apps /home/me/lib/python_related/django_related/apps/tagging /home/me/lib/python_related/django_related/apps/tagging/django-tagging-0.2 /home/me/lib/python_related/django_related/apps/tagging/django-tagging-0.3 /home/me/lib/python_related/django_related/apps/tagging/mycurrent_tagging -&gt; django-tagging-0.3 </code></pre> <p>Now, here is the content of:</p> <pre><code>/home/me/lib/python_related/__init__.py ========================================== import sys, os # tell us where you keep all your modules and this didn't work as it gave me # the location of the site-packages #PYTHON_MODULE_PATH = os.path.dirname(__file__) PYTHON_MODULE_PATH = "/home/me/libs/python_bucket" def run_cmd(cmd): """ Given a command name, this function will run the command and returns the output in a list. """ output = [] phdl = os.popen(cmd) while 1: line = phdl.readline() if line == "": break output.append(line.replace("\n", "")) return output def install(): """ A cheesy way of installing and managing your python apps locally without a need to install them in the site-package. All you'd need is to install the directory containing this file in the site-package and that's it. Anytime you have a python package you want to install, just put it in a proper sub-directory and make a symlink to that directory called mycurrent_xyz and you are done. (e.g. mycurrent_django, mycurrent_tagging .. etc) """ cmd = "find %s -name mycurrent_*" % PYTHON_MODULE_PATH modules_to_be_installed = run_cmd(cmd) sys.path += modules_to_be_installed install() ======================================================= </code></pre> <p>Now in any new python project, just import your mymodules and that pulls in any apps that you have in the above directory with the proper symbolic link. This way you can have multiple copies of apps and just use the mycurrent_xyz to the one you want to use.</p> <p>Now here is question. Is this a good way of doing it?</p>
0
2009-09-08T01:50:32Z
1,391,947
<p>Have a look at <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>.</p> <p>It may do what you are after.</p>
4
2009-09-08T04:19:34Z
[ "python", "django", "module", "pythonpath" ]
Django: How to create a leaderboard
1,391,601
<p>Lets say I have around 1,000,000 users. I want to find out what position any given user is in, and which users are around him. A user can get a new achievement at any time, and if he could see his standing update, that would be wonderful.</p> <p>Honestly, every way I think of doing this would be horrendously expensive in time and/or memory. Ideas? My closest idea so far is to order the users offline and build percentile buckets, but that can't show a user his exact position.</p> <p>Some code if that helps you django people :</p> <pre><code>class Alias(models.Model) : awards = models.ManyToManyField('Award', through='Achiever') @property def points(self) : p = cache.get('alias_points_' + str(self.id)) if p is not None : return p points = 0 for a in self.achiever_set.all() : points += a.award.points * a.count cache.set('alias_points_' + str(self.id), points, 60 * 60) # 1 hour return points class Award(MyBaseModel): owner_points = models.IntegerField(help_text="A non-normalized point value. Very subjective but try to be consistent. Should be proporional. 2x points = 2x effort (or skill)") true_points = models.FloatField(help_text="The true value of this award. Recalculated with a cron job. Based on number of people who won it", editable=False, null=True) @property def points(self) : if self.true_points : # blend true_points into real points over 30 days age = datetime.now() - self.created blend_days = 30 if age &gt; timedelta(days=blend_days) : age = timedelta(days=blend_days) num_days = 1.0 * age.days / blend_days r = self.true_points * num_days + self.owner_points * (1 - num_days) return int(r * 10) / 10.0 else : return self.owner_points class Achiever(MyBaseModel): award = models.ForeignKey(Award) alias = models.ForeignKey(Alias) count = models.IntegerField(default=1) </code></pre>
8
2009-09-08T01:58:50Z
1,391,622
<p>I think Counterstrike solves this by requiring users to meet a minimum threshold to become ranked--you only need to accurately sort the top 10% or whatever.</p> <p>If you want to sort everyone, consider that you don't need to sort them perfectly: sort them to 2 significant figures. With 1M users you could update the leaderboard for the top 100 users in real time, the next 1000 users to the nearest 10, then the masses to the nearest 1% or 10%. You won't jump from place 500,000 to place 99 in one round.</p> <p>Its meaningless to get the 10 user context above and below place 500,000--the ordering of the masses will be incredibly jittery from round to round due to the exponential distribution.</p> <p>Edit: Take a look at the <a href="http://stackoverflow.com/users">SO leaderboard</a>. Now go to <a href="http://stackoverflow.com/users?page=500">page 500</a> out of 2500 (roughly 20th percentile). Is there any point to telling the people with rep '157' that the 10 people on either side of them also have rep '157'? You'll jump 20 places either way if your rep goes up or down a point. More extreme, is that right now the bottom 1056 pages (out of 2538), or the bottom 42% of users, are tied with rep 1. you get one more point, and you jumped up <a href="http://stackoverflow.com/users?page=1482">1055 pages</a>. Which is roughly a 37,000 increase in rank. It might be cool to tell them "you can beat 37k people if you get one more point!" but does it matter how many significant figures the 37k number has?</p> <p>There's no value in knowing your peers on a ladder until you're already at the top, because anywhere but the top, there's an overwhelming number of them.</p>
4
2009-09-08T02:07:59Z
[ "python", "sql", "django", "leaderboard" ]
Django: How to create a leaderboard
1,391,601
<p>Lets say I have around 1,000,000 users. I want to find out what position any given user is in, and which users are around him. A user can get a new achievement at any time, and if he could see his standing update, that would be wonderful.</p> <p>Honestly, every way I think of doing this would be horrendously expensive in time and/or memory. Ideas? My closest idea so far is to order the users offline and build percentile buckets, but that can't show a user his exact position.</p> <p>Some code if that helps you django people :</p> <pre><code>class Alias(models.Model) : awards = models.ManyToManyField('Award', through='Achiever') @property def points(self) : p = cache.get('alias_points_' + str(self.id)) if p is not None : return p points = 0 for a in self.achiever_set.all() : points += a.award.points * a.count cache.set('alias_points_' + str(self.id), points, 60 * 60) # 1 hour return points class Award(MyBaseModel): owner_points = models.IntegerField(help_text="A non-normalized point value. Very subjective but try to be consistent. Should be proporional. 2x points = 2x effort (or skill)") true_points = models.FloatField(help_text="The true value of this award. Recalculated with a cron job. Based on number of people who won it", editable=False, null=True) @property def points(self) : if self.true_points : # blend true_points into real points over 30 days age = datetime.now() - self.created blend_days = 30 if age &gt; timedelta(days=blend_days) : age = timedelta(days=blend_days) num_days = 1.0 * age.days / blend_days r = self.true_points * num_days + self.owner_points * (1 - num_days) return int(r * 10) / 10.0 else : return self.owner_points class Achiever(MyBaseModel): award = models.ForeignKey(Award) alias = models.ForeignKey(Alias) count = models.IntegerField(default=1) </code></pre>
8
2009-09-08T01:58:50Z
1,395,801
<p>One million is not so much, I would try it the easy way first. If the points property is the thing you are sorting on that needs to be a database column. Then you can just do a count of points greater than the person in question to get the rank. To get other people near a person in question you do a query of people with higher points and sort ascending limit it to the number of people you want.</p> <p>The tricky thing will be calculating the points on save. You need to use the current time as a bonus multiplier. One point now needs to turn into a number that is less than 1 point 5 days from now. If your users frequently gain points you will need to create a queue to handle the load.</p>
0
2009-09-08T19:14:35Z
[ "python", "sql", "django", "leaderboard" ]
Is it possible to deploy one GAE application from another GAE application?
1,391,608
<p>In order to redeploy a GAE application, I currently have to install the GAE deployment tools on the system that I am using for deployment. While this process is relatively straight forward, the deployment process is a manual process that does not work from behind a firewall and the deployment tools must be installed on every machine that will be used for updating GAE apps. A more ideal solution would be if I could update a GAE application from another GAE application that I have deployed previously. This would remove the need to have multiple systems configured to deploy apps. </p> <p>Since the GAE deployment tools are written in Python and the GAE App Engine supports Python, is it possible to modify appcfg.py to work from within GAE? The use case would be to pull a project from GitHub or some other online repository and update one GAE application from another GAE app. If this is not possible, what is the limiting constraint?</p>
3
2009-09-08T02:02:11Z
1,391,649
<p>One limiting constraint could be the protocol that the python sdk uses to communicate with the GAE servers. If it only uses HTTP, you might be OK. but if it's anything else, you might be out of luck because you can't open a socket directly from within GAE.</p>
2
2009-09-08T02:21:14Z
[ "python", "google-app-engine" ]
Is it possible to deploy one GAE application from another GAE application?
1,391,608
<p>In order to redeploy a GAE application, I currently have to install the GAE deployment tools on the system that I am using for deployment. While this process is relatively straight forward, the deployment process is a manual process that does not work from behind a firewall and the deployment tools must be installed on every machine that will be used for updating GAE apps. A more ideal solution would be if I could update a GAE application from another GAE application that I have deployed previously. This would remove the need to have multiple systems configured to deploy apps. </p> <p>Since the GAE deployment tools are written in Python and the GAE App Engine supports Python, is it possible to modify appcfg.py to work from within GAE? The use case would be to pull a project from GitHub or some other online repository and update one GAE application from another GAE app. If this is not possible, what is the limiting constraint?</p>
3
2009-09-08T02:02:11Z
1,391,652
<p>What problem did you have by trying to update behind a firewall?</p> <p>I've got some, but finally I manage to work around them. </p> <p>About your question, the constraint is that you cannot write files into a GAE app, so even though you could possibly pull from the VCS you can't write those pulled files. </p> <p>So you would have to update from outside the GAE in first place.</p> <p>Anyway every machine that needs to update the GAE should have the SDK anyway just to see if they changes work.</p> <p>So, If you really want to do this you have two alternatives:</p> <ol> <li><p>Host your own "updater" site and istall the SDK there, then when you want to update log into your side ( or run a script ) and do the remote update.</p></li> <li><p>Although I don't know Amazon EC2 well, I think you can do pretty much the same thing as op 1 from there. </p></li> </ol> <p>Finally I think the password to update has to be typed always. ( you could have the SDK of the App engine and modify that, because it is open source ) </p>
0
2009-09-08T02:22:18Z
[ "python", "google-app-engine" ]
Is it possible to deploy one GAE application from another GAE application?
1,391,608
<p>In order to redeploy a GAE application, I currently have to install the GAE deployment tools on the system that I am using for deployment. While this process is relatively straight forward, the deployment process is a manual process that does not work from behind a firewall and the deployment tools must be installed on every machine that will be used for updating GAE apps. A more ideal solution would be if I could update a GAE application from another GAE application that I have deployed previously. This would remove the need to have multiple systems configured to deploy apps. </p> <p>Since the GAE deployment tools are written in Python and the GAE App Engine supports Python, is it possible to modify appcfg.py to work from within GAE? The use case would be to pull a project from GitHub or some other online repository and update one GAE application from another GAE app. If this is not possible, what is the limiting constraint?</p>
3
2009-09-08T02:02:11Z
1,392,766
<p>Is it possible? Yes. The protocol appcfg uses to update apps is entirely HTTP-based, so there's absolutely no reason you couldn't write an app that's capable of deploying other apps (or redeploying itself - self-modifying code)! You may even be able to reuse large parts of appcfg.py to do it.</p> <p>Is it easy? Probably not. It's quite likely you'll need to understand a decent chunk of appcfg's internals, and the RPCs it uses to upload new apps - not a trivial undertaking. You'll also need to store your credentials in the app, in all likelihood - though you can use a role account that is and admin only for the apps it's deploying to minimize risk there.</p>
5
2009-09-08T08:44:38Z
[ "python", "google-app-engine" ]
Python web scraping involving HTML tags with attributes
1,391,657
<p>I'm trying to make a web scraper that will parse a web-page of publications and extract the authors. The skeletal structure of the web-page is the following:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;div id="contents"&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class="author"&gt;####I want whatever is located here ###&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I've been trying to use BeautifulSoup and lxml thus far to accomplish this task, but I'm not sure how to handle the two div tags and td tag because they have attributes. In addition to this, I'm not sure whether I should rely more on BeautifulSoup or lxml or a combination of both. What should I do?</p> <p>At the moment, my code looks like what is below:</p> <pre><code> import re import urllib2,sys import lxml from lxml import etree from lxml.html.soupparser import fromstring from lxml.etree import tostring from lxml.cssselect import CSSSelector from BeautifulSoup import BeautifulSoup, NavigableString address='http://www.example.com/' html = urllib2.urlopen(address).read() soup = BeautifulSoup(html) html=soup.prettify() html=html.replace('&amp;nbsp', '&amp;#160') html=html.replace('&amp;iacute','&amp;#237') root=fromstring(html) </code></pre> <p>I realize that a lot of the import statements may be redundant, but I just copied whatever I currently had in more source file.</p> <p>EDIT: I suppose that I didn't make this quite clear, but I have multiple tags in page that I want to scrape. </p>
6
2009-09-08T02:23:25Z
1,391,752
<p>It's not clear to me from your question why you need to worry about the <code>div</code> tags -- what about doing just:</p> <pre><code>soup = BeautifulSoup(html) thetd = soup.find('td', attrs={'class': 'author'}) print thetd.string </code></pre> <p>On the HTML you give, running this emits exactly:</p> <pre><code>####I want whatever is located here ### </code></pre> <p>which appears to be what you want. Maybe you can specify better exactly what it is you need and this super-simple snippet doesn't do -- multiple <code>td</code> tags all of class <code>author</code> of which you need to consider (all? just some? which ones?), possibly missing any such tag (what do you want to do in that case), and the like. It's hard to infer what exactly are your specs, just from this simple example and overabundant code;-).</p> <p><strong>Edit</strong>: if, as per the OP's latest comment, there are multiple such td tags, one per author:</p> <pre><code>thetds = soup.findAll('td', attrs={'class': 'author'}) for thetd in thetds: print thetd.string </code></pre> <p>...i.e., not much harder at all!-)</p>
10
2009-09-08T03:01:06Z
[ "python", "beautifulsoup", "lxml", "screen-scraping" ]
Python web scraping involving HTML tags with attributes
1,391,657
<p>I'm trying to make a web scraper that will parse a web-page of publications and extract the authors. The skeletal structure of the web-page is the following:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;div id="contents"&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class="author"&gt;####I want whatever is located here ###&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I've been trying to use BeautifulSoup and lxml thus far to accomplish this task, but I'm not sure how to handle the two div tags and td tag because they have attributes. In addition to this, I'm not sure whether I should rely more on BeautifulSoup or lxml or a combination of both. What should I do?</p> <p>At the moment, my code looks like what is below:</p> <pre><code> import re import urllib2,sys import lxml from lxml import etree from lxml.html.soupparser import fromstring from lxml.etree import tostring from lxml.cssselect import CSSSelector from BeautifulSoup import BeautifulSoup, NavigableString address='http://www.example.com/' html = urllib2.urlopen(address).read() soup = BeautifulSoup(html) html=soup.prettify() html=html.replace('&amp;nbsp', '&amp;#160') html=html.replace('&amp;iacute','&amp;#237') root=fromstring(html) </code></pre> <p>I realize that a lot of the import statements may be redundant, but I just copied whatever I currently had in more source file.</p> <p>EDIT: I suppose that I didn't make this quite clear, but I have multiple tags in page that I want to scrape. </p>
6
2009-09-08T02:23:25Z
1,391,820
<p>BeautifulSoup is certainly the canonical HTML parser/processor. But if you have just this kind of snippet you need to match, instead of building a whole hierarchical object representing the HTML, pyparsing makes it easy to define leading and trailing HTML tags as part of creating a larger search expression:</p> <pre><code>from pyparsing import makeHTMLTags, withAttribute, SkipTo author_td, end_td = makeHTMLTags("td") # only interested in &lt;td&gt;'s where class="author" author_td.setParseAction(withAttribute(("class","author"))) search = author_td + SkipTo(end_td)("body") + end_td for match in search.searchString(html): print match.body </code></pre> <p>Pyparsing's makeHTMLTags function does a lot more than just emit <code>"&lt;tag&gt;"</code> and <code>"&lt;/tag&gt;"</code> expressions. It also handles:</p> <ul> <li>caseless matching of tags</li> <li><code>"&lt;tag/&gt;"</code> syntax</li> <li>zero or more attribute in the opening tag</li> <li>attributes defined in arbitrary order</li> <li>attribute names with namespaces</li> <li>attribute values in single, double, or no quotes</li> <li>intervening whitespace between tag and symbols, or attribute name, '=', and value</li> <li>attributes are accessible after parsing as named results</li> </ul> <p>These are the common pitfalls when considering using a regex for HTML scraping.</p>
1
2009-09-08T03:31:52Z
[ "python", "beautifulsoup", "lxml", "screen-scraping" ]
Python web scraping involving HTML tags with attributes
1,391,657
<p>I'm trying to make a web scraper that will parse a web-page of publications and extract the authors. The skeletal structure of the web-page is the following:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;div id="contents"&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class="author"&gt;####I want whatever is located here ###&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I've been trying to use BeautifulSoup and lxml thus far to accomplish this task, but I'm not sure how to handle the two div tags and td tag because they have attributes. In addition to this, I'm not sure whether I should rely more on BeautifulSoup or lxml or a combination of both. What should I do?</p> <p>At the moment, my code looks like what is below:</p> <pre><code> import re import urllib2,sys import lxml from lxml import etree from lxml.html.soupparser import fromstring from lxml.etree import tostring from lxml.cssselect import CSSSelector from BeautifulSoup import BeautifulSoup, NavigableString address='http://www.example.com/' html = urllib2.urlopen(address).read() soup = BeautifulSoup(html) html=soup.prettify() html=html.replace('&amp;nbsp', '&amp;#160') html=html.replace('&amp;iacute','&amp;#237') root=fromstring(html) </code></pre> <p>I realize that a lot of the import statements may be redundant, but I just copied whatever I currently had in more source file.</p> <p>EDIT: I suppose that I didn't make this quite clear, but I have multiple tags in page that I want to scrape. </p>
6
2009-09-08T02:23:25Z
2,752,712
<p>or you could be using pyquery, since BeautifulSoup is not actively maintained anymore, see <a href="http://www.crummy.com/software/BeautifulSoup/3.1-problems.html">http://www.crummy.com/software/BeautifulSoup/3.1-problems.html</a></p> <p>first, install pyquery with </p> <pre><code>easy_install pyquery </code></pre> <p>then your script could be as simple as</p> <pre><code>from pyquery import PyQuery d = PyQuery('http://mywebpage/') allauthors = [ td.text() for td in d('td.author') ] </code></pre> <p>pyquery uses the css selector syntax familiar from jQuery which I find more intuitive than BeautifulSoup's. It uses lxml underneath, and is much faster than BeautifulSoup. But BeautifulSoup is pure python, and thus works on Google's app engine as well</p>
6
2010-05-02T07:01:44Z
[ "python", "beautifulsoup", "lxml", "screen-scraping" ]
Python web scraping involving HTML tags with attributes
1,391,657
<p>I'm trying to make a web scraper that will parse a web-page of publications and extract the authors. The skeletal structure of the web-page is the following:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;div id="contents"&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class="author"&gt;####I want whatever is located here ###&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I've been trying to use BeautifulSoup and lxml thus far to accomplish this task, but I'm not sure how to handle the two div tags and td tag because they have attributes. In addition to this, I'm not sure whether I should rely more on BeautifulSoup or lxml or a combination of both. What should I do?</p> <p>At the moment, my code looks like what is below:</p> <pre><code> import re import urllib2,sys import lxml from lxml import etree from lxml.html.soupparser import fromstring from lxml.etree import tostring from lxml.cssselect import CSSSelector from BeautifulSoup import BeautifulSoup, NavigableString address='http://www.example.com/' html = urllib2.urlopen(address).read() soup = BeautifulSoup(html) html=soup.prettify() html=html.replace('&amp;nbsp', '&amp;#160') html=html.replace('&amp;iacute','&amp;#237') root=fromstring(html) </code></pre> <p>I realize that a lot of the import statements may be redundant, but I just copied whatever I currently had in more source file.</p> <p>EDIT: I suppose that I didn't make this quite clear, but I have multiple tags in page that I want to scrape. </p>
6
2009-09-08T02:23:25Z
5,882,262
<p>The lxml library is now the standard for parsing html in python. The interface can seem awkward at first, but it is very serviceable for what it does. </p> <p>You should let the libary handle the xml specialism, such as those escaped &entities;</p> <pre><code>import lxml.html html = """&lt;html&gt;&lt;body&gt;&lt;div id="container"&gt;&lt;div id="contents"&gt;&lt;table&gt;&lt;tbody&gt;&lt;tr&gt; &lt;td class="author"&gt;####I want whatever is located here, eh? &amp;iacute; ###&lt;/td&gt; &lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;""" root = lxml.html.fromstring(html) tds = root.cssselect("div#contents td.author") print tds # gives [&lt;Element td at 84ee2cc&gt;] print tds[0].text # what you want, including the 'í' </code></pre>
5
2011-05-04T10:51:34Z
[ "python", "beautifulsoup", "lxml", "screen-scraping" ]
How can I run gtk.main() asynchronsly in pygtk?
1,391,680
<p>The basic code that I have so far is below. How do I thread gtk.main() so that the code after Display is initialized runs asynchronously?</p> <pre><code>import pygtk pygtk.require("2.0") import gtk class Display(): def __init__(self): self.fail = "This will fail to display" window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("destroy", lambda w: gtk.main_quit()) window.show() self.main() def main(self): gtk.main() class Test(): def __init__(self, display): print display.fail d = Display() t = Test(d) </code></pre>
0
2009-09-08T02:33:36Z
1,394,773
<p>Just put the <code>gtk.main</code> call after everything else. If you need to have the controller in a separate thread, make sure you do all gtk related function/methods by doing gobject.idle_add(<em>widget.method</em>).</p> <pre><code>import pygtk pygtk.require("2.0") import gtk class Display(object): def __init__(self): self.fail = "This will fail to display" window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("destroy", lambda w: gtk.main_quit()) window.show() class Test(object): def __init__(self, display): print display.fail d = Display() t = Test(d) gtk.main() </code></pre>
0
2009-09-08T15:50:59Z
[ "python", "multithreading", "pygtk" ]
How can I run gtk.main() asynchronsly in pygtk?
1,391,680
<p>The basic code that I have so far is below. How do I thread gtk.main() so that the code after Display is initialized runs asynchronously?</p> <pre><code>import pygtk pygtk.require("2.0") import gtk class Display(): def __init__(self): self.fail = "This will fail to display" window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("destroy", lambda w: gtk.main_quit()) window.show() self.main() def main(self): gtk.main() class Test(): def __init__(self, display): print display.fail d = Display() t = Test(d) </code></pre>
0
2009-09-08T02:33:36Z
3,405,343
<p>You could use Twisted with the gtk2reactor. </p> <p><a href="http://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html" rel="nofollow">http://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html</a></p>
0
2010-08-04T12:12:23Z
[ "python", "multithreading", "pygtk" ]
how to encode a key in mime format
1,392,194
<p>if the key is in ascii armored form ,taken by any pgp public key server and i want to convert it in mime encoded format.how to do ?is there any python api methods ?</p> <p>thnks a lot</p>
0
2009-09-08T05:44:59Z
1,392,395
<p>What do you mean by MIME encoded? Please elaborate.</p> <p>Did you ask the same question already? See my answer to other question about PEM,</p> <p><a href="http://stackoverflow.com/questions/1387867/how-to-convert-base64-radix64-public-key-to-a-pem-format-in-python">http://stackoverflow.com/questions/1387867/how-to-convert-base64-radix64-public-key-to-a-pem-format-in-python</a></p>
0
2009-09-08T07:00:08Z
[ "python", "encoding" ]
Advantages of UserDict class in Python
1,392,396
<p>What are advantages of using <strong>UserDict</strong> class?</p> <p>I mean, what I really get if instead of</p> <pre><code>class MyClass(object): def __init__(self): self.a = 0 self.b = 0 ... m = MyClass() m.a = 5 m.b = 7 </code></pre> <p>I will write the following:</p> <pre><code>class MyClass(UserDict): def __init__(self): UserDict.__init__(self) self["a"] = 0 self["b"] = 0 ... m = MyClass() m["a"] = 5 m["b"] = 7 </code></pre> <p><strong>Edit</strong>: If I understand right I can add new fields to an object in a runtime in both cases?</p> <pre><code>m.c = "Cool" </code></pre> <p>and</p> <pre><code>m["c"] = "Cool" </code></pre>
9
2009-09-08T07:00:17Z
1,392,402
<p>Subclassing the dict gives you all the features of a dict, like <code>if x in dict:</code>. You normally do this if you want to extend the features of the dict, creating an ordered dict for example.</p> <p>BTW: In more recent Python versions you can subclass <code>dict</code> directly, you don't need <code>UserDict</code>.</p>
6
2009-09-08T07:03:36Z
[ "python", "oop" ]
Advantages of UserDict class in Python
1,392,396
<p>What are advantages of using <strong>UserDict</strong> class?</p> <p>I mean, what I really get if instead of</p> <pre><code>class MyClass(object): def __init__(self): self.a = 0 self.b = 0 ... m = MyClass() m.a = 5 m.b = 7 </code></pre> <p>I will write the following:</p> <pre><code>class MyClass(UserDict): def __init__(self): UserDict.__init__(self) self["a"] = 0 self["b"] = 0 ... m = MyClass() m["a"] = 5 m["b"] = 7 </code></pre> <p><strong>Edit</strong>: If I understand right I can add new fields to an object in a runtime in both cases?</p> <pre><code>m.c = "Cool" </code></pre> <p>and</p> <pre><code>m["c"] = "Cool" </code></pre>
9
2009-09-08T07:00:17Z
1,394,572
<p><a href="http://docs.python.org/library/userdict.html?#UserDict.UserDict"><code>UserDict.UserDict</code> has no substantial added value since Python 2.2, since, as @gs mention, you can now subclass <code>dict</code> directly -- it exists only for backwards compatibility with Python 2.1 and earlier, when builtin types could not be subclasses. Still, it was kept in Python 3 (now in its proper place in the <code>collections</code> module) since, as <a href="http://docs.python.org/3.1/library/collections.html?#collections.UserDict">the docs</a> now mention,</p> <blockquote> <p>The need for this class has been partially supplanted by the ability to subclass directly from dict; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute.</p> </blockquote> <p><code>UserDict.DictMixin</code></a>, in Python 2, is quite handy -- as the docs say,</p> <blockquote> <p>The module defines a mixin, DictMixin, defining all dictionary methods for classes that already have a minimum mapping interface. This greatly simplifies writing classes that need to be substitutable for dictionaries (such as the shelve module).</p> </blockquote> <p>You subclass it, define some fundamental methods (at least <code>__getitem__</code>, which is sufficient for a read-only mapping without the ability to get keys or iterate; also <code>keys</code> if you need those abilities; possibly <code>__setitem__</code>, and you have a R/W mapping without the ability of removing items; add <code>__delitem__</code> for full capability, and possibly override other methods for reasons of performance), and get a full-fledged implementation of <code>dict</code>'s rich API (<code>update</code>, <code>get</code>, and so on). A great example of the <a href="http://en.wikipedia.org/wiki/Template%5Fmethod%5Fpattern">Template Method</a> design pattern.</p> <p>In Python 3, <code>DictMixin</code> is gone; you can get <em>almost</em> the same functionality by relying on <code>collections.MutableMapping</code> instead (or just <code>collections.Mapping</code> for R/O mappings). It's a bit more elegant, though not QUITE as handy (see <a href="http://bugs.python.org/issue5402">this issue</a>, which was closed with "won't fix"; the short discussion is worth reading).</p>
25
2009-09-08T15:11:39Z
[ "python", "oop" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
1,392,549
<p>This grabs subdirectories:</p> <pre><code>import os def get_size(start_path = '.'): total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size print get_size() </code></pre> <p>And a oneliner for fun using <a href="http://docs.python.org/library/os.html?highlight=shutil#os.listdir">os.listdir</a> (<em>Does not include sub-directories</em>):</p> <pre><code>import os sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)) </code></pre> <p>Reference:</p> <p><a href="http://docs.python.org/library/os.path.html#os.path.getsize">os.path.getsize</a> - Gives the size in bytes</p> <p><a href="http://docs.python.org/library/os.html?highlight=shutil#os.walk">os.walk</a></p> <p><strong>Updated</strong> To use <em>os.path.getsize</em>, this is clearer than using the os.stat().st_size method.</p> <p><em>Thanks to ghostdog74 for pointing this out!</em></p> <p><a href="http://docs.python.org/library/os.html?highlight=shutil#os.stat">os.stat</a> - <em>st_size</em> Gives the size in bytes. Can also be used to get file size and other file related information.</p> <p><strong>Update 2015</strong></p> <p><code>scandir</code> is available and may be faster than the <code>os.walk</code> method. A package is available from pypi, and <code>os.scandir()</code> is to be included in python 3.5:</p> <p><a href="https://pypi.python.org/pypi/scandir">https://pypi.python.org/pypi/scandir</a></p>
104
2009-09-08T07:48:15Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
1,776,987
<p>monknut answer is good but it fails on broken symlink, so you also have to check if this path really exists</p> <pre><code>if os.path.exists(fp): total_size += os.stat(fp).st_size </code></pre>
5
2009-11-21T22:24:26Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
1,777,225
<p>for getting the size of one file, there is os.path.getsize()</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.getsize("/path/file") 35L </code></pre> <p>its reported in bytes.</p>
0
2009-11-21T23:57:12Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
4,368,431
<p>Here is a recursive function (it recursively sums up the size of all subfolders and their respective files) which returns exactly the same bytes as when running "du -sb ." in linux (where the "." means "the current folder"):</p> <pre><code>import os def getFolderSize(folder): total_size = os.path.getsize(folder) for item in os.listdir(folder): itempath = os.path.join(folder, item) if os.path.isfile(itempath): total_size += os.path.getsize(itempath) elif os.path.isdir(itempath): total_size += getFolderSize(itempath) return total_size print "Size: " + str(getFolderSize(".")) </code></pre>
13
2010-12-06T16:12:22Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
12,984,676
<p>The accepted answer doesn't take into account hard or soft links, and would count those files twice. You'd want to keep track of which inodes you've seen, and not add the size for those files.</p> <pre><code>import os def get_size(start_path='.'): total_size = 0 seen = {} for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) try: stat = os.stat(fp) except OSError: continue try: seen[stat.st_ino] except KeyError: seen[stat.st_ino] = True else: continue total_size += stat.st_size return total_size print get_size() </code></pre>
4
2012-10-20T02:18:48Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
13,475,351
<p>You can do something like this : </p> <pre><code>import commands size = commands.getoutput('du -sh /path/').split()[0] </code></pre> <p>in this case I have not tested the result before returning it, if you want you can check it with commands.getstatusoutput.</p>
3
2012-11-20T14:30:24Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
17,936,789
<p>Chris' answer is good but could be made more idiomatic by using a set to check for seen directories, which also avoids using an exception for control flow:</p> <pre><code>def directory_size(path): total_size = 0 seen = set() for dirpath, dirnames, filenames in os.walk(path): for f in filenames: fp = os.path.join(dirpath, f) try: stat = os.stat(fp) except OSError: continue if stat.st_ino in seen: continue seen.add(stat.st_ino) total_size += stat.st_size return total_size # size in bytes </code></pre>
4
2013-07-30T01:09:50Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
18,763,675
<p>a recursive one-liner:</p> <pre><code>def getFolderSize(p): from functools import partial prepend = partial(os.path.join, p) return sum([(os.path.getsize(f) if os.path.isfile(f) else getFolderSize(f)) for f in map(prepend, os.listdir(p))]) </code></pre>
2
2013-09-12T11:58:01Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
23,850,720
<pre><code>import os def get_size(path): total_size = 0 for dirpath, dirnames, filenames in os.walk(path): for f in filenames: if os.path.exists(fp): fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size # in megabytes </code></pre> <p>Thanks monkut &amp; troex! This works really good!</p>
0
2014-05-24T23:46:34Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
24,341,821
<p>This script tells you which file is the biggest in the CWD and also tells you in which folder the file is. This script works for me on win8 and python 3.3.3 shell</p> <pre><code>import os folder=os.cwd() number=0 string="" for root, dirs, files in os.walk(folder): for file in files: pathname=os.path.join(root,file) ## print (pathname) ## print (os.path.getsize(pathname)/1024/1024) if number &lt; os.path.getsize(pathname): number = os.path.getsize(pathname) string=pathname ## print () print (string) print () print (number) print ("Number in bytes") </code></pre>
0
2014-06-21T12:56:07Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
25,574,638
<p>Some of the approaches suggested so far implement a recursion, others employ a shell or will not produce neatly formatted results. When your code is one-off for Linux platforms, you can get formatting as usual, recursion included, as a one-liner. Except for the <code>print</code> in the last line, it will work for current versions of <code>python2</code> and <code>python3</code>: </p> <pre><code>du.py ----- #!/usr/bin/python3 import subprocess def du(path): """disk usage in human readable format (e.g. '2,1GB')""" return subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8') if __name__ == "__main__": print(du('.')) </code></pre> <p>is simple, efficient and will work for files and multilevel directories:</p> <pre><code>$ chmod 750 du.py $ ./du.py 2,9M </code></pre> <p>A bit late after 5 years, but because this is still in the hitlists of search engines, it might be of help...</p>
13
2014-08-29T19:00:48Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
25,666,231
<p>For the second part of the question</p> <pre><code>def human(size): B = "B" KB = "KB" MB = "MB" GB = "GB" TB = "TB" UNITS = [B, KB, MB, GB, TB] HUMANFMT = "%f %s" HUMANRADIX = 1024. for u in UNITS[:-1]: if size &lt; HUMANRADIX : return HUMANFMT % (size, u) size /= HUMANRADIX return HUMANFMT % (size, UNITS[-1]) </code></pre>
3
2014-09-04T13:01:07Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
29,611,830
<p>One-liner you say... Here is a one liner:</p> <pre><code>sum([sum(map(lambda fname: os.path.getsize(os.path.join(directory, fname)), files)) for directory, folders, files in os.walk(path)]) </code></pre> <p>Although I would probably split it out and it performs no checks.</p> <p>To convert to kb see <a href="http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size">Reusable library to get human readable version of file size?</a> and work it in</p>
1
2015-04-13T17:53:19Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
34,580,785
<p>The following script prints directory size of all sub-directories for the specified directory. It also tries to benefit (if possible) from caching the calls of a recursive functions. If an argument is omitted, the script will work in the current directory. The output is sorted by the directory size from biggest to smallest ones. So you can adapt it for your needs.</p> <p>PS i've used recipe 578019 for showing directory size in human-friendly format (<a href="http://code.activestate.com/recipes/578019/" rel="nofollow">http://code.activestate.com/recipes/578019/</a>)</p> <pre><code>from __future__ import print_function import os import sys import operator def null_decorator(ob): return ob if sys.version_info &gt;= (3,2,0): import functools my_cache_decorator = functools.lru_cache(maxsize=4096) else: my_cache_decorator = null_decorator start_dir = os.path.normpath(os.path.abspath(sys.argv[1])) if len(sys.argv) &gt; 1 else '.' @my_cache_decorator def get_dir_size(start_path = '.'): total_size = 0 if 'scandir' in dir(os): # using fast 'os.scandir' method (new in version 3.5) for entry in os.scandir(start_path): if entry.is_dir(follow_symlinks = False): total_size += get_dir_size(entry.path) elif entry.is_file(follow_symlinks = False): total_size += entry.stat().st_size else: # using slow, but compatible 'os.listdir' method for entry in os.listdir(start_path): full_path = os.path.abspath(os.path.join(start_path, entry)) if os.path.isdir(full_path): total_size += get_dir_size(full_path) elif os.path.isfile(full_path): total_size += os.path.getsize(full_path) return total_size def get_dir_size_walk(start_path = '.'): total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size def bytes2human(n, format='%(value).0f%(symbol)s', symbols='customary'): """ (c) http://code.activestate.com/recipes/578019/ Convert n bytes into a human readable string based on format. symbols can be either "customary", "customary_ext", "iec" or "iec_ext", see: http://goo.gl/kTQMs &gt;&gt;&gt; bytes2human(0) '0.0 B' &gt;&gt;&gt; bytes2human(0.9) '0.0 B' &gt;&gt;&gt; bytes2human(1) '1.0 B' &gt;&gt;&gt; bytes2human(1.9) '1.0 B' &gt;&gt;&gt; bytes2human(1024) '1.0 K' &gt;&gt;&gt; bytes2human(1048576) '1.0 M' &gt;&gt;&gt; bytes2human(1099511627776127398123789121) '909.5 Y' &gt;&gt;&gt; bytes2human(9856, symbols="customary") '9.6 K' &gt;&gt;&gt; bytes2human(9856, symbols="customary_ext") '9.6 kilo' &gt;&gt;&gt; bytes2human(9856, symbols="iec") '9.6 Ki' &gt;&gt;&gt; bytes2human(9856, symbols="iec_ext") '9.6 kibi' &gt;&gt;&gt; bytes2human(10000, "%(value).1f %(symbol)s/sec") '9.8 K/sec' &gt;&gt;&gt; # precision can be adjusted by playing with %f operator &gt;&gt;&gt; bytes2human(10000, format="%(value).5f %(symbol)s") '9.76562 K' """ SYMBOLS = { 'customary' : ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'), 'customary_ext' : ('byte', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zetta', 'iotta'), 'iec' : ('Bi', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'), 'iec_ext' : ('byte', 'kibi', 'mebi', 'gibi', 'tebi', 'pebi', 'exbi', 'zebi', 'yobi'), } n = int(n) if n &lt; 0: raise ValueError("n &lt; 0") symbols = SYMBOLS[symbols] prefix = {} for i, s in enumerate(symbols[1:]): prefix[s] = 1 &lt;&lt; (i+1)*10 for symbol in reversed(symbols[1:]): if n &gt;= prefix[symbol]: value = float(n) / prefix[symbol] return format % locals() return format % dict(symbol=symbols[0], value=n) ############################################################ ### ### main () ### ############################################################ if __name__ == '__main__': dir_tree = {} ### version, that uses 'slow' [os.walk method] #get_size = get_dir_size_walk ### this recursive version can benefit from caching the function calls (functools.lru_cache) get_size = get_dir_size for root, dirs, files in os.walk(start_dir): for d in dirs: dir_path = os.path.join(root, d) if os.path.isdir(dir_path): dir_tree[dir_path] = get_size(dir_path) for d, size in sorted(dir_tree.items(), key=operator.itemgetter(1), reverse=True): print('%s\t%s' %(bytes2human(size, format='%(value).2f%(symbol)s'), d)) print('-' * 80) if sys.version_info &gt;= (3,2,0): print(get_dir_size.cache_info()) </code></pre> <p>Sample output:</p> <pre><code>37.61M .\subdir_b 2.18M .\subdir_a 2.17M .\subdir_a\subdir_a_2 4.41K .\subdir_a\subdir_a_1 ---------------------------------------------------------- CacheInfo(hits=2, misses=4, maxsize=4096, currsize=4) </code></pre> <p>EDIT: moved null_decorator above, as user2233949 recommended</p>
1
2016-01-03T19:36:43Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
37,367,965
<p>Python 3.5 recursive folder size using <code>os.scandir</code></p> <pre><code>def folder_size(path='.'): total = 0 for entry in os.scandir(path): if entry.is_file(): total += entry.stat().st_size elif entry.is_dir(): total += folder_size(entry.path) return total </code></pre>
0
2016-05-21T21:01:22Z
[ "python", "directory" ]
Calculating a directory size using Python?
1,392,413
<p>Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.</p>
78
2009-09-08T07:06:42Z
39,615,417
<p>A little late to the party but in one line provided that you have <a href="https://pypi.python.org/pypi/glob2" rel="nofollow">glob2</a> and <a href="https://pypi.python.org/pypi/humanize" rel="nofollow">humanize</a> installed. Note that in Python 3, the default <code>iglob</code> has a recursive mode. How to modify the code for Python 3 is left as a trivial exercise for the reader.</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; from humanize import naturalsize &gt;&gt;&gt; from glob2 import iglob &gt;&gt;&gt; naturalsize(sum(os.path.getsize(x) for x in iglob('/var/**')))) '546.2 MB' </code></pre>
0
2016-09-21T11:32:50Z
[ "python", "directory" ]
Python: Why is ("hello" is "hello")?
1,392,433
<p>Why is <code>"hello" is "hello" == True</code> in Python?</p> <p>I read the following <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">here</a>:</p> <blockquote> <p>If two string literals are equal, they have been put to same memory location. A string is an immutable entity. No harm can be done.</p> </blockquote> <p>So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?</p>
48
2009-09-08T07:13:19Z
1,392,437
<p>Why is it strange. If the string is immutable it makes a lot of sense to only store it once. .NET has the same behavior. </p>
0
2009-09-08T07:14:42Z
[ "python", "identity" ]