title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Sanitising user input using Python | 16,861 | 46 | 2008-08-19T20:18:31Z | 25,136 | 23 | 2008-08-24T16:08:37Z | [
"python",
"xss"
] | What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) or SQL injection attack? | Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use `onclick`).
It is a modified version of <http://www.djangosnippets.org/snippets/205/>, with the regex on the attribute values to prevent people from using `href="javascript:..."`, ... |
Sanitising user input using Python | 16,861 | 46 | 2008-08-19T20:18:31Z | 93,857 | 12 | 2008-09-18T15:56:09Z | [
"python",
"xss"
] | What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) or SQL injection attack? | The best way to prevent XSS is not to try and filter everything, but rather to simply do HTML Entity encoding. For example, automatically turn < into <. This is the ideal solution assuming you don't need to accept any html input (outside of forum/comment areas where it is used as markup, it should be pretty rare to ... |
Sanitising user input using Python | 16,861 | 46 | 2008-08-19T20:18:31Z | 248,933 | 18 | 2008-10-30T00:41:40Z | [
"python",
"xss"
] | What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) or SQL injection attack? | **Edit**: [bleach](https://github.com/jsocol/bleach) is a wrapper around html5lib which makes it even easier to use as a whitelist-based sanitiser.
[`html5lib`](http://code.google.com/p/html5lib/) comes with a whitelist-based HTML sanitiser - it's easy to subclass it to restrict the tags and attributes users are allow... |
Create an encrypted ZIP file in Python | 17,250 | 24 | 2008-08-20T00:16:40Z | 16,050,005 | 13 | 2013-04-17T01:39:00Z | [
"python",
"zip"
] | I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far:
```
import zipfile, os
locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()
```
but I couldn't find how to encrypt the files in the ZIP file.
I could use system... | I created a simple library to create a password encrypted zip file in python. - [**here**](https://github.com/smihica/pyminizip)
```
import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("src.txt", "dst.zip", "password", compression_level)
```
**The library requires zlib.**
I have checked that the file ca... |
What's the best way to distribute python command-line tools? | 17,893 | 36 | 2008-08-20T13:07:25Z | 17,933 | 33 | 2008-08-20T13:25:23Z | [
"python",
"command-line",
"packaging"
] | My current setup.py script works okay, but it installs tvnamer.py (the tool) as "tvnamer.py" into site-packages or somewhere similar..
Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications? | Try the `entry_points.console_scripts` parameter in the setup() call. As described in the [setuptools docs](http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation), this should do what I think you want.
To reproduce here:
```
from setuptools import setup
setup(
# other arguments here...
... |
Build a Basic Python Iterator | 19,151 | 321 | 2008-08-21T00:36:11Z | 19,152 | 90 | 2008-08-21T00:36:33Z | [
"python",
"object",
"iterator"
] | How would one create an iterative function (or iterator object) in python? | First of all the [itertools module](https://docs.python.org/3/library/itertools.html) is incredibly useful for all sorts of cases in which an iterator would be useful, but here is all you need to create an iterator in python:
> yield
Isn't that cool? Yield can be used to replace a normal **return** in a function. It ... |
Build a Basic Python Iterator | 19,151 | 321 | 2008-08-21T00:36:11Z | 24,377 | 374 | 2008-08-23T16:57:28Z | [
"python",
"object",
"iterator"
] | How would one create an iterative function (or iterator object) in python? | Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: `__iter__()` and `next()`. The `__iter__` returns the iterator object and is implicitly called at the start of loops. The `next()` method returns the next value and is implicitly called at each loop increment. `... |
Build a Basic Python Iterator | 19,151 | 321 | 2008-08-21T00:36:11Z | 7,542,261 | 202 | 2011-09-24T22:13:44Z | [
"python",
"object",
"iterator"
] | How would one create an iterative function (or iterator object) in python? | There are four ways to build an iterative function:
* create a generator (uses the [yield keyword](http://docs.python.org/py3k/reference/expressions.html#yield-expressions))
* use a generator expression ([genexp](http://docs.python.org/py3k/reference/expressions.html#generator-expressions))
* create an iterator (defin... |
Build a Basic Python Iterator | 19,151 | 321 | 2008-08-21T00:36:11Z | 11,690,539 | 52 | 2012-07-27T15:05:12Z | [
"python",
"object",
"iterator"
] | How would one create an iterative function (or iterator object) in python? | I see some of you doing `return self` in `__iter__`. I just wanted to note that `__iter__` itself can be a generator (thus removing the need for `__next__` and raising `StopIteration` exceptions)
```
class range:
def __init__(self,a,b):
self.a = a
self.b = b
def __iter__(self):
i = self.a
while i <... |
A Transpose/Unzip Function in Python (inverse of zip) | 19,339 | 241 | 2008-08-21T04:29:07Z | 19,343 | 397 | 2008-08-21T04:36:29Z | [
"python",
"list",
"matrix",
"unzip",
"transpose"
] | I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.
**For example:**
```
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
```
... | [`zip`](http://docs.python.org/library/functions.html#zip) is its own inverse! Provided you use the special \* operator.
```
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
```
The way this works is by calling `zip` with the arguments:
```
zip(('a', 1), ('b', 2), ('c', 3), ('d... |
A Transpose/Unzip Function in Python (inverse of zip) | 19,339 | 241 | 2008-08-21T04:29:07Z | 25,193 | 17 | 2008-08-24T17:07:57Z | [
"python",
"list",
"matrix",
"unzip",
"transpose"
] | I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.
**For example:**
```
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
```
... | You could also do
```
result = ([ a for a,b in original ], [ b for a,b in original ])
```
It *should* scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.
(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like `zip` does.)
If generators... |
A Transpose/Unzip Function in Python (inverse of zip) | 19,339 | 241 | 2008-08-21T04:29:07Z | 4,578,299 | 14 | 2011-01-02T12:14:17Z | [
"python",
"list",
"matrix",
"unzip",
"transpose"
] | I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.
**For example:**
```
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
```
... | If you have lists that are not the same length, you may not want to use zip as per Patricks answer. This works:
```
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
```
But with different length lists, zip truncates each item to the length of the shortest list:
```
>>> zip(*[('... |
A Transpose/Unzip Function in Python (inverse of zip) | 19,339 | 241 | 2008-08-21T04:29:07Z | 22,115,957 | 7 | 2014-03-01T15:00:15Z | [
"python",
"list",
"matrix",
"unzip",
"transpose"
] | I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.
**For example:**
```
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
```
... | I like to use `zip(*iterable)` (which is the piece of code you're looking for) in my programs as so:
```
def unzip(iterable):
return zip(*iterable)
```
I find `unzip` more readable. |
Introducing Python | 19,654 | 5 | 2008-08-21T11:48:03Z | 19,715 | 13 | 2008-08-21T12:25:21Z | [
"php",
"python"
] | The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.
But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to ... | I recently introduced Python to my company, which does consulting work for the Post Office. I did this by waiting until there was a project for which I would be the only programmer, then getting permission to do this new project in Python. I then did another small project in Python with similarly impressive results. In... |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | 84 | 2008-08-21T14:24:41Z | 20,065 | 13 | 2008-08-21T14:25:19Z | [
"python",
"command-line",
"command-line-arguments"
] | What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments? | Use `optparse` which comes with the standard library. For example:
```
#!/usr/bin/env python
import optparse
def main():
p = optparse.OptionParser()
p.add_option('--person', '-p', default="world")
options, arguments = p.parse_args()
print 'Hello %s' % options.person
if __name__ == '__main__':
main()
```
S... |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | 84 | 2008-08-21T14:24:41Z | 20,069 | 14 | 2008-08-21T14:26:57Z | [
"python",
"command-line",
"command-line-arguments"
] | What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments? | Pretty much everybody is using [getopt](http://python.active-venture.com/lib/module-getopt.html)
Here is the example code for the doc :
```
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError:
# print help informa... |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | 84 | 2008-08-21T14:24:41Z | 26,910 | 85 | 2008-08-25T21:11:03Z | [
"python",
"command-line",
"command-line-arguments"
] | What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments? | **This answer suggests `optparse` which is appropriate for older Python versions. For Python 2.7 and above, `argparse` replaces `optparse`. See [this answer](http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse) for more information.**
As other people pointed out, you are better off going w... |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | 84 | 2008-08-21T14:24:41Z | 979,871 | 32 | 2009-06-11T07:54:53Z | [
"python",
"command-line",
"command-line-arguments"
] | What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments? | The new hip way is `argparse` for [these](http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html) reasons. argparse > optparse > getopt
**update:** As of py2.7 [argparse](http://docs.python.org/library/argparse.html) is part of the standard library and [optparse](http://docs.python.org/library/optparse... |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | 84 | 2008-08-21T14:24:41Z | 16,377,263 | 37 | 2013-05-04T17:51:38Z | [
"python",
"command-line",
"command-line-arguments"
] | What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments? | Since 2012 Python has a very easy, powerful and really *cool* module for argument parsing called [docopt](https://github.com/docopt/docopt). It works with Python 2.6 to 3.5 and needs no installation (just copy it). Here is an example taken from it's documentation:
```
"""Naval Fate.
Usage:
naval_fate.py ship new <n... |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | 84 | 2008-08-21T14:24:41Z | 30,493,366 | 27 | 2015-05-27T21:21:26Z | [
"python",
"command-line",
"command-line-arguments"
] | What's the **easiest, tersest, and most flexible** method or library for parsing Python command line arguments? | Other answers do mention that `argparse` is the way to go for new Python, but do not give usage examples. For completeness, here is a short summary of how to use argparse:
**1) Initialize**
```
import argparse
# Instantiate the parser
parser = argparse.ArgumentParser(description='Optional app description')
```
**2)... |
Find broken symlinks with Python | 20,794 | 13 | 2008-08-21T19:00:52Z | 20,848 | 11 | 2008-08-21T19:15:33Z | [
"python",
"linux",
"symlink"
] | If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux? | [os.lstat()](https://docs.python.org/2/library/os.html#os.lstat) may be helpful. If lstat() succeeds and stat() fails, then it's probably a broken link. |
Find broken symlinks with Python | 20,794 | 13 | 2008-08-21T19:00:52Z | 26,957 | 18 | 2008-08-25T21:32:20Z | [
"python",
"linux",
"symlink"
] | If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux? | A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls ... |
Specifying a mySQL ENUM in a Django model | 21,454 | 65 | 2008-08-21T23:48:08Z | 21,468 | 75 | 2008-08-21T23:54:52Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] | How do I go about specifying and using an ENUM in a Django model? | From the [Django documentation](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices):
```
MAYBECHOICE = (
('y', 'Yes'),
('n', 'No'),
('u', 'Unknown'),
)
```
And you define a charfield in your model :
```
married = models.CharField(max_length=1, choices=MAYBECHOICE)
```... |
Specifying a mySQL ENUM in a Django model | 21,454 | 65 | 2008-08-21T23:48:08Z | 33,932 | 26 | 2008-08-29T03:57:14Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] | How do I go about specifying and using an ENUM in a Django model? | Using the `choices` parameter won't use the ENUM db type; it will just create a VARCHAR or INTEGER, depending on whether you use `choices` with a CharField or IntegerField. Generally, this is just fine. If it's important to you that the ENUM type is used at the database level, you have three options:
1. Use "./manage.... |
Specifying a mySQL ENUM in a Django model | 21,454 | 65 | 2008-08-21T23:48:08Z | 1,530,858 | 31 | 2009-10-07T10:47:46Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] | How do I go about specifying and using an ENUM in a Django model? | ```
from django.db import models
class EnumField(models.Field):
"""
A field class that maps to MySQL's ENUM type.
Usage:
class Card(models.Model):
suit = EnumField(values=('Clubs', 'Diamonds', 'Spades', 'Hearts'))
c = Card()
c.suit = 'Clubs'
c.save()
"""
def __init__(self... |
Why Java and Python garbage collection methods are different? | 21,934 | 35 | 2008-08-22T07:35:26Z | 21,937 | 8 | 2008-08-22T07:40:12Z | [
"java",
"python",
"garbage-collection"
] | Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.
But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.
Why does Java choose this strategy and what is the benefit from this?
Is this bette... | I think the article "[Java theory and practice: A brief history of garbage collection](http://www.ibm.com/developerworks/java/library/j-jtp10283/)" from IBM should help explain some of the questions you have. |
Why Java and Python garbage collection methods are different? | 21,934 | 35 | 2008-08-22T07:35:26Z | 21,964 | 40 | 2008-08-22T09:10:06Z | [
"java",
"python",
"garbage-collection"
] | Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.
But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.
Why does Java choose this strategy and what is the benefit from this?
Is this bette... | There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (refer... |
Why Java and Python garbage collection methods are different? | 21,934 | 35 | 2008-08-22T07:35:26Z | 22,219 | 11 | 2008-08-22T12:40:03Z | [
"java",
"python",
"garbage-collection"
] | Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.
But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.
Why does Java choose this strategy and what is the benefit from this?
Is this bette... | Darren Thomas gives a good answer. However, one big difference between the Java and Python approaches is that with reference counting in the common case (no circular references) objects are cleaned up immediately rather than at some indeterminate later date.
For example, I can write sloppy, non-portable code in CPytho... |
Why Java and Python garbage collection methods are different? | 21,934 | 35 | 2008-08-22T07:35:26Z | 196,487 | 22 | 2008-10-13T01:42:10Z | [
"java",
"python",
"garbage-collection"
] | Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.
But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.
Why does Java choose this strategy and what is the benefit from this?
Is this bette... | Actually reference counting and the strategies used by the Sun JVM are all different types of garbage collection algorithms.
There are two broad approaches for tracking down dead objects: tracing and reference counting. In tracing the GC starts from the "roots" - things like stack references, and traces all reachable ... |
Why does this python date/time conversion seem wrong? | 21,961 | 3 | 2008-08-22T09:06:43Z | 21,975 | 7 | 2008-08-22T09:24:25Z | [
"python",
"datetime"
] | ```
>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
```
time.mktime should return the number of seconds since the epoch. Since ... | Short answer: Because of timezones.
The Epoch is in UTC.
For example, I'm on IST (Irish Stsandard Time) or GMT+1. time.mktime() is relative to my timezone, so on my system this refers to
```
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000.0
```
Because you got the result 1233378000, that would suggest... |
How do content discovery engines, like Zemanta and Open Calais work? | 22,059 | 4 | 2008-08-22T10:51:19Z | 35,667 | 7 | 2008-08-30T03:56:57Z | [
"python",
"ruby",
"semantics",
"zemanta"
] | I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against?
How would a service like Zemanta know what images to suggest to a piece of text for inst... | I'm not familiar with the specific services listed, but the field of natural language processing has developed a number of techniques that enable this sort of information extraction from general text. As Sean stated, once you have candidate terms, it's not to difficult to search for those terms with some of the other e... |
How do content discovery engines, like Zemanta and Open Calais work? | 22,059 | 4 | 2008-08-22T10:51:19Z | 821,663 | 9 | 2009-05-04T19:45:20Z | [
"python",
"ruby",
"semantics",
"zemanta"
] | I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against?
How would a service like Zemanta know what images to suggest to a piece of text for inst... | Michal Finkelstein from OpenCalais here.
First, thanks for your interest. I'll reply here but I also encourage you to read more on OpenCalais forums; there's a lot of information there including - but not limited to:
<http://opencalais.com/tagging-information>
<http://opencalais.com/how-does-calais-learn>
Also feel fr... |
Unicode vs UTF-8 confusion in Python / Django? | 22,149 | 25 | 2008-08-22T12:01:53Z | 22,208 | 8 | 2008-08-22T12:32:59Z | [
"python",
"django",
"unicode"
] | I stumbled over this passage in the [Django tutorial](http://www.djangoproject.com/documentation/tutorial01/):
> Django models have a default **str**() method that calls **unicode**() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal... | Meanwhile, I did a refined research to verify what the internal representation in Python is, and also what its limits are. "[The Truth About Unicode In Python](http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python)" is a very good article which cites directly from the Python developers. Apparently, i... |
Unicode vs UTF-8 confusion in Python / Django? | 22,149 | 25 | 2008-08-22T12:01:53Z | 522,827 | 45 | 2009-02-07T00:54:09Z | [
"python",
"django",
"unicode"
] | I stumbled over this passage in the [Django tutorial](http://www.djangoproject.com/documentation/tutorial01/):
> Django models have a default **str**() method that calls **unicode**() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal... | > what is a "Unicode string" in Python? Does that mean UCS-2?
Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux... |
Format numbers to strings in Python | 22,617 | 68 | 2008-08-22T15:10:46Z | 22,624 | 103 | 2008-08-22T15:12:41Z | [
"python",
"string-formatting"
] | I need to find out how to format numbers as strings. My code is here:
```
return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
```
Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59... | Formatting in Python is done via the [string formatting (`%`) operator](http://docs.python.org/2/library/stdtypes.html#string-formatting):
```
"%02d:%02d:%02d" % (hours, minutes, seconds)
```
/Edit: There's also [strftime](https://docs.python.org/2/library/time.html#time.strftime). |
Format numbers to strings in Python | 22,617 | 68 | 2008-08-22T15:10:46Z | 2,550,630 | 74 | 2010-03-31T05:13:20Z | [
"python",
"string-formatting"
] | I need to find out how to format numbers as strings. My code is here:
```
return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
```
Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59... | Starting in Python 2.6, there is an alternative: the `str.format()` method. Here are some examples using the existing string format operator (`%`):
```
>>> "Name: %s, age: %d" % ('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)
'dec: 45/oct: 055/hex: 0X2D'
>>> "MM/DD/YY = %... |
How do I download a file over HTTP using Python? | 22,676 | 492 | 2008-08-22T15:34:13Z | 22,682 | 286 | 2008-08-22T15:38:22Z | [
"python"
] | I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I wou... | In Python 2, use urllib2 which comes with the standard library.
```
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
```
This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. The documentation ca... |
How do I download a file over HTTP using Python? | 22,676 | 492 | 2008-08-22T15:34:13Z | 22,721 | 118 | 2008-08-22T15:58:17Z | [
"python"
] | I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I wou... | ```
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
output.write(mp3file.read())
```
The `wb` in `open('test.mp3','wb')` opens a file (and erases any existing file) in binary mode so you can save data with it instead of just text. |
How do I download a file over HTTP using Python? | 22,676 | 492 | 2008-08-22T15:34:13Z | 22,723 | 9 | 2008-08-22T15:58:52Z | [
"python"
] | I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I wou... | I agree with Corey, urllib2 is more complete than [urllib](http://docs.python.org/lib/module-urllib.html) and should likely be the module used if you want to do more complex things, but to make the answers more complete, urllib is a simpler module if you want just the basics:
```
import urllib
response = urllib.urlope... |
How do I download a file over HTTP using Python? | 22,676 | 492 | 2008-08-22T15:34:13Z | 22,776 | 759 | 2008-08-22T16:19:09Z | [
"python"
] | I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I wou... | One more, using [`urlretrieve`](http://docs.python.org/2/library/urllib.html#urllib.urlretrieve):
```
import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
```
(for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve)
Yet another one, with a "progressbar"
```
import u... |
How do I download a file over HTTP using Python? | 22,676 | 492 | 2008-08-22T15:34:13Z | 10,744,565 | 224 | 2012-05-24T20:08:29Z | [
"python"
] | I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I wou... | In 2012, use the [python requests library](http://docs.python-requests.org/en/latest/index.html)
```
>>> import requests
>>>
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760
```
You can run `pip install requests` to get it.
Requests has many advanta... |
How do I download a file over HTTP using Python? | 22,676 | 492 | 2008-08-22T15:34:13Z | 16,518,224 | 14 | 2013-05-13T08:59:44Z | [
"python"
] | I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I wou... | An improved version of the PabloG code for Python 2/3:
```
from __future__ import ( division, absolute_import, print_function, unicode_literals )
import sys, os, tempfile, logging
if sys.version_info >= (3,):
import urllib.request as urllib2
import urllib.parse as urlparse
else:
import urllib2
import... |
How do I download a file over HTTP using Python? | 22,676 | 492 | 2008-08-22T15:34:13Z | 19,011,916 | 12 | 2013-09-25T17:55:16Z | [
"python"
] | I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I wou... | Wrote [wget](https://pypi.python.org/pypi/wget) library in pure Python just for this purpose. It is pumped up `urlretrieve` with [these features](https://bitbucket.org/techtonik/python-wget/src/6859e7b4aba37cef57616111be890fb59631bc4c/wget.py?at=default#cl-330) as of version 2.0. |
How do I download a file over HTTP using Python? | 22,676 | 492 | 2008-08-22T15:34:13Z | 31,857,152 | 14 | 2015-08-06T13:30:31Z | [
"python"
] | I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows `.bat` file to download the actual MP3 however. I wou... | Here's how to do it in Python 3 using the standard library:
* [`urllib.request.urlopen`](https://docs.python.org/3.0/library/urllib.request.html#urllib.request.urlopen)
```
import urllib.request
response = urllib.request.urlopen('http://www.example.com/')
html = response.read()
```
* [`urllib.request.urlret... |
What's the best way to duplicate fork() in windows? | 23,397 | 20 | 2008-08-22T20:27:46Z | 170,387 | 10 | 2008-10-04T14:10:36Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] | How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the `fork()` system call, using Python?
I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting. | `fork()` *has* in fact been duplicated in Windows, under [Cygwin](https://en.wikipedia.org/wiki/Cygwin), but it's pretty hairy.
> The fork call in Cygwin is particularly interesting because it does not map well on top of the Win32 API. This makes it very difficult to implement correctly.
See the [The Cygwin User's Gu... |
What's the best way to duplicate fork() in windows? | 23,397 | 20 | 2008-08-22T20:27:46Z | 6,020,663 | 15 | 2011-05-16T16:51:18Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] | How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the `fork()` system call, using Python?
I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting. | Use the python [multiprocessing module](http://docs.python.org/library/multiprocessing.html) which will work everywhere.
Here is a [IBM developerWords article](http://www.ibm.com/developerworks/aix/library/au-multiprocessing/) that shows how to convert from os.fork() to the multiprocessing module. |
How can I graph the Lines of Code history for git repo? | 23,907 | 34 | 2008-08-23T03:00:46Z | 35,664 | 22 | 2008-08-30T03:55:23Z | [
"python",
"ruby",
"git",
"lines-of-code",
"sloc"
] | Basically I want to get the number of lines-of-code in the repository after each commit.
The only (really crappy) ways I have found is to use git filter-branch to run "wc -l \*", and a script that run git reset --hard on each commit, then ran wc -l
To make it a bit clearer, when the tool is run, it would output the l... | You may get both added and removed lines with git log, like:
```
git log --shortstat --reverse --pretty=oneline
```
From this, you can write a similar script to the one you did using this info. In python:
```
#!/usr/bin/python
"""
Display the per-commit size of the current git branch.
"""
import subprocess
import ... |
How can I graph the Lines of Code history for git repo? | 23,907 | 34 | 2008-08-23T03:00:46Z | 2,854,506 | 22 | 2010-05-18T04:09:01Z | [
"python",
"ruby",
"git",
"lines-of-code",
"sloc"
] | Basically I want to get the number of lines-of-code in the repository after each commit.
The only (really crappy) ways I have found is to use git filter-branch to run "wc -l \*", and a script that run git reset --hard on each commit, then ran wc -l
To make it a bit clearer, when the tool is run, it would output the l... | You might also consider [gitstats](http://gitstats.sourceforge.net/), which generates this graph as an html file. |
How can I graph the Lines of Code history for git repo? | 23,907 | 34 | 2008-08-23T03:00:46Z | 3,180,919 | 9 | 2010-07-05T16:18:32Z | [
"python",
"ruby",
"git",
"lines-of-code",
"sloc"
] | Basically I want to get the number of lines-of-code in the repository after each commit.
The only (really crappy) ways I have found is to use git filter-branch to run "wc -l \*", and a script that run git reset --hard on each commit, then ran wc -l
To make it a bit clearer, when the tool is run, it would output the l... | <http://github.com/ITikhonov/git-loc> worked right out of the box for me. |
How to capture Python interpreter's and/or CMD.EXE's output from a Python script? | 24,931 | 7 | 2008-08-24T08:46:57Z | 24,949 | 9 | 2008-08-24T09:39:08Z | [
"python",
"windows",
"cmd"
] | 1. Is it possible to capture Python interpreter's output from a Python script?
2. Is it possible to capture Windows CMD's output from a Python script?
If so, which librar(y|ies) should I look into? | If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standa... |
Binary buffer in Python | 25,116 | 41 | 2008-08-24T15:37:50Z | 25,180 | 24 | 2008-08-24T16:52:29Z | [
"python",
"binary",
"io",
"buffer"
] | In Python you can use [StringIO](https://docs.python.org/library/struct.html) for a file-like buffer for character data. [Memory-mapped file](https://docs.python.org/library/mmap.html) basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is ... | As long as you don't try to put any unicode data into your `StringIO` and you are careful NOT to use `cStringIO` you should be fine.
According to the [StringIO](https://docs.python.org/library/stringio.html) documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, `Strin... |
Binary buffer in Python | 25,116 | 41 | 2008-08-24T15:37:50Z | 7,357,938 | 55 | 2011-09-09T06:34:34Z | [
"python",
"binary",
"io",
"buffer"
] | In Python you can use [StringIO](https://docs.python.org/library/struct.html) for a file-like buffer for character data. [Memory-mapped file](https://docs.python.org/library/mmap.html) basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is ... | You are probably looking for [io.BytesIO](http://docs.python.org/release/3.1.3/library/io.html#binary-i-o) class. It works exactly like StringIO except that it supports binary data:
```
from io import BytesIO
bio = BytesIO(b"some initial binary data: \x00\x01")
```
StringIO will throw TypeError:
```
from io import S... |
pyGame within a pyGTK application | 25,661 | 7 | 2008-08-25T04:36:48Z | 28,935 | 7 | 2008-08-26T19:36:24Z | [
"python",
"gtk",
"pygtk",
"sdl",
"pygame"
] | What is the best way to use PyGame (SDL) within a PyGTK application?
I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events. | I've never attempted it myself, but hearing plenty about other people who've tried, it's not a road you want to go down.
There is the alternative of putting the gui in pygame itself. There are plenty of gui toolkits built specifically for pygame that you could use. Most of them are rather unfinished, but there are 2 b... |
Python super class reflection | 25,807 | 30 | 2008-08-25T09:06:16Z | 25,815 | 36 | 2008-08-25T09:22:22Z | [
"python",
"reflection"
] | If I have Python code
```
class A():
pass
class B():
pass
class C(A, B):
pass
```
and I have class `C`, is there a way to iterate through it's super classed (`A` and `B`)? Something like pseudocode:
```
>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)
```
One solution seems to be [inspect module](ht... | `C.__bases__` is an array of the super classes, so you could implement your hypothetical function like so:
```
def magicGetSuperClasses(cls):
return cls.__bases__
```
But I imagine it would be easier to just reference `cls.__bases__` directly in most cases. |
Python super class reflection | 25,807 | 30 | 2008-08-25T09:06:16Z | 35,111 | 11 | 2008-08-29T19:30:31Z | [
"python",
"reflection"
] | If I have Python code
```
class A():
pass
class B():
pass
class C(A, B):
pass
```
and I have class `C`, is there a way to iterate through it's super classed (`A` and `B`)? Something like pseudocode:
```
>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)
```
One solution seems to be [inspect module](ht... | @John: Your snippet doesn't work -- you are returning the *class* of the base classes (which are also known as metaclasses). You really just want `cls.__bases__`:
```
class A: pass
class B: pass
class C(A, B): pass
c = C() # Instance
assert C.__bases__ == (A, B) # Works
assert c.__class__.__bases__ == (A, B) # Works... |
Is there any difference between "foo is None" and "foo == None"? | 26,595 | 193 | 2008-08-25T18:27:16Z | 26,611 | 223 | 2008-08-25T18:38:10Z | [
"python"
] | Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it sh... | `is` always returns `True` if it compares the same object instance
Whereas `==` is ultimately determined by the `__eq__()` method
i.e.
```
>>> class foo(object):
def __eq__(self, other):
return True
>>> f = foo()
>>> f == None
True
>>> f is None
False
``` |
Is there any difference between "foo is None" and "foo == None"? | 26,595 | 193 | 2008-08-25T18:27:16Z | 26,626 | 46 | 2008-08-25T18:48:20Z | [
"python"
] | Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it sh... | You may want to read this [object identity and equivalence](http://mail.python.org/pipermail/python-list/2001-November/094920.html).
The statement 'is' is used for object identity, it checks if objects refer to the same instance (same address in memory).
And the '==' statement refers to equality (same value). |
Is there any difference between "foo is None" and "foo == None"? | 26,595 | 193 | 2008-08-25T18:27:16Z | 28,067 | 21 | 2008-08-26T13:44:11Z | [
"python"
] | Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it sh... | A word of caution:
```
if foo:
# do something
```
Is **not** exactly the same as:
```
if x is not None:
# do something
```
The former is a boolean value test and can evaluate to false in different contexts. There are a number of things that represent false in a boolean value tests for example empty containers, ... |
Is there any difference between "foo is None" and "foo == None"? | 26,595 | 193 | 2008-08-25T18:27:16Z | 585,491 | 12 | 2009-02-25T10:34:49Z | [
"python"
] | Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it sh... | `(ob1 is ob2)` equal to `(id(ob1) == id(ob2))` |
Is there any difference between "foo is None" and "foo == None"? | 26,595 | 193 | 2008-08-25T18:27:16Z | 2,932,590 | 10 | 2010-05-28T21:15:53Z | [
"python"
] | Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it sh... | The reason `foo is None` is the preferred way is that you might be handling an object that defines its own `__eq__`, and that defines the object to be equal to None. So, always use `foo is None` if you need to see if it is infact `None`. |
Is there any difference between "foo is None" and "foo == None"? | 26,595 | 193 | 2008-08-25T18:27:16Z | 16,636,358 | 8 | 2013-05-19T15:35:38Z | [
"python"
] | Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it sh... | There is no difference because objects which are identical will of course be equal. However, [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP 8") clearly states you should use `is`:
> Comparisons to singletons like None should always be done with is or is not, never the equality operators. |
Most Pythonic way equivalent for: while ((x = next()) != END) | 28,559 | 9 | 2008-08-26T16:37:52Z | 426,415 | 14 | 2009-01-08T23:06:34Z | [
"c",
"python"
] | What's the best Python idiom for this C construct?
```
while ((x = next()) != END) {
....
}
```
I don't have the ability to recode next().
update: and the answer from seems to be:
```
for x in iter(next, END):
....
``` | @Mark Harrison's answer:
```
for x in iter(next_, END):
....
```
Here's an excerpt from [Python's documentation](http://docs.python.org/library/functions.html):
```
iter(o[, sentinel])
```
> Return an iterator object.
> *...(snip)...* If the second argument, `sentinel`, is given, then `o` must be
> a callable o... |
What refactoring tools do you use for Python? | 28,796 | 52 | 2008-08-26T18:26:51Z | 29,770 | 43 | 2008-08-27T09:15:42Z | [
"python",
"refactoring"
] | I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.
Simple search and replace only gets me so far. In my case... | In the meantime, I've tried it two tools that have some sort of integration with vim.
The first is [Rope](http://rope.sourceforge.net/), a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring... |
What refactoring tools do you use for Python? | 28,796 | 52 | 2008-08-26T18:26:51Z | 26,381,548 | 12 | 2014-10-15T11:34:58Z | [
"python",
"refactoring"
] | I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.
Simple search and replace only gets me so far. In my case... | I would strongly recommend [PyCharm](https://www.jetbrains.com/pycharm/) - not just for refactorings. Since the first PyCharm answer was posted here a few years ago the refactoring support in PyCharm has improved significantly.
[Python Refactorings available in PyCharm](https://www.jetbrains.com/pycharm/webhelp/refact... |
How do I create an xml document in python | 29,243 | 14 | 2008-08-27T00:21:35Z | 29,255 | 8 | 2008-08-27T00:35:29Z | [
"python",
"xml"
] | Here is my sample code:
```
from xml.dom.minidom import *
def make_xml():
doc = Document()
node = doc.createElement('foo')
node.innerText = 'bar'
doc.appendChild(node)
return doc
if __name__ == '__main__':
make_xml().writexml(sys.stdout)
```
when I run the above code I get this:
```
<?xml ver... | Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "`node.noSuchAttr = 'bar'`" would also not give an error).
Unless you need a specific feature of `minidom`, I would look at `ElementTree`:
```
import sys
from xml.etree... |
How do I create an xml document in python | 29,243 | 14 | 2008-08-27T00:21:35Z | 29,262 | 8 | 2008-08-27T00:42:32Z | [
"python",
"xml"
] | Here is my sample code:
```
from xml.dom.minidom import *
def make_xml():
doc = Document()
node = doc.createElement('foo')
node.innerText = 'bar'
doc.appendChild(node)
return doc
if __name__ == '__main__':
make_xml().writexml(sys.stdout)
```
when I run the above code I get this:
```
<?xml ver... | @Daniel
Thanks for the reply, I also figured out how to do it with the minidom (I'm not sure of the difference between the ElementTree vs the minidom)
```
from xml.dom.minidom import *
def make_xml():
doc = Document();
node = doc.createElement('foo')
node.appendChild(doc.createTextNode('bar'))
doc.app... |
Python distutils - does anyone know how to use it? | 29,562 | 23 | 2008-08-27T05:03:07Z | 29,575 | 13 | 2008-08-27T05:12:47Z | [
"python",
"linux",
"installer",
"debian",
"distutils"
] | I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in \*nix anyway so I'm not worried about it being cross platform.
my main goal is to create a .deb package for debian/u... | See the [distutils simple example](http://docs.python.org/dist/simple-example.html). That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installe... |
How do threads work in Python, and what are common Python-threading specific pitfalls? | 31,340 | 71 | 2008-08-27T23:44:47Z | 31,358 | 18 | 2008-08-27T23:52:59Z | [
"python",
"multithreading"
] | I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.
From what I can te... | Below is a basic threading sample. It will spawn 20 threads; each thread will output its thread number. Run it and observe the order in which they print.
```
import threading
class Foo (threading.Thread):
def __init__(self,x):
self.__x = x
threading.Thread.__init__(self)
def run (self):
... |
How do threads work in Python, and what are common Python-threading specific pitfalls? | 31,340 | 71 | 2008-08-27T23:44:47Z | 31,372 | 32 | 2008-08-28T00:00:18Z | [
"python",
"multithreading"
] | I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.
From what I can te... | Python's a fairly easy language to thread in, but there are caveats. The biggest thing you need to know about is the Global Interpreter Lock. This allows only one thread to access the interpreter. This means two things: 1) you rarely ever find yourself using a lock statement in python and 2) if you want to take advanta... |
How do threads work in Python, and what are common Python-threading specific pitfalls? | 31,340 | 71 | 2008-08-27T23:44:47Z | 31,398 | 41 | 2008-08-28T00:19:50Z | [
"python",
"multithreading"
] | I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.
From what I can te... | Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this:
* <http://www.artima.com/weblogs/viewpost.jsp?thread=214235>
* <http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-ut... |
How do threads work in Python, and what are common Python-threading specific pitfalls? | 31,340 | 71 | 2008-08-27T23:44:47Z | 31,552 | 9 | 2008-08-28T02:34:18Z | [
"python",
"multithreading"
] | I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.
From what I can te... | Use threads in python if the individual workers are doing I/O bound operations. If you are trying to scale across multiple cores on a machine either find a good [IPC](http://www.python.org/dev/peps/pep-0371/) framework for python or pick a different language. |
How can I render a tree structure (recursive) using a django template? | 32,044 | 44 | 2008-08-28T11:43:10Z | 32,125 | 23 | 2008-08-28T12:47:29Z | [
"python",
"django"
] | I have a tree structure in memory that I would like to render in HTML using a Django template.
```
class Node():
name = "node name"
children = []
```
There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template.
I have found [this](h... | I think the canonical answer is: "Don't".
What you should probably do instead is unravel the thing in your *view* code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" ... |
How can I render a tree structure (recursive) using a django template? | 32,044 | 44 | 2008-08-28T11:43:10Z | 32,857 | 18 | 2008-08-28T17:23:22Z | [
"python",
"django"
] | I have a tree structure in memory that I would like to render in HTML using a Django template.
```
class Node():
name = "node name"
children = []
```
There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template.
I have found [this](h... | this might be way more than you need, but there is a django module called 'mptt' - this stores a hierarchical tree structure in an sql database, and includes templates for display in the view code. you might be able to find something useful there.
here's the link : [django-mptt](https://github.com/django-mptt/django-m... |
How can I render a tree structure (recursive) using a django template? | 32,044 | 44 | 2008-08-28T11:43:10Z | 48,262 | 9 | 2008-09-07T08:49:51Z | [
"python",
"django"
] | I have a tree structure in memory that I would like to render in HTML using a Django template.
```
class Node():
name = "node name"
children = []
```
There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template.
I have found [this](h... | Django has a built in template helper for this exact scenario:
<https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list> |
How can I render a tree structure (recursive) using a django template? | 32,044 | 44 | 2008-08-28T11:43:10Z | 957,761 | 7 | 2009-06-05T19:40:13Z | [
"python",
"django"
] | I have a tree structure in memory that I would like to render in HTML using a Django template.
```
class Node():
name = "node name"
children = []
```
There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template.
I have found [this](h... | I had the same problem and I wrote a template tag. I know there are other tags like this out there but I needed to learn to make custom tags anyway :) I think it turned out pretty well.
Read the docstring for usage instructions.
[github.com/skid/django-recurse](http://github.com/skid/django-recurse) |
How can I render a tree structure (recursive) using a django template? | 32,044 | 44 | 2008-08-28T11:43:10Z | 11,644,588 | 51 | 2012-07-25T07:21:27Z | [
"python",
"django"
] | I have a tree structure in memory that I would like to render in HTML using a Django template.
```
class Node():
name = "node name"
children = []
```
There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template.
I have found [this](h... | Using `with` template tag, I could do tree/recursive list.
Sample code:
main template: assuming 'all\_root\_elems' is list of one or more root of tree
```
<ul>
{%for node in all_root_elems %}
{%include "tree_view_template.html" %}
{%endfor%}
</ul>
```
tree\_view\_template.html renders the nested `ul`, `li` and... |
How can I render a tree structure (recursive) using a django template? | 32,044 | 44 | 2008-08-28T11:43:10Z | 12,558,610 | 9 | 2012-09-24T03:50:27Z | [
"python",
"django"
] | I have a tree structure in memory that I would like to render in HTML using a Django template.
```
class Node():
name = "node name"
children = []
```
There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template.
I have found [this](h... | Yes, you can do it. It's a little trick,
passing the filename to {% include %} as a variable:
```
{% with template_name="file/to_include.html" %}
{% include template_name %}
{% endwith %}
``` |
Is it possible to run a Python script as a service in Windows? If possible, how? | 32,404 | 165 | 2008-08-28T14:28:04Z | 32,440 | 169 | 2008-08-28T14:39:04Z | [
"python",
"windows",
"cross-platform"
] | I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.
I am currently a... | Yes you can. I do it using the pythoncom libraries that come included with [ActivePython](http://www.activestate.com/Products/activepython/index.mhtml) or can be installed with [pywin32](https://sourceforge.net/projects/pywin32/) (Python for Windows extensions).
This is a basic skeleton for a simple service:
```
impo... |
Is it possible to run a Python script as a service in Windows? If possible, how? | 32,404 | 165 | 2008-08-28T14:28:04Z | 597,750 | 19 | 2009-02-28T08:30:54Z | [
"python",
"windows",
"cross-platform"
] | I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.
I am currently a... | There are a couple alternatives for installing as a service virtually any Windows executable.
## Method 1: Use instsrv and srvany from rktools.exe
For Windows Home Server or Windows Server 2003 (works with WinXP too), the [Windows Server 2003 Resource Kit Tools](http://www.microsoft.com/downloads/details.aspx?FamilyI... |
Is it possible to run a Python script as a service in Windows? If possible, how? | 32,404 | 165 | 2008-08-28T14:28:04Z | 24,996,607 | 17 | 2014-07-28T13:41:31Z | [
"python",
"windows",
"cross-platform"
] | I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.
I am currently a... | Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?
I stumbled across the wonderful [Non-s... |
How to generate dynamic (parametrized) unit tests in python? | 32,899 | 111 | 2008-08-28T17:49:02Z | 32,939 | 75 | 2008-08-28T18:02:33Z | [
"python",
"unit-testing",
"parameterized-unit-test"
] | I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", ... | i use something like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequense(unittest.TestCase):
pass
def test_generator(a, b):
def test(self):
self.assertEqual(a,b)
return test
if __name__ == '__main__':
for t in l:
test_name = 't... |
How to generate dynamic (parametrized) unit tests in python? | 32,899 | 111 | 2008-08-28T17:49:02Z | 34,094 | 48 | 2008-08-29T07:10:31Z | [
"python",
"unit-testing",
"parameterized-unit-test"
] | I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", ... | The [nose](https://nose.readthedocs.org/en/latest/) testing framework [supports this](https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators).
Example (the code below is the entire contents of the file containing the test):
```
param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]
def test_generator()... |
How to generate dynamic (parametrized) unit tests in python? | 32,899 | 111 | 2008-08-28T17:49:02Z | 20,870,875 | 31 | 2014-01-01T16:52:24Z | [
"python",
"unit-testing",
"parameterized-unit-test"
] | I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", ... | This can be solved elegantly using Metaclasses:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequenceMeta(type):
def __new__(mcs, name, bases, dict):
def gen_test(a, b):
def test(self):
self.assertEqual(a, b)
return ... |
How to generate dynamic (parametrized) unit tests in python? | 32,899 | 111 | 2008-08-28T17:49:02Z | 23,508,426 | 18 | 2014-05-07T03:55:21Z | [
"python",
"unit-testing",
"parameterized-unit-test"
] | I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", ... | [load\_tests](https://docs.python.org/2/library/unittest.html#load-tests-protocol) is a little known mechanism introduced in 2.7 to dynamically create a TestSuite. With it, you can easily create parametrized tests.
For example:
```
import unittest
class GeneralTestCase(unittest.TestCase):
def __init__(self, meth... |
How to generate dynamic (parametrized) unit tests in python? | 32,899 | 111 | 2008-08-28T17:49:02Z | 25,626,660 | 12 | 2014-09-02T15:08:01Z | [
"python",
"unit-testing",
"parameterized-unit-test"
] | I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", ... | It can be done by using [pytest](http://pytest.org). Just write the file `test_me.py` with content:
```
import pytest
@pytest.mark.parametrize('name, left, right', [['foo', 'a', 'a'],
['bar', 'a', 'b'],
['baz', 'b', 'b']])
d... |
How to generate dynamic (parametrized) unit tests in python? | 32,899 | 111 | 2008-08-28T17:49:02Z | 29,384,495 | 13 | 2015-04-01T06:46:45Z | [
"python",
"unit-testing",
"parameterized-unit-test"
] | I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", ... | As of Python 3.4 subtests have been introduced to unittest for this purpose. See [the documentation](https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests) for details. TestCase.subTest is a context manager which allows to isolate asserts in a test so that a failure will be repor... |
Extending base classes in Python | 33,534 | 10 | 2008-08-28T22:18:02Z | 33,663 | 22 | 2008-08-28T23:41:55Z | [
"python"
] | I'm trying to extend some "base" classes in Python:
```
class xlist (list):
def len(self):
return len(self)
def add(self, *args):
self.extend(args)
return None
class xint (int):
def add(self, value):
self += value
return self
x = xlist([1,2,3])
print x.len() #... | Your two `xint` examples don't work for two different reasons.
The first doesn't work because `self += value` is equivalent to `self = self + value` which just reassigns the local variable `self` to a different object (an integer) but doesn't change the original object. You can't really get this
```
>>> x = xint(10)
... |
Find out how much memory is being used by an object in Python | 33,978 | 117 | 2008-08-29T04:59:31Z | 35,645 | 67 | 2008-08-30T03:25:43Z | [
"python",
"performance",
"memory-profiling"
] | How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. | **There's no easy way to find out the memory size of a python object**. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overh... |
Find out how much memory is being used by an object in Python | 33,978 | 117 | 2008-08-29T04:59:31Z | 12,924,399 | 14 | 2012-10-16T22:25:06Z | [
"python",
"performance",
"memory-profiling"
] | How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. | Another approach is to use pickle. See [this answer](http://stackoverflow.com/a/565382/420867) to a duplicate of this question. |
Find out how much memory is being used by an object in Python | 33,978 | 117 | 2008-08-29T04:59:31Z | 19,865,746 | 24 | 2013-11-08T18:11:11Z | [
"python",
"performance",
"memory-profiling"
] | How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. | Try this:
```
sys.getsizeof(object)
```
[getsizeof()](https://docs.python.org/3/library/sys.html#sys.getsizeof) calls the objectâs `__sizeof__` method and adds an additional garbage collector overhead **if** the object is managed by the garbage collector. |
Are Python threads buggy? | 34,020 | 17 | 2008-08-29T05:43:16Z | 34,060 | 43 | 2008-08-29T06:33:54Z | [
"python",
"multithreading"
] | A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor? | Python threads are good for **concurrent I/O programming**. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example.
Howev... |
Are Python threads buggy? | 34,020 | 17 | 2008-08-29T05:43:16Z | 34,078 | 7 | 2008-08-29T06:55:14Z | [
"python",
"multithreading"
] | A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor? | The GIL (Global Interpreter Lock) might be a problem, but the API is quite OK. Try out the excellent `processing` module, which implements the Threading API for separate processes. I am using that right now (albeit on OS X, have yet to do some testing on Windows) and am really impressed. The Queue class is really savin... |
Are Python threads buggy? | 34,020 | 17 | 2008-08-29T05:43:16Z | 34,782 | 13 | 2008-08-29T17:17:18Z | [
"python",
"multithreading"
] | A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor? | The standard implementation of Python (generally known as CPython as it is written in C) uses OS threads, but since there is the [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock), only one thread at a time is allowed to run Python code. But within those limitations, the threading libraries... |
How to specify an authenticated proxy for a python http connection? | 34,079 | 44 | 2008-08-29T06:55:54Z | 34,116 | 53 | 2008-08-29T07:30:35Z | [
"python",
"http",
"proxy"
] | What's the best way to specify a proxy with username and password for an http connection in python? | This works for me:
```
import urllib2
proxy = urllib2.ProxyHandler({'http': 'http://
username:password@proxyurl:proxyport'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
conn = urllib2.urlopen('http://python.org')
return_str = co... |
How to specify an authenticated proxy for a python http connection? | 34,079 | 44 | 2008-08-29T06:55:54Z | 35,443 | 8 | 2008-08-29T22:52:47Z | [
"python",
"http",
"proxy"
] | What's the best way to specify a proxy with username and password for an http connection in python? | The best way of going through a proxy that requires authentication is using [urllib2](http://docs.python.org/lib/module-urllib2.html) to build a custom url opener, then using that to make all the requests you want to go through the proxy. Note in particular, you probably don't want to embed the proxy password in the ur... |
How to specify an authenticated proxy for a python http connection? | 34,079 | 44 | 2008-08-29T06:55:54Z | 3,942,980 | 11 | 2010-10-15T14:06:56Z | [
"python",
"http",
"proxy"
] | What's the best way to specify a proxy with username and password for an http connection in python? | Setting an environment var named **http\_proxy** like this: **http://username:password@proxy\_url:port** |
How do I make Windows aware of a service I have written in Python? | 34,328 | 10 | 2008-08-29T10:18:21Z | 34,330 | 8 | 2008-08-29T10:20:39Z | [
"python",
"windows",
"cross-platform"
] | In [another question](http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how "Python scripts as Windows service") I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the servic... | Here is code to install a python-script as a service, written in python :)
<http://code.activestate.com/recipes/551780/>
This post could also help you out:
<http://essiene.blogspot.com/2005/04/python-windows-services.html> |
Finding what methods an object has | 34,439 | 159 | 2008-08-29T15:05:17Z | 34,452 | 188 | 2008-08-29T15:09:05Z | [
"python",
"introspection"
] | Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?
Or,
if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? | It appears you can use this code, replacing 'object' with the object you're interested in:-
```
[method for method in dir(object) if callable(getattr(object, method))]
```
I discovered it at [this site](http://www.diveintopython.net/power_of_introspection/index.html), hopefully that should provide some further detail... |
Finding what methods an object has | 34,439 | 159 | 2008-08-29T15:05:17Z | 34,467 | 78 | 2008-08-29T15:36:55Z | [
"python",
"introspection"
] | Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?
Or,
if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? | You can use the built in `dir()` function to get a list of all the attributes a module has. Try this at the command line to see how it works.
```
>>> import moduleName
>>> dir(moduleName)
```
Also, you can use the `hasattr(module_name, "attr_name")` function to find out if a module has a specific attribute.
See the ... |
Finding what methods an object has | 34,439 | 159 | 2008-08-29T15:05:17Z | 34,472 | 20 | 2008-08-29T15:40:05Z | [
"python",
"introspection"
] | Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?
Or,
if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? | To check if it has a particular method:
```
hasattr(object,"method")
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.