title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Truncating floats in Python | 783,897 | <p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p>
<pre><code>1.923328437452 -> 1.923
</code></pre>
<p>I need to output as a string to another function, not print.</p>
<p>Also I want to ignore the lost digits, not round them.</p>
| 46 | 2009-04-23T22:56:44Z | 28,323,804 | <p>So many of the answers given for this question are just completely wrong. They either round up floats (rather than truncate) or do not work for all cases.</p>
<p>This is the top Google result when I search for 'Python truncate float', a concept which is really straightforward, and which deserves better answers. I agree with Hatchkins that using the <code>decimal</code> module is the pythonic way of doing this, so I give here a function which I think answers the question correctly, and which works as expected for all cases.</p>
<p>As a side-note, fractional values, in general, cannot be represented exactly by binary floating point variables (see <a href="http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary">here</a> for a discussion of this), which is why my function returns a string. </p>
<pre class="lang-py prettyprint-override"><code>from decimal import Decimal, localcontext, ROUND_DOWN
def truncate(number, places):
if not isinstance(places, int):
raise ValueError("Decimal places must be an integer.")
if places < 1:
raise ValueError("Decimal places must be at least 1.")
# If you want to truncate to 0 decimal places, just do int(number).
with localcontext() as context:
context.rounding = ROUND_DOWN
exponent = Decimal(str(10 ** - places))
return Decimal(str(number)).quantize(exponent).to_eng_string()
</code></pre>
| 4 | 2015-02-04T14:26:37Z | [
"python",
"floating-point"
] |
Truncating floats in Python | 783,897 | <p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p>
<pre><code>1.923328437452 -> 1.923
</code></pre>
<p>I need to output as a string to another function, not print.</p>
<p>Also I want to ignore the lost digits, not round them.</p>
| 46 | 2009-04-23T22:56:44Z | 29,247,646 | <p>You can do:</p>
<pre><code>def truncate(f, n):
return math.floor(f * 10 ** n) / 10 ** n
</code></pre>
<p>testing:</p>
<pre><code>>>> f=1.923328437452
>>> [truncate(f, n) for n in range(5)]
[1.0, 1.9, 1.92, 1.923, 1.9233]
</code></pre>
| 2 | 2015-03-25T04:47:01Z | [
"python",
"floating-point"
] |
Truncating floats in Python | 783,897 | <p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p>
<pre><code>1.923328437452 -> 1.923
</code></pre>
<p>I need to output as a string to another function, not print.</p>
<p>Also I want to ignore the lost digits, not round them.</p>
| 46 | 2009-04-23T22:56:44Z | 29,574,663 | <p>use numpy.round</p>
<pre><code>import numpy as np
precision = 3
floats = [1.123123123, 2.321321321321]
new_float = np.round(floats, precision)
</code></pre>
| 1 | 2015-04-11T06:02:06Z | [
"python",
"floating-point"
] |
Truncating floats in Python | 783,897 | <p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p>
<pre><code>1.923328437452 -> 1.923
</code></pre>
<p>I need to output as a string to another function, not print.</p>
<p>Also I want to ignore the lost digits, not round them.</p>
| 46 | 2009-04-23T22:56:44Z | 32,303,199 | <pre><code># value value to be truncated
# n number of values after decimal
value = 0.999782
n = 3
float(int(value*1en))*1e-n
</code></pre>
| -1 | 2015-08-31T02:24:03Z | [
"python",
"floating-point"
] |
Truncating floats in Python | 783,897 | <p>I want to remove digits from a float to have a fixed number of digits after the dot, like:</p>
<pre><code>1.923328437452 -> 1.923
</code></pre>
<p>I need to output as a string to another function, not print.</p>
<p>Also I want to ignore the lost digits, not round them.</p>
| 46 | 2009-04-23T22:56:44Z | 34,707,419 | <p>Simple python script -</p>
<pre><code>n = 1.923328437452
n = int(n*1000)
n /= 1000
</code></pre>
| 2 | 2016-01-10T15:49:15Z | [
"python",
"floating-point"
] |
Is there a way to resize images in Django via imagename.230x150.jpg? | 784,099 | <p>There's a nice plugin for Frog CMS that lets you just type in yourpicture.120x120.jpg or whatever, and it will automatically use the image in that dimension. If it doesn't exist, it creates it and adds it to the filesystem.</p>
<p><a href="http://www.naehrstoff.ch/code/image-resize-for-frog" rel="nofollow">http://www.naehrstoff.ch/code/image-resize-for-frog</a></p>
<p>I was wondering if there's anything like this in Django/Python?</p>
| 2 | 2009-04-24T00:22:29Z | 784,434 | <p>I think this snippet is close to what you need: <a href="http://www.djangosnippets.org/snippets/619/" rel="nofollow">Dynamic thumbnail generator</a></p>
<p>You might also want to investigate <a href="http://code.google.com/p/sorl-thumbnail/" rel="nofollow">sorl-thumbnail</a> which, even though it codes the thumbnail dimensions in the template instead of the URL, is more flexible/powerful.</p>
| 5 | 2009-04-24T03:47:34Z | [
"python",
"django"
] |
Python Django Template: Iterate Through List | 784,124 | <p>Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code:</p>
<pre><code><div id="right_pod">
{%for i in rangeLength%}
<div class="user_pod" >
{{c.i.0.from_user}}
</div>
{% endfor %}
</code></pre>
<p></p>
<p>This currently outputs nothing :( If I replace "i" with 0...{{c.0.0.from_user}}...it will output something.. (the first user 10 times)</p>
| 6 | 2009-04-24T00:35:14Z | 784,145 | <p>Do you need <code>i</code> to be an index? If not, see if the following code does what you're after:</p>
<pre><code><div id="right_pod">
{% for i in c %}
<div class="user_pod">
{{ i.0.from_user }}
</div>
{% endfor %}
</code></pre>
| 10 | 2009-04-24T00:51:21Z | [
"python",
"django",
"django-templates"
] |
Python Django Template: Iterate Through List | 784,124 | <p>Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code:</p>
<pre><code><div id="right_pod">
{%for i in rangeLength%}
<div class="user_pod" >
{{c.i.0.from_user}}
</div>
{% endfor %}
</code></pre>
<p></p>
<p>This currently outputs nothing :( If I replace "i" with 0...{{c.0.0.from_user}}...it will output something.. (the first user 10 times)</p>
| 6 | 2009-04-24T00:35:14Z | 786,873 | <p>You should use the slice template filter to achieve what you want:</p>
<p>Iterate over the object (c in this case) like so:</p>
<p>{% for c in objects|slice:":30" %}</p>
<p>This would make sure that you only iterate over the first 30 objects.</p>
<p>Also, you can use the forloop.counter object to keep track of which loop iteration you're on.</p>
| 7 | 2009-04-24T17:37:56Z | [
"python",
"django",
"django-templates"
] |
Python Django Template: Iterate Through List | 784,124 | <p>Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code:</p>
<pre><code><div id="right_pod">
{%for i in rangeLength%}
<div class="user_pod" >
{{c.i.0.from_user}}
</div>
{% endfor %}
</code></pre>
<p></p>
<p>This currently outputs nothing :( If I replace "i" with 0...{{c.0.0.from_user}}...it will output something.. (the first user 10 times)</p>
| 6 | 2009-04-24T00:35:14Z | 788,029 | <p>Please read the entire [documentation on the template language's for loops]. First of all, that iteration (like in Python) is over objects, not indexes. Secondly, that within any for loop there is a forloop variable with two fields you'll be interested in:</p>
<pre><code>Variable Description
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
</code></pre>
| 13 | 2009-04-25T01:25:13Z | [
"python",
"django",
"django-templates"
] |
Python Module/Class Variable Bleeding | 784,149 | <p>Okay, it took me a little while to narrow down this problem, but it appears python is doing this one purpose. Can someone explain why this is happening and what I can do to fix this?</p>
<p>File: library/testModule.py</p>
<pre><code>class testClass:
myvars = dict()
def __getattr__(self, k):
if self.myvars.has_key(k):
return self.myvars[k]
def __setattr__(self, k, v):
self.myvars[k] = v
def __str__(self):
l = []
for k, v in self.myvars.iteritems():
l.append(str(k) + ":" + str(v))
return " - ".join(l)
</code></pre>
<p>test.py</p>
<pre><code>from library import testModule
#I get the same result if I instantiate both classes one after another
c1 = testClass()
c1.foo = "hello"
c2 = testClass()
print("c1: " + str(c1) + "\n")
print("c2: " + str(c2) + "\n")
</code></pre>
<p>Output:</p>
<pre><code>c1: foo:hello
c2: foo:hello
</code></pre>
<p>My best guess is that because <code>library</code> has an <code>"__init__.py"</code> file, the whole module is loaded like a class object and it's now become part of a lasting object.. is this the case?</p>
| 0 | 2009-04-24T00:57:06Z | 784,154 | <p><code>myvars</code> is a property of the <em>class</em>, not the <em>instance</em>. This means that when you insert an attribute into <code>myvars</code> from the instance <code>c1</code>, the attribute gets associated with the class <code>testClass</code>, not the instance <code>c1</code> specifically. Since <code>c2</code> is an instance of the same class, it also has the same attribute.</p>
<p>You could get the behavior you want by writing this:</p>
<pre><code>class testClass:
def __init__(self):
self.myvars = dict()
def __getattr__(self, k):
if self.myvars.has_key(k):
return self.myvars[k]
def __setattr__(self, k, v):
self.myvars[k] = v
def __str__(self):
l = []
for k, v in self.myvars.iteritems():
l.append(str(k) + ":" + str(v))
return " - ".join(l)
</code></pre>
| 7 | 2009-04-24T01:00:30Z | [
"python",
"oop",
"class"
] |
Python Module/Class Variable Bleeding | 784,149 | <p>Okay, it took me a little while to narrow down this problem, but it appears python is doing this one purpose. Can someone explain why this is happening and what I can do to fix this?</p>
<p>File: library/testModule.py</p>
<pre><code>class testClass:
myvars = dict()
def __getattr__(self, k):
if self.myvars.has_key(k):
return self.myvars[k]
def __setattr__(self, k, v):
self.myvars[k] = v
def __str__(self):
l = []
for k, v in self.myvars.iteritems():
l.append(str(k) + ":" + str(v))
return " - ".join(l)
</code></pre>
<p>test.py</p>
<pre><code>from library import testModule
#I get the same result if I instantiate both classes one after another
c1 = testClass()
c1.foo = "hello"
c2 = testClass()
print("c1: " + str(c1) + "\n")
print("c2: " + str(c2) + "\n")
</code></pre>
<p>Output:</p>
<pre><code>c1: foo:hello
c2: foo:hello
</code></pre>
<p>My best guess is that because <code>library</code> has an <code>"__init__.py"</code> file, the whole module is loaded like a class object and it's now become part of a lasting object.. is this the case?</p>
| 0 | 2009-04-24T00:57:06Z | 784,200 | <p>The other answers are correct and to the point. Let me address some of what I think your misconceptions are.</p>
<blockquote>
<p>My best guess is that because library has an "<code>__init__.py</code>" file, the whole module is loaded like a class object and it's now become part of a lasting object.. is this the case?</p>
</blockquote>
<p>All packages have an <code>__init__.py</code> file. It is necessary to make something a python package. That package may or may not have any code in it. If it does it is guaranteed to execute. In the general case, this doesn't have anything to do with how the other modules in the package are executed, although it certainly is possible to put a lot of really cool trickery in there that does affect it.</p>
<p>As for how modules and classes work, it is often a really good idea to think of a module as a class object that gets instantiated once. The loader executes the files once and all variables, class definitions, and function definitions that are available at the end of the file are then accessible as part of the module.</p>
<p>The same is true of classes, with the main exception that functions declared within classes are transformed into methods (and one special method let's you instantiate the class). So <code>testModule</code> has-a <code>testClass</code> has-a <code>myvars</code>. All three objects are unique: there will not be multiple instances of any of them. And the has-a relathionship is really more-or-less the same whether we say "module has-a class object" or "class object has-a class variable". (The difference being implementation details that you ought not be concerned with.)</p>
| 2 | 2009-04-24T01:26:44Z | [
"python",
"oop",
"class"
] |
Python Module/Class Variable Bleeding | 784,149 | <p>Okay, it took me a little while to narrow down this problem, but it appears python is doing this one purpose. Can someone explain why this is happening and what I can do to fix this?</p>
<p>File: library/testModule.py</p>
<pre><code>class testClass:
myvars = dict()
def __getattr__(self, k):
if self.myvars.has_key(k):
return self.myvars[k]
def __setattr__(self, k, v):
self.myvars[k] = v
def __str__(self):
l = []
for k, v in self.myvars.iteritems():
l.append(str(k) + ":" + str(v))
return " - ".join(l)
</code></pre>
<p>test.py</p>
<pre><code>from library import testModule
#I get the same result if I instantiate both classes one after another
c1 = testClass()
c1.foo = "hello"
c2 = testClass()
print("c1: " + str(c1) + "\n")
print("c2: " + str(c2) + "\n")
</code></pre>
<p>Output:</p>
<pre><code>c1: foo:hello
c2: foo:hello
</code></pre>
<p>My best guess is that because <code>library</code> has an <code>"__init__.py"</code> file, the whole module is loaded like a class object and it's now become part of a lasting object.. is this the case?</p>
| 0 | 2009-04-24T00:57:06Z | 784,228 | <p>For a good reference on how to use <strong>getattr</strong> and other methods like it, refer to <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">How-To Guide for Descriptors</a> and there's nothing like practice!</p>
| 0 | 2009-04-24T01:42:53Z | [
"python",
"oop",
"class"
] |
Is there a Python MTA (Mail transfer agent) | 784,201 | <p>Just wondering if there is a Python <a href="http://en.wikipedia.org/wiki/Mail%5Ftransfer%5Fagent">MTA</a>. I took a look at <a href="http://docs.python.org/library/smtpd.html">smtpd</a> but they all look like forwarders without any functionality.</p>
| 7 | 2009-04-24T01:27:00Z | 784,394 | <p>Yes, Twisted includes a framework for building SMTP servers. There's a simple Twisted-based email server available <a href="https://launchpad.net/tx/txmailserver" rel="nofollow">here</a> (also see <a href="http://oubiwann.blogspot.com/2009/01/twisted-mail-server-conclusion.html" rel="nofollow">here</a> for some information about its development).</p>
<p>If you want something closer to a mail <em>application</em> server, there's <a href="https://github.com/zedshaw/lamson" rel="nofollow">Lamson</a>.</p>
| 4 | 2009-04-24T03:31:56Z | [
"python",
"smtp",
"mta",
"smtpd"
] |
Is there a Python MTA (Mail transfer agent) | 784,201 | <p>Just wondering if there is a Python <a href="http://en.wikipedia.org/wiki/Mail%5Ftransfer%5Fagent">MTA</a>. I took a look at <a href="http://docs.python.org/library/smtpd.html">smtpd</a> but they all look like forwarders without any functionality.</p>
| 7 | 2009-04-24T01:27:00Z | 784,529 | <p>It's pretty new, so nothing like the maturity of Twisted's SMTP, but there's also <a href="https://launchpad.net/lamson" rel="nofollow">Lamson</a>.</p>
| 4 | 2009-04-24T04:29:27Z | [
"python",
"smtp",
"mta",
"smtpd"
] |
Is there a Python MTA (Mail transfer agent) | 784,201 | <p>Just wondering if there is a Python <a href="http://en.wikipedia.org/wiki/Mail%5Ftransfer%5Fagent">MTA</a>. I took a look at <a href="http://docs.python.org/library/smtpd.html">smtpd</a> but they all look like forwarders without any functionality.</p>
| 7 | 2009-04-24T01:27:00Z | 22,879,789 | <p>If you're looking for a full MTA solution you should check out <a href="http://slimta.org/">http://slimta.org/</a> or as previously mentioned here <a href="http://lamsonproject.org">http://lamsonproject.org</a>
I myself has experimented a bit with slimta and it seems to work well.</p>
| 5 | 2014-04-05T10:42:18Z | [
"python",
"smtp",
"mta",
"smtpd"
] |
In Python, can you call an instance method of class A, but pass in an instance of class B? | 784,331 | <p>In the interest of reusing some existing code that was defined as an instance method of a different class, I was tying to do something like the following:</p>
<pre><code>class Foo(object):
def __init__(self):
self.name = "Foo"
def hello(self):
print "Hello, I am " + self.name + "."
class Bar(object):
def __init__(self):
self.name = "Bar"
bar = Bar()
Foo.hello(bar)
</code></pre>
<p>but that results in:</p>
<blockquote>
<p>TypeError: unbound method hello() must be called with Foo instance as first argument (got Bar instance instead)</p>
</blockquote>
<p>Is something like this possible?</p>
<p><hr /></p>
<p>I should have been clear that I know this is a bad idea. Obviously the real solution is a bit of refactoring. I just figured there must be a way, and it turns out there is.</p>
<p>Thanks for the comments.</p>
| 5 | 2009-04-24T02:38:58Z | 784,337 | <p>Looks like this works:</p>
<pre><code>Foo.hello.im_func(bar)
</code></pre>
<blockquote>
<p>Hello, I am Bar.</p>
</blockquote>
<p>I guess I need to read a <a href="http://docs.python.org/reference/datamodel.html">this</a> little harder...</p>
| 6 | 2009-04-24T02:43:14Z | [
"python",
"oop",
"coding-style"
] |
In Python, can you call an instance method of class A, but pass in an instance of class B? | 784,331 | <p>In the interest of reusing some existing code that was defined as an instance method of a different class, I was tying to do something like the following:</p>
<pre><code>class Foo(object):
def __init__(self):
self.name = "Foo"
def hello(self):
print "Hello, I am " + self.name + "."
class Bar(object):
def __init__(self):
self.name = "Bar"
bar = Bar()
Foo.hello(bar)
</code></pre>
<p>but that results in:</p>
<blockquote>
<p>TypeError: unbound method hello() must be called with Foo instance as first argument (got Bar instance instead)</p>
</blockquote>
<p>Is something like this possible?</p>
<p><hr /></p>
<p>I should have been clear that I know this is a bad idea. Obviously the real solution is a bit of refactoring. I just figured there must be a way, and it turns out there is.</p>
<p>Thanks for the comments.</p>
| 5 | 2009-04-24T02:38:58Z | 784,550 | <p>A while back I wondered about the same "feature" in Perl on PerlMonks, and the <a href="http://www.perlmonks.org/?node%5Fid=432172" rel="nofollow">general consensus</a> was that while it works (as it does in Python) you should not be doing things that way.</p>
| 0 | 2009-04-24T04:44:28Z | [
"python",
"oop",
"coding-style"
] |
In Python, can you call an instance method of class A, but pass in an instance of class B? | 784,331 | <p>In the interest of reusing some existing code that was defined as an instance method of a different class, I was tying to do something like the following:</p>
<pre><code>class Foo(object):
def __init__(self):
self.name = "Foo"
def hello(self):
print "Hello, I am " + self.name + "."
class Bar(object):
def __init__(self):
self.name = "Bar"
bar = Bar()
Foo.hello(bar)
</code></pre>
<p>but that results in:</p>
<blockquote>
<p>TypeError: unbound method hello() must be called with Foo instance as first argument (got Bar instance instead)</p>
</blockquote>
<p>Is something like this possible?</p>
<p><hr /></p>
<p>I should have been clear that I know this is a bad idea. Obviously the real solution is a bit of refactoring. I just figured there must be a way, and it turns out there is.</p>
<p>Thanks for the comments.</p>
| 5 | 2009-04-24T02:38:58Z | 784,864 | <p>It happens because python wraps class functions as an "unbound method" which performs this type checking. There's some description of the decisions involved in this <a href="http://python-history.blogspot.com/2009/02/first-class-everything.html" rel="nofollow">here</a>.</p>
<p>Note that this type checking has actually been dropped in python 3 (see the note at the end of that article), so your approach will work there.</p>
| 5 | 2009-04-24T07:43:20Z | [
"python",
"oop",
"coding-style"
] |
In Python, can you call an instance method of class A, but pass in an instance of class B? | 784,331 | <p>In the interest of reusing some existing code that was defined as an instance method of a different class, I was tying to do something like the following:</p>
<pre><code>class Foo(object):
def __init__(self):
self.name = "Foo"
def hello(self):
print "Hello, I am " + self.name + "."
class Bar(object):
def __init__(self):
self.name = "Bar"
bar = Bar()
Foo.hello(bar)
</code></pre>
<p>but that results in:</p>
<blockquote>
<p>TypeError: unbound method hello() must be called with Foo instance as first argument (got Bar instance instead)</p>
</blockquote>
<p>Is something like this possible?</p>
<p><hr /></p>
<p>I should have been clear that I know this is a bad idea. Obviously the real solution is a bit of refactoring. I just figured there must be a way, and it turns out there is.</p>
<p>Thanks for the comments.</p>
| 5 | 2009-04-24T02:38:58Z | 34,514,821 | <p>This is an old question, but Python has evolved and looks like it's worth pointing it out: </p>
<p>with Python 3 there's no more <code><unbound method C.x></code>, since an unbound method is simply a <code><function __main__.C.x></code>!</p>
<p>Which probably means the code in the original question should not be considered /that/ off. Python has always been about duck typing in any case, hasn't it?! </p>
<h2>Refs:</h2>
<ul>
<li><a href="https://mail.python.org/pipermail/python-dev/2005-January/050625.html" rel="nofollow">Guido proposing to remove unbound methods from python</a></li>
<li><a href="https://docs.python.org/3.0/whatsnew/3.0.html#operators-and-special-methods" rel="nofollow">What's new</a> for Python 3 release</li>
<li><a href="http://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3">Get defining class of unbound method object in Python 3</a></li>
</ul>
<h2>Alternative solution in Py2</h2>
<p>Note that there's also an alternative solution to the "explorative" question (see <a href="http://stackoverflow.com/questions/1015307/python-bind-an-unbound-method">Python: Bind an Unbound Method?</a>):</p>
<pre><code>In [6]: a = A.a.im_func.__get__(B(), B)
In [7]: a
Out[7]: <bound method B.a of <__main__.B instance at 0x7f37d81a1ea8>>
In [8]: a(2)
2
</code></pre>
<p>Ref:</p>
<h1>Some ipython code samples</h1>
<h2>python 2</h2>
<pre><code>In [1]: class A():
def a(self, a=0):
print a
...:
In [2]: A.a
Out[2]: <unbound method A.a>
In [3]: A.a.im_func
Out[3]: <function __main__.a>
In [4]: A.a(B())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-7694121f3429> in <module>()
----> 1 A.a(B())
TypeError: unbound method a() must be called with A instance as first argument (got B instance instead)
</code></pre>
<h2>python 3</h2>
<pre><code>In [2]: class A():
def a(self, a=0):
print(a)
...:
In [3]: def a():
...: pass
...:
In [4]: class B():
...: pass
In [5]: A.a(B())
0
In [6]: A.a
Out[6]: <function __main__.A.a>
</code></pre>
| 2 | 2015-12-29T16:13:32Z | [
"python",
"oop",
"coding-style"
] |
Browscap For Python | 784,418 | <p>I was looking around, and couldn't find the Python equivalent of browscap (that I've used in PHP to detect what browser a given user-agent string is.</p>
<p>I'm hoping I'm not going to have to write my own.. :P</p>
| 1 | 2009-04-24T03:41:05Z | 784,712 | <p>Check this out, it should do what you want: <a href="http://www.djangosnippets.org/snippets/267/" rel="nofollow">browscap.ini-parser</a>.</p>
<p>Please note that even though it is on the Django Snippets website it is standalone and you can use it with whatever setup you have.</p>
| 2 | 2009-04-24T06:12:36Z | [
"python",
"browscap"
] |
Browscap For Python | 784,418 | <p>I was looking around, and couldn't find the Python equivalent of browscap (that I've used in PHP to detect what browser a given user-agent string is.</p>
<p>I'm hoping I'm not going to have to write my own.. :P</p>
| 1 | 2009-04-24T03:41:05Z | 8,015,667 | <p>Checkout the pybrowscap library, it is equivalent for php get_browser : <a href="http://pypi.python.org/pypi/pybrowscap/" rel="nofollow">http://pypi.python.org/pypi/pybrowscap/</a></p>
| 1 | 2011-11-04T21:00:34Z | [
"python",
"browscap"
] |
Random strings in Python 2.6 (Is this OK?) | 785,058 | <p>I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to</p>
<pre><code>''.join(random.choice(string.letters) for i in xrange(len))
</code></pre>
<p>It sucks if you want to generate long string.</p>
<p>I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast.</p>
<p>It generates a 50mil random string on my notebook in just about 3 seconds.</p>
<pre><code>def rand1(leng):
nbits = leng * 6 + 1
bits = random.getrandbits(nbits)
uc = u"%0x" % bits
newlen = int(len(uc) / 2) * 2 # we have to make the string an even length
ba = bytearray.fromhex(uc[:newlen])
return base64.urlsafe_b64encode(str(ba))[:leng]
</code></pre>
<p><hr /></p>
<p><strong>edit</strong></p>
<p>heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.</p>
<p>Still curious if there's a better way of doing this that's just as fast.</p>
| 76 | 2009-04-24T09:01:29Z | 785,086 | <pre><code>import os
random_string = os.urandom(string_length)
</code></pre>
| 131 | 2009-04-24T09:09:39Z | [
"python",
"random",
"python-2.6"
] |
Random strings in Python 2.6 (Is this OK?) | 785,058 | <p>I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to</p>
<pre><code>''.join(random.choice(string.letters) for i in xrange(len))
</code></pre>
<p>It sucks if you want to generate long string.</p>
<p>I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast.</p>
<p>It generates a 50mil random string on my notebook in just about 3 seconds.</p>
<pre><code>def rand1(leng):
nbits = leng * 6 + 1
bits = random.getrandbits(nbits)
uc = u"%0x" % bits
newlen = int(len(uc) / 2) * 2 # we have to make the string an even length
ba = bytearray.fromhex(uc[:newlen])
return base64.urlsafe_b64encode(str(ba))[:leng]
</code></pre>
<p><hr /></p>
<p><strong>edit</strong></p>
<p>heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.</p>
<p>Still curious if there's a better way of doing this that's just as fast.</p>
| 76 | 2009-04-24T09:01:29Z | 785,087 | <p>It seems the <code>fromhex()</code> method expects an even number of hex digits. Your string is 75 characters long.
Be aware that <code>something[:-1]</code> <em>excludes</em> the last element! Just use <code>something[:]</code>.</p>
| 2 | 2009-04-24T09:09:45Z | [
"python",
"random",
"python-2.6"
] |
Random strings in Python 2.6 (Is this OK?) | 785,058 | <p>I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to</p>
<pre><code>''.join(random.choice(string.letters) for i in xrange(len))
</code></pre>
<p>It sucks if you want to generate long string.</p>
<p>I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast.</p>
<p>It generates a 50mil random string on my notebook in just about 3 seconds.</p>
<pre><code>def rand1(leng):
nbits = leng * 6 + 1
bits = random.getrandbits(nbits)
uc = u"%0x" % bits
newlen = int(len(uc) / 2) * 2 # we have to make the string an even length
ba = bytearray.fromhex(uc[:newlen])
return base64.urlsafe_b64encode(str(ba))[:leng]
</code></pre>
<p><hr /></p>
<p><strong>edit</strong></p>
<p>heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.</p>
<p>Still curious if there's a better way of doing this that's just as fast.</p>
| 76 | 2009-04-24T09:01:29Z | 786,772 | <p>Taken from the <a href="http://bugs.python.org/issue1023290">1023290</a> bug report at Python.org:</p>
<pre><code>junk_len = 1024
junk = (("%%0%dX" % junk_len) % random.getrandbits(junk_len *
8)).decode("hex")
</code></pre>
<p>Also, see the issues <a href="http://bugs.python.org/issue923643">923643</a> and <a href="http://bugs.python.org/issue1023290">1023290</a></p>
| 5 | 2009-04-24T17:04:55Z | [
"python",
"random",
"python-2.6"
] |
Random strings in Python 2.6 (Is this OK?) | 785,058 | <p>I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to</p>
<pre><code>''.join(random.choice(string.letters) for i in xrange(len))
</code></pre>
<p>It sucks if you want to generate long string.</p>
<p>I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast.</p>
<p>It generates a 50mil random string on my notebook in just about 3 seconds.</p>
<pre><code>def rand1(leng):
nbits = leng * 6 + 1
bits = random.getrandbits(nbits)
uc = u"%0x" % bits
newlen = int(len(uc) / 2) * 2 # we have to make the string an even length
ba = bytearray.fromhex(uc[:newlen])
return base64.urlsafe_b64encode(str(ba))[:leng]
</code></pre>
<p><hr /></p>
<p><strong>edit</strong></p>
<p>heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.</p>
<p>Still curious if there's a better way of doing this that's just as fast.</p>
| 76 | 2009-04-24T09:01:29Z | 939,504 | <p>Regarding the last example, the following fix to make sure the line is even length, whatever the junk_len value:</p>
<pre><code>junk_len = 1024
junk = (("%%0%dX" % (junk_len * 2)) % random.getrandbits(junk_len * 8)).decode("hex")
</code></pre>
| 2 | 2009-06-02T13:24:54Z | [
"python",
"random",
"python-2.6"
] |
Random strings in Python 2.6 (Is this OK?) | 785,058 | <p>I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to</p>
<pre><code>''.join(random.choice(string.letters) for i in xrange(len))
</code></pre>
<p>It sucks if you want to generate long string.</p>
<p>I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented. Somehow I got it to work, and it seems really fast.</p>
<p>It generates a 50mil random string on my notebook in just about 3 seconds.</p>
<pre><code>def rand1(leng):
nbits = leng * 6 + 1
bits = random.getrandbits(nbits)
uc = u"%0x" % bits
newlen = int(len(uc) / 2) * 2 # we have to make the string an even length
ba = bytearray.fromhex(uc[:newlen])
return base64.urlsafe_b64encode(str(ba))[:leng]
</code></pre>
<p><hr /></p>
<p><strong>edit</strong></p>
<p>heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.</p>
<p>Still curious if there's a better way of doing this that's just as fast.</p>
| 76 | 2009-04-24T09:01:29Z | 12,218,477 | <p>Sometimes a uuid is short enough and if you don't like the dashes you can always.replace('-', '') them</p>
<pre><code>from uuid import uuid4
random_string = str(uuid4())
</code></pre>
<p>If you want it a specific length without dashes</p>
<pre><code>random_string_length = 16
str(uuid4()).replace('-', '')[:random_string_length]
</code></pre>
| 9 | 2012-08-31T15:32:38Z | [
"python",
"random",
"python-2.6"
] |
Getting Python System Calls as string results | 785,078 | <p>I'd like to use <code>os.system("md5sum myFile")</code> and have the result returned from os.system instead of just runned in a subshell where it's echoed.</p>
<p>In short I'd like to do this:</p>
<pre><code>resultMD5 = os.system("md5sum myFile")
</code></pre>
<p>And only have the md5sum in resultMD5 and not echoed.</p>
| 6 | 2009-04-24T09:07:29Z | 785,092 | <p>You should probably use the subprocess module as a replacement for os.system.</p>
| 0 | 2009-04-24T09:11:23Z | [
"python"
] |
Getting Python System Calls as string results | 785,078 | <p>I'd like to use <code>os.system("md5sum myFile")</code> and have the result returned from os.system instead of just runned in a subshell where it's echoed.</p>
<p>In short I'd like to do this:</p>
<pre><code>resultMD5 = os.system("md5sum myFile")
</code></pre>
<p>And only have the md5sum in resultMD5 and not echoed.</p>
| 6 | 2009-04-24T09:07:29Z | 785,149 | <p><a href="http://docs.python.org/library/subprocess.html"><code>subprocess</code></a> is better than using <code>os.system</code> or <code>os.popen</code></p>
<pre><code>import subprocess
resultMD5 = subprocess.Popen(["md5sum","myFile"],stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>Or just calculate the md5sum yourself with the <a href="http://docs.python.org/library/hashlib.html"><code>hashlib</code></a> module.</p>
<pre><code>import hashlib
resultMD5 = hashlib.md5(open("myFile").read()).hexdigest()
</code></pre>
| 11 | 2009-04-24T09:24:52Z | [
"python"
] |
Getting Python System Calls as string results | 785,078 | <p>I'd like to use <code>os.system("md5sum myFile")</code> and have the result returned from os.system instead of just runned in a subshell where it's echoed.</p>
<p>In short I'd like to do this:</p>
<pre><code>resultMD5 = os.system("md5sum myFile")
</code></pre>
<p>And only have the md5sum in resultMD5 and not echoed.</p>
| 6 | 2009-04-24T09:07:29Z | 785,162 | <pre><code>import subprocess
p = subprocess.Popen("md5sum gmail.csv", shell=True, stdout=subprocess.PIPE)
resultMD5, filename = p.communicate()[0].split()
print resultMD5
</code></pre>
| 0 | 2009-04-24T09:30:17Z | [
"python"
] |
Color picking from given coordinates | 785,157 | <p>What is the simplest way to pick up the RGB color code of the given coordinates? For simplicity let's assume that the screen resolution is 1024x768 and color depth/quality 32 bits. The coordinates are given relative to the upper left corner of the screen. I'd like to get some tips or examples how it can be done with Python.</p>
| 0 | 2009-04-24T09:27:19Z | 786,081 | <p>The <a href="http://docs.activestate.com/activepython/2.6/pywin32/win32gui.html" rel="nofollow">win32gui</a> ActivePython documentation should be useful.
I think you can construct something like:</p>
<pre><code>import win32gui
GetPixel(GetDC(WindowFromPoint( (XPos,YPos) )), XPos , YPos )
</code></pre>
| 1 | 2009-04-24T14:28:58Z | [
"python",
"windows",
"color-picker"
] |
Twitter Data Mining: Degrees of separation | 785,327 | <p>What ready available algorithms could I use to data mine twitter to find out the degrees of separation between 2 people on twitter.</p>
<p>How does it change when the social graph keeps changing and updating constantly.</p>
<p>And then, is there any dump of twitter social graph data which I could use rather than making so many API calls to start over.</p>
| 3 | 2009-04-24T10:30:18Z | 785,356 | <p>From the <a href="http://apiwiki.twitter.com">Twitter API</a></p>
<p><strong><a href="http://apiwiki.twitter.com/FAQ&sp=1#WhatstheDataMiningFeedandcanInbsphaveaccesstoit">What's the Data Mining Feed and can I have access to it?</a></strong></p>
<p><a href="http://apiwiki.twitter.com/Streaming-API-Documentation&sp=2">The Data Mining Feed</a> is an expanded version of our /statuses/public_timeline REST API method. It returns 600 recent public statuses, cached for a minute at a time. You can request it up to once per minute to get a representative sample of the public statuses on Twitter. We offer this for free (and with no quality of service guarantees) to researchers and hobbyists. All we ask is that you provide a brief description of your research or project and the IP address(es) you'll be requesting the feed from; just fill out this form. Note that the Data Mining Feed is not intended to provide a contiguous stream of all public updates on Twitter; please see above for more information on the forthcoming "firehose" solution.</p>
<p>and also see: <a href="http://apiwiki.twitter.com/Streaming-API-Documentation&sp=2">Streaming API Documentation</a></p>
| 5 | 2009-04-24T10:43:58Z | [
"python",
"twitter",
"dump",
"social-graph"
] |
Twitter Data Mining: Degrees of separation | 785,327 | <p>What ready available algorithms could I use to data mine twitter to find out the degrees of separation between 2 people on twitter.</p>
<p>How does it change when the social graph keeps changing and updating constantly.</p>
<p>And then, is there any dump of twitter social graph data which I could use rather than making so many API calls to start over.</p>
| 3 | 2009-04-24T10:30:18Z | 817,451 | <p>There was a company offering a dump of the social graph, but it was taken down and no longer available. As you already realized - it is kind of hard, as it is changing all the time.</p>
<p>I would recommend checking out their social_graph api methods as they give the most info with the least API calls.</p>
| 0 | 2009-05-03T16:34:30Z | [
"python",
"twitter",
"dump",
"social-graph"
] |
Twitter Data Mining: Degrees of separation | 785,327 | <p>What ready available algorithms could I use to data mine twitter to find out the degrees of separation between 2 people on twitter.</p>
<p>How does it change when the social graph keeps changing and updating constantly.</p>
<p>And then, is there any dump of twitter social graph data which I could use rather than making so many API calls to start over.</p>
| 3 | 2009-04-24T10:30:18Z | 5,430,461 | <p>There might be other ways of doing it but I've just spent the past 10 minutes looking at doing something similar and stumbled upon this Q.</p>
<p>I'd use an undirected (& weighted - as I want to look at location too) graph - use JgraphT or similar in py; JGraphT is java based but includes different prewritten algos.</p>
<p>You can then use an algorithm called BellmanFord; takes an integer input and searches the graph for the shortest path with the integer input, and only integer input, unlike Dijkstras.</p>
<p><a href="http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm</a></p>
<p>I used it recently in a project for flight routing, iterating up to find shortest path with shortest 'hops' (edges).</p>
| 0 | 2011-03-25T09:09:21Z | [
"python",
"twitter",
"dump",
"social-graph"
] |
Python tool that suggests refactorings | 785,667 | <p>When digging into legacy Python code and writing Python code myself, I often use <a href="http://www.logilab.org/857">pylint</a>. I'm also using <a href="http://clonedigger.sourceforge.net/">Clone Digger</a>. I've recently started to use <a href="http://rope.sourceforge.net/">rope</a>, which is a library for automated refactoring.</p>
<p>But I'm looking for something else than rope. I would prefer a tool that just makes suggestions about possible refactorings: names the refactoring, optionally provides a short description of it (great for learning purposes), highlights the code section and lets me do the refactoring myself. Is there such a tool?</p>
| 10 | 2009-04-24T12:41:02Z | 788,175 | <p>Check out bicycle repair man <a href="http://bicyclerepair.sourceforge.net/" rel="nofollow">http://bicyclerepair.sourceforge.net/</a></p>
<p>What is Bicycle Repair Man?
The Bicycle Repair Man project is an attempt to create refactoring browser functionality for python. It is packaged as a library that can be added to IDEs and editors to provide refactoring capabilities. Bindings for Emacs and Vi are included with the package.</p>
<p>Never used it myself, but have read about it. Sounds like what you are looking for.</p>
| 2 | 2009-04-25T03:20:34Z | [
"python",
"refactoring"
] |
Python tool that suggests refactorings | 785,667 | <p>When digging into legacy Python code and writing Python code myself, I often use <a href="http://www.logilab.org/857">pylint</a>. I'm also using <a href="http://clonedigger.sourceforge.net/">Clone Digger</a>. I've recently started to use <a href="http://rope.sourceforge.net/">rope</a>, which is a library for automated refactoring.</p>
<p>But I'm looking for something else than rope. I would prefer a tool that just makes suggestions about possible refactorings: names the refactoring, optionally provides a short description of it (great for learning purposes), highlights the code section and lets me do the refactoring myself. Is there such a tool?</p>
| 10 | 2009-04-24T12:41:02Z | 790,273 | <p>NetBeans has an early access version that supports Python, and it is rather nice. It has some basic refactoring tools that I found the be useful. As an added bonus it works on Windows, Linux, Mac OS X and Solaris.</p>
<p>Check it out at:
<a href="http://www.netbeans.org/features/python/" rel="nofollow">http://www.netbeans.org/features/python/</a></p>
| 0 | 2009-04-26T05:09:09Z | [
"python",
"refactoring"
] |
Python tool that suggests refactorings | 785,667 | <p>When digging into legacy Python code and writing Python code myself, I often use <a href="http://www.logilab.org/857">pylint</a>. I'm also using <a href="http://clonedigger.sourceforge.net/">Clone Digger</a>. I've recently started to use <a href="http://rope.sourceforge.net/">rope</a>, which is a library for automated refactoring.</p>
<p>But I'm looking for something else than rope. I would prefer a tool that just makes suggestions about possible refactorings: names the refactoring, optionally provides a short description of it (great for learning purposes), highlights the code section and lets me do the refactoring myself. Is there such a tool?</p>
| 10 | 2009-04-24T12:41:02Z | 790,287 | <p>I don't if that type of tool exists in any specific language, although the concept was mentioned in Martin Fowler's refactoring book (<a href="http://www.refactoring.com/" rel="nofollow">web reference</a>).</p>
<p>The best tool I know of that currently exists is cyclomatic complexity. <a href="http://www.traceback.org/2008/03/31/measuring-cyclomatic-complexity-of-python-code/" rel="nofollow">This article</a> implements a cyclomatic complexity counter for python. </p>
<p>The other easy metric to target is method/function length, number of attributes of objects/classes and number of parameters to functions, if I recall, pylint already counted those.</p>
| 1 | 2009-04-26T05:24:43Z | [
"python",
"refactoring"
] |
Python tool that suggests refactorings | 785,667 | <p>When digging into legacy Python code and writing Python code myself, I often use <a href="http://www.logilab.org/857">pylint</a>. I'm also using <a href="http://clonedigger.sourceforge.net/">Clone Digger</a>. I've recently started to use <a href="http://rope.sourceforge.net/">rope</a>, which is a library for automated refactoring.</p>
<p>But I'm looking for something else than rope. I would prefer a tool that just makes suggestions about possible refactorings: names the refactoring, optionally provides a short description of it (great for learning purposes), highlights the code section and lets me do the refactoring myself. Is there such a tool?</p>
| 10 | 2009-04-24T12:41:02Z | 1,802,902 | <p>Oh Forget about your tool, instead use TDD and a good book like refactoring to design patterns by Kerievsky. The problem is that refactoring is a way to improve your code and design, but only You can know what you want to achieve, no refactoring tool can do it for you.</p>
<p>My point is that best way to learn refactoring is to study examples, not to follow some stupid/simple tools, because they wont teach you any sophisticated refactoring nor they will tell you if you have refactoring that compose well with you code.</p>
<p>PS Read Fowler "Refactoring" and Kerievsky "Refactoring to design Patterns" those books are must read when learning refactoring. And they mention simple way to checking if refactoring is needed (smells).</p>
<p>Also consider TDD as good way to ensure that your refs are safe and do not break your code.
Beck "Test-Driven Development by example" is a good book to start with.
And Python have PyUnit for TDD.</p>
| 2 | 2009-11-26T10:35:19Z | [
"python",
"refactoring"
] |
Python tool that suggests refactorings | 785,667 | <p>When digging into legacy Python code and writing Python code myself, I often use <a href="http://www.logilab.org/857">pylint</a>. I'm also using <a href="http://clonedigger.sourceforge.net/">Clone Digger</a>. I've recently started to use <a href="http://rope.sourceforge.net/">rope</a>, which is a library for automated refactoring.</p>
<p>But I'm looking for something else than rope. I would prefer a tool that just makes suggestions about possible refactorings: names the refactoring, optionally provides a short description of it (great for learning purposes), highlights the code section and lets me do the refactoring myself. Is there such a tool?</p>
| 10 | 2009-04-24T12:41:02Z | 9,784,067 | <p>You might like <a href="http://pythoscope.org/" rel="nofollow">Pythoscope</a>, an automatic Python unit test generator, which is supposed to help you bootstrap a unit test suite by dynamically executing code.</p>
<p>Also, have you checked out the <a href="http://rope.sourceforge.net/library.html#rope-contrib-codeassist" rel="nofollow"><code>rope.contrib.codeassist</code></a> module? It is supposed to automatically propose and perform refactorings of your source code for you.</p>
| 2 | 2012-03-20T09:19:33Z | [
"python",
"refactoring"
] |
Is there a way to retrieve process stats using Perl or Python? | 785,810 | <p>Is there a way to generically retrieve process stats using Perl or Python? We could keep it Linux specific.</p>
<p>There are a few problems: I won't know the PID ahead of time, but I <em>can</em> run the process in question from the script itself. For example, I'd have no problem doing:</p>
<p><code>./myscript.pl some/process/I/want/to/get/stats/for</code></p>
<p>Basically, I'd like to, at the very least, get the memory consumption of the process, but the more information I can get the better (like run time of the process, average CPU usage of the process, etc.)</p>
<p>Thanks.</p>
| 2 | 2009-04-24T13:18:16Z | 785,836 | <p>If you are <code>fork()</code>ing the child, you will know it's PID.</p>
<p>From within the parent you can then parse the files in <code>/proc/<PID/</code> to check the memory and CPU usage, albeit only for as long as the child process is running.</p>
| 2 | 2009-04-24T13:25:11Z | [
"python",
"linux",
"perl",
"process"
] |
Is there a way to retrieve process stats using Perl or Python? | 785,810 | <p>Is there a way to generically retrieve process stats using Perl or Python? We could keep it Linux specific.</p>
<p>There are a few problems: I won't know the PID ahead of time, but I <em>can</em> run the process in question from the script itself. For example, I'd have no problem doing:</p>
<p><code>./myscript.pl some/process/I/want/to/get/stats/for</code></p>
<p>Basically, I'd like to, at the very least, get the memory consumption of the process, but the more information I can get the better (like run time of the process, average CPU usage of the process, etc.)</p>
<p>Thanks.</p>
| 2 | 2009-04-24T13:18:16Z | 785,855 | <p>A common misconception is that reading /proc is like reading /home. /proc is designed to give you the same information with one open() that 20 similar syscalls filling some structure could provide. Reading it does not pollute buffers, send innocent programs to paging hell or otherwise contribute to the death of kittens.</p>
<p>Accessing /proc/foo is just telling the kernel "give me information on foo that I can process in a language agnostic way"</p>
<p>If you need more details on what is in /proc/{pid}/ , update your question and I'll post them.</p>
| 1 | 2009-04-24T13:32:10Z | [
"python",
"linux",
"perl",
"process"
] |
Is there a way to retrieve process stats using Perl or Python? | 785,810 | <p>Is there a way to generically retrieve process stats using Perl or Python? We could keep it Linux specific.</p>
<p>There are a few problems: I won't know the PID ahead of time, but I <em>can</em> run the process in question from the script itself. For example, I'd have no problem doing:</p>
<p><code>./myscript.pl some/process/I/want/to/get/stats/for</code></p>
<p>Basically, I'd like to, at the very least, get the memory consumption of the process, but the more information I can get the better (like run time of the process, average CPU usage of the process, etc.)</p>
<p>Thanks.</p>
| 2 | 2009-04-24T13:18:16Z | 786,386 | <p>Have a look at the <a href="http://search.cpan.org/~durist/Proc-ProcessTable-0.45/ProcessTable.pm" rel="nofollow">Proc::ProcessTable</a> module which returns quite a bit of information on the processes in the system. Call the "fields" method to get a list of details that you can extract from each process.</p>
<p>I recently discovered the above module which has just about replaced the Process module that I had written when writing a Perl kill program for Linux. You can have a look at my script <a href="http://pastebin.com/f16edcba3" rel="nofollow">here</a>. </p>
<p>It can be easily extended to extract further information from the ps command. For eg. the '<strong>getbycmd</strong>' method returns a list of pid's whose command line invocation matches the passed argument. You can then retrieve a specific process' details by calling '<strong>getdetail</strong>' by passing that PID to it like so,</p>
<pre><code>my $psTable = Process->new();
# Get list of process owned by 'root'
for my $pid ( $psTable->getbyuser("root") ) {
$psDetail = $psList->getdetail( $pid );
# Do something with the psDetail..
}
</code></pre>
| 7 | 2009-04-24T15:38:56Z | [
"python",
"linux",
"perl",
"process"
] |
AttributeError: xmlNode instance has no attribute 'isCountNode' | 785,972 | <p>I'm using libxml2 in a Python app I'm writing, and am trying to run some test code to parse an XML file. The program downloads an XML file from the internet and parses it. However, I have run into a problem.</p>
<p>With the following code:</p>
<pre><code>xmldoc = libxml2.parseDoc(gfile_content)
droot = xmldoc.children # Get document root
dchild = droot.children # Get child nodes
while dchild is not None:
if dchild.type == "element":
print "\tAn element with ", dchild.isCountNode(), "child(ren)"
print "\tAnd content", repr(dchild.content)
dchild = dchild.next
xmldoc.freeDoc();
</code></pre>
<p>...which is based on the code example found on <a href="http://www.xml.com/pub/a/2003/05/14/py-xml.html" rel="nofollow">this article on XML.com</a>, I receive the following error when I attempt to run this code on Python 2.4.3 (CentOS 5.2 package).</p>
<pre><code>Traceback (most recent call last):
File "./xml.py", line 25, in ?
print "\tAn element with ", dchild.isCountNode(), "child(ren)"
AttributeError: xmlNode instance has no attribute 'isCountNode'
</code></pre>
<p>I'm rather stuck here.</p>
<p><strong>Edit:</strong> I should note here I also tried IsCountNode() and it still threw an error.</p>
| 0 | 2009-04-24T14:02:30Z | 785,980 | <p>isCountNode should read "lsCountNode" (a lower-case "L")</p>
| 3 | 2009-04-24T14:04:39Z | [
"python",
"xml",
"centos",
"libxml2",
"centos5"
] |
Django blows up with 1.1, Can't find urls module ... totally confused | 785,987 | <p>EDIT: Issue solved, answered it below. Lame error. Blah</p>
<p>So I upgraded to Django 1.1 and for the life of me I can't figure out what I'm missing. Here is my traceback:</p>
<p><a href="http://dpaste.com/37391/" rel="nofollow">http://dpaste.com/37391/</a> - This happens on any page I try to go to.</p>
<p>I've modified my urls.py to include the admin in the new method:</p>
<blockquote>
<p>from django.contrib import admin</p>
<p>admin.autodiscover()</p>
<p>.... urlpatterns declaration</p>
<p>(r'^admin/', include(admin.site.urls)),</p>
</blockquote>
<p>I've tried fidgeting with paths and the like but nothing fixes my problem and I can't figure it out.</p>
<p>Has something major changed since Django 1.1 alpha -> Django 1.1 beta that I am missing? Apart from the admin I can't see what else is new. Are urls still stored in a urls.py within each app?</p>
<p>Thanks for the help in advance, this is beyond frustrating.</p>
| 1 | 2009-04-24T14:06:28Z | 786,028 | <p>try this:</p>
<pre><code> (r'^admin/(.*)', admin.site.root),
</code></pre>
<p><a href="http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Mergednewforms-adminintotrunk" rel="nofollow">More info</a></p>
| 0 | 2009-04-24T14:15:02Z | [
"python",
"django"
] |
Django blows up with 1.1, Can't find urls module ... totally confused | 785,987 | <p>EDIT: Issue solved, answered it below. Lame error. Blah</p>
<p>So I upgraded to Django 1.1 and for the life of me I can't figure out what I'm missing. Here is my traceback:</p>
<p><a href="http://dpaste.com/37391/" rel="nofollow">http://dpaste.com/37391/</a> - This happens on any page I try to go to.</p>
<p>I've modified my urls.py to include the admin in the new method:</p>
<blockquote>
<p>from django.contrib import admin</p>
<p>admin.autodiscover()</p>
<p>.... urlpatterns declaration</p>
<p>(r'^admin/', include(admin.site.urls)),</p>
</blockquote>
<p>I've tried fidgeting with paths and the like but nothing fixes my problem and I can't figure it out.</p>
<p>Has something major changed since Django 1.1 alpha -> Django 1.1 beta that I am missing? Apart from the admin I can't see what else is new. Are urls still stored in a urls.py within each app?</p>
<p>Thanks for the help in advance, this is beyond frustrating.</p>
| 1 | 2009-04-24T14:06:28Z | 786,103 | <p>What is the value of your ROOT_URLCONF in your settings.py file? Is the file named by that setting on your python path? </p>
<p>Are you using the development server or what?</p>
| 0 | 2009-04-24T14:34:18Z | [
"python",
"django"
] |
Django blows up with 1.1, Can't find urls module ... totally confused | 785,987 | <p>EDIT: Issue solved, answered it below. Lame error. Blah</p>
<p>So I upgraded to Django 1.1 and for the life of me I can't figure out what I'm missing. Here is my traceback:</p>
<p><a href="http://dpaste.com/37391/" rel="nofollow">http://dpaste.com/37391/</a> - This happens on any page I try to go to.</p>
<p>I've modified my urls.py to include the admin in the new method:</p>
<blockquote>
<p>from django.contrib import admin</p>
<p>admin.autodiscover()</p>
<p>.... urlpatterns declaration</p>
<p>(r'^admin/', include(admin.site.urls)),</p>
</blockquote>
<p>I've tried fidgeting with paths and the like but nothing fixes my problem and I can't figure it out.</p>
<p>Has something major changed since Django 1.1 alpha -> Django 1.1 beta that I am missing? Apart from the admin I can't see what else is new. Are urls still stored in a urls.py within each app?</p>
<p>Thanks for the help in advance, this is beyond frustrating.</p>
| 1 | 2009-04-24T14:06:28Z | 786,108 | <p>I figured it out. I was missing a urls.py that I referenced (for some reason, SVN said it was in the repo but it never was fetched on an update) and it simply said could not find urls (with no reference to notes.urls which WAS missing) so it got very confusing.</p>
<p>Either way, fixed -- Awesome!</p>
| 2 | 2009-04-24T14:35:21Z | [
"python",
"django"
] |
How to design an email system? | 786,138 | <p>I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communication with a web interface (which will be only for internal use to change the email templates) and most important it will check some database tables and based on those results will send emails ... lots of them.</p>
<p>Now, I am wondering how can this be designed so it can be made scalable and provide the necessary performance as it will probably have to handle a few thousands emails per hours (this should be the peek). I am mostly interested about how would this kind of architecture should be thought in order to be easily scaled in the future if needed.</p>
<p>Python will be used on the backend with Postgres and probably whatever comes first between a Python web framework and GWT on the frontend (which seems the simplest task).</p>
| 3 | 2009-04-24T14:45:27Z | 786,171 | <p>This sound to me, that you're trying to optimize for batch processing, where the heat doenst happen on the web interface but in the backend. This also sounds a job for a queuing architecture.</p>
<p><a href="http://aws.amazon.com/sqs/" rel="nofollow">Amazon</a> offers queuing systems for instance if you really need massive scale. So you can add multiple machines on your side to deliver the messages as eMails. So you allow one machines only taking perhaps 100 messages from the queue at one time.</p>
<p>The pattern with eMail systems should be asychonous, so have a look at other asynchonous archictures if you dont like queues.</p>
| 2 | 2009-04-24T14:51:16Z | [
"python",
"linux",
"design",
"email"
] |
How to design an email system? | 786,138 | <p>I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communication with a web interface (which will be only for internal use to change the email templates) and most important it will check some database tables and based on those results will send emails ... lots of them.</p>
<p>Now, I am wondering how can this be designed so it can be made scalable and provide the necessary performance as it will probably have to handle a few thousands emails per hours (this should be the peek). I am mostly interested about how would this kind of architecture should be thought in order to be easily scaled in the future if needed.</p>
<p>Python will be used on the backend with Postgres and probably whatever comes first between a Python web framework and GWT on the frontend (which seems the simplest task).</p>
| 3 | 2009-04-24T14:45:27Z | 786,176 | <p>This is a real good candidate for using some off the shelf software. There are any number of open-source mailing list manager packages around; they already know how to do the mass mailings. It's not completely clear whether these mailings would go to the <em>same</em> set of people each time; if so, get any one of the regular mailing list programs.</p>
<p>If not, the easy answer is</p>
<pre><code>$ mail address -s subject < file
</code></pre>
<p>once per mail.</p>
<p>By the way, investigate the policies of whoever is upstream from you on the net. Some ISPs see lots of mails as probable spam, and may surprise you by cutting off or metering your internet access.</p>
| 5 | 2009-04-24T14:51:48Z | [
"python",
"linux",
"design",
"email"
] |
How to design an email system? | 786,138 | <p>I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communication with a web interface (which will be only for internal use to change the email templates) and most important it will check some database tables and based on those results will send emails ... lots of them.</p>
<p>Now, I am wondering how can this be designed so it can be made scalable and provide the necessary performance as it will probably have to handle a few thousands emails per hours (this should be the peek). I am mostly interested about how would this kind of architecture should be thought in order to be easily scaled in the future if needed.</p>
<p>Python will be used on the backend with Postgres and probably whatever comes first between a Python web framework and GWT on the frontend (which seems the simplest task).</p>
| 3 | 2009-04-24T14:45:27Z | 787,170 | <p>A few thousand emails per hour isn't really that much, as long as your outgoing mail server is willing to accept them in a timely manner.</p>
<p>I would send them using a local mta, like postfix, or exim (which would then send them through your outgoing relay if required). That service is then responsible for the mail queues, retries, bounces, etc. If your looking for more "mailing list" features, try adding mailman into the mix. It's written in python, and you've probably seen it, as it runs tons of internet mailing lists. </p>
| 3 | 2009-04-24T19:11:25Z | [
"python",
"linux",
"design",
"email"
] |
How to design an email system? | 786,138 | <p>I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communication with a web interface (which will be only for internal use to change the email templates) and most important it will check some database tables and based on those results will send emails ... lots of them.</p>
<p>Now, I am wondering how can this be designed so it can be made scalable and provide the necessary performance as it will probably have to handle a few thousands emails per hours (this should be the peek). I am mostly interested about how would this kind of architecture should be thought in order to be easily scaled in the future if needed.</p>
<p>Python will be used on the backend with Postgres and probably whatever comes first between a Python web framework and GWT on the frontend (which seems the simplest task).</p>
| 3 | 2009-04-24T14:45:27Z | 787,214 | <p>You might want to try Twisted Mail for implementing your own backend in pure Python.</p>
| 0 | 2009-04-24T19:23:34Z | [
"python",
"linux",
"design",
"email"
] |
How to design an email system? | 786,138 | <p>I am working for a company that provides customer support to its clients. I am trying to design a system that would send emails automatically to clients when some event occurs. The system would consist of a backend part and a web interface part. The backend will handle the communication with a web interface (which will be only for internal use to change the email templates) and most important it will check some database tables and based on those results will send emails ... lots of them.</p>
<p>Now, I am wondering how can this be designed so it can be made scalable and provide the necessary performance as it will probably have to handle a few thousands emails per hours (this should be the peek). I am mostly interested about how would this kind of architecture should be thought in order to be easily scaled in the future if needed.</p>
<p>Python will be used on the backend with Postgres and probably whatever comes first between a Python web framework and GWT on the frontend (which seems the simplest task).</p>
| 3 | 2009-04-24T14:45:27Z | 787,225 | <p>You might want to check out <a href="http://support.lamsonproject.org" rel="nofollow">Lamson</a>, a state machine-based e-mail server written in Python that should be able to do what you have described. It's written by Zed Shaw, and he blogged about it recently <a href="http://zedshaw.com/blog/2009-04-03.html" rel="nofollow">here</a>.</p>
| 2 | 2009-04-24T19:25:42Z | [
"python",
"linux",
"design",
"email"
] |
Basic MVT issue in Django | 786,149 | <p>I have a Django website as follows:</p>
<ul>
<li>site has several views</li>
<li>each view has its own template to show its data</li>
<li>each template extends a base template</li>
<li>base template is the base of the site, has all the JS/CSS and the basic layout</li>
</ul>
<p>So up until now it's all good. So now we have the master head of the site (which exists in the base template), and it is common to all the views.</p>
<p>But now I want to make it dynamic, and add some dynamic data to it. On which view do I do this? All my views are basically <code>render_to_response('viewtemplate.html', someContext)</code>. So how do add a common view to a base template?</p>
<p>Obviously I will not duplicate the common code to each separate view...</p>
<p>I think I'm missing something fundamental in the MVT basis of Django.</p>
| 6 | 2009-04-24T14:46:45Z | 786,249 | <p>You want to use <code>context_instance</code> and <code>RequestContext</code>s. </p>
<p>First, add at the top of your <code>views.py</code>:</p>
<pre><code>from django.template import RequestContext
</code></pre>
<p>Then, update all of your views to look like:</p>
<pre><code>def someview(request, ...)
...
return render_to_response('viewtemplate.html', someContext, context_instance=RequestContext(request))
</code></pre>
<p>In your <code>settings.py</code>, add:</p>
<pre><code>TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
...
'myproj.app.context_processors.dynamic',
'myproj.app.context_processors.sidebar',
'myproj.app.context_processors.etc',
)
</code></pre>
<p>Each of these <code>context_processors</code> is a function takes the <code>request</code> object and returns a context in the form of a dictionary. Just put all the functions in <code>context_processors.py</code> inside the appropriate app. For example, a blog might have a sidebar with a list of recent entries and comments. <code>context_processors.py</code> would just define:</p>
<pre><code>def sidebar(request):
recent_entry_list = Entry.objects...
recent_comment_list = Comment.objects...
return {'recent_entry_list': recent_entry_list, 'recent_comment_list': recent_comment_list}
</code></pre>
<p>You can add as many or as few as you like.</p>
<p>For more, check out the <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#id1" rel="nofollow">Django Template Docs</a>.</p>
| 7 | 2009-04-24T15:08:44Z | [
"python",
"django",
"django-templates"
] |
Basic MVT issue in Django | 786,149 | <p>I have a Django website as follows:</p>
<ul>
<li>site has several views</li>
<li>each view has its own template to show its data</li>
<li>each template extends a base template</li>
<li>base template is the base of the site, has all the JS/CSS and the basic layout</li>
</ul>
<p>So up until now it's all good. So now we have the master head of the site (which exists in the base template), and it is common to all the views.</p>
<p>But now I want to make it dynamic, and add some dynamic data to it. On which view do I do this? All my views are basically <code>render_to_response('viewtemplate.html', someContext)</code>. So how do add a common view to a base template?</p>
<p>Obviously I will not duplicate the common code to each separate view...</p>
<p>I think I'm missing something fundamental in the MVT basis of Django.</p>
| 6 | 2009-04-24T14:46:45Z | 786,440 | <p>or use a <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/" rel="nofollow">generic view</a>, because they are automatically passed the request context.</p>
<p>a simple direct to template generic view can be used to avoid having to import/pass in the request context.</p>
| -1 | 2009-04-24T15:50:48Z | [
"python",
"django",
"django-templates"
] |
Basic MVT issue in Django | 786,149 | <p>I have a Django website as follows:</p>
<ul>
<li>site has several views</li>
<li>each view has its own template to show its data</li>
<li>each template extends a base template</li>
<li>base template is the base of the site, has all the JS/CSS and the basic layout</li>
</ul>
<p>So up until now it's all good. So now we have the master head of the site (which exists in the base template), and it is common to all the views.</p>
<p>But now I want to make it dynamic, and add some dynamic data to it. On which view do I do this? All my views are basically <code>render_to_response('viewtemplate.html', someContext)</code>. So how do add a common view to a base template?</p>
<p>Obviously I will not duplicate the common code to each separate view...</p>
<p>I think I'm missing something fundamental in the MVT basis of Django.</p>
| 6 | 2009-04-24T14:46:45Z | 793,167 | <p>Context processors and RequestContext (see Tyler's answer) are the way to go for data that is used on every page load. For data that you may need on various views, but not all (especially data that isn't really related to the primary purpose of the view, but appears in something like a navigation sidebar), it often makes most sense to define a custom template tag for retrieving the data.</p>
| 2 | 2009-04-27T11:51:17Z | [
"python",
"django",
"django-templates"
] |
Django restapi passing parameter to read() | 786,199 | <p>In the test example <a href="http://django-rest-interface.googlecode.com/svn/trunk/django_restapi_tests/examples/custom_urls.py" rel="nofollow">http://django-rest-interface.googlecode.com/svn/trunk/django_restapi_tests/examples/custom_urls.py</a> on line 19 to they parse the request.path to get the poll_id. This looks very fragile to me. If the url changes then this line breaks. I have attempted to pass in the poll_id but this did not work.
So my question is how do I use the poll_id (or any other value) gathered from the url? </p>
| 0 | 2009-04-24T14:56:40Z | 786,369 | <p>Views are only called when the associated url is matched. By crafting the url regex properly, you can guarantee that any request passed to your view will have the <code>poll_id</code> at the correct position in the request path. This is what the example does:</p>
<pre><code>url(r'^json/polls/(?P<poll_id>\d+)/choices/$', json_choice_resource, {'is_entry':False}),
</code></pre>
<p>The <code>json_choice_resource</code> view is an instance of <code>django_restapi.model_resource.Collection</code> and thus the <code>read()</code> method of <code>Collection</code> will only ever act on requests with paths of the expected format.</p>
| 0 | 2009-04-24T15:34:02Z | [
"python",
"django"
] |
Python-getting data from an asp.net AJAX application | 786,603 | <p>Using Python, I'm trying to read the values on <a href="http://utahcritseries.com/RawResults.aspx">http://utahcritseries.com/RawResults.aspx</a>. I can read the page just fine, but am having difficulty changing the value of the year combo box, to view data from other years. How can I read the data for years other than the default of 2002?</p>
<p>The page appears to be doing an HTTP Post once the year combo box has changed. The name of the control is ct100$ContentPlaceHolder1$ddlSeries. I try setting a value for this control using urllib.urlencode(postdata), but I must be doing something wrong-the data on the page is not changing. Can this be done in Python?</p>
<p>I'd prefer not to use Selenium, if at all possible.</p>
<p>I've been using code like this(from stackoverflow user dbr)</p>
<pre><code>import urllib
postdata = {'ctl00$ContentPlaceHolder1$ddlSeries': 9}
src = urllib.urlopen(
"http://utahcritseries.com/RawResults.aspx",
data = urllib.urlencode(postdata)
).read()
print src
</code></pre>
<p>But seems to be pulling up the same 2002 data. I've tried using firebug to inspect the headers and I see a lot of extraneous and random-looking data being sent back and forth-do I need to post these values back to the server also?</p>
| 5 | 2009-04-24T16:24:09Z | 787,300 | <p>Use the excellent <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> library:</p>
<pre><code>from mechanize import Browser
b = Browser()
b.open("http://utahcritseries.com/RawResults.aspx")
b.select_form(nr=0)
year = b.form.find_control(type='select')
year.get(label='2005').selected = True
src = b.submit().read()
print src
</code></pre>
<p>Mechanize is available on PyPI: <code>easy_install mechanize</code></p>
| 3 | 2009-04-24T19:47:01Z | [
"asp.net",
"python",
"asp.net-ajax",
"screen-scraping"
] |
Is there a Vector3 type in Python? | 786,691 | <p>I quickly checked numPy but it looks like it's using arrays as vectors? I am looking for a proper Vector3 type that I can instance and work on.</p>
| 3 | 2009-04-24T16:46:17Z | 786,748 | <p>Found <a href="http://code.google.com/p/gameobjects/source/browse/trunk/vector3.py">this</a>, maybe it can do what you want.</p>
| 5 | 2009-04-24T16:59:33Z | [
"python",
"vector"
] |
Is there a Vector3 type in Python? | 786,691 | <p>I quickly checked numPy but it looks like it's using arrays as vectors? I am looking for a proper Vector3 type that I can instance and work on.</p>
| 3 | 2009-04-24T16:46:17Z | 786,758 | <p>I don't believe there is anything standard (but I could be wrong, I don't keep up with python that closely).</p>
<p>It's very easy to implement though, and you may want to build on top of the numpy array as a container for it anyway, which gives you lots of good (and efficient) bits and pieces.</p>
| 2 | 2009-04-24T17:01:46Z | [
"python",
"vector"
] |
Is there a Vector3 type in Python? | 786,691 | <p>I quickly checked numPy but it looks like it's using arrays as vectors? I am looking for a proper Vector3 type that I can instance and work on.</p>
| 3 | 2009-04-24T16:46:17Z | 786,893 | <p><a href="http://dirac.cnrs-orleans.fr/plone/software/scientificpython/" rel="nofollow">ScientificPython</a> has a <a href="http://dirac.cnrs-orleans.fr/ScientificPython/ScientificPythonManual/Scientific.Geometry.Vector-class.html" rel="nofollow">Vector</a> class. for example:</p>
<pre><code>In [1]: from Scientific.Geometry import Vector
In [2]: v1 = Vector(1, 2, 3)
In [3]: v2 = Vector(0, 8, 2)
In [4]: v1.cross(v2)
Out[4]: Vector(-20.000000,-2.000000,8.000000)
In [5]: v1.normal()
Out[5]: Vector(0.267261,0.534522,0.801784)
In [6]: v2.cross(v1)
Out[6]: Vector(20.000000,2.000000,-8.000000)
In [7]: v1*v2 # dot product
Out[7]: 22.0
</code></pre>
| 4 | 2009-04-24T17:44:07Z | [
"python",
"vector"
] |
What is wrong with my attempt to do a string replace operation in Python? | 786,881 | <p>What am I doing wrong here?</p>
<pre><code>import re
x = "The sky is red"
r = re.compile ("red")
y = r.sub(x, "blue")
print x # Prints "The sky is red"
print y # Prints "blue"
</code></pre>
<p>How do i get it to print "The sky is blue"?</p>
| 2 | 2009-04-24T17:39:56Z | 786,887 | <p>Try:</p>
<pre><code>x = r.sub("blue", x)
</code></pre>
| 1 | 2009-04-24T17:42:06Z | [
"python"
] |
What is wrong with my attempt to do a string replace operation in Python? | 786,881 | <p>What am I doing wrong here?</p>
<pre><code>import re
x = "The sky is red"
r = re.compile ("red")
y = r.sub(x, "blue")
print x # Prints "The sky is red"
print y # Prints "blue"
</code></pre>
<p>How do i get it to print "The sky is blue"?</p>
| 2 | 2009-04-24T17:39:56Z | 786,902 | <p>The problem with your code is that there are two sub functions in the re module. One is the general one and there's one tied to regular expression objects. Your code is not following either one:</p>
<p>The two methods are:</p>
<p><code>re.sub(pattern, repl, string[, count])</code> <a href="http://docs.python.org/library/re.html#re.sub" rel="nofollow">(docs here)</a></p>
<p>Used like so:</p>
<pre><code>>>> y = re.sub(r, 'blue', x)
>>> y
'The sky is blue'
</code></pre>
<p>And for when you compile it before hand, as you tried, you can use:</p>
<p><code>RegexObject.sub(repl, string[, count=0])</code> <a href="http://docs.python.org/library/re.html#re.RegexObject.sub" rel="nofollow">(docs here)</a></p>
<p>Used like so:</p>
<pre><code>>>> z = r.sub('blue', x)
>>> z
'The sky is blue'
</code></pre>
| 12 | 2009-04-24T17:46:05Z | [
"python"
] |
What is wrong with my attempt to do a string replace operation in Python? | 786,881 | <p>What am I doing wrong here?</p>
<pre><code>import re
x = "The sky is red"
r = re.compile ("red")
y = r.sub(x, "blue")
print x # Prints "The sky is red"
print y # Prints "blue"
</code></pre>
<p>How do i get it to print "The sky is blue"?</p>
| 2 | 2009-04-24T17:39:56Z | 786,916 | <p>You read the API wrong</p>
<p><a href="http://docs.python.org/library/re.html#re.sub">http://docs.python.org/library/re.html#re.sub</a></p>
<p>pattern.sub(repl, string[, count])¶</p>
<pre><code>r.sub(x, "blue")
# should be
r.sub("blue", x)
</code></pre>
| 6 | 2009-04-24T17:50:36Z | [
"python"
] |
What is wrong with my attempt to do a string replace operation in Python? | 786,881 | <p>What am I doing wrong here?</p>
<pre><code>import re
x = "The sky is red"
r = re.compile ("red")
y = r.sub(x, "blue")
print x # Prints "The sky is red"
print y # Prints "blue"
</code></pre>
<p>How do i get it to print "The sky is blue"?</p>
| 2 | 2009-04-24T17:39:56Z | 786,917 | <p>You have the arguments to your call to <code>sub</code> the wrong way round it should be:</p>
<pre>
<code>
import re
x = "The sky is red"
r = re.compile ("red")
y = r.sub("blue", x)
print x # Prints "The sky is red"
print y # Prints "The sky is blue"
</code>
</pre>
| 3 | 2009-04-24T17:50:41Z | [
"python"
] |
What is wrong with my attempt to do a string replace operation in Python? | 786,881 | <p>What am I doing wrong here?</p>
<pre><code>import re
x = "The sky is red"
r = re.compile ("red")
y = r.sub(x, "blue")
print x # Prints "The sky is red"
print y # Prints "blue"
</code></pre>
<p>How do i get it to print "The sky is blue"?</p>
| 2 | 2009-04-24T17:39:56Z | 790,077 | <p>By the way, for such a simple example, the <code>re</code> module is overkill:</p>
<pre><code>x= "The sky is red"
y= x.replace("red", "blue")
print y
</code></pre>
| 3 | 2009-04-26T01:25:09Z | [
"python"
] |
Is site-packages appropriate for applications or just libraries? | 787,015 | <p>I'm in a bit of a discussion with some other developers on an open source project. I'm new to python but it seems to me that site-packages is meant for libraries and not end user applications. Is that true or is site-packages an appropriate place to install an application meant to be run by an end user?</p>
| 5 | 2009-04-24T18:22:20Z | 787,128 | <p>The program run by the end user is usually somewhere in their path, with most of the code in the module directory, which is often in site-packages.</p>
<p>Many python programs will have a small script located in the path, which imports the module, and calls a "main" method to run the program. This allows the programmer to do some upfront checks, and possibly modify sys.path if needed to find the needed module. This can also speed up load time on larger programs, because only files that are imported will be run from bytecode.</p>
| 3 | 2009-04-24T18:58:55Z | [
"python"
] |
Is site-packages appropriate for applications or just libraries? | 787,015 | <p>I'm in a bit of a discussion with some other developers on an open source project. I'm new to python but it seems to me that site-packages is meant for libraries and not end user applications. Is that true or is site-packages an appropriate place to install an application meant to be run by an end user?</p>
| 5 | 2009-04-24T18:22:20Z | 787,200 | <p>We do it like this.</p>
<p>Most stuff we download is in site-packages. They come from <code>pypi</code> or Source Forge or some other external source; they are easy to rebuild; they're highly reused; they don't change much.</p>
<p>Must stuff we write is in other locations (usually under <code>/opt</code>, or <code>c:\opt</code>) AND is included in the <code>PYTHONPATH</code>.</p>
<p>There's no <em>great</em> reason for keeping our stuff out of <code>site-packages</code>. However, our feeble excuse is that our stuff changes a lot. Pretty much constantly. To reinstall in site-packages every time we think we have something better is a bit of a pain.</p>
<p>Since we're testing out of our working directories or SVN checkout directories, our test environments make heavy use of <code>PYTHONPATH</code>. </p>
<p>The development use of <code>PYTHONPATH</code> bled over into production. We use a <code>setup.py</code> for production installs, but install to an alternate home under <code>/opt</code> and set the <code>PYTHONPATH</code> to include <code>/opt/ourapp-1.1</code>.</p>
| 4 | 2009-04-24T19:18:15Z | [
"python"
] |
Is site-packages appropriate for applications or just libraries? | 787,015 | <p>I'm in a bit of a discussion with some other developers on an open source project. I'm new to python but it seems to me that site-packages is meant for libraries and not end user applications. Is that true or is site-packages an appropriate place to install an application meant to be run by an end user?</p>
| 5 | 2009-04-24T18:22:20Z | 787,203 | <p>Site-packages is for libraries, definitely.</p>
<p>A hybrid approach might work: you can install the libraries required by your application in site-packages and then install the main module elsewhere.</p>
| 0 | 2009-04-24T19:19:54Z | [
"python"
] |
Is site-packages appropriate for applications or just libraries? | 787,015 | <p>I'm in a bit of a discussion with some other developers on an open source project. I'm new to python but it seems to me that site-packages is meant for libraries and not end user applications. Is that true or is site-packages an appropriate place to install an application meant to be run by an end user?</p>
| 5 | 2009-04-24T18:22:20Z | 788,253 | <p>If you can turn part of the application to a library and provide an API, then site-packages is a good place for it. This is actually how many python applications do it.</p>
<p>But from user or administrator point of view that isn't actually the problem. The problem is how we can manage the installed stuff. After I have installed it, how can I upgrade and uninstall it?</p>
<p>I use Fedora. If I use the python that came with it, I don't like installing things to site-packages outside the RPM system. In some cases I have built rpm myself to install it.</p>
<p>If I build my own python outside RPM, then I naturally want to use python's mechanisms to manage it.</p>
<p>Third way is to use something like easy_install to install such thing for example as a user to home directory.</p>
<p>So</p>
<ul>
<li>Allow packaging to distributions.</li>
<li>Allow selecting the python to use.</li>
<li>Allow using python installed by distribution where you don't have permissions to site-packages.</li>
<li>Allow using python installed outside distribution where you can use site-packages.</li>
</ul>
| 0 | 2009-04-25T04:54:16Z | [
"python"
] |
Is site-packages appropriate for applications or just libraries? | 787,015 | <p>I'm in a bit of a discussion with some other developers on an open source project. I'm new to python but it seems to me that site-packages is meant for libraries and not end user applications. Is that true or is site-packages an appropriate place to install an application meant to be run by an end user?</p>
| 5 | 2009-04-24T18:22:20Z | 793,187 | <p>Once you get to the point where your application is ready for distribution, package it up for your favorite distributions/OSes in a way that puts your library code in site-packages and executable scripts on the system path.</p>
<p>Until then (i.e. for all development work), don't do any of the above: save yourself major headaches and use <a href="http://pypi.python.org/pypi/zc.buildout">zc.buildout</a> or <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> to keep your development code (and, if you like, its dependencies as well) isolated from the rest of the system.</p>
| 5 | 2009-04-27T11:58:15Z | [
"python"
] |
is it possible to define name of function's arguments dynamically? | 787,262 | <p>Now I have this code:</p>
<pre><code> attitude = request.REQUEST['attitude']
if attitude == 'want':
qs = qs.filter(attitudes__want=True)
elif attitude == 'like':
qs = qs.filter(attitudes__like=True)
elif attitude == 'hate':
qs = qs.filter(attitudes__hate=True)
elif attitude == 'seen':
qs = qs.filter(attitudes__seen=True)
</code></pre>
<p>It's will be better to define name of "attitudes__xxxx" dynamically. Is there any ways to do that ? </p>
<p>Thanks!</p>
| 2 | 2009-04-24T19:36:01Z | 787,282 | <p>Yes.</p>
<pre><code>qs.filter( **{ 'attitudes__%s'%arg:True } )
</code></pre>
| 7 | 2009-04-24T19:41:33Z | [
"python",
"django"
] |
How to convert SVG images for use with Pisa / XHTML2PDF? | 787,287 | <p>I'm using <a href="http://www.xhtml2pdf.com/" rel="nofollow">Pisa/XHTML2PDF</a> to generate PDFs on the fly in Django. Unfortunately, I need to include SVG images as well, which I don't believe is an easy task.</p>
<p>What's the best way to go about either a) converting the SVGs to PNG / JPG (in Python) or b) including SVGs in the PDF export from Pisa?</p>
| 3 | 2009-04-24T19:42:30Z | 787,646 | <p>There's the Java based Apache <a href="http://xmlgraphics.apache.org/batik/tools/rasterizer.html" rel="nofollow">Batik SVG toolkit</a>.</p>
<p>In a <a href="http://stackoverflow.com/questions/58910/converting-svg-to-png-using-c">similar question regarding C#</a> it was proposed using the <a href="http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx" rel="nofollow">command line version of Inkscape</a> for this.</p>
<p>For Python, here's a useful suggestion from <a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2007-09/msg02200.html" rel="nofollow">this discussion thread</a>:</p>
<pre><code>import rsvg
from gtk import gdk
h = rsvg.Handle('svg-file.svg')
pixbuf = h.get_pixbuf()
pixbuf.save('foobar.png', 'png')
</code></pre>
<p>the step <code>from gtk import gdk</code>, suggested by <a href="http://stackoverflow.com/users/211413/lukasz">Lukasz</a>, is necessary and has to precede creation of the pixbuf, otherwise you will not get the <code>save</code> method, as observed by <a href="http://stackoverflow.com/users/22468/nick-sergeant">the original poster</a>.</p>
| 2 | 2009-04-24T21:30:50Z | [
"python",
"pdf",
"pdf-generation",
"svg",
"pisa"
] |
How to convert SVG images for use with Pisa / XHTML2PDF? | 787,287 | <p>I'm using <a href="http://www.xhtml2pdf.com/" rel="nofollow">Pisa/XHTML2PDF</a> to generate PDFs on the fly in Django. Unfortunately, I need to include SVG images as well, which I don't believe is an easy task.</p>
<p>What's the best way to go about either a) converting the SVGs to PNG / JPG (in Python) or b) including SVGs in the PDF export from Pisa?</p>
| 3 | 2009-04-24T19:42:30Z | 2,653,073 | <p>"I got rsvg working, but here's what I get when I try to save: AttributeError: 'gtk.gdk.Pixbuf' object has no attribute 'save' â Nick Sergeant Apr 25 '09 at 0:10"</p>
<p>You need to import gdk to have access to pixbuf methods:</p>
<pre><code>import rsvg
from gtk import gdk
h = rsvg.Handle('svg-file.svg')
pixbuf = h.get_pixbuf()
pixbuf.save('foobar.png', 'png')
</code></pre>
<p>And to convert from string that contains svg data:</p>
<pre><code>import rsvg
from gtk import gdk
h = rsvg.Handle()
h.write(svg_string)
h.close()
pixbuf = h.get_pixbuf()
pixbuf.save('foobar.png', 'png')
</code></pre>
| 1 | 2010-04-16T12:57:40Z | [
"python",
"pdf",
"pdf-generation",
"svg",
"pisa"
] |
How to install Python on mac os x and windows with Aptana Studio? | 787,330 | <p>How do I get python to work with aptana studio?</p>
<p><s>I've downloaded a bunch of stuff, but none of them seem to give me a straight text editor where I can interpret code into an executable type thing. I know there's interactive mode in IDLE, but I want to actually use an editor. So I downloaded the pydev extensions for Aptana studio, but it wants me to configure a python interpreter (so I guess it actually doesn't have one). Where can I find a straight python interpreter that will work with this? or another IDE? </s></p>
| 2 | 2009-04-24T19:57:11Z | 787,338 | <p>It's easier than you think. First, there's a version of python on your machine by default. It's kind of out of date, though.</p>
<p><a href="http://macports.org" rel="nofollow">MacPorts</a> is a nice method to get lots of good stuff.</p>
<p><a href="http://ActiveState.com" rel="nofollow">ActiveState</a> has a <a href="http://www.activestate.com/activepython/" rel="nofollow">Python Mac package</a> downloadable for free.</p>
<p><a href="http://Python.org" rel="nofollow">Python.org</a> will lead you to some other options as well.</p>
| 5 | 2009-04-24T19:58:44Z | [
"python",
"aptana"
] |
How to install Python on mac os x and windows with Aptana Studio? | 787,330 | <p>How do I get python to work with aptana studio?</p>
<p><s>I've downloaded a bunch of stuff, but none of them seem to give me a straight text editor where I can interpret code into an executable type thing. I know there's interactive mode in IDLE, but I want to actually use an editor. So I downloaded the pydev extensions for Aptana studio, but it wants me to configure a python interpreter (so I guess it actually doesn't have one). Where can I find a straight python interpreter that will work with this? or another IDE? </s></p>
| 2 | 2009-04-24T19:57:11Z | 787,373 | <p>A lot of the sites in the Windows list mirror the Mac list.</p>
<p><a href="http://python.org/download/" rel="nofollow">Python.org</a> has Win32 and Win64 installers.</p>
<p>ActiveState has a free <a href="http://www.activestate.com/activepython/" rel="nofollow">Python Win32 package</a> downloadable for free. There is no Win64 version (yet?).</p>
<p><a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">PyWin32</a> is a Python package with extra modules for interfacing with Windows. <strong>This is not Python itself.</strong> These haven't been updated for Python 3.0, though. Despite the name, there is a Win64 version for Python 2.6 on this site.</p>
| 0 | 2009-04-24T20:07:40Z | [
"python",
"aptana"
] |
How to install Python on mac os x and windows with Aptana Studio? | 787,330 | <p>How do I get python to work with aptana studio?</p>
<p><s>I've downloaded a bunch of stuff, but none of them seem to give me a straight text editor where I can interpret code into an executable type thing. I know there's interactive mode in IDLE, but I want to actually use an editor. So I downloaded the pydev extensions for Aptana studio, but it wants me to configure a python interpreter (so I guess it actually doesn't have one). Where can I find a straight python interpreter that will work with this? or another IDE? </s></p>
| 2 | 2009-04-24T19:57:11Z | 787,389 | <p>Idle has a complete text editor -- open a "new window" and type away. Be sure to save it before you run it.</p>
<p>What didn't you like about the IDLE editor?</p>
<p>Also, look at <a href="http://www.activestate.com/komodo%5Fedit/" rel="nofollow">Komodo Edit</a> for Mac OS X. Very nice.</p>
| 1 | 2009-04-24T20:10:42Z | [
"python",
"aptana"
] |
How to install Python on mac os x and windows with Aptana Studio? | 787,330 | <p>How do I get python to work with aptana studio?</p>
<p><s>I've downloaded a bunch of stuff, but none of them seem to give me a straight text editor where I can interpret code into an executable type thing. I know there's interactive mode in IDLE, but I want to actually use an editor. So I downloaded the pydev extensions for Aptana studio, but it wants me to configure a python interpreter (so I guess it actually doesn't have one). Where can I find a straight python interpreter that will work with this? or another IDE? </s></p>
| 2 | 2009-04-24T19:57:11Z | 788,002 | <p>On Mac OS X Leopard and Tiger, Python is already installed.</p>
<p>On Mac, I've tried a few editor. Textmate is my current choice. If you're looking for a free one, I really liked Xcode. But you'll have to run your script from the command line.</p>
<p>If you want a cross-platform environment, you could try Eclipse and the pydev extension. So you don't get lost between the two platform.</p>
| 0 | 2009-04-25T01:00:08Z | [
"python",
"aptana"
] |
How to install Python on mac os x and windows with Aptana Studio? | 787,330 | <p>How do I get python to work with aptana studio?</p>
<p><s>I've downloaded a bunch of stuff, but none of them seem to give me a straight text editor where I can interpret code into an executable type thing. I know there's interactive mode in IDLE, but I want to actually use an editor. So I downloaded the pydev extensions for Aptana studio, but it wants me to configure a python interpreter (so I guess it actually doesn't have one). Where can I find a straight python interpreter that will work with this? or another IDE? </s></p>
| 2 | 2009-04-24T19:57:11Z | 788,012 | <p>For windows, I'd recommend the aforementioned ActivePython. Mainly because it comes with Python win32, which you're <em>going</em> to end up installing anyway.</p>
<p>Secondly, if you're coming from the world of Java and C#, you might be expecting too much out of your IDE. I eventually found that more powerful IDEs just made things more difficult than they helped. So my advice is to try to go with something simple. In other words, go with something that will let you jump in and start coding rather than bugging you with a lot of features you probably won't need anyway. :-)</p>
<p>EDIT: One other thing, find and install <a href="http://pip.openplans.org/" rel="nofollow">pip</a>. It makes installing python packages so much easier.</p>
| 1 | 2009-04-25T01:13:18Z | [
"python",
"aptana"
] |
How to install Python on mac os x and windows with Aptana Studio? | 787,330 | <p>How do I get python to work with aptana studio?</p>
<p><s>I've downloaded a bunch of stuff, but none of them seem to give me a straight text editor where I can interpret code into an executable type thing. I know there's interactive mode in IDLE, but I want to actually use an editor. So I downloaded the pydev extensions for Aptana studio, but it wants me to configure a python interpreter (so I guess it actually doesn't have one). Where can I find a straight python interpreter that will work with this? or another IDE? </s></p>
| 2 | 2009-04-24T19:57:11Z | 9,511,198 | <p>For Windows Operating system,
If you want to work with python using Aptana Studio. You have to do some simple basic settings with the interpreter.
For detailed step by step guide. You can follow this website link
<a href="http://www.infoknol.com/aptana-python-setup-guide/" rel="nofollow">http://www.infoknol.com/aptana-python-setup-guide/</a></p>
| 0 | 2012-03-01T05:42:33Z | [
"python",
"aptana"
] |
How to install Python on mac os x and windows with Aptana Studio? | 787,330 | <p>How do I get python to work with aptana studio?</p>
<p><s>I've downloaded a bunch of stuff, but none of them seem to give me a straight text editor where I can interpret code into an executable type thing. I know there's interactive mode in IDLE, but I want to actually use an editor. So I downloaded the pydev extensions for Aptana studio, but it wants me to configure a python interpreter (so I guess it actually doesn't have one). Where can I find a straight python interpreter that will work with this? or another IDE? </s></p>
| 2 | 2009-04-24T19:57:11Z | 14,819,410 | <p>To add the current Python version on Mac:</p>
<ol>
<li>Add new interpreter via Aptana Studio 3/Preferences/PyDev/Interpreter-Python.</li>
<li>Give it name (check version using the Terminal and then <code>python</code> or <code>/usr/bin/python</code>.</li>
<li>Then add the path (2.7 in my case): <code>/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python</code></li>
</ol>
<p>If you install your own (2.6 in my case) use the following path instead:
<code>/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python</code></p>
<p>Don't forget to hit the "Apply" button...</p>
| 2 | 2013-02-11T19:28:26Z | [
"python",
"aptana"
] |
How to add seconds on a datetime value in Python? | 787,564 | <p>I tried modifying the second property, but didn't work.</p>
<p>Basically I wanna do:</p>
<pre><code>datetime.now().second += 3
</code></pre>
| 8 | 2009-04-24T21:01:16Z | 787,583 | <p>Have you checked out timedeltas?</p>
<pre><code>from datetime import datetime, timedelta
x = datetime.now() + timedelta(seconds=3)
x += timedelta(seconds=3)
</code></pre>
| 24 | 2009-04-24T21:06:58Z | [
"python"
] |
How to add seconds on a datetime value in Python? | 787,564 | <p>I tried modifying the second property, but didn't work.</p>
<p>Basically I wanna do:</p>
<pre><code>datetime.now().second += 3
</code></pre>
| 8 | 2009-04-24T21:01:16Z | 787,599 | <p>You cannot add seconds to a datetime object. From the <a href="http://pypi.python.org/pypi/DateTime" rel="nofollow">docs</a>:</p>
<blockquote>
<p>A DateTime object should be considered immutable; all conversion and numeric operations return a new DateTime object rather than modify the current object.</p>
</blockquote>
<p>You must create another datetime object, or use the product of the existing object and a timedelta.</p>
| 2 | 2009-04-24T21:13:24Z | [
"python"
] |
Python embedding -- how to get the if() truth test behavior from C/C++? | 787,711 | <p>I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc.
I have been looking at the python/include headers, but haven't found anything that seems to do this. The closest I came was PyObject_RichCompare() with True as the second value, but that returns False for "1" == True for example.
Is there a convenient function to do this, or do I have to test against a sequence of types and do special-case tests for each possible type? What does the internal implementation of if() do?</p>
| 2 | 2009-04-24T21:55:15Z | 787,721 | <p>Isn't this it, in object.h:</p>
<pre><code>PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
</code></pre>
<p>?</p>
| 5 | 2009-04-24T22:00:07Z | [
"python",
"embedded-language"
] |
Python embedding -- how to get the if() truth test behavior from C/C++? | 787,711 | <p>I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc.
I have been looking at the python/include headers, but haven't found anything that seems to do this. The closest I came was PyObject_RichCompare() with True as the second value, but that returns False for "1" == True for example.
Is there a convenient function to do this, or do I have to test against a sequence of types and do special-case tests for each possible type? What does the internal implementation of if() do?</p>
| 2 | 2009-04-24T21:55:15Z | 787,762 | <p>Use</p>
<p><code>int PyObject_IsTrue(PyObject *o)</code><br/>
Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.
</p>
<p>(from <a href="http://docs.python.org/c-api/object.html" rel="nofollow">Python/C API Reference Manual</a>)</p>
| 1 | 2009-04-24T22:12:23Z | [
"python",
"embedded-language"
] |
Python: email get_payload decode fails when hitting equal sign? | 787,739 | <p>Running into strangeness with get_payload: it seems to crap out when it sees an equal sign in the message it's decoding. Here's code that displays the error:</p>
<pre><code>import email
data = file('testmessage.txt').read()
msg = email.message_from_string( data )
payload = msg.get_payload(decode=True)
print payload
</code></pre>
<p>And here's a sample message: <a href="http://parand.com/tmp/testmessage.txt">test message</a>. </p>
<p>The message is printed only until the first "=" . The rest is omitted. Anybody know what's going on?</p>
<p>The same script with "decode=False" returns the full message, so it appears the decode is unhappy with the equal sign.</p>
<p>This is under Python 2.5 .</p>
| 7 | 2009-04-24T22:04:32Z | 787,791 | <p>You have a line endings problem. The body of your test message uses bare carriage returns (\r) without newlines (\n). If you fix up the line endings before parsing the email, it all works:</p>
<pre><code>import email, re
data = file('testmessage.txt').read()
data = re.sub(r'\r(?!\n)', '\r\n', data) # Bare \r becomes \r\n
msg = email.message_from_string( data )
payload = msg.get_payload(decode=True)
print payload
</code></pre>
| 6 | 2009-04-24T22:24:01Z | [
"python",
"email"
] |
Find free disk space in python on OS/X | 787,776 | <p>I'm looking for the number of free bytes on my HD, but have trouble doing so on python.</p>
<p>I've tried the following:</p>
<pre><code>import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
</code></pre>
<p>But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.</p>
<p>What's the best way to get to this figure?</p>
| 21 | 2009-04-24T22:17:32Z | 787,816 | <p>What's wrong with</p>
<pre><code>import subprocess
proc= subprocess.Popen( "df", stdout=subprocess.PIPE )
proc.stdout.read()
proc.wait()
</code></pre>
| -5 | 2009-04-24T22:34:47Z | [
"python",
"diskspace"
] |
Find free disk space in python on OS/X | 787,776 | <p>I'm looking for the number of free bytes on my HD, but have trouble doing so on python.</p>
<p>I've tried the following:</p>
<pre><code>import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
</code></pre>
<p>But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.</p>
<p>What's the best way to get to this figure?</p>
| 21 | 2009-04-24T22:17:32Z | 787,832 | <p>Try using <code>f_frsize</code> instead of <code>f_bsize</code>.</p>
<pre><code>>>> s = os.statvfs('/')
>>> (s.f_bavail * s.f_frsize) / 1024
23836592L
>>> os.system('df -k /')
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/disk0s2 116884912 92792320 23836592 80% /
</code></pre>
| 32 | 2009-04-24T22:42:45Z | [
"python",
"diskspace"
] |
Find free disk space in python on OS/X | 787,776 | <p>I'm looking for the number of free bytes on my HD, but have trouble doing so on python.</p>
<p>I've tried the following:</p>
<pre><code>import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
</code></pre>
<p>But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.</p>
<p>What's the best way to get to this figure?</p>
| 21 | 2009-04-24T22:17:32Z | 788,282 | <p>It's not OS-independent, but this works on Linux, and probably on OS X as well:</p>
<p>print commands.getoutput('df .').split('\n')[1].split()[3]</p>
<p>How does it work? It gets the output of the 'df .' command, which gives you disk information about the partition of which the current directory is a part, splits it into two lines (just as it is printed to the screen), then takes the second line of that (by appending [1] after the first split()), then splits <em>that</em> line into different whitespace-separated pieces, and, finally, gives you the 4th element in that list.</p>
<pre><code>>>> commands.getoutput('df .')
'Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/sda3 80416836 61324872 15039168 81% /'
>>> commands.getoutput('df .').split('\n')
['Filesystem 1K-blocks Used Available Use% Mounted on', '/dev/sda3 80416836 61324908 15039132 81% /']
>>> commands.getoutput('df .').split('\n')[1]
'/dev/sda3 80416836 61324908 15039132 81% /'
>>> commands.getoutput('df .').split('\n')[1].split()
['/dev/sda3', '80416836', '61324912', '15039128', '81%', '/']
>>> commands.getoutput('df .').split('\n')[1].split()[3]
'15039128'
>>> print commands.getoutput('df .').split('\n')[1].split()[3]
15039128
</code></pre>
| -1 | 2009-04-25T05:19:24Z | [
"python",
"diskspace"
] |
Find free disk space in python on OS/X | 787,776 | <p>I'm looking for the number of free bytes on my HD, but have trouble doing so on python.</p>
<p>I've tried the following:</p>
<pre><code>import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
</code></pre>
<p>But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.</p>
<p>What's the best way to get to this figure?</p>
| 21 | 2009-04-24T22:17:32Z | 7,285,483 | <p>On UNIX:</p>
<pre><code>import os
from collections import namedtuple
_ntuple_diskusage = namedtuple('usage', 'total used free')
def disk_usage(path):
"""Return disk usage statistics about the given path.
Returned valus is a named tuple with attributes 'total', 'used' and
'free', which are the amount of total, used and free space, in bytes.
"""
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return _ntuple_diskusage(total, used, free)
</code></pre>
<p>Usage:</p>
<pre><code>>>> disk_usage('/')
usage(total=21378641920, used=7650934784, free=12641718272)
>>>
</code></pre>
<p>For Windows you might use <a href="http://code.google.com/p/psutil/">psutil</a>.</p>
| 17 | 2011-09-02T15:10:15Z | [
"python",
"diskspace"
] |
Find free disk space in python on OS/X | 787,776 | <p>I'm looking for the number of free bytes on my HD, but have trouble doing so on python.</p>
<p>I've tried the following:</p>
<pre><code>import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
</code></pre>
<p>But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.</p>
<p>What's the best way to get to this figure?</p>
| 21 | 2009-04-24T22:17:32Z | 15,220,122 | <p><a href="http://code.google.com/p/psutil/" rel="nofollow">Psutil module</a>
can also be used.</p>
<pre><code>>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
</code></pre>
<p>documentation can be found <a href="http://code.google.com/p/psutil/wiki/Documentation#Disks" rel="nofollow">here</a>.</p>
| 3 | 2013-03-05T09:25:10Z | [
"python",
"diskspace"
] |
Find free disk space in python on OS/X | 787,776 | <p>I'm looking for the number of free bytes on my HD, but have trouble doing so on python.</p>
<p>I've tried the following:</p>
<pre><code>import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
</code></pre>
<p>But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.</p>
<p>What's the best way to get to this figure?</p>
| 21 | 2009-04-24T22:17:32Z | 19,002,311 | <pre><code>def FreeSpace(drive):
""" Return the FreeSape of a shared drive in bytes"""
try:
fso = com.Dispatch("Scripting.FileSystemObject")
drv = fso.GetDrive(drive)
return drv.FreeSpace
except:
return 0
</code></pre>
| 0 | 2013-09-25T10:22:28Z | [
"python",
"diskspace"
] |
Find free disk space in python on OS/X | 787,776 | <p>I'm looking for the number of free bytes on my HD, but have trouble doing so on python.</p>
<p>I've tried the following:</p>
<pre><code>import os
stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail
</code></pre>
<p>But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.</p>
<p>What's the best way to get to this figure?</p>
| 21 | 2009-04-24T22:17:32Z | 31,500,428 | <p>In python 3.3 and above shutil provides you the same feature</p>
<pre><code>>>> import shutil
>>> shutil.disk_usage("/")
usage(total=488008343552, used=202575314944, free=260620050432)
>>>
</code></pre>
| 2 | 2015-07-19T10:57:34Z | [
"python",
"diskspace"
] |
How does a threading.Thread yield the rest of its quantum in Python? | 787,803 | <p>I've got a thread that's polling a piece of hardware.</p>
<pre><code>while not hardware_is_ready():
pass
process_data_from_hardware()
</code></pre>
<p>But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've dealt with threading, and when I did it wasn't Python, but I believe most threading libraries have a <code>yield</code> function or something that allows a thread to tell the scheduler "Give the other threads a chance."</p>
<pre><code>while not hardware_is_ready():
threading.yield() # This function doesn't exist.
process_data_from_hardware()
</code></pre>
<p>But I can't find any reference to something like this in the threading documentation. Python does have a <code>yield</code> statement, but I'm pretty sure that's something else entirely (to do with generators).</p>
<p>What's the correct thing to do here?</p>
| 34 | 2009-04-24T22:29:18Z | 787,810 | <p>Read up on the Global Interpreter Lock (GIL). </p>
<p>For example: <a href="http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/">http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/</a></p>
<p>Also: <a href="http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html">http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html</a></p>
<p>Do this in your code if you must do <strong>Busy Waiting</strong> (e.g. polling a device).</p>
<pre><code>time.sleep( 0.0001 )
</code></pre>
<p>This will yield to the thread scheduler.</p>
<p>Also, I collected some notes and references in <a href="http://homepage.mac.com/s_lott/iblog/architecture/C551260341/E20081031204203/index.html">http://homepage.mac.com/s_lott/iblog/architecture/C551260341/E20081031204203/index.html</a></p>
| 9 | 2009-04-24T22:31:16Z | [
"python",
"multithreading",
"yield"
] |
How does a threading.Thread yield the rest of its quantum in Python? | 787,803 | <p>I've got a thread that's polling a piece of hardware.</p>
<pre><code>while not hardware_is_ready():
pass
process_data_from_hardware()
</code></pre>
<p>But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've dealt with threading, and when I did it wasn't Python, but I believe most threading libraries have a <code>yield</code> function or something that allows a thread to tell the scheduler "Give the other threads a chance."</p>
<pre><code>while not hardware_is_ready():
threading.yield() # This function doesn't exist.
process_data_from_hardware()
</code></pre>
<p>But I can't find any reference to something like this in the threading documentation. Python does have a <code>yield</code> statement, but I'm pretty sure that's something else entirely (to do with generators).</p>
<p>What's the correct thing to do here?</p>
| 34 | 2009-04-24T22:29:18Z | 788,045 | <p>If you're doing this on *nix, you might find the <a href="http://docs.python.org/library/select.html" rel="nofollow">select</a> library useful. <a href="http://www.kamaelia.org/Home" rel="nofollow">Kamaela</a> also has a few components you may find useful, but it may require a bit of a paradigm change.</p>
| 2 | 2009-04-25T01:37:31Z | [
"python",
"multithreading",
"yield"
] |
How does a threading.Thread yield the rest of its quantum in Python? | 787,803 | <p>I've got a thread that's polling a piece of hardware.</p>
<pre><code>while not hardware_is_ready():
pass
process_data_from_hardware()
</code></pre>
<p>But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've dealt with threading, and when I did it wasn't Python, but I believe most threading libraries have a <code>yield</code> function or something that allows a thread to tell the scheduler "Give the other threads a chance."</p>
<pre><code>while not hardware_is_ready():
threading.yield() # This function doesn't exist.
process_data_from_hardware()
</code></pre>
<p>But I can't find any reference to something like this in the threading documentation. Python does have a <code>yield</code> statement, but I'm pretty sure that's something else entirely (to do with generators).</p>
<p>What's the correct thing to do here?</p>
| 34 | 2009-04-24T22:29:18Z | 790,246 | <p><code>time.sleep(0)</code> is sufficient to yield control -- no need to use a positive epsilon. Indeed, <code>time.sleep(0)</code> MEANS "yield to whatever other thread may be ready".</p>
| 46 | 2009-04-26T04:39:41Z | [
"python",
"multithreading",
"yield"
] |
How to install python-rsvg without python-gnome2-desktop on Ubuntu 8.10? | 787,812 | <p>I need rsvg support in Python 2.5.2. It <em>appears</em> that I have to install all 199 deps along with the package python-gnome2-desktop, which doesn't sound fun at all.</p>
<p>Alternatives?</p>
| 4 | 2009-04-24T22:32:09Z | 787,960 | <p>No longer relevant. Installed the entire package, and got rsvg that way.</p>
| 2 | 2009-04-25T00:37:04Z | [
"python",
"librsvg",
"rsvg"
] |
Case insensitivity in Python strings | 787,842 | <p>I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I know to do this is with Regex's and it seems a little poor to do so via that.</p>
<p>Is there a case insensitive version of replace()?</p>
| 4 | 2009-04-24T23:42:44Z | 787,879 | <p>The easiest way is to convert it all to lowercase then do the replace. But is obviously an issue if you want to retain the original case.</p>
<p>I would do a regex replace, you can instruct the Regex engine to ignore casing all together.</p>
<p>See <a href="http://www.akeric.com/blog/?p=312" rel="nofollow">this site</a> for an example.</p>
| 1 | 2009-04-24T23:59:12Z | [
"python"
] |
Case insensitivity in Python strings | 787,842 | <p>I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I know to do this is with Regex's and it seems a little poor to do so via that.</p>
<p>Is there a case insensitive version of replace()?</p>
| 4 | 2009-04-24T23:42:44Z | 787,881 | <p>You can supply the flag re.IGNORECASE to functions in the re module as described in the <a href="http://docs.python.org/library/re.html">docs</a>.</p>
<pre><code>matcher = re.compile(myExpression, re.IGNORECASE)
</code></pre>
| 10 | 2009-04-25T00:00:19Z | [
"python"
] |
Case insensitivity in Python strings | 787,842 | <p>I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I know to do this is with Regex's and it seems a little poor to do so via that.</p>
<p>Is there a case insensitive version of replace()?</p>
| 4 | 2009-04-24T23:42:44Z | 789,113 | <p>Using <code>re</code> is the best solution even if you think it's complicated.</p>
<p>To replace all occurrences of <code>'abc'</code>, <code>'ABC'</code>, <code>'Abc'</code>, etc., with <code>'Python'</code>, say:</p>
<pre><code>re.sub(r'(?i)abc', 'Python', a)
</code></pre>
<p>Example session:</p>
<pre><code>>>> a = 'abc asd Abc asd ABCDE XXAbCXX'
>>> import re
>>> re.sub(r'(?i)abc', 'Python', a)
'Python asd Python asd PythonDE XXPythonXX'
>>>
</code></pre>
<p>Note how embedding <code>(?i)</code> at the start of the regexp makes it case sensitive. Also note the <code>r'...'</code> string literal for the regexp (which in this specific case is redundant but helps as soon as your regexp has backslashes <code>(\)</code> in them.</p>
| 5 | 2009-04-25T15:19:17Z | [
"python"
] |
python 2.5 dated? | 787,849 | <p>I am just learning python on my ubuntu 8.04 machine which comes with
python 2.5 install. Is 2.5 too dated to continue learning? How much
of 2.5 version is still valid python code in the newer version?</p>
| 2 | 2009-04-24T23:45:06Z | 787,862 | <p>Basically, python code, for the moment, will be divided into python 2.X code and python 3 code. Python 3 breaks many changes in the interest of cleaning up the language. The majority of code and libraries are written for 2.X in mind. It is probably best to learn one, and know what is different with the other. On an ubuntu machine, the <code>python3</code> package will install Python 3, which can be run with the command <code>python3</code>, at least on my 8.10 install.</p>
<p>To answer your question, learning with 2.5 is fine, just keep in mind that 3 is a significant change, and learn the changes - ask yourself as you code, "how would this be different in 3, if at all?".</p>
<p>(As an aside, I do wish Ubuntu would upgrade to 2.6 though. It has a nice compatibility mode which tries and points out potential difficulties. But python is in such big use on a modern Linux distro, it can be a difficult change to make)</p>
<p><a href="http://docs.python.org/3.0/whatsnew/3.0.html" rel="nofollow">Here's an article describing 2.6 -> 3's changes</a></p>
| 6 | 2009-04-24T23:50:10Z | [
"python"
] |
python 2.5 dated? | 787,849 | <p>I am just learning python on my ubuntu 8.04 machine which comes with
python 2.5 install. Is 2.5 too dated to continue learning? How much
of 2.5 version is still valid python code in the newer version?</p>
| 2 | 2009-04-24T23:45:06Z | 787,863 | <p>I don't think it is 'too dated' to use, but there are some really nice features in python 2.6 that make it worth the update. <a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow">This article</a> will give you the details. As long as you have control of the machine, it is worth it.</p>
| 3 | 2009-04-24T23:51:13Z | [
"python"
] |
python 2.5 dated? | 787,849 | <p>I am just learning python on my ubuntu 8.04 machine which comes with
python 2.5 install. Is 2.5 too dated to continue learning? How much
of 2.5 version is still valid python code in the newer version?</p>
| 2 | 2009-04-24T23:45:06Z | 787,867 | <p>Python 2.5 will be fine for learning purposes. In the interest of learning you will probably want to look into the <a href="http://docs.python.org/3.0/whatsnew/3.0.html" rel="nofollow">differences</a> that python 3.0 has introduced, but I think most of the Python community is still using Python 2, as the majority of libraries haven't been ported over yet.</p>
<p>If your interested in 2.6 <a href="http://www.saltycrane.com/blog/2008/10/installing-python-26-source-ubuntu-hardy/" rel="nofollow">here</a> is a blog post on compiling it on Hardy, there may even be a package for it somewhere out there on the internets.</p>
<p>Follow up, if there is a package I'm not finding it. Self compiling is pretty simple for most things, though I've never tried to compile Python.</p>
| 4 | 2009-04-24T23:51:54Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.