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 |
|---|---|---|---|---|---|---|---|---|---|
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 26,336,546 | 8 | 2014-10-13T09:17:53Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | Lets say you have digits in string.
str = "100949"
and you would like to check if it has only numbers
```
if str.isdigit():
returns TRUE or FALSE
```
[isdigit docs](http://docs.python.org/2/library/stdtypes.html#str.isdigit)
otherwise your method works great to find the occurrence of a digit in a string. |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 32,453,110 | 10 | 2015-09-08T08:42:14Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | For `int` use this:
```
>>> "1221323".isdigit()
True
```
But for `float` we need some tricks ;-). Every float number has one point...
```
>>> "12.34".isdigit()
False
>>> "12.34".replace('.','',1).isdigit()
True
>>> "12.3.4".replace('.','',1).isdigit()
False
```
Also for negative numbers just add `lstrip()`:
```
>>... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 34,615,173 | 7 | 2016-01-05T15:21:27Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | I know this is particularly old but I would add an answer I believe covers the information missing from the highest voted answer that could be very valuable to any who find this:
For each of the following methods connect them with a count if you need any input to be accepted. (Assuming we are using vocal definitions o... |
How to configure vim to not put comments at the beginning of lines while editing python files | 354,097 | 40 | 2008-12-09T20:21:40Z | 354,422 | 26 | 2008-12-09T22:07:18Z | [
"python",
"vim"
] | When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.
For example, when writing this in vim
```
for i in range(10):
#
```
the # does not stay there where I entered ... | I found an answer here <http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash>
It seems that the vim smartindent option is the cause of the problem.
The referenced page above describes work-a-rounds but after reading the help in smartindent in vim itself (:help smartindent), I decided to try cindent instead of ... |
How to configure vim to not put comments at the beginning of lines while editing python files | 354,097 | 40 | 2008-12-09T20:21:40Z | 385,724 | 8 | 2008-12-22T07:27:50Z | [
"python",
"vim"
] | When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.
For example, when writing this in vim
```
for i in range(10):
#
```
the # does not stay there where I entered ... | I have the following lines in my .vimrc, seems to be installed by default with my Ubuntu 8.10
```
set smartindent
inoremap # X^H#
set autoindent
```
And I don't observe the problem. Maybe you can try this. (Note that ^H should be entered by Ctrl-V Ctrl-H) |
How to configure vim to not put comments at the beginning of lines while editing python files | 354,097 | 40 | 2008-12-09T20:21:40Z | 777,385 | 15 | 2009-04-22T14:07:40Z | [
"python",
"vim"
] | When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.
For example, when writing this in vim
```
for i in range(10):
#
```
the # does not stay there where I entered ... | @PolyThinker Though I see that response a lot to this question, in my opinion it's not a good solution. The editor still thinks it should be indented all the way to left - check this by pushing == on a line that starts with a hash, or pushing = while a block of code with comments in it is highlighted to reindent.
I wo... |
Are there statistical studies that indicates that Python is "more productive"? | 354,124 | 44 | 2008-12-09T20:29:40Z | 354,249 | 16 | 2008-12-09T21:09:45Z | [
"python",
"productivity"
] | If I do a google search with the string "python productive" the first results is a page <http://www.ferg.org/projects/python_java_side-by-side.html> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the argu... | All evidence is anecdotal.
You can't ever find published studies that show the general superiority of one language over another because there are too many confounds:
* Individual programmers differ greatly in ability
* Some tasks are more amenable to a given language/library than others (what constitues representativ... |
Are there statistical studies that indicates that Python is "more productive"? | 354,124 | 44 | 2008-12-09T20:29:40Z | 354,250 | 19 | 2008-12-09T21:09:52Z | [
"python",
"productivity"
] | If I do a google search with the string "python productive" the first results is a page <http://www.ferg.org/projects/python_java_side-by-side.html> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the argu... | Yes, there's an excellent paper by Lutz Prechelt on this subject:
[An Empirical Comparison of Seven Programming Languages](http://page.mi.fu-berlin.de/prechelt/Biblio//jccpprt_computer2000.pdf)
Of course, this paper doesnât âproveâ the superiority of any particular language. But it probably comes as close as an... |
Are there statistical studies that indicates that Python is "more productive"? | 354,124 | 44 | 2008-12-09T20:29:40Z | 354,361 | 28 | 2008-12-09T21:50:45Z | [
"python",
"productivity"
] | If I do a google search with the string "python productive" the first results is a page <http://www.ferg.org/projects/python_java_side-by-side.html> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the argu... | Yes, and there are also statistical studies that prove that dogs are more productive than cats. Both are equally valid. ;-)
by popular demand, here are a couple of "studies" - take them with a block of salt!
1. [An empirical comparison of C, C++, Java, Perl, Python, Rexx, and Tcl](http://page.mi.fu-berlin.de/prechelt... |
How is ** implemented in Python? | 354,421 | 9 | 2008-12-09T22:07:10Z | 354,626 | 23 | 2008-12-09T23:33:18Z | [
"python"
] | I'm wondering where I find the source to show how the operator \*\* is implemented in Python. Can someone point me in the right direction? | The python grammar definition (from which the parser is generated using [pgen](http://www.python.org/dev/peps/pep-0269/)), look for 'power': [Gramar/Gramar](http://svn.python.org/view/python/trunk/Grammar/Grammar?rev=65872&view=markup)
The python ast, look for 'ast\_for\_power': [Python/ast.c](http://svn.python.org/vi... |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 354,892 | 9 | 2008-12-10T02:00:49Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | I prefer
```
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
```
it seems everything else is just extra code to do the same thing. |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 354,918 | 7 | 2008-12-10T02:15:34Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | Generally, the "specialized structure" actually IS a sensible current state of an object, with its own methods.
```
class Some3SpaceThing(object):
def __init__(self,x):
self.g(x)
def g(self,x):
self.y0 = x + 1
self.y1 = x * 3
self.y2 = y0 ** y3
r = Some3SpaceThing( x )
r.y0
r.y1
r.y2
```
I like t... |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 354,929 | 84 | 2008-12-10T02:22:28Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).
Returning a dictionary with keys y0, y1, y2 etc doesn't ... |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 354,955 | 14 | 2008-12-10T02:40:43Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | I prefer to use tuples whenever a tuple feels "natural"; coordinates are a typical example, where the separate objects can stand on their own, e.g. in one-axis only scaling calculations.
I use dictionaries as a return value only when the grouped objects aren't always the same. Think optional email headers.
For the re... |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 354,958 | 33 | 2008-12-10T02:42:05Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | I vote for the dictionary.
I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.
Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have... |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 355,036 | 9 | 2008-12-10T03:51:47Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | +1 on S.Lott's suggestion of a named container class.
For python 2.6 and up, a [named tuple](http://docs.python.org/library/collections.html#collections.namedtuple) provides a useful way of easily creating these container classes, and the results are "lightweight and require no more memory than regular tuples". |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 356,695 | 278 | 2008-12-10T16:36:01Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | [Named tuples](http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields) were added in 2.6 for this purpose. Also see [os.stat](http://docs.python.org/library/os.html#os.stat) for a similar builtin example.
```
>>> import collections
>>> point = collections.namedtuple('P... |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 21,970,184 | 13 | 2014-02-23T15:26:30Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | Another option would be using generators:
```
>>> def f(x):
y0 = x + 1
yield y0
yield x * 3
yield y0 ** 4
>>> a, b, c = f(5)
>>> a
6
>>> b
15
>>> c
1296
```
Although IMHO tuples are usually best, except in cases where the values being returned are candidates for encapsulation in a cl... |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 28,076,666 | 11 | 2015-01-21T20:57:30Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | ```
>>> def func():
... return [1,2,3]
...
>>> a,b,c = func()
>>> a
1
>>> b
2
>>> c
3
``` |
How do you return multiple values in Python? | 354,883 | 435 | 2008-12-10T01:55:50Z | 36,632,980 | 9 | 2016-04-14T20:08:13Z | [
"python",
"coding-style",
"return",
"return-value"
] | The canonical way to return multiple values in languages that support it is often [tupling](http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python).
### Option: Using a tuple
Consider this trivial example:
```
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y... | A lot of the answers seem to suggest you need to return a collection of some sort, like a dictionary or a list. You could also leave off the extra syntax and just write out the return values, comma-separated. Note: this technically returns a tuple.
```
def f():
return True, False
x, y = f()
print x
print y
```
gi... |
A get() like method for checking for Python attributes | 355,539 | 37 | 2008-12-10T09:49:39Z | 355,562 | 15 | 2008-12-10T09:59:36Z | [
"python",
"attributes"
] | If I had a dictionary `dict` and I wanted to check for `dict['key']` I could either do so in a `try` block (bleh!) or use the `get()` method, with `False` as a default value.
I'd like to do the same thing for `object.attribute`. That is, I already have object to return `False` if it hasn't been set, but then that give... | Do you mean `hasattr()` perhaps?
```
hasattr(object, "attribute name") #Returns True or False
```
[Python.org doc - Built in functions - hasattr()](http://docs.python.org/library/functions.html#hasattr)
You can also do this, which is a bit more cluttered and doesn't work for methods.
```
"attribute" in obj.__dict__... |
A get() like method for checking for Python attributes | 355,539 | 37 | 2008-12-10T09:49:39Z | 356,227 | 58 | 2008-12-10T14:27:29Z | [
"python",
"attributes"
] | If I had a dictionary `dict` and I wanted to check for `dict['key']` I could either do so in a `try` block (bleh!) or use the `get()` method, with `False` as a default value.
I'd like to do the same thing for `object.attribute`. That is, I already have object to return `False` if it hasn't been set, but then that give... | A more direct analogue to `dict.get(key, default)` than `hasattr` is `getattr`.
```
val = getattr(obj, 'attr_to_check', default_value)
```
(Where `default_value` is optional, raising an exception on no attribute if not found.)
For your example, you would pass `False`. |
How to compute the nth root of a very big integer | 356,090 | 17 | 2008-12-10T13:49:19Z | 356,187 | 14 | 2008-12-10T14:17:08Z | [
"python",
"math",
"nth-root"
] | I need a way to compute the nth root of a long integer in Python.
I tried `pow(m, 1.0/n)`, but it doesn't work:
> OverflowError: long int too large to convert to float
Any ideas?
By long integer I mean REALLY long integers like:
> 11968003966030964356885611480383408833172346450467339251
> 1960931441410456834630852... | [Gmpy](http://code.google.com/p/gmpy/) is a C-coded Python extension module that wraps the GMP library to provide to Python code fast multiprecision arithmetic (integer, rational, and float), random number generation, advanced number-theoretical functions, and more.
Includes a `root` function:
> x.root(n): returns a ... |
How to compute the nth root of a very big integer | 356,090 | 17 | 2008-12-10T13:49:19Z | 356,206 | 16 | 2008-12-10T14:22:21Z | [
"python",
"math",
"nth-root"
] | I need a way to compute the nth root of a long integer in Python.
I tried `pow(m, 1.0/n)`, but it doesn't work:
> OverflowError: long int too large to convert to float
Any ideas?
By long integer I mean REALLY long integers like:
> 11968003966030964356885611480383408833172346450467339251
> 1960931441410456834630852... | If it's a REALLY big number. You could use a binary search.
```
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n <= x:
high *= 2
low = high/2
while low < high:
mid = (low... |
Minimal Python build for my application's scripting needs? | 356,452 | 2 | 2008-12-10T15:22:41Z | 356,579 | 7 | 2008-12-10T16:00:10Z | [
"python",
"scripting",
"python-embedding"
] | what are your advices on building a very minimalistic version of Python(2.x) for my application's scripting needs.
My main motive here is to keep the foot print (both memory and disk wise) as low as possible so that my native application won't suffer from any major performance hit. Even the Python DLL size is in consi... | Have you tried [Tiny Python](http://www.tinypy.org/)? |
Python regex findall numbers and dots | 356,483 | 6 | 2008-12-10T15:33:09Z | 356,494 | 12 | 2008-12-10T15:36:07Z | [
"python",
"regex",
"findall"
] | I'm using re.findall() to extract some version numbers from an HTML file:
```
>>> import re
>>> text = "<table><td><a href=\"url\">Test0.2.1.zip</a></td><td>Test0.2.1</td></table> Test0.2.1"
>>> re.findall("Test([\.0-9]*)", text)
['0.2.1.', '0.2.1', '0.2.1']
```
but I would like to only get the ones that do not end i... | ```
re.findall(r"Test([0-9.]*[0-9]+)", text)
```
or, a bit shorter:
```
re.findall(r"Test([\d.]*\d+)", text)
```
By the way - you must not escape the dot in a character class:
```
[\.0-9] // matches: 0 1 2 3 4 5 6 7 8 9 . \
[.0-9] // matches: 0 1 2 3 4 5 6 7 8 9 .
``` |
How would you parse indentation (python style)? | 356,638 | 9 | 2008-12-10T16:17:25Z | 356,954 | 10 | 2008-12-10T17:48:55Z | [
"python",
"parsing",
"indentation",
"lexer"
] | How would you define your parser and lexer rules to parse a language that uses indentation for defining scope.
I have already googled and found a clever approach for parsing it by generating INDENT and DEDENT tokens in the lexer.
I will go deeper on this problem and post an answer if I come to something interesting, ... | This is kind of hypothetical, as it would depend on what technology you have for your lexer and parser, but the easiest way would seem to be to have BEGINBLOCK and ENDBLOCK tokens analogous to braces in C. Using the ["offsides rule"](http://en.wikipedia.org/wiki/Off-side_rule) your lexer needs to keep track of a stack ... |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | 14 | 2008-12-10T16:42:08Z | 356,820 | 10 | 2008-12-10T17:14:02Z | [
"python"
] | Is there a way in Python, to have more than one constructor or more than one method with the *same name*, who differ in the *number of arguments* they accept or the *type(s) of one or more argument(s)*?
If not, what would be the best way to handle such situations?
For an example I made up a color class. *This class s... | You can have the factory methods, it is fine. But why not just call it as it is?
```
Color(r, g, b)
Color(*[r, g, b])
Color(**{'r': r, 'g': g, 'b': b})
```
This is the python way. As for the from object constructor, I would prefer something like:
```
Color(*Color2.as_list())
```
*Explicit is better than implicit* -... |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | 14 | 2008-12-10T16:42:08Z | 357,004 | 7 | 2008-12-10T18:02:06Z | [
"python"
] | Is there a way in Python, to have more than one constructor or more than one method with the *same name*, who differ in the *number of arguments* they accept or the *type(s) of one or more argument(s)*?
If not, what would be the best way to handle such situations?
For an example I made up a color class. *This class s... | Python doesn't accept multiple methods with the same name, period. One method does one thing.
I've seen different approaches recommended on how to handle this ... classmethods (like you outlined above) or factory functions. I like keyword arguments the most.
```
class Color (object):
def __init__(self, **parms):
... |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | 14 | 2008-12-10T16:42:08Z | 357,256 | 9 | 2008-12-10T19:22:09Z | [
"python"
] | Is there a way in Python, to have more than one constructor or more than one method with the *same name*, who differ in the *number of arguments* they accept or the *type(s) of one or more argument(s)*?
If not, what would be the best way to handle such situations?
For an example I made up a color class. *This class s... | In general, use factory methods, marked up as `@classmethod`s. They'll also work correctly on subclasses. From a design perspective, they are more explicit, especially when given a good name.
In this case, mixing everything together is probably more convenient, but it also makes the contract for your constructor more ... |
What is the recommended way to use Vim folding for Python code | 357,785 | 83 | 2008-12-10T22:10:45Z | 360,634 | 83 | 2008-12-11T19:47:43Z | [
"python",
"vim",
"folding"
] | I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.
Does anyone have a preferred way to do Python code folding in Vim? I.e,
* Do you have a particular Vim plugin that you use and like?
* Do you use manual folding or do you place markers in comments?
* Any other reco... | Personally I can't convince myself to litter my code with the markers. I've become pretty used to (and efficient) at using indent-folding. Together with my mapping of space bar (see below) to open/close folds and the zR and zM commands, I'm right at home. Perfect for Python!
> `nnoremap <space> za`
>
> `vnoremap <spac... |
What is the recommended way to use Vim folding for Python code | 357,785 | 83 | 2008-12-10T22:10:45Z | 361,548 | 21 | 2008-12-12T00:32:01Z | [
"python",
"vim",
"folding"
] | I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.
Does anyone have a preferred way to do Python code folding in Vim? I.e,
* Do you have a particular Vim plugin that you use and like?
* Do you use manual folding or do you place markers in comments?
* Any other reco... | I use [this](http://www.vim.org/scripts/script.php?script_id=2462 "this") syntax file for Python. It sets the folding method to syntax and folds all classes and functions, but nothing else. |
Does Python have something like anonymous inner classes of Java? | 357,997 | 28 | 2008-12-10T23:26:57Z | 358,012 | 13 | 2008-12-10T23:35:43Z | [
"python",
"class",
"anonymous-class"
] | In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.
Suppose that you want create a subclass of `OptionParser` that overrides only a single method (for example `exit()`). In Java you can write something like this:
```
new O... | Java uses anonymous classes mostly to imitate closures or simply code blocks. Since in Python you can easily pass around methods there's no need for a construct as clunky as anonymous inner classes:
```
def printStuff():
print "hello"
def doit(what):
what()
doit(printStuff)
```
Edit: I'm aware that this is no... |
Does Python have something like anonymous inner classes of Java? | 357,997 | 28 | 2008-12-10T23:26:57Z | 358,055 | 11 | 2008-12-11T00:01:54Z | [
"python",
"class",
"anonymous-class"
] | In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.
Suppose that you want create a subclass of `OptionParser` that overrides only a single method (for example `exit()`). In Java you can write something like this:
```
new O... | You can accomplish this in three ways:
1. Proper subclass (of course)
2. a custom method that you invoke with the object as an argument
3. (what you probably want) -- adding a new method to an object (or replacing an existing one).
Example of option 3 (edited to remove use of "new" module -- It's deprecated, I did no... |
Does Python have something like anonymous inner classes of Java? | 357,997 | 28 | 2008-12-10T23:26:57Z | 358,062 | 10 | 2008-12-11T00:05:13Z | [
"python",
"class",
"anonymous-class"
] | In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.
Suppose that you want create a subclass of `OptionParser` that overrides only a single method (for example `exit()`). In Java you can write something like this:
```
new O... | Well, classes are first class objects, so you can create them in methods if you want. e.g.
```
from optparse import OptionParser
def make_custom_op(i):
class MyOP(OptionParser):
def exit(self):
print 'custom exit called', i
return MyOP
custom_op_class = make_custom_op(3)
custom_op = custom_op_class()
c... |
Does Python have something like anonymous inner classes of Java? | 357,997 | 28 | 2008-12-10T23:26:57Z | 3,915,434 | 22 | 2010-10-12T13:53:02Z | [
"python",
"class",
"anonymous-class"
] | In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.
Suppose that you want create a subclass of `OptionParser` that overrides only a single method (for example `exit()`). In Java you can write something like this:
```
new O... | You can use the [`type(name, bases, dict)`](http://docs.python.org/library/functions.html#type) builtin function to create classes on the fly. For example:
```
op = type("MyOptionParser", (OptionParser,object), {"foo": lambda self: "foo" })
op().foo()
```
Since OptionParser isn't a new-style class, you have to explic... |
log4j with timestamp per log entry | 358,225 | 41 | 2008-12-11T01:44:39Z | 358,247 | 77 | 2008-12-11T01:59:03Z | [
"java",
"python",
"log4j",
"jython"
] | this is my log output
```
INFO main digestemails - process inbox
INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source
INFO main digestemails - digesting 003d01c95a7b_3446880_0202fea9@xxxx.com.eml
INFO main digestemails - extracting attachments
INFO main digestemails - no attachments or... | Use %d in your PatternLayout.
Also %d can take a format pattern as in %d{dd MMM yyyy HH:mm:ss,SSS} you can pick and choose the elements that you want. When the format pattern is omitted the date will be in ISO8601 format. |
log4j with timestamp per log entry | 358,225 | 41 | 2008-12-11T01:44:39Z | 358,641 | 13 | 2008-12-11T07:45:42Z | [
"java",
"python",
"log4j",
"jython"
] | this is my log output
```
INFO main digestemails - process inbox
INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source
INFO main digestemails - digesting 003d01c95a7b_3446880_0202fea9@xxxx.com.eml
INFO main digestemails - extracting attachments
INFO main digestemails - no attachments or... | A extract from my properties file
```
log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p (%t) [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppe... |
python, set terminal type in pexpect | 358,783 | 4 | 2008-12-11T09:32:43Z | 359,241 | 7 | 2008-12-11T12:52:34Z | [
"python",
"pexpect"
] | I have a script which uses pexpect to start a CLI program. It works a bit like a shell where you get a prompt where you can enter some commands.
The problem I have, I think, is that this program uses a coloured prompt.
This is what I do
```
import pprint
import pexpect
1 a = pexpect.spawn('program')
2 a.expect("pro... | Ok, I found the answer. csl's answer set me on the right path.
pexpect has a "env" option which I thought I could use. like this:
```
a = pexpect.spawn('program', env = {"TERM": "dumb"})
```
But this spawns a new shell which does not work for me, our development environment
depends on a lot of environmental variable... |
Execute Commands Sequentially in Python | 359,347 | 13 | 2008-12-11T13:30:23Z | 359,506 | 17 | 2008-12-11T14:23:17Z | [
"python",
"windows",
"subprocess"
] | I would like to execute multiple commands in a row:
ie (just to illustrate my need):
**cmd** (the shell)
then
**cd dir**
and
**ls**
and read the result of the ls.
Any idea with subprocess module ?
UPDATE:
cd dir and ls are just an example. I need to run complex commands (following a particular order, without ... | There is an easy way to execute a sequence of commands.
Use the following in `subprocess.Popen`
```
"command1; command2; command3"
```
Or, if you're stuck with windows, you have several choices.
* Create a temporary ".BAT" file, and provide this to `subprocess.Popen`
* Create a sequence of commands with "\n" separa... |
Execute Commands Sequentially in Python | 359,347 | 13 | 2008-12-11T13:30:23Z | 359,737 | 18 | 2008-12-11T15:35:32Z | [
"python",
"windows",
"subprocess"
] | I would like to execute multiple commands in a row:
ie (just to illustrate my need):
**cmd** (the shell)
then
**cd dir**
and
**ls**
and read the result of the ls.
Any idea with subprocess module ?
UPDATE:
cd dir and ls are just an example. I need to run complex commands (following a particular order, without ... | To do that, you would have to:
* supply the `shell=True` argument in the `subprocess.Popen` call, and
* separate the commands with:
+ `;` if running under a \*nix shell (bash, ash, sh, ksh, csh, tcsh, zsh etc)
+ `&` if running under the `cmd.exe` of Windows |
How can I unload a DLL using ctypes in Python? | 359,498 | 10 | 2008-12-11T14:21:06Z | 359,570 | 10 | 2008-12-11T14:41:16Z | [
"python",
"dll",
"ctypes"
] | I'm using ctypes to load a DLL in Python. This works great.
Now we'd like to be able to reload that DLL at runtime.
The straightforward approach would seem to be:
1. Unload DLL
2. Load DLL
Unfortunately I'm not sure what the correct way to unload the DLL is.
\_ctypes.FreeLibrary is available, but private.
Is there... | you should be able to do it by disposing the object
```
mydll = ctypes.CDLL('...')
del mydll
mydll = ctypes.CDLL('...')
```
**EDIT:** Hop's comment is right, this unbinds the name, but garbage collection doesn't happen that quickly, in fact I even doubt it even releases the loaded library.
Ctypes doesn't seem to pro... |
Lambda function for classes in python? | 360,368 | 6 | 2008-12-11T18:27:21Z | 360,425 | 11 | 2008-12-11T18:44:54Z | [
"python",
"lambda"
] | There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that ... | Does the library really specify that it wants an "uninitialized version" (i.e. a class reference)?
It looks to me as if the library actually wants an object factory. In that case, it's acceptable to type:
```
lib3 = Library(lambda: Multiply(5))
```
To understand how the lambda works, consider the following:
```
Mul... |
Lambda function for classes in python? | 360,368 | 6 | 2008-12-11T18:27:21Z | 360,456 | 8 | 2008-12-11T18:53:30Z | [
"python",
"lambda"
] | There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that ... | There's no need for lambda at all. lambda is just syntatic sugar to define a function and use it at the same time. Just like any lambda call can be replaced with an explicit def, we can solve your problem by creating a real class that meets your needs and returning it.
```
class Double:
def run(self,x):
... |
What GUI toolkit looks best for a native LAF for Python in Windows and Linux? | 360,602 | 4 | 2008-12-11T19:38:02Z | 361,672 | 8 | 2008-12-12T01:48:15Z | [
"python",
"windows",
"linux",
"native",
"gui-toolkit"
] | I need to decide on a GUI/Widget toolkit to use with Python for a new project. The target platforms will be Linux with KDE and Windows XP (and probably Vista). What Python GUI toolkit looks best and consistent with the native look and feel of the run time platform?
If possible, cite strengths and weaknesses of the sug... | Python binding of Wx is very strong since at least one of the core developer is a python guy itself. WxWdgets is robust, time proven stable, mature, but also bit more than just GUI. Even is a lot is left out in WxPython - because Python itself offers that already - you might find that extra convenient for your project.... |
Implementing a "[command] [action] [parameter]" style command-line interfaces? | 362,426 | 9 | 2008-12-12T10:35:03Z | 362,700 | 9 | 2008-12-12T13:17:11Z | [
"python",
"command-line",
"user-interface"
] | What is the "cleanest" way to implement an command-line UI, similar to git's, for example:
```
git push origin/master
git remote add origin git://example.com master
```
Ideally also allowing the more flexible parsing, for example,
```
jump_to_folder app theappname v2
jump_to_folder app theappname source
jump_to_fold... | The `cmd` module would probably work well for this.
Example:
```
import cmd
class Calc(cmd.Cmd):
def do_add(self, arg):
print sum(map(int, arg.split()))
if __name__ == '__main__':
Calc().cmdloop()
```
Run it:
```
$python calc.py
(Cmd) add 4 5
9
(Cmd) help
Undocumented commands:
==================... |
Implementing a "[command] [action] [parameter]" style command-line interfaces? | 362,426 | 9 | 2008-12-12T10:35:03Z | 10,913,734 | 7 | 2012-06-06T11:56:29Z | [
"python",
"command-line",
"user-interface"
] | What is the "cleanest" way to implement an command-line UI, similar to git's, for example:
```
git push origin/master
git remote add origin git://example.com master
```
Ideally also allowing the more flexible parsing, for example,
```
jump_to_folder app theappname v2
jump_to_folder app theappname source
jump_to_fold... | [argparse](http://docs.python.org/library/argparse.html#sub-commands) is perfect for this, specifically ["sub-commands"](http://docs.python.org/library/argparse.html#sub-commands) and positional args
```
import argparse
def main():
arger = argparse.ArgumentParser()
# Arguments for top-level, e.g "subcmds.py... |
django is very slow on my machine | 362,808 | 12 | 2008-12-12T13:53:04Z | 368,583 | 17 | 2008-12-15T14:46:40Z | [
"python",
"django",
"dns"
] | I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.
I start the server using
```
python manage.py testserver
```
I can see each GET request (PNGs and style sheets) take about half a second.
Another weird thing, which I think... | Firefox has a problem browsing to localhost on some Windows machines. You can solve it by switching off ipv6, which isn't really recommended. Using 127.0.0.1 directly is another way round the problem. |
Python idiom to return first item or None | 363,944 | 110 | 2008-12-12T19:56:02Z | 363,955 | 35 | 2008-12-12T20:00:03Z | [
"python",
"idioms",
"python-2.4"
] | I'm sure there's a simpler way of doing this that's just not occurring to me.
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:
```
my_list = get_list()
if len(my_list) > 0: return my_... | ```
(get_list() or [None])[0]
```
That should work.
BTW I didn't use the variable `list`, because that overwrites the builtin `list()` function.
Edit: I had a slightly simpler, but wrong version here earlier. |
Python idiom to return first item or None | 363,944 | 110 | 2008-12-12T19:56:02Z | 363,995 | 134 | 2008-12-12T20:12:27Z | [
"python",
"idioms",
"python-2.4"
] | I'm sure there's a simpler way of doing this that's just not occurring to me.
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:
```
my_list = get_list()
if len(my_list) > 0: return my_... | The best way is this:
```
a = get_list()
return a[0] if a else None
```
You could also do it in one line, but it's much harder for the programmer to read:
```
return (get_list()[:1] or [None])[0]
``` |
Python idiom to return first item or None | 363,944 | 110 | 2008-12-12T19:56:02Z | 364,405 | 9 | 2008-12-12T22:41:48Z | [
"python",
"idioms",
"python-2.4"
] | I'm sure there's a simpler way of doing this that's just not occurring to me.
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:
```
my_list = get_list()
if len(my_list) > 0: return my_... | The OP's solution is nearly there, there are just a few things to make it more Pythonic.
For one, there's no need to get the length of the list. Empty lists in Python evaluate to False in an if check. Just simply say
```
if list:
```
Additionally, it's a very Bad Idea to assign to variables that overlap with reserve... |
Python idiom to return first item or None | 363,944 | 110 | 2008-12-12T19:56:02Z | 365,934 | 32 | 2008-12-13T23:31:55Z | [
"python",
"idioms",
"python-2.4"
] | I'm sure there's a simpler way of doing this that's just not occurring to me.
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:
```
my_list = get_list()
if len(my_list) > 0: return my_... | ```
def get_first(iterable, default=None):
if iterable:
for item in iterable:
return item
return default
```
Example:
```
x = get_first(get_first_list())
if x:
...
y = get_first(get_second_list())
if y:
...
```
Another option is to inline the above function:
```
for x in get_firs... |
Python idiom to return first item or None | 363,944 | 110 | 2008-12-12T19:56:02Z | 25,398,201 | 20 | 2014-08-20T06:36:29Z | [
"python",
"idioms",
"python-2.4"
] | I'm sure there's a simpler way of doing this that's just not occurring to me.
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:
```
my_list = get_list()
if len(my_list) > 0: return my_... | The most python idiomatic way is to use the next() on a iterator since list is *iterable*. just like what @J.F.Sebastian put in the comment on Dec 13, 2011.
`next(iter(the_list), None)` This returns None if `the_list` is empty. see [next() Python 2.6+](https://docs.python.org/2/library/functions.html#next)
or if you ... |
MVC and django fundamentals | 364,015 | 8 | 2008-12-12T20:22:29Z | 364,074 | 15 | 2008-12-12T20:37:36Z | [
"python",
"django",
"django-models",
"django-templates"
] | Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framew... | "data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before"
Django imposes best practices on you. You don't have a lot of choices and can't make a lot of mistakes.
MVC (while a noble aspiration) is implemented as follows:
* Data is def... |
Markup-based GUI for python | 364,327 | 7 | 2008-12-12T22:10:08Z | 768,465 | 7 | 2009-04-20T14:18:21Z | [
"python",
"user-interface",
"markup"
] | I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them.
I think GUI design should be done in a separate text-based file ... | You can try Mozilla's XUL. It supports Python via XPCOM.
See this project: [pyxpcomext](http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html)
XUL isn't compiled, it is packaged and loaded at runtime. Firefox and many other great applications use it, but most of them use Javascript fo... |
In Python, how do I iterate over a dictionary in sorted order? | 364,519 | 136 | 2008-12-12T23:57:05Z | 364,521 | 63 | 2008-12-12T23:57:53Z | [
"python",
"dictionary"
] | There's an existing function that ends in:
```
return dict.iteritems()
```
that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that? | Use the [`sorted()`](http://pydoc.org/2.5.1/__builtin__.html#-sorted) function:
```
return sorted(dict.iteritems())
```
If you want an actual iterator over the sorted results, since `sorted()` returns a list, use:
```
return iter(sorted(dict.iteritems()))
``` |
In Python, how do I iterate over a dictionary in sorted order? | 364,519 | 136 | 2008-12-12T23:57:05Z | 364,524 | 25 | 2008-12-13T00:00:20Z | [
"python",
"dictionary"
] | There's an existing function that ends in:
```
return dict.iteritems()
```
that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that? | Greg's answer is right. Note that in Python 3.0 you'll have to do
```
sorted(dict.items())
```
as `iteritems` will be gone. |
In Python, how do I iterate over a dictionary in sorted order? | 364,519 | 136 | 2008-12-12T23:57:05Z | 364,588 | 35 | 2008-12-13T00:44:32Z | [
"python",
"dictionary"
] | There's an existing function that ends in:
```
return dict.iteritems()
```
that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that? | A dict's keys are stored in a hashtable so that is their 'natural order', i.e. psuedo-random. Any other ordering is a concept of the consumer of the dict.
sorted() always returns a list, not a dict. If you pass it a dict.items() (which produces a list of tuples), it will return a list of tuples [(k1,v1), (k2,v2), ...]... |
In Python, how do I iterate over a dictionary in sorted order? | 364,519 | 136 | 2008-12-12T23:57:05Z | 364,599 | 100 | 2008-12-13T00:49:38Z | [
"python",
"dictionary"
] | There's an existing function that ends in:
```
return dict.iteritems()
```
that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that? | Haven't tested this very extensively, but works in Python 2.5.2.
```
>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>
``` |
How to get item's position in a list? | 364,621 | 103 | 2008-12-13T01:20:32Z | 364,638 | 8 | 2008-12-13T01:33:30Z | [
"python",
"list"
] | I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
```
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
``` | ```
for i in xrange(len(testlist)):
if testlist[i] == 1:
print i
```
xrange instead of range as requested (see comments). |
How to get item's position in a list? | 364,621 | 103 | 2008-12-13T01:20:32Z | 364,641 | 36 | 2008-12-13T01:37:46Z | [
"python",
"list"
] | I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
```
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
``` | Use enumerate:
```
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
``` |
How to get item's position in a list? | 364,621 | 103 | 2008-12-13T01:20:32Z | 364,769 | 168 | 2008-12-13T03:28:26Z | [
"python",
"list"
] | I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
```
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
``` | Hmmm. There was an answer with a list comprehension here, but it's disappeared.
Here:
```
[i for i,x in enumerate(testlist) if x == 1]
```
Example:
```
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
```
Update:
Okay, you want a generator expression, we'll have... |
How to get item's position in a list? | 364,621 | 103 | 2008-12-13T01:20:32Z | 10,266,829 | 82 | 2012-04-22T09:35:15Z | [
"python",
"list"
] | I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
```
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
``` | What about the following?
```
print testlist.index(element)
```
If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like
```
if element in testlist:
print testlist.index(element)
```
or
```
print(testlist.index(element) if element in testlist else None)... |
generator comprehension | 364,802 | 37 | 2008-12-13T03:55:44Z | 364,816 | 10 | 2008-12-13T04:08:34Z | [
"python"
] | What does generator comprehension do? How does it work? I couldn't find a tutorial about it. | A generator comprehension is the lazy version of a list comprehension.
It is just like a list comprehension except that it returns an iterator instead of the list ie an object with a next() method that will yield the next element.
If you are not familiar with list comprehensions see [here](http://docs.python.org/tuto... |
generator comprehension | 364,802 | 37 | 2008-12-13T03:55:44Z | 364,824 | 76 | 2008-12-13T04:14:04Z | [
"python"
] | What does generator comprehension do? How does it work? I couldn't find a tutorial about it. | Do you understand list comprehensions? If so, a generator expression is like a list comprehension, but instead of finding all the items you're interested and packing them into list, it waits, and yields each item out of the expression, one by one.
```
>>> my_list = [1, 3, 5, 9, 2, 6]
>>> filtered_list = [item for item... |
Can you change a field label in the Django Admin application? | 365,082 | 19 | 2008-12-13T10:30:41Z | 365,236 | 37 | 2008-12-13T13:59:40Z | [
"python",
"django",
"django-admin",
"django-forms"
] | As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information? | the [verbose name](http://docs.djangoproject.com/en/dev/topics/db/models/#verbose-field-names) of the field is the (optional) first parameter at field construction. |
Can you change a field label in the Django Admin application? | 365,082 | 19 | 2008-12-13T10:30:41Z | 14,743,532 | 12 | 2013-02-07T04:25:28Z | [
"python",
"django",
"django-admin",
"django-forms"
] | As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information? | If your field is a property (a method) then you should use short\_description:
```
class Person(models.Model):
...
def address_report(self, instance):
...
# short_description functions like a model field's verbose_name
address_report.short_description = "Address"
``` |
Cross platform keylogger | 365,110 | 9 | 2008-12-13T11:10:29Z | 365,225 | 10 | 2008-12-13T13:46:12Z | [
"python",
"cross-platform",
"time-management",
"keylogger"
] | I'm looking for ways to watch mouse and keyboard events on Windows, Linux and Mac from Python.
My application is a time tracker. I'm not looking into the event, I just record the time when it happens. If there are no events for a certain time, say 10 minutes, I assume that the user has left and stop the current projec... | There are couple of open source apps that might give you some pointers:
* [PyKeylogger](http://sourceforge.net/p/pykeylogger/wiki/Main_Page/) is python keylogger for windows and linux
* [logKext](http://code.google.com/p/logkext/) is a c++ keylogger for mac |
Cross platform keylogger | 365,110 | 9 | 2008-12-13T11:10:29Z | 2,074,117 | 7 | 2010-01-15T19:16:24Z | [
"python",
"cross-platform",
"time-management",
"keylogger"
] | I'm looking for ways to watch mouse and keyboard events on Windows, Linux and Mac from Python.
My application is a time tracker. I'm not looking into the event, I just record the time when it happens. If there are no events for a certain time, say 10 minutes, I assume that the user has left and stop the current projec... | There's a great article on **Writing Linux Kernel Keyloggers**
<http://www.phrack.com/issues.html?issue=59&id=14#article>
If you are attempting to run a honeypot, then definitely give Sebek a try:
<https://projects.honeynet.org/sebek/>
> Sebek is a data capture tool designed
> to capture attacker's activities on... |
What is the pythonic way to avoid default parameters that are empty lists? | 366,422 | 34 | 2008-12-14T11:23:54Z | 366,430 | 68 | 2008-12-14T11:27:30Z | [
"python"
] | Sometimes it seems natural to have a default parameter which is an empty list. Yet Python gives unexpected behavior in these situations.
If for example, I have a function:
```
def myFunc(working_list = []):
working_list.append("a")
print working_list
```
The first time it is called with the default will work... | ```
def myFunc(working_list=None):
if working_list is None:
working_list = []
working_list.append("a")
print working_list
```
is how I do it. |
What is the pythonic way to avoid default parameters that are empty lists? | 366,422 | 34 | 2008-12-14T11:23:54Z | 366,446 | 9 | 2008-12-14T11:43:57Z | [
"python"
] | Sometimes it seems natural to have a default parameter which is an empty list. Yet Python gives unexpected behavior in these situations.
If for example, I have a function:
```
def myFunc(working_list = []):
working_list.append("a")
print working_list
```
The first time it is called with the default will work... | Not that it matters in this case, but you can use object identity to test for None:
```
if working_list is None: working_list = []
```
You could also take advantage of how the boolean operator or is defined in python:
```
working_list = working_list or []
```
Though this will behave unexpectedly if the caller gives... |
What is the pythonic way to avoid default parameters that are empty lists? | 366,422 | 34 | 2008-12-14T11:23:54Z | 2,021,717 | 7 | 2010-01-07T16:09:07Z | [
"python"
] | Sometimes it seems natural to have a default parameter which is an empty list. Yet Python gives unexpected behavior in these situations.
If for example, I have a function:
```
def myFunc(working_list = []):
working_list.append("a")
print working_list
```
The first time it is called with the default will work... | If the intent of the function is to *modify* the parameter passed as `working_list`, see HenryR's answer (=None, check for None inside).
But if you didn't intend to mutate the argument, just use it as starting point for a list, you can simply copy it:
```
def myFunc(starting_list = []):
starting_list = list(start... |
How to limit execution time of a function call in Python | 366,682 | 37 | 2008-12-14T16:20:24Z | 366,763 | 29 | 2008-12-14T17:27:50Z | [
"python",
"multithreading"
] | There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread. | I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.
<http://docs.python.org/library/signal.html>
So your code is going to look something like this.
```
import ... |
How to limit execution time of a function call in Python | 366,682 | 37 | 2008-12-14T16:20:24Z | 601,168 | 46 | 2009-03-02T03:14:25Z | [
"python",
"multithreading"
] | There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread. | An improvement on @rik.the.vik's answer would be to use the [`with` statement](http://www.python.org/dev/peps/pep-0343/) to give the timeout function some syntactic sugar:
```
from __future__ import with_statement # Required in 2.5
import signal
from contextlib import contextmanager
class TimeoutException(Exception):... |
How to limit execution time of a function call in Python | 366,682 | 37 | 2008-12-14T16:20:24Z | 1,114,567 | 7 | 2009-07-11T20:30:32Z | [
"python",
"multithreading"
] | There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread. | Doing this from within a signal handler is dangerous: you might be inside an exception handler at the time the exception is raised, and leave things in a broken state. For example,
```
def function_with_enforced_timeout():
f = open_temporary_file()
try:
...
finally:
here()
unlink(f.filename)
```
If you... |
How to limit execution time of a function call in Python | 366,682 | 37 | 2008-12-14T16:20:24Z | 26,664,130 | 13 | 2014-10-30T22:05:02Z | [
"python",
"multithreading"
] | There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread. | Here's a Linux/OSX way to limit a function's running time. This is in case you don't want to use threads, and want your program to wait until the function ends, or the time limit expires.
```
from multiprocessing import Process
from time import sleep
def f(time):
sleep(time)
def run_with_limited_time(func, args... |
Bitwise subtraction in Python | 366,706 | 9 | 2008-12-14T16:41:28Z | 366,735 | 9 | 2008-12-14T17:06:34Z | [
"python",
"low-level"
] | This is a follow-up to [my question yesterday](http://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator):
CMS kindly provided this example of using bitwise operators to add two numbers in C:
```
#include<stdio.h>
int add(int x, int y) {
int a, b;
do {
... | As I pointed out in my response to CMS' answer yesterday, left-shifting a negative number is undefined behavior in C so this isn't even guaranteed to work in C (the problem is how to handle the signed bit, do you shift it like a value bit or is it not affected by a shift? The standards committee couldn't agree on a beh... |
How to organize python test in a way that I can run all tests in a single command? | 366,720 | 14 | 2008-12-14T16:52:50Z | 366,828 | 10 | 2008-12-14T18:41:31Z | [
"python",
"unit-testing",
"python-nose"
] | Currently my code is organized in the following tree structure:
```
src/
module1.py
module2.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
test_moduleA.py
test_moduleB.py
```
Where the `module*.py` files contains the source... | Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc).
When you're using nosetests, make sure that all directories with tests are real packages:
```
src/
module1.py
module2.py
subpackage1/
... |
How to organize python test in a way that I can run all tests in a single command? | 366,720 | 14 | 2008-12-14T16:52:50Z | 373,150 | 7 | 2008-12-16T23:28:39Z | [
"python",
"unit-testing",
"python-nose"
] | Currently my code is organized in the following tree structure:
```
src/
module1.py
module2.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
test_moduleA.py
test_moduleB.py
```
Where the `module*.py` files contains the source... | If they all begin with `test` then just `nosetest` should work. Nose automatically searches for any files beginning with 'test'. |
How to localize Content of a Django application | 366,838 | 9 | 2008-12-14T18:48:49Z | 367,698 | 10 | 2008-12-15T07:40:50Z | [
"python",
"django",
"localization",
"internationalization"
] | Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application.
Users can save "products" in the database and give them names and descriptions, but since the whole sit... | I would suggest checking out [django-multilingual](http://code.google.com/p/django-multilingual/). It is a third party app that lets you define translation fields on your models.
Of course, you still have to type in the actual translations, but they are stored transparently in the database (as opposed to in static PO ... |
No print output from child multiprocessing.Process unless the program crashes | 367,053 | 12 | 2008-12-14T22:07:56Z | 367,065 | 21 | 2008-12-14T22:18:22Z | [
"python",
"multithreading",
"io",
"multiprocessing"
] | I am having trouble with the Python multiprocessing module. I am using the `Process` class to spawn a new process in order to utilize my second core. This second process loads a bunch of data into RAM and then waits patiently instead of consuming.
I wanted to see what that process printed with the `print` command, how... | Have you tried flushing stdout?
```
import sys
print "foo"
sys.stdout.flush()
``` |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | 15 | 2008-12-14T22:57:33Z | 367,136 | 23 | 2008-12-14T23:12:50Z | [
"python",
"perl",
"command-line",
"language-features"
] | I know of `python -c '<code>'`, but I'm wondering if there's a more elegant python equivalent to `perl -pi -e '<code>'`. I still use it quite a bit for things like find and replace in a whole directory (`perl -pi -e s/foo/bar/g *` or even `find . | xargs perl -pi -e s/foo/bar/g` for sub-directories).
I actually feel t... | Python is for muggles. If magic you want, Perl you should use! |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | 15 | 2008-12-14T22:57:33Z | 367,181 | 9 | 2008-12-14T23:53:48Z | [
"python",
"perl",
"command-line",
"language-features"
] | I know of `python -c '<code>'`, but I'm wondering if there's a more elegant python equivalent to `perl -pi -e '<code>'`. I still use it quite a bit for things like find and replace in a whole directory (`perl -pi -e s/foo/bar/g *` or even `find . | xargs perl -pi -e s/foo/bar/g` for sub-directories).
I actually feel t... | The command line usage from '`python -h`' certainly strongly suggests there is no such equivalent. Perl tends to make extensive use of '`$_`' (your examples make implicit use of it), and I don't think Python supports any similar concept, thereby making Python equivalents of the Perl one-liners much harder. |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | 15 | 2008-12-14T22:57:33Z | 367,238 | 9 | 2008-12-15T00:58:30Z | [
"python",
"perl",
"command-line",
"language-features"
] | I know of `python -c '<code>'`, but I'm wondering if there's a more elegant python equivalent to `perl -pi -e '<code>'`. I still use it quite a bit for things like find and replace in a whole directory (`perl -pi -e s/foo/bar/g *` or even `find . | xargs perl -pi -e s/foo/bar/g` for sub-directories).
I actually feel t... | An equivalent to -pi isn't that hard to write in Python.
1. Write yourself a handy module with the -p and -i features you really like. Let's call it `pypi.py`.
2. Use `python -c 'import pypi; pypi.subs("this","that")'`
You can implement the basic -p loop with the [fileinput](http://docs.python.org/library/fileinput.h... |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | 15 | 2008-12-14T22:57:33Z | 14,429,701 | 9 | 2013-01-20T21:45:29Z | [
"python",
"perl",
"command-line",
"language-features"
] | I know of `python -c '<code>'`, but I'm wondering if there's a more elegant python equivalent to `perl -pi -e '<code>'`. I still use it quite a bit for things like find and replace in a whole directory (`perl -pi -e s/foo/bar/g *` or even `find . | xargs perl -pi -e s/foo/bar/g` for sub-directories).
I actually feel t... | I know this is a couple of years too late, but I've recently
found a very nice tool called [pyp](http://code.google.com/p/pyp/), which does
exactly what you've asked for.
I think your command should be:
```
pyp "p.replace('foo','bar')"
``` |
Splitting a string into words and punctuation | 367,155 | 22 | 2008-12-14T23:30:33Z | 367,292 | 35 | 2008-12-15T01:53:18Z | [
"python",
"string",
"split"
] | I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.
For instance:
```
>>> c = "help, me"
>>> print c.split()
['help,', 'me']
```
What I really want the list to look like is:
```
['help', ',', 'me']
```
So, I want the string split at whitespace with ... | This is more or less the way to do it:
```
>>> import re
>>> re.findall(r"[\w']+|[.,!?;]", "Hello, I'm a string!")
['Hello', ',', "I'm", 'a', 'string', '!']
```
The trick is, not to think about where to split the string, but what to include in the tokens.
Caveats:
* The underscore (\_) is considered an inner-word c... |
Splitting a string into words and punctuation | 367,155 | 22 | 2008-12-14T23:30:33Z | 8,930,959 | 13 | 2012-01-19T17:58:09Z | [
"python",
"string",
"split"
] | I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.
For instance:
```
>>> c = "help, me"
>>> print c.split()
['help,', 'me']
```
What I really want the list to look like is:
```
['help', ',', 'me']
```
So, I want the string split at whitespace with ... | Here is a Unicode-aware version:
```
re.findall(r"\w+|[^\w\s]", text, re.UNICODE)
```
The first alternative catches sequences of word characters (as defined by unicode, so "résumé" won't turn into `['r', 'sum']`); the second catches individual non-word characters, ignoring whitespace.
Note that, unlike the top ans... |
Setting up a foreign key to an abstract base class with Django | 367,461 | 21 | 2008-12-15T04:16:33Z | 367,479 | 7 | 2008-12-15T04:33:46Z | [
"python",
"django",
"inheritance",
"django-models"
] | I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table.
The following example should illustrate my problem:
```
class Answer(m... | My gut would be to suggest removing the abstract modifier on the base class. You'll get the same model structure, but Answer will be it's own table. The downside of this is that if these are large tables and/or your queries are complex, queries against it could be noticeably slower.
Alternatively, you could keep your ... |
Setting up a foreign key to an abstract base class with Django | 367,461 | 21 | 2008-12-15T04:16:33Z | 367,765 | 15 | 2008-12-15T08:24:54Z | [
"python",
"django",
"inheritance",
"django-models"
] | I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table.
The following example should illustrate my problem:
```
class Answer(m... | A [generic relation](https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations) seems to be the solution. But it will complicate things even further.
It seems to me; your model structure is already more complex than necessary. I would simply merge all three `Answer` models into one. This way:
... |
How much input validation should I be doing on my python functions/methods? | 367,560 | 15 | 2008-12-15T05:39:52Z | 368,054 | 10 | 2008-12-15T11:18:12Z | [
"python",
"validation"
] | I'm interested in how much up front validation people do in the Python they write.
Here are a few examples of simple functions:
```
def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Sa... | I `assert` what's absolutely essential.
Important: What's *absolutely* essential. Some people over-test things.
```
def factorial(num):
assert int(num)
assert num > 0
```
Isn't completely correct. long is also a legal possibility.
```
def factorial(num):
assert type(num) in ( int, long )
assert num ... |
How do I build a numpy array from a generator? | 367,565 | 81 | 2008-12-15T05:44:31Z | 367,599 | 72 | 2008-12-15T06:31:12Z | [
"python",
"numpy",
"generator"
] | How can I build a numpy array out of a generator object?
Let me illustrate the problem:
```
>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5,... | Numpy arrays require their length to be set explicitly at creation time, unlike python lists. This is necessary so that space for each item can be consecutively allocated in memory. Consecutive allocation is the key feature of numpy arrays: this combined with native code implementation let operations on them execute mu... |
How do I build a numpy array from a generator? | 367,565 | 81 | 2008-12-15T05:44:31Z | 580,416 | 115 | 2009-02-24T03:53:18Z | [
"python",
"numpy",
"generator"
] | How can I build a numpy array out of a generator object?
Let me illustrate the problem:
```
>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5,... | One google behind this stackoverflow result, I found that there is a [`numpy.fromiter(data, dtype, count)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html). The default `count=-1` takes all elements from the iterable. It requires a `dtype` to be set explicitly. In my case, this worked:
`numpy.... |
Generating random text strings of a given pattern | 367,586 | 11 | 2008-12-15T06:03:40Z | 367,594 | 12 | 2008-12-15T06:18:07Z | [
"python",
"string",
"random"
] | I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. | See an example - [Recipe 59873: Random Password Generation](http://code.activestate.com/recipes/59873/) .
Building on the recipe, here is a solution to your question :
```
from random import choice
import string
def GenPasswd2(length=8, chars=string.letters + string.digits):
return ''.join([choice(chars) for i i... |
Generating random text strings of a given pattern | 367,586 | 11 | 2008-12-15T06:03:40Z | 367,596 | 37 | 2008-12-15T06:19:22Z | [
"python",
"string",
"random"
] | I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. | ```
#!/usr/bin/python
import random
import string
digits = "".join( [random.choice(string.digits) for i in xrange(8)] )
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
print digits + chars
```
EDIT: liked the idea of using random.choice better than randint() so I've updated the code to reflect... |
Making a virtual package available via sys.modules | 368,057 | 9 | 2008-12-15T11:20:14Z | 368,178 | 13 | 2008-12-15T12:13:05Z | [
"python",
"import",
"module"
] | Say I have a package "mylibrary".
I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.
I.e., I do:
```
import sys, types
sys.modules['mylibrary.con... | You need to monkey-patch the module not only into sys.modules, but also into its parent module:
```
>>> import sys,types,xml
>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')
>>> import xml.config
>>> from xml import config
>>> from xml import config as x
>>> x
<module 'xml.config' (built-in)... |
How can I stop a While loop? | 368,545 | 3 | 2008-12-15T14:35:02Z | 368,550 | 8 | 2008-12-15T14:37:59Z | [
"python",
"while-loop"
] | I wrote a `while loop` in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?
```
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
... | just indent your code correctly:
```
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i w... |
How can I stop a While loop? | 368,545 | 3 | 2008-12-15T14:35:02Z | 368,554 | 7 | 2008-12-15T14:38:42Z | [
"python",
"while-loop"
] | I wrote a `while loop` in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?
```
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
... | ```
def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
``` |
Questions about Setuptools and alternatives | 368,636 | 20 | 2008-12-15T15:06:49Z | 370,062 | 24 | 2008-12-15T23:29:35Z | [
"python",
"packaging",
"setuptools",
"pip"
] | I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's [On packaging](http://www.b-list.org/weblog/2008/dec/14/packaging/) post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who absolutely detest ... | pip uses Setuptools, and doesn't require any changes to packages. It actually installs packages with Setuptools, using:
```
python -c 'import setuptools; __file__="setup.py"; execfile(__file__)' \
install \
--single-version-externally-managed
```
Because it uses that option (`--single-version-externally-manag... |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | 49 | 2008-12-15T15:57:24Z | 370,199 | 190 | 2008-12-16T00:45:11Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] | Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.
```
>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal ... | â¦there's a reason they're called "encodings"â¦
A little preamble: think of unicode as the norm, or the ideal state. Unicode is just a table of characters. â65 is latin capital A. â937 is greek capital omega. Just that.
In order for a computer to store and-or manipulate Unicode, it has to *encode* it into bytes... |
Difference between dict.clear() and assigning {} in Python | 369,898 | 104 | 2008-12-15T22:23:18Z | 369,925 | 187 | 2008-12-15T22:30:29Z | [
"python",
"dictionary"
] | In python, is there a difference between calling `clear()` and assigning `{}` to a dictionary? If yes, what is it?
Example:
```
d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
``` | If you have another variable also referring to the same dictionary, there is a big difference:
```
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}
```
This is because assigning `d = {}` creates a new, empty dictionary and assi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.