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 |
|---|---|---|---|---|---|---|---|---|---|
Subtracting 2 lists in Python | 534,855 | 33 | 2009-02-10T23:57:22Z | 534,914 | 49 | 2009-02-11T00:19:03Z | [
"python",
"list",
"tuples",
"vector"
] | Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like
```
[2,2,2] - [1,1,1] = [1,1,1]
```
Should I use tuples?
If none of them defines these operands on these types, can I define it instead?
If not, should I create a new vector3 class? | Here's an alternative to list comprehensions. Map iterates through the list(s) (the latter arguments), doing so simulataneously, and passes their elements as arguments to the function (the first arg). It returns the resulting list.
```
map(operator.sub, a, b)
```
This code because has less syntax (which is more aesthetic for me), and apparently it's 40% faster for lists of length 5 (see bobince's comment). Still, either solution will work. |
practice with threads in python | 535,331 | 2 | 2009-02-11T03:42:33Z | 535,399 | 7 | 2009-02-11T04:10:34Z | [
"python",
"multithreading",
"image-manipulation"
] | I know that Python has a [global lock](http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock) and i've read Glyph's explaination of [python multithreading](http://stackoverflow.com/questions/203912/does-python-support-multiprocessor-multicore-programming/204150#204150). But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture.
Here's what's happening (pseudocode):
```
for pixels in picture:
apply sobel operator horizontal
for pixels in picture:
apply sobel operator vertical
```
[info on sobel operator](http://en.wikipedia.org/wiki/Sobel_operator).
These two loops can run completely independent of each other, and so would be prime candidates for multithreading. (running these two loops on any significantly large picture can take 10+ seconds). However, when I have tried to use the `threading` module in python, it takes twice as long because of the global lock. My question is should I abandon all hope of doing this in two threads in python and try in another language? If i can forge ahead, what module(s) should I use? If not, what language should I experiment in? | Python 2.6 now includes the [**mulitprocessing**](http://docs.python.org/library/multiprocessing.html) module (formerly [**processing**](http://pyprocessing.berlios.de/doc/index.html) module on older versions of Python).
It has essentially the same interface as the **threading** module, but launches the execution into separate processes rather than threads. This allows Python to take advantage of multiple cores/CPUs and scales well for CPU-intensive tasks compared to the threading module approach. |
Python libraries to construct classes from a relational database? (ORM in reverse) | 535,426 | 3 | 2009-02-11T04:22:19Z | 535,437 | 11 | 2009-02-11T04:27:42Z | [
"python",
"database",
"orm"
] | Are there any Python object-relational mapping libraries that, given a database schema, can generate a set of Python classes? I know that the major libraries such as [SQLObject](http://www.sqlobject.org/), [SQLAlchemy](http://www.sqlalchemy.org/), and [Django](http://www.djangoproject.com/)'s internal SQL ORM library do a very good job of creating a DB schema given a set of classes, but I'm looking for a library that works in reverse.
There is a [related question for Perl libraries](http://stackoverflow.com/questions/362929/is-there-a-perl-orm-with-database-reverse-engineering) on Stack Overflow. | [SQLAlchemy extension to create a python code model from an existing database](http://code.google.com/p/sqlautocode/) |
C++ string parsing (python style) | 536,148 | 15 | 2009-02-11T09:49:23Z | 536,177 | 13 | 2009-02-11T09:59:21Z | [
"c++",
"python",
"parsing",
"string",
"text-files"
] | I love how in python I can do something like:
```
points = []
for line in open("data.txt"):
a,b,c = map(float, line.split(','))
points += [(a,b,c)]
```
Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas
How can this be done in C++ without too much headache?
Performance is not very important, this parsing only happens one time, so simplicity is more important.
P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,
it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things. | ```
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm> // For replace()
using namespace std;
struct Point {
double a, b, c;
};
int main(int argc, char **argv) {
vector<Point> points;
ifstream f("data.txt");
string str;
while (getline(f, str)) {
replace(str.begin(), str.end(), ',', ' ');
istringstream iss(str);
Point p;
iss >> p.a >> p.b >> p.c;
points.push_back(p);
}
// Do something with points...
return 0;
}
``` |
C++ string parsing (python style) | 536,148 | 15 | 2009-02-11T09:49:23Z | 536,224 | 7 | 2009-02-11T10:19:55Z | [
"c++",
"python",
"parsing",
"string",
"text-files"
] | I love how in python I can do something like:
```
points = []
for line in open("data.txt"):
a,b,c = map(float, line.split(','))
points += [(a,b,c)]
```
Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas
How can this be done in C++ without too much headache?
Performance is not very important, this parsing only happens one time, so simplicity is more important.
P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,
it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things. | This answer is based on the previous answer by j\_random\_hacker and makes use of Boost Spirit.
```
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/spirit.hpp>
using namespace std;
using namespace boost;
using namespace boost::spirit;
struct Point {
double a, b, c;
};
int main(int argc, char **argv)
{
vector<Point> points;
ifstream f("data.txt");
string str;
Point p;
rule<> point_p =
double_p[assign_a(p.a)] >> ','
>> double_p[assign_a(p.b)] >> ','
>> double_p[assign_a(p.c)] ;
while (getline(f, str))
{
parse( str, point_p, space_p );
points.push_back(p);
}
// Do something with points...
return 0;
}
``` |
C++ string parsing (python style) | 536,148 | 15 | 2009-02-11T09:49:23Z | 536,265 | 24 | 2009-02-11T10:33:17Z | [
"c++",
"python",
"parsing",
"string",
"text-files"
] | I love how in python I can do something like:
```
points = []
for line in open("data.txt"):
a,b,c = map(float, line.split(','))
points += [(a,b,c)]
```
Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas
How can this be done in C++ without too much headache?
Performance is not very important, this parsing only happens one time, so simplicity is more important.
P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,
it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things. | I`d do something like this:
```
ifstream f("data.txt");
string str;
while (getline(f, str)) {
Point p;
sscanf(str.c_str(), "%f, %f, %f\n", &p.x, &p.y, &p.z);
points.push_back(p);
}
```
x,y,z must be floats.
And include:
```
#include <iostream>
#include <fstream>
``` |
C++ string parsing (python style) | 536,148 | 15 | 2009-02-11T09:49:23Z | 536,431 | 16 | 2009-02-11T11:45:35Z | [
"c++",
"python",
"parsing",
"string",
"text-files"
] | I love how in python I can do something like:
```
points = []
for line in open("data.txt"):
a,b,c = map(float, line.split(','))
points += [(a,b,c)]
```
Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas
How can this be done in C++ without too much headache?
Performance is not very important, this parsing only happens one time, so simplicity is more important.
P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,
it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things. | All these good examples aside, in C++ you would normally override the `operator >>` for your point type to achieve something like this:
```
point p;
while (file >> p)
points.push_back(p);
```
or even:
```
copy(
istream_iterator<point>(file),
istream_iterator<point>(),
back_inserter(points)
);
```
The relevant implementation of the operator could look very much like the code by j\_random\_hacker. |
C++ string parsing (python style) | 536,148 | 15 | 2009-02-11T09:49:23Z | 768,898 | 13 | 2009-04-20T15:57:05Z | [
"c++",
"python",
"parsing",
"string",
"text-files"
] | I love how in python I can do something like:
```
points = []
for line in open("data.txt"):
a,b,c = map(float, line.split(','))
points += [(a,b,c)]
```
Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas
How can this be done in C++ without too much headache?
Performance is not very important, this parsing only happens one time, so simplicity is more important.
P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,
it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things. | The [C++ String Toolkit Library (StrTk)](http://www.partow.net/programming/strtk/index.html) has the following solution to your problem:
```
#include <string>
#include <deque>
#include "strtk.hpp"
struct point { double x,y,z; }
int main()
{
std::deque<point> points;
point p;
strtk::for_each_line("data.txt",
[&points,&p](const std::string& str)
{
strtk::parse(str,",",p.x,p.y,p.z);
points.push_back(p);
});
return 0;
}
```
More examples can be found [Here](http://www.codeproject.com/KB/recipes/Tokenizer.aspx) |
Python, Sqlite3 - How to convert a list to a BLOB cell | 537,077 | 8 | 2009-02-11T14:38:06Z | 539,636 | 17 | 2009-02-12T01:27:31Z | [
"python",
"sqlite"
] | What is the most elegant method for dumping a list in python into an sqlite3 DB as binary data (i.e., a BLOB cell)?
```
data = [ 0, 1, 2, 3, 4, 5 ]
# now write this to db as binary data
# 0000 0000
# 0000 0001
# ...
# 0000 0101
``` | It seems that Brian's solution fits your needs, but keep in mind that with that method your just storing the data as a string.
If you want to store the raw binary data into the database (so it doesn't take up as much space), convert your data to a **Binary** sqlite object and then add it to your database.
```
query = u'''insert into testtable VALUES(?)'''
b = sqlite3.Binary(some_binarydata)
cur.execute(query,(b,))
con.commit()
```
(For some reason this doesn't seem to be documented in the python documentation)
Here are some notes on sqlite BLOB data restrictions:
<http://effbot.org/zone/sqlite-blob.htm> |
Reserve memory for list in Python? | 537,086 | 30 | 2009-02-11T14:41:14Z | 537,134 | 11 | 2009-02-11T14:49:25Z | [
"python",
"performance",
"arrays",
"memory-management",
"list"
] | When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.
Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate **all** objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists? | you can create list of the known length like this:
```
>>> [None] * known_number
``` |
Reserve memory for list in Python? | 537,086 | 30 | 2009-02-11T14:41:14Z | 537,405 | 26 | 2009-02-11T15:47:29Z | [
"python",
"performance",
"arrays",
"memory-management",
"list"
] | When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.
Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate **all** objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists? | Here's four variants:
* an incremental list creation
* "pre-allocated" list
* array.array()
* numpy.zeros()
```
python -mtimeit -s"N=10**6" "a = []; app = a.append;"\
"for i in xrange(N): app(i);"
10 loops, best of 3: 390 msec per loop
python -mtimeit -s"N=10**6" "a = [None]*N; app = a.append;"\
"for i in xrange(N): a[i] = i"
10 loops, best of 3: 245 msec per loop
python -mtimeit -s"from array import array; N=10**6" "a = array('i', [0]*N)"\
"for i in xrange(N):" " a[i] = i"
10 loops, best of 3: 541 msec per loop
python -mtimeit -s"from numpy import zeros; N=10**6" "a = zeros(N,dtype='i')"\
"for i in xrange(N):" " a[i] = i"
10 loops, best of 3: 353 msec per loop
```
It shows that `[None]*N` is the fastest and `array.array` is the slowest in this case. |
Reserve memory for list in Python? | 537,086 | 30 | 2009-02-11T14:41:14Z | 13,865,566 | 7 | 2012-12-13T17:52:13Z | [
"python",
"performance",
"arrays",
"memory-management",
"list"
] | When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several times while building it? I've looked through the docs for a Python list type, and have not found anything that seems to do this. However, this type of list building shows up in a few hotspots of my code, so I want to make it as efficient as possible.
Edit: Also, does it even make sense to do something like this in a language like Python? I'm a fairly experienced programmer, but new to Python and still getting a feel for its way of doing things. Does Python internally allocate **all** objects in separate heap spaces, defeating the purpose of trying to minimize allocations, or are primitives like ints, floats, etc. stored directly in lists? | Take a look at this:
```
In [7]: %timeit array.array('f', [0.0]*4000*1000)
1 loops, best of 3: 306 ms per loop
In [8]: %timeit array.array('f', [0.0])*4000*1000
100 loops, best of 3: 5.96 ms per loop
In [11]: %timeit np.zeros(4000*1000, dtype='f')
100 loops, best of 3: 6.04 ms per loop
In [9]: %timeit [0.0]*4000*1000
10 loops, best of 3: 32.4 ms per loop
```
So don't ever use `array.array('f', [0.0]*N)`, use `array.array('f', [0.0])*N` or `numpy.zeros`. |
Standard python interpreter has a vi command mode? | 537,522 | 20 | 2009-02-11T16:11:44Z | 537,633 | 24 | 2009-02-11T16:32:38Z | [
"python",
"vi"
] | this is going to sound pretty ignorant, but:
I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x...
I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?).
Can anyone shed some light on how to enable this mode in the interpreter? | This kind of all depends on a few things.
First of all, the python shell uses readline, and as such, your `~/.inputrc` is important here. That's the same with psql the PostgreSQL command-line interpreter and mysql the MySQL shell. All of those can be configured to use vi-style command bindings, with history etc.
`<ESC>` will put you into vi mode at the python shell once you've got your editing mode set to vi
You may need the following definition in your `~/.inputrc`
```
set editing-mode vi
```
**OSX info**
OSX uses libedit which uses ~/.editrc. You can *man editrc* for more information.
For example, to mimick a popular key combination which searches in your history, you can add the following to your .editrc
```
bind "^R" em-inc-search-prev
``` |
Standard python interpreter has a vi command mode? | 537,522 | 20 | 2009-02-11T16:11:44Z | 538,573 | 18 | 2009-02-11T20:18:07Z | [
"python",
"vi"
] | this is going to sound pretty ignorant, but:
I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x...
I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?).
Can anyone shed some light on how to enable this mode in the interpreter? | Ctrl-Alt-J switches from Emacs mode to Vi mode in [readline programs](http://tiswww.case.edu/php/chet/readline/rluserman.html#SEC22).
Alternatively add "set editing-mode vi" to your ~/.inputrc |
How can I create multiple hashes of a file using only one pass? | 537,542 | 6 | 2009-02-11T16:17:38Z | 537,585 | 15 | 2009-02-11T16:25:24Z | [
"python",
"hash"
] | How can I get a MD5, SHA and other hashes from a file but only doing one pass? I have 100mb files, so I'd hate to process those 100MB files multiple times. | Something like this perhaps?
```
>>> import hashlib
>>> hashes = (hashlib.md5(), hashlib.sha1())
>>> f = open('some_file', 'r')
>>> for line in f:
... for hash in hashes:
... hash.update(line)
...
>>> for hash in hashes:
... print hash.name, hash.hexdigest()
```
or loop over f.read(1024) or something like that to get fixed-length blocks |
Python IDE built into Visual Studio 2008? | 537,689 | 16 | 2009-02-11T16:42:09Z | 537,761 | 8 | 2009-02-11T16:55:48Z | [
"python",
"visual-studio-2008",
"ide"
] | Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET.
If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love)
Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name.
I installed integrated and got this: <http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png> :( no console like here: <http://www.codeplex.com/IronPythonStudio> | Have a look at [PyScripter](http://code.google.com/p/pyscripter/), I haven't tried it extensively but heard good things about it.
It's not an addon to Visual Studio, it's an independent IDE. |
Iterating over a string | 538,346 | 282 | 2009-02-11T19:22:15Z | 538,352 | 65 | 2009-02-11T19:24:12Z | [
"python",
"string",
"iteration"
] | In C++, I could do:
```
for (int i = 0; i < str.length(); ++i)
std::cout << str[i] << std::endl;
```
How do I iterate over a string in Python? | Even easier:
```
for c in "test":
print c
``` |
Iterating over a string | 538,346 | 282 | 2009-02-11T19:22:15Z | 538,374 | 213 | 2009-02-11T19:30:23Z | [
"python",
"string",
"iteration"
] | In C++, I could do:
```
for (int i = 0; i < str.length(); ++i)
std::cout << str[i] << std::endl;
```
How do I iterate over a string in Python? | As Johannes pointed out,
```
for c in "string":
#do something with c
```
You can iterate pretty much anything in python using the `for loop` construct,
for example, `open("file.txt")` returns a file object (and opens the file), iterating over it iterates over lines in that file
```
for line in open(filename):
# do something with line
```
If that seems like magic, well it kinda is, but the idea behind it is really simple.
There's a simple iterator protocol that can be applied to any kind of object to make the `for` loop work on it.
Simply implement an iterator that defines a `next()` method, and implement an `__iter__` method on a class to make it iterable. (the `__iter__` of course, should return an iterator object, that is, an object that defines `next()`)
[See official documentation](http://docs.python.org/library/stdtypes.html#iterator-types) |
Iterating over a string | 538,346 | 282 | 2009-02-11T19:22:15Z | 555,631 | 24 | 2009-02-17T05:36:55Z | [
"python",
"string",
"iteration"
] | In C++, I could do:
```
for (int i = 0; i < str.length(); ++i)
std::cout << str[i] << std::endl;
```
How do I iterate over a string in Python? | Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.
```
i = 0
while i < len(str):
print str[i]
i += 1
```
But then again, why do that when strings are inherently iterable?
```
for i in str:
print i
``` |
Iterating over a string | 538,346 | 282 | 2009-02-11T19:22:15Z | 4,547,728 | 169 | 2010-12-28T16:54:32Z | [
"python",
"string",
"iteration"
] | In C++, I could do:
```
for (int i = 0; i < str.length(); ++i)
std::cout << str[i] << std::endl;
```
How do I iterate over a string in Python? | If you need access to the index as you iterate through the string, use [`enumerate()`](http://docs.python.org/library/functions.html#enumerate):
```
>>> for i, c in enumerate('test'):
... print i, c
...
0 t
1 e
2 s
3 t
``` |
Handling very large numbers in Python | 538,551 | 48 | 2009-02-11T20:13:45Z | 538,571 | 13 | 2009-02-11T20:18:04Z | [
"python",
"optimization",
"largenumber"
] | I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:
```
class PokerCard:
faces = '23456789TJQKA'
suits = 'cdhs'
facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61]
suitPrimes = [2, 3, 5, 7]
```
AND
```
def HashVal(self):
return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit]
```
This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.
The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it? | python supports arbitrarily large integers naturally:
```
In [1]: 59**3*61**4*2*3*5*7*3*5*7
Out[1]: 62702371781194950
In [2]: _ % 61**4
Out[2]: 0
``` |
Handling very large numbers in Python | 538,551 | 48 | 2009-02-11T20:13:45Z | 538,583 | 71 | 2009-02-11T20:19:45Z | [
"python",
"optimization",
"largenumber"
] | I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:
```
class PokerCard:
faces = '23456789TJQKA'
suits = 'cdhs'
facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61]
suitPrimes = [2, 3, 5, 7]
```
AND
```
def HashVal(self):
return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit]
```
This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.
The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it? | Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called `long` and is separate from the `int` type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the `int` type has been dropped completely.
That's just an implementation detail, though â as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.
You can find all the gory details in [PEP 0237](http://www.python.org/dev/peps/pep-0237). |
Handling very large numbers in Python | 538,551 | 48 | 2009-02-11T20:13:45Z | 538,797 | 19 | 2009-02-11T21:07:15Z | [
"python",
"optimization",
"largenumber"
] | I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:
```
class PokerCard:
faces = '23456789TJQKA'
suits = 'cdhs'
facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61]
suitPrimes = [2, 3, 5, 7]
```
AND
```
def HashVal(self):
return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit]
```
This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.
The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it? | You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.
* Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.
* Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.
* The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing. |
Handling very large numbers in Python | 538,551 | 48 | 2009-02-11T20:13:45Z | 20,980,470 | 21 | 2014-01-07T19:50:08Z | [
"python",
"optimization",
"largenumber"
] | I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:
```
class PokerCard:
faces = '23456789TJQKA'
suits = 'cdhs'
facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61]
suitPrimes = [2, 3, 5, 7]
```
AND
```
def HashVal(self):
return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit]
```
This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.
The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it? | python supports ***arbitrarily*** large ***integers*** naturally:
example:
> **>>>** 10\*\*1000 100000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 00000000000000000000000000000000000000000000000000000000000000000
You could even get, for example of a huge integer value, fib(4000000).
But still it does **not** (for now) supports an arbitrarily large **float** !!
If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: [OverflowError: (34, 'Result too large')](http://stackoverflow.com/questions/20201706/overflowerror-34-result-too-large)
Another reference: <http://docs.python.org/2/library/decimal.html>
You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): [Handling big numbers in code](http://stackoverflow.com/questions/1386604/handling-big-numbers-in-code)
Another reference: <https://code.google.com/p/gmpy/> |
Python format timedelta to string | 538,666 | 125 | 2009-02-11T20:40:43Z | 538,687 | 29 | 2009-02-11T20:44:39Z | [
"python",
"string",
"datetime",
"format",
"timedelta"
] | I'm a Python newbie (2 weeks) and I'm having trouble formatting a `datetime.timedelta` object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using `Google AppEngine` with `Django Templates` for presentation.
If anyone can help or knows of a better way to resolve this, I would be very happy.
Thanks, | ```
>>> str(datetime.timedelta(hours=10.56))
10:33:36
>>> td = datetime.timedelta(hours=10.505) # any timedelta object
>>> ':'.join(str(td).split(':')[:2])
10:30
```
Passing the `timedelta` object to the `str()` function calls the same formatting code used if we simply type `print td`. Since you don't want the seconds, we can split the string by colons (3 parts) and put it back together with only the first 2 parts. |
Python format timedelta to string | 538,666 | 125 | 2009-02-11T20:40:43Z | 538,721 | 119 | 2009-02-11T20:52:24Z | [
"python",
"string",
"datetime",
"format",
"timedelta"
] | I'm a Python newbie (2 weeks) and I'm having trouble formatting a `datetime.timedelta` object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using `Google AppEngine` with `Django Templates` for presentation.
If anyone can help or knows of a better way to resolve this, I would be very happy.
Thanks, | You can just convert the timedelta to a string with str(). Here's an example:
```
import datetime
start = datetime.datetime(2009,2,10,14,00)
end = datetime.datetime(2009,2,10,16,00)
delta = end-start
print str(delta)
# prints 2:00:00
``` |
Python format timedelta to string | 538,666 | 125 | 2009-02-11T20:40:43Z | 539,360 | 116 | 2009-02-11T23:34:33Z | [
"python",
"string",
"datetime",
"format",
"timedelta"
] | I'm a Python newbie (2 weeks) and I'm having trouble formatting a `datetime.timedelta` object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using `Google AppEngine` with `Django Templates` for presentation.
If anyone can help or knows of a better way to resolve this, I would be very happy.
Thanks, | As you know, you can get the seconds from a timedelta object by accessing the `.seconds` attribute.
You can convert that to hours and remainder by using a combination of modulo and subtraction:
```
# arbitrary number of seconds
s = 13420
# hours
hours = s // 3600
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
# total time
print '%s:%s:%s' % (hours, minutes, seconds)
# result: 3:43:40
```
However, python provides the builtin function divmod() which allows us to simplify this code:
```
s = 13420
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
print '%s:%s:%s' % (hours, minutes, seconds)
# result: 3:43:40
```
Hope this helps! |
Python format timedelta to string | 538,666 | 125 | 2009-02-11T20:40:43Z | 1,644,095 | 9 | 2009-10-29T14:23:22Z | [
"python",
"string",
"datetime",
"format",
"timedelta"
] | I'm a Python newbie (2 weeks) and I'm having trouble formatting a `datetime.timedelta` object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using `Google AppEngine` with `Django Templates` for presentation.
If anyone can help or knows of a better way to resolve this, I would be very happy.
Thanks, | My `datetime.timedelta` objects went greater than a day. So here is a further problem. All the discussion above assumes less than a day. A `timedelta` is actually a tuple of days, seconds and microseconds. The above discussion should use `td.seconds` as joe did, but if you have days it is NOT included in the seconds value.
I am getting a span of time between 2 datetimes and printing days and hours.
```
span = currentdt - previousdt
print '%d,%d\n' % (span.days,span.seconds/3600)
``` |
Python format timedelta to string | 538,666 | 125 | 2009-02-11T20:40:43Z | 13,756,038 | 20 | 2012-12-07T02:24:53Z | [
"python",
"string",
"datetime",
"format",
"timedelta"
] | I'm a Python newbie (2 weeks) and I'm having trouble formatting a `datetime.timedelta` object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using `Google AppEngine` with `Django Templates` for presentation.
If anyone can help or knows of a better way to resolve this, I would be very happy.
Thanks, | ```
def td_format(td_object):
seconds = int(td_object.total_seconds())
periods = [
('year', 60*60*24*365),
('month', 60*60*24*30),
('day', 60*60*24),
('hour', 60*60),
('minute', 60),
('second', 1)
]
strings=[]
for period_name,period_seconds in periods:
if seconds > period_seconds:
period_value , seconds = divmod(seconds,period_seconds)
if period_value == 1:
strings.append("%s %s" % (period_value, period_name))
else:
strings.append("%s %ss" % (period_value, period_name))
return ", ".join(strings)
``` |
Python format timedelta to string | 538,666 | 125 | 2009-02-11T20:40:43Z | 14,247,500 | 9 | 2013-01-09T22:16:26Z | [
"python",
"string",
"datetime",
"format",
"timedelta"
] | I'm a Python newbie (2 weeks) and I'm having trouble formatting a `datetime.timedelta` object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using `Google AppEngine` with `Django Templates` for presentation.
If anyone can help or knows of a better way to resolve this, I would be very happy.
Thanks, | Questioner wants a nicer format than the typical:
```
>>> import datetime
>>> datetime.timedelta(seconds=41000)
datetime.timedelta(0, 41000)
>>> str(datetime.timedelta(seconds=41000))
'11:23:20'
>>> str(datetime.timedelta(seconds=4102.33))
'1:08:22.330000'
>>> str(datetime.timedelta(seconds=413302.33))
'4 days, 18:48:22.330000'
```
So, really there's two formats, one where days are 0 and it's left out, and another where there's text "n days, h:m:s". But, the seconds may have fractions, and there's no leading zeroes in the printouts, so columns are messy.
Here's my routine, if you like it:
```
def printNiceTimeDelta(stime, etime):
delay = datetime.timedelta(seconds=(etime - stime))
if (delay.days > 0):
out = str(delay).replace(" days, ", ":")
else:
out = "0:" + str(delay)
outAr = out.split(':')
outAr = ["%02d" % (int(float(x))) for x in outAr]
out = ":".join(outAr)
return out
```
this returns output as dd:hh:mm:ss format:
```
00:00:00:15
00:00:00:19
02:01:31:40
02:01:32:22
```
I did think about adding years to this, but this is left as an exercise for the reader, since the output is safe at over 1 year:
```
>>> str(datetime.timedelta(seconds=99999999))
'1157 days, 9:46:39'
``` |
Python format timedelta to string | 538,666 | 125 | 2009-02-11T20:40:43Z | 17,195,550 | 9 | 2013-06-19T15:41:24Z | [
"python",
"string",
"datetime",
"format",
"timedelta"
] | I'm a Python newbie (2 weeks) and I'm having trouble formatting a `datetime.timedelta` object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using `Google AppEngine` with `Django Templates` for presentation.
If anyone can help or knows of a better way to resolve this, I would be very happy.
Thanks, | He already has a timedelta object so why not use its built-in method total\_seconds() to convert it to seconds, then use divmod() to get hours and minutes?
```
hours, remainder = divmod(myTimeDelta.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
# Formatted only for hours and minutes as requested
print '%s:%s' % (hours, minutes)
```
This works regardless if the time delta has even days or years. |
Return a tuple of arguments to be fed to string.format() | 539,066 | 21 | 2009-02-11T22:10:10Z | 539,106 | 53 | 2009-02-11T22:20:47Z | [
"python",
"string-formatting",
"tuples"
] | Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter, and then pass them to the string method. My code looks something like this:
```
class PairEvaluator(HandEvaluator):
def returnArbitrary(self):
return ('ace', 'king')
pe = PairEvaluator()
cards = pe.returnArbitrary()
print('Two pair, {0}s and {1}s'.format(cards))
```
When I try to run this code, the compiler gives an IndexError: tuple index out of range.
How should I structure my return value to pass it as an argument to `.format()`? | ```
print('Two pair, {0}s and {1}s'.format(*cards))
```
You are missing only the star :D |
Python 3.0 urllib.parse error "Type str doesn't support the buffer API" | 540,342 | 21 | 2009-02-12T07:24:05Z | 542,080 | 25 | 2009-02-12T16:14:50Z | [
"python",
"cgi",
"python-3.x",
"urllib"
] | ```
File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__
self.read_urlencoded()
File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded
self.strict_parsing):
File "/usr/local/lib/python3.0/urllib/parse.py", line 377, in parse_qsl
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
TypeError: Type str doesn't support the buffer API
```
Can anybody direct me on how to avoid this? I'm getting it through feeding data into the `cgi.Fieldstorage` and I can't seem to do it any other way. | urllib is trying to do:
```
b'a,b'.split(',')
```
Which doesn't work. byte strings and unicode strings mix even less smoothly in Py3k than they used toâââdeliberately, to make encoding problems go wrong sooner rather than later.
So the error is rather opaquely telling you âyou can't pass a byte string to urllib.parseâ. Presumably you are doing a POST request, where the form-encoded string is coming into cgi as a content body; the content body is still a byte string/stream so it now clashes with the new urllib.
So yeah, it's a bug in cgi.py, yet another victim of 2to3 conversion that hasn't been fixed properly for the new string model. It should be converting the incoming byte stream to characters before passing them to urllib.
Did I mention Python 3.0's libraries (especially web-related ones) still being rather shonky? :-) |
Python 3.0 urllib.parse error "Type str doesn't support the buffer API" | 540,342 | 21 | 2009-02-12T07:24:05Z | 2,159,263 | 14 | 2010-01-29T01:13:39Z | [
"python",
"cgi",
"python-3.x",
"urllib"
] | ```
File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__
self.read_urlencoded()
File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded
self.strict_parsing):
File "/usr/local/lib/python3.0/urllib/parse.py", line 377, in parse_qsl
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
TypeError: Type str doesn't support the buffer API
```
Can anybody direct me on how to avoid this? I'm getting it through feeding data into the `cgi.Fieldstorage` and I can't seem to do it any other way. | From the python tutorial ( <http://www.python.org/doc/3.0/tutorial/stdlib.html> ) there is an example of using urlopen method. It raises the same error.
```
for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
if 'EST' in line or 'EDT' in line: # look for Eastern Time
print(line)
```
You'll need to use the str function to convert the byte thingo to a string with the correct encoding. As follows:
```
for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
lineStr = str( line, encoding='utf8' )
if 'EST' in lineStr or 'EDT' in lineStr: # look for Eastern Time
print(lineStr)
``` |
C to Python via SWIG: can't get void** parameters to hold their value | 540,427 | 7 | 2009-02-12T08:04:16Z | 541,566 | 7 | 2009-02-12T14:46:30Z | [
"python",
"c",
"swig",
"wrapping"
] | I have a C interface that looks like this (simplified):
```
extern bool Operation(void ** ppData);
extern float GetFieldValue(void* pData);
extern void Cleanup(p);
```
which is used as follows:
```
void * p = NULL;
float theAnswer = 0.0f;
if (Operation(&p))
{
theAnswer = GetFieldValue(p);
Cleanup(p);
}
```
You'll note that Operation() allocates the buffer p, that GetFieldValue queries p, and that Cleanup frees p. I don't have any control over the C interface -- that code is widely used elsewhere.
I'd like to call this code from Python via [SWIG](http://www.swig.org/), but I was unable to find any good examples of how to pass a pointer to a pointer -- and retrieve its value.
I think the correct way to do this is by use of typemaps, so I defined an interface that would automatically dereference p for me on the C side:
```
%typemap(in) void** {
$1 = (void**)&($input);
}
```
However, I was unable to get the following python code to work:
```
import test
p = None
theAnswer = 0.0f
if test.Operation(p):
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)
```
After calling test.Operation(), p always kept its initial value of None.
Any help with figuring out the correct way to do this in SWIG would be much appreciated. Otherwise, I'm likely to just write a C++ wrapper around the C code that stops Python from having to deal with the pointer. And then wrap *that* wrapper with SWIG. Somebody stop me!
Edit:
Thanks to [Jorenko](http://stackoverflow.com/users/7161/jorenko), I now have the following SWIG interface:
```
% module Test
%typemap (in,numinputs=0) void** (void *temp)
{
$1 = &temp;
}
%typemap (argout) void**
{
PyObject *obj = PyCObject_FromVoidPtr(*$1, Cleanup);
$result = PyTuple_Pack(2, $result, obj);
}
%{
extern bool Operation(void ** ppData);
extern float GetFieldValue(void *p);
extern void Cleanup(void *p);
%}
%inline
%{
float gfv(void *p){ return GetFieldValue(p);}
%}
%typemap (in) void*
{
if (PyCObject_Check($input))
{
$1 = PyCObject_AsVoidPtr($input);
}
}
```
The python code that uses this SWIG interface is as follows:
```
import test
success, p = test.Operation()
if success:
f = test.GetFieldValue(p) # This doesn't work
f = test.gvp(p) # This works!
test.Cleanup(p)
```
Oddly, in the python code, test.GetFieldValue(p) returns gibberish, but test.gfv(p) returns the correct value. I've inserting debugging code into the typemap for void\*, and both have the same value of p! The call Any ideas about that?
**Update:** I've decided to use ctypes. MUCH easier. | I agree with theller, you should use ctypes instead. It's always easier than thinking about typemaps.
But, if you're dead set on using swig, what you need to do is make a typemap for `void**` that RETURNS the newly allocated `void*`:
```
%typemap (in,numinputs=0) void** (void *temp)
{
$1 = &temp;
}
%typemap (argout) void**
{
PyObject *obj = PyCObject_FromVoidPtr(*$1);
$result = PyTuple_Pack(2, $result, obj);
}
```
Then your python looks like:
```
import test
success, p = test.Operation()
theAnswer = 0.0f
if success:
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)
```
Edit:
I'd expect swig to handle a simple by-value `void*` arg gracefully on its own, but just in case, here's swig code to wrap the `void*` for GetFieldValue() and Cleanup():
```
%typemap (in) void*
{
$1 = PyCObject_AsVoidPtr($input);
}
``` |
Specify a sender when sending mail with Python (smtplib) | 540,976 | 4 | 2009-02-12T11:52:40Z | 541,020 | 11 | 2009-02-12T12:16:10Z | [
"python",
"email"
] | I have a very simple piece of code (just for testing):
```
import smtplib
import time
server = 'smtp.myprovider.com'
recipients = ['[email protected]']
sender = '[email protected]'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
```
This works but the problem is that e-mail clients don't display a sender.
I want to be able to add a sender name to the e-mail. Suggestions? | You can utilize the [email.message.Message](http://docs.python.org/library/email.message.html#email.message.Message) class, and use it to generate mime headers, including `from:`, `to:` and `subject`. Send the `as_string()` result via SMTP.
```
>>> from email import message
>>> m1=message.Message()
>>> m1.add_header('from','[email protected]')
>>> m1.add_header('to','[email protected]')
>>> m1.add_header('subject','test')
>>> m1.set_payload('test\n')
>>> m1.as_string()
'from: [email protected]\nto: [email protected]\nsubject: test\n\ntest\n'
>>>
``` |
Specify a sender when sending mail with Python (smtplib) | 540,976 | 4 | 2009-02-12T11:52:40Z | 541,030 | 7 | 2009-02-12T12:22:54Z | [
"python",
"email"
] | I have a very simple piece of code (just for testing):
```
import smtplib
import time
server = 'smtp.myprovider.com'
recipients = ['[email protected]']
sender = '[email protected]'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
```
This works but the problem is that e-mail clients don't display a sender.
I want to be able to add a sender name to the e-mail. Suggestions? | The "sender" you're specifying in this case is the envelope sender that is passed onto the SMTP server.
What your MUA (Mail User Agent - i.e. outlook/Thunderbird etc.) shows you is the "From:" header.
Normally, if I'm using smtplib, I'd compile the headers separately:
```
headers = "From: %s\nTo: %s\n\n" % (email_from, email_to)
```
The format of the From header is by convention normally `"Name" <user@domain>`
You should be including a "Message-Id" header and a "Reply-To" header as well in all communications. Especially since spam filters may pick up on the lack of these as a great probability that the mail is spam.
If you've got your mail body in the variable body, just compile the overall message with:
```
message = headers + body
```
Note the double newline at the end of the headers. It's also worth noting that SMTP servers should separate headers with newlines only (i.e. LF - linfeed). However, I have seen a Windows SMTP server or two that uses \r\n (i.e. CRLF). If you're on Windows, YMMV. |
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code? | 541,329 | 20 | 2009-02-12T13:53:02Z | 541,397 | 9 | 2009-02-12T14:13:19Z | [
"python",
"serialization",
"stack",
"continuations",
"python-stackless"
] | Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario:
1. You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine.
2. A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort.
3. You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine.
4. The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later.
5. In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script.
6. The event dispatching engine fires the event that the wait condition picks up.
7. The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called.
**The Question**
Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code?
**Edit:** To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one.
**Update:** From some initial investigation, one can get the execution context with `PyThreadState_Get()`. This returns the thread state in a `PyThreadState` (defined in `pystate.h`), which has a reference to the stack frame in `frame`. A stack frame is held in a struct typedef'd to `PyFrameObject`, which is defined in `frameobject.h`. `PyFrameObject` has a field `f_lasti` (props to [bobince](http://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529)) which has a program counter expressed as an offset from the beginning of the code block.
This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter.
The three remaining problems are:
* Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished.
* Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading `__locals__` (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here.
* Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor
In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability.
**Update 2:** `PyCodeObject` (`code.h`) has a list of addr (`f_lasti`)-> line number mappings in `PyCodeObject.co_lnotab` (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising.
**Update 3:** I think the answer to this might be [Stackless Python.](http://www.stackless.com) You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well. | The expat python bindings included in the normal Python distribution is constructing stack frames programtically. Be warned though, it relies on undocumented and private APIs.
<http://svn.python.org/view/python/trunk/Modules/pyexpat.c?rev=64048&view=auto> |
Extracting extension from filename in Python | 541,390 | 599 | 2009-02-12T14:11:50Z | 541,394 | 970 | 2009-02-12T14:12:46Z | [
"python",
"filenames",
"file-extension"
] | Is there a function to extract the extension from a filename? | Yes. Use [`os.path.splitext`](https://docs.python.org/2/library/os.path.html#os.path.splitext):
```
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
``` |
Extracting extension from filename in Python | 541,390 | 599 | 2009-02-12T14:11:50Z | 541,408 | 234 | 2009-02-12T14:15:07Z | [
"python",
"filenames",
"file-extension"
] | Is there a function to extract the extension from a filename? | ```
import os.path
extension = os.path.splitext(filename)[1]
``` |
Extracting extension from filename in Python | 541,390 | 599 | 2009-02-12T14:11:50Z | 7,202,805 | 58 | 2011-08-26T09:37:47Z | [
"python",
"filenames",
"file-extension"
] | Is there a function to extract the extension from a filename? | ```
import os.path
extension = os.path.splitext(filename)[1][1:]
```
To get only text extension |
Extracting extension from filename in Python | 541,390 | 599 | 2009-02-12T14:11:50Z | 7,719,562 | 7 | 2011-10-10T22:48:43Z | [
"python",
"filenames",
"file-extension"
] | Is there a function to extract the extension from a filename? | Any of the solutions above work, but on linux I have found that there is a newline at the end of the extension string which will prevent matches from succeeding. Add the `strip()` method to the end. For example:
```
import os.path
extension = os.path.splitext(filename)[1][1:].strip()
``` |
Extracting extension from filename in Python | 541,390 | 599 | 2009-02-12T14:11:50Z | 10,078,116 | 38 | 2012-04-09T18:48:16Z | [
"python",
"filenames",
"file-extension"
] | Is there a function to extract the extension from a filename? | One option may be splitting from dot:
```
>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'
```
No error when file doesn't have an extension:
```
>>> "filename".split(".")[-1]
'filename'
```
But you must be careful:
```
>>> "png".split(".")[-1]
'png' # But file doesn't have an extension
``` |
Extracting extension from filename in Python | 541,390 | 599 | 2009-02-12T14:11:50Z | 14,066,130 | 21 | 2012-12-28T07:25:49Z | [
"python",
"filenames",
"file-extension"
] | Is there a function to extract the extension from a filename? | worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.
```
os.path.splitext(filename)[1][1:].strip().lower()
``` |
Extracting extension from filename in Python | 541,390 | 599 | 2009-02-12T14:11:50Z | 35,188,296 | 13 | 2016-02-03T21:41:25Z | [
"python",
"filenames",
"file-extension"
] | Is there a function to extract the extension from a filename? | I'm surprised no one has mentioned [`pathlib`](https://docs.python.org/3/library/pathlib.html) yet, `pathlib` IS awesome!
**NOTE:** You require to have Python 3.4 at least though!
```
import pathlib
print(pathlib.Path('yourPathGoesHere').suffix)
```
And if you want to get all the suffixes (for instance if you have a `.tar.gz`), `.suffixes` will return a list of them! Neat! |
How to do variable assignment inside a while(expression) loop in Python? | 542,212 | 12 | 2009-02-12T16:44:14Z | 542,224 | 8 | 2009-02-12T16:48:34Z | [
"python",
"syntax",
"while-loop",
"expression"
] | I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.
Here is how I'm doing it in PHP:
```
while((name = raw_input("Name: ")) != ''):
names.append(name)
```
What I'm trying to do is identical to this in functionality:
```
names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
```
Is there any way to do this in Python? | No, sorry. It's a FAQ, explained well here:
In [Pydocs](http://docs.python.org/faq/design.html#why-can-t-i-use-an-assignment-in-an-expression "http://docs.python.org/faq/design.html#why-can-t-i-use-an-assignment-in-an-expression"), and [Fredrik Lundh's blog](http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm "http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm").
> The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages.
>
> Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.
>
> An interesting phenomenon is that most experienced Python programmers recognize the `while True` idiom and donât seem to be missing the assignment in expression construct much; itâs only newcomers who express a strong desire to add this to the language.
>
> Thereâs an alternative way of spelling this that seems attractive:
>
> ```
> line = f.readline() while line:
> ... # do something with line...
> line = f.readline()
> ``` |
How to do variable assignment inside a while(expression) loop in Python? | 542,212 | 12 | 2009-02-12T16:44:14Z | 542,227 | 12 | 2009-02-12T16:49:06Z | [
"python",
"syntax",
"while-loop",
"expression"
] | I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.
Here is how I'm doing it in PHP:
```
while((name = raw_input("Name: ")) != ''):
names.append(name)
```
What I'm trying to do is identical to this in functionality:
```
names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
```
Is there any way to do this in Python? | You can wrap `raw_input()` to turn it into a generator:
```
def wrapper(s):
while True:
result = raw_input(s)
if result = '': break
yield result
names = wrapper('Name:')
```
which means we're back to square one but with more complex code. So if you need to wrap an existing method, you need to use [nosklo](http://stackoverflow.com/users/17160/nosklo)'s approach. |
How to do variable assignment inside a while(expression) loop in Python? | 542,212 | 12 | 2009-02-12T16:44:14Z | 544,564 | 14 | 2009-02-13T02:58:59Z | [
"python",
"syntax",
"while-loop",
"expression"
] | I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.
Here is how I'm doing it in PHP:
```
while((name = raw_input("Name: ")) != ''):
names.append(name)
```
What I'm trying to do is identical to this in functionality:
```
names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
```
Is there any way to do this in Python? | ```
from functools import partial
for name in iter(partial(raw_input, 'Name:'), ''):
do_something_with(name)
```
or if you want a list:
```
>>> names = list(iter(partial(raw_input, 'Name: '), ''))
Name: nosklo
Name: Andreas
Name: Aaron
Name: Phil
Name:
>>> names
['nosklo', 'Andreas', 'Aaron', 'Phil']
``` |
Are there any good build frameworks written in Python? | 542,289 | 14 | 2009-02-12T16:59:28Z | 542,309 | 20 | 2009-02-12T17:01:59Z | [
"python",
"build-process",
"build-automation"
] | I switched from NAnt to using Python to write build automation scripts. I am curious if whether any build frameworks worth using that are similar to Make, Ant, and NAnt, but, instead, are Python-based. For example, Ruby has Rake. What about Python? | Try [SCons](http://www.scons.org/)
Or are you looking for something just to build python projects? |
Should I use Django's contrib applications or build my own? | 542,594 | 3 | 2009-02-12T18:10:45Z | 542,685 | 7 | 2009-02-12T18:34:34Z | [
"python",
"django",
"django-contrib"
] | The Django apps come with their own features and design. If your requirements don't match 100% with the features of the contib app, you end up customizing and tweaking the app. I feel this involves more effort than just building your own app to fit your requirements.
What do you think? | It all depends. We had a need for something that was 98% similar to contrib.flatpages. We could have monkeypatched it, but we decided that the code was so straightforward that we would just copy and fork it. It worked out fine.
Doing this with contrib.auth, on the other hand, might be a bad move given its interaction with contrib.admin & contrib.session. |
Benefits of os.path.splitext over regular .split? | 542,596 | 23 | 2009-02-12T18:10:51Z | 542,614 | 10 | 2009-02-12T18:16:40Z | [
"python"
] | In [this other question](http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python), the votes clearly show that the `os.path.splitext` function is preferred over the simple `.split('.')[-1]` string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?
EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage. | os.path.splitext will correctly handle the situation where the file has no extension and return an empty string. .split will return the name of the file. |
Benefits of os.path.splitext over regular .split? | 542,596 | 23 | 2009-02-12T18:10:51Z | 542,619 | 28 | 2009-02-12T18:17:46Z | [
"python"
] | In [this other question](http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python), the votes clearly show that the `os.path.splitext` function is preferred over the simple `.split('.')[-1]` string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?
EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage. | Well, there are separate implementations for separate operating systems. This means that if the logic to extract the extension of a file differs on Mac from that on Linux, this distinction will be handled by those things. I don't know of any such distinction so there might be none.
---
**Edit**: [@Brian](http://stackoverflow.com/users/9493/brian) comments that an example like `/directory.ext/file` would of course not work with a simple `.split('.')` call, and you would have to know both that directories can use extensions, as well as the fact that on some operating systems, forward slash is a valid directory separator.
This just emphasizes the *use a library routine unless you have a good reason not to* part of my answer.
Thanks [@Brian](http://stackoverflow.com/users/9493/brian).
---
Additionally, where a file doesn't have an extension, you would have to build in logic to handle that case. And what if the thing you try to split is a directory name ending with a backslash? No filename nor an extension.
The rule should be that unless you have a specific reason not to use a library function that does what you want, use it. This will avoid you having to maintain and bugfix code others have perfectly good solutions to. |
Benefits of os.path.splitext over regular .split? | 542,596 | 23 | 2009-02-12T18:10:51Z | 542,621 | 8 | 2009-02-12T18:18:16Z | [
"python"
] | In [this other question](http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python), the votes clearly show that the `os.path.splitext` function is preferred over the simple `.split('.')[-1]` string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?
EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage. | `splitext()` does a reverse search for '.' and returns the extension portion as soon as it finds it. `split('.')` will do a forward search for all '.' characters and is therefore almost always slower. In other words `splitext()` is specifically written for returning the extension unlike `split()`.
(see posixpath.py in the Python source if you want to examine the implementation). |
Highlighting unmatched brackets in vim | 542,929 | 11 | 2009-02-12T19:47:23Z | 543,554 | 8 | 2009-02-12T21:55:23Z | [
"python",
"vim",
"syntax-highlighting"
] | I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the `c.vim` syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?
Example C code with unmatched parens:
```
int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
```
Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).
BTW, I tried out [this vim plugin](http://www.vim.org/scripts/script.php?script_id=350) but I wasn't happy with the behavior.
Edit:
I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a `file.write()` method call. It would be nice if I could get vim to make that mistake more visually obvious.
**Update:**
Ok, here's what I've tried so far.
```
:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
```
Unfortunately, all this does is highlight as an error the right paren of all **balanced** parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it. | You can get vim to do the opposite: do a
> :set showmatch
and it will highlight matching parens. You'll know when you're unbalanced when it doesn't highlight something.
I'm also assuming you're familiar with the '%' command, which bounces you to the matching element. |
How do I attach a remote debugger to a Python process? | 543,196 | 47 | 2009-02-12T20:54:08Z | 543,258 | 16 | 2009-02-12T21:07:19Z | [
"python",
"remote-debugging"
] | I'm tired of inserting
```
import pdb; pdb.set_trace()
```
lines into my Python programs and debugging through the console. How do I connect a remote debugger and insert breakpoints from a civilized user interface? | Well, you can get something quite similar to that using a twisted manhole, which
works like this:
```
from twisted.internet import reactor
from twisted.cred import portal, checkers
from twisted.conch import manhole, manhole_ssh
def getManholeFactory(namespace):
realm = manhole_ssh.TerminalRealm()
def getManhole(_):
return manhole.Manhole(namespace)
realm.chainedProtocolFactory.protocolFactory = getManhole
p = portal.Portal(realm)
p.registerChecker(
checkers.InMemoryUsernamePassword DatabaseDontUse(admin='foobar'))
f = manhole_ssh.ConchFactory(p)
return f
reactor.listenTCP(2222, getManholeFactory(globals()))
reactor.run()
```
Then you just login to the program over ssh;
```
$ ssh admin@localhost -p 2222
admin@localhost's password:
```
Using **foobar** as the password.
When you login you'll get a normal python prompt where you can just poke at the data.
It's not quite the same as getting a traceback sent over to a host.
Now, this might be tricky to integrate to a GUI program, in that case you might need to choose another reactor, for instance for gtk based programs used the gtk2reactor etc.
If you want the actual traceback sent over you need to create a socket channel for both stderr, stdin and stdout which goes over the network instead of printing to your local host. Shouldn't be too hard to accomplish by using twisted. |
How do I attach a remote debugger to a Python process? | 543,196 | 47 | 2009-02-12T20:54:08Z | 544,838 | 56 | 2009-02-13T05:32:18Z | [
"python",
"remote-debugging"
] | I'm tired of inserting
```
import pdb; pdb.set_trace()
```
lines into my Python programs and debugging through the console. How do I connect a remote debugger and insert breakpoints from a civilized user interface? | use [Winpdb](http://winpdb.org/). It is a **platform independent** graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.
Features:
* GPL license. Winpdb is Free Software.
* Compatible with CPython 2.3 through 2.6 and Python 3000
* Compatible with wxPython 2.6 through 2.8
* Platform independent, and tested on Ubuntu Gutsy and Windows XP.
* User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.
 |
Add Quotes in url string from file | 543,199 | 2 | 2009-02-12T20:54:42Z | 543,210 | 7 | 2009-02-12T20:57:35Z | [
"python",
"ruby",
"perl"
] | I need script to add quotes in url string from url.txt
from `http://www.site.com/info.xx` to `"http://www.site.com/info.xx"` | ```
url = '"%s"' % url
```
Example:
```
line = 'http://www.site.com/info.xx \n'
url = '"%s"' % line.strip()
print url # "http://www.site.com/info.xx"
```
Remember, adding a backslash before a quotation mark will escape it and therefore won't end the string. |
Python string formatting | 543,399 | 2 | 2009-02-12T21:34:14Z | 543,417 | 8 | 2009-02-12T21:37:36Z | [
"python"
] | I see you guys using
```
url = '"%s"' % url # This part
>>> url = "http://www.site.com/info.xx"
>>> print url
http://www.site.com/info.xx
>>> url = '"%s"' % url
>>> print url
"http://www.site.com/info.xx"
```
Is it advanced Python? Is there a tutorial for it? How can I learn about it? | That line of code is using Python string formatting. You can read up more on how to use it here: <http://docs.python.org/library/stdtypes.html#string-formatting> |
Python string formatting | 543,399 | 2 | 2009-02-12T21:34:14Z | 543,453 | 10 | 2009-02-12T21:43:26Z | [
"python"
] | I see you guys using
```
url = '"%s"' % url # This part
>>> url = "http://www.site.com/info.xx"
>>> print url
http://www.site.com/info.xx
>>> url = '"%s"' % url
>>> print url
"http://www.site.com/info.xx"
```
Is it advanced Python? Is there a tutorial for it? How can I learn about it? | It's common string formatting, and very useful. It's analogous to C-style printf formatting. See [String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting) in the Python.org docs. You can use multiple arguments like this:
```
"%3d\t%s" % (42, "the answer to ...")
``` |
Using different versions of python for different projects in Eclipse | 543,466 | 12 | 2009-02-12T21:45:27Z | 545,880 | 7 | 2009-02-13T13:16:16Z | [
"python",
"eclipse"
] | So, I'm slowly working in some Python 3.0, but I still have a lot of things that rely on 2.5.
But, in Eclipse, every time I change projects between a 3.0 and a 2.5, I need to go through
Project -> Properties -> project type.
**Issue 1:** if I just switch the interpreter in the drop down box, that doesn't seem to change anything. I need to click "click here to configure an interpreter not listed", and **UP** the interpreter I wish to use.
**Issue 2:** That would be fine if I was switching to 3.0 for every project for the rest of my life, but I still am doing a lot of switching between projects and I don't see that changing anytime soon. So, I'm just trying to save a few operations.
Is there a way to configure Eclipse so that it remembers which interpreter I want associated with which project?
What if I created an entirely new workspace? Is "interpreter" a property of a workspace?
Also, it doesn't seem to matter what I choose when I create a new project via File -> New -> Pydev Project. Whatever I last selected through "Properties" is what eclipse is using.
This is Eclipse 3.4.0, running in Windows XP. | You can set the interpreter version on a per-script basis through the Run Configurations menu.
To do this go to Run -> Run Configurations, and then make a new entry under Python Run. Fill in your project name and the main script, and then go to the Interpeter tab and you can pick which interpreter you want to use for that script.
I've used this to have Python 2.2, 2.5, and 3.0 projects in the same workspace. |
Why is KeyboardInterrupt not working in python? | 543,534 | 3 | 2009-02-12T21:53:42Z | 543,628 | 14 | 2009-02-12T22:04:34Z | [
"python"
] | Why doesn't code like the following catch CTRL-C?
```
MAXVAL = 10000
STEP_INTERVAL = 10
for i in range(1, MAXVAL, STEP_INTERVAL):
try:
print str(i)
except KeyboardInterrupt:
break
print "done"
```
My expectation is -- if CTRL-C is pressed while program is running, `KeyboardInterrupt` is supposed to leave the loop. It does not.
Any help on what I'm doing wrong? | Sounds like the program is done by the time control-c has been hit, but your operating system hasn't finished showing you all the output. . |
Why is KeyboardInterrupt not working in python? | 543,534 | 3 | 2009-02-12T21:53:42Z | 543,912 | 11 | 2009-02-12T23:01:11Z | [
"python"
] | Why doesn't code like the following catch CTRL-C?
```
MAXVAL = 10000
STEP_INTERVAL = 10
for i in range(1, MAXVAL, STEP_INTERVAL):
try:
print str(i)
except KeyboardInterrupt:
break
print "done"
```
My expectation is -- if CTRL-C is pressed while program is running, `KeyboardInterrupt` is supposed to leave the loop. It does not.
Any help on what I'm doing wrong? | code flow is as follows:
1. `for` grabs new object from list (generated by `range`) and sets `i` to it
2. `try`
3. `print`
4. go back to `1`
If you hit CTRL-C in the part 1 it is outside the `try`/`except`, so it won't catch the exception.
Try this instead:
```
MaxVal = 10000
StepInterval = 10
try:
for i in range(1, MaxVal, StepInterval):
print i
except KeyboardInterrupt:
pass
print "done"
``` |
Mapping a global variable from a shared library with ctypes | 544,173 | 12 | 2009-02-13T00:11:38Z | 546,128 | 15 | 2009-02-13T14:30:16Z | [
"python",
"ctypes"
] | I'd like to map an int value `pbs_errno` declared as a global in the library `libtorque.so` using ctypes.
Currently I can load the library like so:
```
from ctypes import *
libtorque = CDLL("libtorque.so")
```
and have successfully mapped a bunch of the functions. However, for error checking purposes many of them set the `pbs_errno` variable so I need access to that as well. However if I try to access it I get:
```
>>> pytorque.libtorque.pbs_errno
<_FuncPtr object at 0x9fc690>
```
Of course, it's not a function pointer and attempting to call it results in a seg fault.
It's declared as `int pbs_errno;` in the main header and `extern int pbs_errno;` in the API header files.
Objdump shows the symbol as:
```
00000000001294f8 g DO .bss 0000000000000004 Base pbs_errno
``` | There's a section in the ctypes docs about accessing values exported in dlls:
<http://docs.python.org/library/ctypes.html#accessing-values-exported-from-dlls>
e.g.
```
def pbs_errno():
return c_int.in_dll(libtorque, "pbs_errno")
``` |
How do you verify an RSA SHA1 signature in Python? | 544,433 | 27 | 2009-02-13T01:50:48Z | 545,237 | 23 | 2009-02-13T08:54:06Z | [
"python",
"cryptography",
"rsa",
"sha1",
"signature"
] | I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:
```
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW
nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl
XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal
VvXw13PLINE/YptjkQIDAQAB
-----END PUBLIC KEY-----
```
I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:
```
openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1);
```
Also, if I'm confused about any terminology, please let me know. | The data between the markers is the base64 encoding of the ASN.1 DER-encoding of a PKCS#8 PublicKeyInfo containing an PKCS#1 RSAPublicKey.
That is a lot of standards, and you will be best served with using a crypto-library to decode it (such as M2Crypto as [suggested by joeforker](http://stackoverflow.com/questions/544433/how-do-you-verify-an-rsa-sha1-signature-in-python/546043#546043)). Treat the following as some fun info about the format:
If you want to, you can decode it like this:
Base64-decode the string:
```
30819f300d06092a864886f70d010101050003818d0030818902818100df1b822e14eda1fcb74336
6a27c06370e6cad69d4116ce806b3d117534cf0baa938c0f8e4500fb59d4d98fb471a8d01012d54b
32244197c7434f27c1b0d73fa1b8bae55e70155f907879ce9c25f28a9a92ff97de1684fdaff05dce
196ae76845f598b328c5ed76e0f71f6a6b7448f08691e6a556f5f0d773cb20d13f629b6391020301
0001
```
This is the DER-encoding of:
```
0 30 159: SEQUENCE {
3 30 13: SEQUENCE {
5 06 9: OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
16 05 0: NULL
: }
18 03 141: BIT STRING 0 unused bits, encapsulates {
22 30 137: SEQUENCE {
25 02 129: INTEGER
: 00 DF 1B 82 2E 14 ED A1 FC B7 43 36 6A 27 C0 63
: 70 E6 CA D6 9D 41 16 CE 80 6B 3D 11 75 34 CF 0B
: AA 93 8C 0F 8E 45 00 FB 59 D4 D9 8F B4 71 A8 D0
: 10 12 D5 4B 32 24 41 97 C7 43 4F 27 C1 B0 D7 3F
: A1 B8 BA E5 5E 70 15 5F 90 78 79 CE 9C 25 F2 8A
: 9A 92 FF 97 DE 16 84 FD AF F0 5D CE 19 6A E7 68
: 45 F5 98 B3 28 C5 ED 76 E0 F7 1F 6A 6B 74 48 F0
: 86 91 E6 A5 56 F5 F0 D7 73 CB 20 D1 3F 62 9B 63
: 91
157 02 3: INTEGER 65537
: }
: }
: }
```
For a 1024 bit RSA key, you can treat `"30819f300d06092a864886f70d010101050003818d00308189028181"` as a constant header, followed by a 00-byte, followed by the 128 bytes of the RSA modulus. After that 95% of the time you will get `0203010001`, which signifies a RSA public exponent of 0x10001 = 65537.
You can use those two values as `n` and `e` in a tuple to construct a RSAobj. |
How do you verify an RSA SHA1 signature in Python? | 544,433 | 27 | 2009-02-13T01:50:48Z | 546,476 | 27 | 2009-02-13T15:59:41Z | [
"python",
"cryptography",
"rsa",
"sha1",
"signature"
] | I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:
```
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW
nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl
XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal
VvXw13PLINE/YptjkQIDAQAB
-----END PUBLIC KEY-----
```
I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:
```
openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1);
```
Also, if I'm confused about any terminology, please let me know. | Use [M2Crypto](http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.X509-module.html). Here's how to verify for RSA and any other algorithm supported by OpenSSL:
```
pem = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW
nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl
XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal
VvXw13PLINE/YptjkQIDAQAB
-----END PUBLIC KEY-----""" # your example key
from M2Crypto import BIO, RSA, EVP
bio = BIO.MemoryBuffer(pem)
rsa = RSA.load_pub_key_bio(bio)
pubkey = EVP.PKey()
pubkey.assign_rsa(rsa)
# if you need a different digest than the default 'sha1':
pubkey.reset_context(md='sha1')
pubkey.verify_init()
pubkey.verify_update('test message')
assert pubkey.verify_final(signature) == 1
``` |
Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers? | 544,542 | 8 | 2009-02-13T02:41:45Z | 638,511 | 10 | 2009-03-12T12:58:58Z | [
"python",
"coding-style",
"matplotlib"
] | I am trying to plot a bunch of data points (many thousands) in Python using [matplotlib](http://matplotlib.sourceforge.net/index.html) so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data:
```
matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black')
```
Then I can look at it either with `pl.show()` and then save it. Or directly use `plt.savefig('filename.ps')` in the code to save it. The problem is this: when I use `pl.show()` to view the file in the GUI it looks great with small tiny black marks, however when I save from the `show()` GUI to a file or use directly `savefig` and then view the `ps` I created it looks different! Each marker has gained a little blue halo around it (as if it started at each point to connect them with the default blue lines, but did not) and the style is all wrong. Why does it change the style when saved? How do I stop python from forcing the style of the markers? And yes I have looked at some alternative packages like [CairoPlot](http://linil.wordpress.com/2008/09/16/cairoplot-11/), but I want to keep using matplotlib for now.
**Update:** It turns out that the save to PNG first makes the colors turn out okay, but it forces a conversion of the image when I want to save it again as a `.ps` later (for inclusion in a PDF) and then I lose quality. How do I preserve the vector nature of the file and get the right formatting? | For nice-looking vectorized output, don't use the `'.'` marker style. Use e.g. `'o'` (circle) or `'s'` (square) (see `help(plot)` for the options) and set the `markersize` keyword argument to something suitably small, e.g.:
```
plot(x, y, 'ko', markersize=2)
savefig('foo.ps')
```
That `'.'` (point) produces less nice results could be construed as a bug in matplotlib, but then, what *should* "point" mean in a vector graphic format? |
Can I print original variable's name in Python? | 544,919 | 31 | 2009-02-13T06:30:06Z | 544,944 | 23 | 2009-02-13T06:38:01Z | [
"python",
"variables"
] | I have enum and use the variables like `myEnum.SomeNameA`, `myEnum.SomeNameB`, etc. When I return one of these variables from a function, can I print their names (such as `myEnum.SomeNameA`) instead of the value they returned? | Short answer: no.
Long answer: this is possible with some ugly hacks using traceback, inspect and the like, but it's generally probably not recommended for production code. For example see:
* <http://groups.google.com/group/comp.lang.python/msg/237dc92f3629dd9a?pli=1>
* <http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/330294>
Perhaps you can use a workaround to translate the value back to a name/representational string. If you post some more sample code and details about what you're wanting this for maybe we can provide more in-depth assistance. |
Can I print original variable's name in Python? | 544,919 | 31 | 2009-02-13T06:30:06Z | 544,966 | 21 | 2009-02-13T06:45:43Z | [
"python",
"variables"
] | I have enum and use the variables like `myEnum.SomeNameA`, `myEnum.SomeNameB`, etc. When I return one of these variables from a function, can I print their names (such as `myEnum.SomeNameA`) instead of the value they returned? | To add to [@Jay's answer](http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name/544944#544944), some concepts...
Python "variables" are simply references to values. Each value occupies a given memory location (see `id()`)
```
>>> id(1)
10052552
>>> sys.getrefcount(1)
569
```
From the above, you may notice that the value "1" is present at the memory location 10052552. It is referred to 569 times in this instance of the interpreter.
```
>>> MYVAR = 1
>>> sys.getrefcount(1)
570
```
Now, see that because yet another name is bound to this value, the reference count went up by one.
Based on these facts, it is not realistic/possible to tell what single variable name is pointing to a value.
I think the best way to address your issue is to add a mapping and function to your enum reference back to a string name.
```
myEnum.get_name(myEnum.SomeNameA)
```
Please comment if you would like sample code. |
Can I print original variable's name in Python? | 544,919 | 31 | 2009-02-13T06:30:06Z | 545,663 | 17 | 2009-02-13T11:50:19Z | [
"python",
"variables"
] | I have enum and use the variables like `myEnum.SomeNameA`, `myEnum.SomeNameB`, etc. When I return one of these variables from a function, can I print their names (such as `myEnum.SomeNameA`) instead of the value they returned? | There is no such thing as a unique or original variable name
<http://www.amk.ca/quotations/python-quotes/page-8>
> The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)...
>
> ....and don't be surprised if you'll find that it's known by many names, or no name at all!
>
> **Fredrik Lundh, 3 Nov 2000, in answer to the question "How can I get the name of a variable from C++ when I have the PyObject\*?"** |
Best method for reading newline delimited files in Python and discarding the newlines? | 544,921 | 68 | 2009-02-13T06:31:11Z | 544,932 | 169 | 2009-02-13T06:35:50Z | [
"python",
"file",
"readline"
] | I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.
What I've come up with is the following code, include throwaway code to test.
```
import os
def getfile(filename,results):
f = open(filename)
filecontents = f.readlines()
for line in filecontents:
foo = line.strip('\n')
results.append(foo)
return results
blahblah = []
getfile('/tmp/foo',blahblah)
for x in blahblah:
print x
```
Suggestions? | ```
lines = open(filename).read().splitlines()
``` |
Best method for reading newline delimited files in Python and discarding the newlines? | 544,921 | 68 | 2009-02-13T06:31:11Z | 544,935 | 7 | 2009-02-13T06:36:08Z | [
"python",
"file",
"readline"
] | I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.
What I've come up with is the following code, include throwaway code to test.
```
import os
def getfile(filename,results):
f = open(filename)
filecontents = f.readlines()
for line in filecontents:
foo = line.strip('\n')
results.append(foo)
return results
blahblah = []
getfile('/tmp/foo',blahblah)
for x in blahblah:
print x
```
Suggestions? | ```
for line in file('/tmp/foo'):
print line.strip('\n')
``` |
Best method for reading newline delimited files in Python and discarding the newlines? | 544,921 | 68 | 2009-02-13T06:31:11Z | 545,188 | 19 | 2009-02-13T08:35:46Z | [
"python",
"file",
"readline"
] | I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.
What I've come up with is the following code, include throwaway code to test.
```
import os
def getfile(filename,results):
f = open(filename)
filecontents = f.readlines()
for line in filecontents:
foo = line.strip('\n')
results.append(foo)
return results
blahblah = []
getfile('/tmp/foo',blahblah)
for x in blahblah:
print x
```
Suggestions? | Here's a generator that does what you requested. In this case, using rstrip is sufficient and slightly faster than strip.
```
lines = (line.rstrip('\n') for line in open(filename))
```
However, you'll most likely want to use this to get rid of trailing whitespaces too.
```
lines = (line.rstrip() for line in open(filename))
``` |
Best method for reading newline delimited files in Python and discarding the newlines? | 544,921 | 68 | 2009-02-13T06:31:11Z | 6,978,940 | 8 | 2011-08-08T07:26:31Z | [
"python",
"file",
"readline"
] | I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.
What I've come up with is the following code, include throwaway code to test.
```
import os
def getfile(filename,results):
f = open(filename)
filecontents = f.readlines()
for line in filecontents:
foo = line.strip('\n')
results.append(foo)
return results
blahblah = []
getfile('/tmp/foo',blahblah)
for x in blahblah:
print x
```
Suggestions? | What do you think about this approach?
```
with open(filename) as data:
datalines = (line.rstrip('\r\n') for line in data)
for line in datalines:
...do something awesome...
```
Generator expression avoids loading whole file into memory and `with` ensures closing the file |
Kerberos authentication with python | 545,294 | 10 | 2009-02-13T09:15:43Z | 545,499 | 11 | 2009-02-13T10:33:42Z | [
"python",
"security",
"kerberos"
] | I need to write a script in python to check a webpage, which is protected by kerberos. Is there any possibility to do this from within python and how? The script is going to be deployed on a linux environment with python 2.4.something installed.
dertoni | I think that `python-krbV` and most Linux distributions also have a `python-kerberos` package. For example, Debian has one of the same name. Here's the documentation on [it](http://packages.debian.org/testing/python/python-kerberos)
Extract from link:
> "This Python package is a high-level wrapper for Kerberos (GSSAPI)
> operations. The goal is to avoid having to build a module that wraps
> the entire Kerberos.framework, and instead offer a limited set of
> functions that do what is needed for client/server Kerberos
> authentication based on <http://www.ietf.org/rfc/rfc4559.txt>. " |
Linux: compute a single hash for a given folder & contents? | 545,387 | 33 | 2009-02-13T09:51:40Z | 545,413 | 48 | 2009-02-13T09:59:36Z | [
"python",
"linux",
"bash",
"hash"
] | Surely there must be a way to do this easily!
I've tried the linux command-line apps sha1sum & md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file.
I need to generate a single hash for the entire contents of a folder (not just the filenames).
I'd like to do something like
```
sha1sum /folder/of/stuff > singlehashvalue
```
**Edit:** to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder. | One possible way would be:
```
sha1sum path/to/folder/* | sha1sum
```
If there is a whole directory tree, you're probably better off using find and xargs. One possible command would be
```
find path/to/folder -type f -print0 | xargs -0 sha1sum | sha1sum
```
**Edit**: Good point, it's probably a good thing to sort the list of files, so:
```
find path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum
```
And, finally, if you also need to take account of permissions and empty directories:
```
(find path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum;
find path/to/folder \( -type f -o -type d \) -print0 | sort -z | \
xargs -0 stat -c '%n %a') \
| sha1sum
```
The arguments to `stat` will cause it to print the name of the file, followed by its octal permissions. The two finds will run one after the other, causing double the amount of disk IO, the first finding all file names and checksumming the contents, the second finding all file and directory names, printing name and mode. The list of "file names and checksums", followed by "names and directories, with permissions" will then be checksummed, for a smaller checksum. |
Linux: compute a single hash for a given folder & contents? | 545,387 | 33 | 2009-02-13T09:51:40Z | 545,420 | 11 | 2009-02-13T10:04:00Z | [
"python",
"linux",
"bash",
"hash"
] | Surely there must be a way to do this easily!
I've tried the linux command-line apps sha1sum & md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file.
I need to generate a single hash for the entire contents of a folder (not just the filenames).
I'd like to do something like
```
sha1sum /folder/of/stuff > singlehashvalue
```
**Edit:** to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder. | * Commit the directory to git, use the commit hash. See [metastore](http://david.hardeman.nu/software.php#metastore) for a way to also control permissions.
* Use a file system intrusion detection tool like [aide](http://sourceforge.net/projects/aide/).
* hash a tar ball of the directory:
tar cvf - /path/to/folder | sha1sum
* Code something yourself, like [vatine's oneliner](http://stackoverflow.com/questions/545387/linux-compute-a-single-hash-for-a-given-folder-contents/545413#545413):
find /path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum |
Using base class constructor as factory in Python? | 545,419 | 5 | 2009-02-13T10:03:19Z | 545,446 | 12 | 2009-02-13T10:15:37Z | [
"python",
"factory"
] | I'm using base class constructor as factory and changing class in this constructor/factory to select appropriate class -- is this approach is good python practice or there are more elegant ways?
I've tried to read help about metaclasses but without big success.
Here example of what I'm doing.
```
class Project(object):
"Base class and factory."
def __init__(self, url):
if is_url_local(url):
self.__class__ = ProjectLocal
else:
self.__class__ = ProjectRemote
self.url = url
class ProjectLocal(Project):
def do_something(self):
# do the stuff locally in the dir pointed by self.url
class ProjectRemote(Project):
def do_something(self):
# do the stuff communicating with remote server pointed by self.url
```
Having this code I can create the instance of ProjectLocal/ProjectRemote via base class Project:
```
project = Project('http://example.com')
project.do_something()
```
I know that alternate way is to using fabric function that will return the class object based on url, then code will looks similar:
```
def project_factory(url):
if is_url_local(url):
return ProjectLocal(url)
else:
return ProjectRemote(url)
project = project_factory(url)
project.do_something()
```
Is my first approach just matter of taste or it has some hidden pitfalls? | I would stick with the factory function approach. It's very standard python and easy to read and understand. You could make it more generic to handle more options in several ways such as by passing in the discriminator function and a map of results to classes.
If the first example works it's more by luck than by design. What if you wanted to have an `__init__` defined in your subclass? |
Using base class constructor as factory in Python? | 545,419 | 5 | 2009-02-13T10:03:19Z | 545,786 | 11 | 2009-02-13T12:49:18Z | [
"python",
"factory"
] | I'm using base class constructor as factory and changing class in this constructor/factory to select appropriate class -- is this approach is good python practice or there are more elegant ways?
I've tried to read help about metaclasses but without big success.
Here example of what I'm doing.
```
class Project(object):
"Base class and factory."
def __init__(self, url):
if is_url_local(url):
self.__class__ = ProjectLocal
else:
self.__class__ = ProjectRemote
self.url = url
class ProjectLocal(Project):
def do_something(self):
# do the stuff locally in the dir pointed by self.url
class ProjectRemote(Project):
def do_something(self):
# do the stuff communicating with remote server pointed by self.url
```
Having this code I can create the instance of ProjectLocal/ProjectRemote via base class Project:
```
project = Project('http://example.com')
project.do_something()
```
I know that alternate way is to using fabric function that will return the class object based on url, then code will looks similar:
```
def project_factory(url):
if is_url_local(url):
return ProjectLocal(url)
else:
return ProjectRemote(url)
project = project_factory(url)
project.do_something()
```
Is my first approach just matter of taste or it has some hidden pitfalls? | You shouldn't need metaclasses for this. Take a look at the [`__new__`](http://docs.python.org/reference/datamodel.html#object.__new__) method. This will allow you to take control of the creation of the object, rather than just the initialisation, and so return an object of your choosing.
```
class Project(object):
"Base class and factory."
def __new__(cls, url):
if is_url_local(url):
return super(Project, cls).__new__(ProjectLocal, url)
else:
return super(Project, cls).__new__(ProjectRemote, url)
def __init__(self, url):
self.url = url
``` |
Tool (or combination of tools) for reproducible environments in Python | 545,730 | 9 | 2009-02-13T12:20:56Z | 545,912 | 18 | 2009-02-13T13:24:24Z | [
"python",
"continuous-integration",
"installation",
"development-environment",
"automated-deploy"
] | I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team.
I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java. | 1. [virtualenv](http://pypi.python.org/pypi/virtualenv) to create a contained virtual environment (prevent different versions of Python or Python packages from stomping on each other). There is increasing buzz from people moving to this tool. The author is the same as the older working-env.py mentioned by Aaron.
2. [pip](http://pypi.python.org/pypi/pip) to install packages inside a virtualenv. The traditional is easy\_install as answered by S. Lott, but pip works better with virtualenv. easy\_install still has features not found in pip though.
3. [scons](http://www.scons.org/) as a build tool, although you won't need this if you stay purely Python.
4. [Fabric](http://pypi.python.org/pypi/Fabric/0.0.3) paste, or [paver](http://www.blueskyonmars.com/projects/paver/) for deployment.
5. [buildbot](http://buildbot.net/trac) for continuous integration.
6. Bazaar, mercurial, or git for version control.
7. [Nose](http://somethingaboutorange.com/mrl/projects/nose/) as an extension for unit testing.
8. [PyFit](http://pypi.python.org/pypi/PyFIT/0.8a2) for [FIT](http://fit.c2.com) testing. |
How do I calculate the date six months from the current date using the datetime Python module? | 546,321 | 143 | 2009-02-13T15:16:25Z | 546,332 | 10 | 2009-02-13T15:21:07Z | [
"python",
"datetime"
] | I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. | What do you mean by '6 months'. Is 2009-02-13 + 6 months == 2009-08-13 or is it 2009-02-13 + 6\*30 days?
```
import mx.DateTime as dt
#6 Months
dt.now()+dt.RelativeDateTime(months=6)
#result is '2009-08-13 16:28:00.84'
#6*30 days
dt.now()+dt.RelativeDateTime(days=30*6)
#result is '2009-08-12 16:30:03.35'
```
More info about [mx.DateTime](http://www.egenix.com/products/python/mxBase/mxDateTime/) |
How do I calculate the date six months from the current date using the datetime Python module? | 546,321 | 143 | 2009-02-13T15:16:25Z | 546,347 | 7 | 2009-02-13T15:26:05Z | [
"python",
"datetime"
] | I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. | [Dateutil package](http://labix.org/python-dateutil) has implementation of such functionality. But be aware, that this will be *naive*, as others pointed already. |
How do I calculate the date six months from the current date using the datetime Python module? | 546,321 | 143 | 2009-02-13T15:16:25Z | 546,354 | 36 | 2009-02-13T15:29:24Z | [
"python",
"datetime"
] | I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. | Well, that depends what you mean by 6 months from the current date.
1. Using natural months:
```
(day, month, year) = (day, (month+6)%12, year+(month+6)/12)
```
2. Using a banker's definition, 6\*30:
```
date += datetime.timedelta(6*30)
``` |
How do I calculate the date six months from the current date using the datetime Python module? | 546,321 | 143 | 2009-02-13T15:16:25Z | 546,356 | 57 | 2009-02-13T15:29:46Z | [
"python",
"datetime"
] | I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. | ```
import datetime
print (datetime.date.today() + datetime.timedelta(6*365/12)).isoformat()
``` |
How do I calculate the date six months from the current date using the datetime Python module? | 546,321 | 143 | 2009-02-13T15:16:25Z | 3,463,303 | 9 | 2010-08-11T22:18:29Z | [
"python",
"datetime"
] | I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. | This solution works correctly for December, which most of the answers on this page do not.
You need to first shift the months from base 1 (ie Jan = 1) to base 0 (ie Jan = 0) before using modulus ( % ) or integer division ( // ), otherwise November (11) plus 1 month gives you 12, which when finding the remainder ( 12 % 12 ) gives 0.
(And dont suggest "(month % 12) + 1" or Oct + 1 = december!)
```
def AddMonths(d,x):
newmonth = ((( d.month - 1) + x ) % 12 ) + 1
newyear = d.year + ((( d.month - 1) + x ) / 12 )
return datetime.date( newyear, newmonth, d.day)
```
However ... This doesnt account for problem like Jan 31 + one month. So we go back to the OP - what do you mean by adding a month? One soln is to backtrack until you get to a valid day, given that most people would presume the last day of jan, plus one month, equals the last day of Feb.
This will work on negative numbers of months too.
Proof:
```
>>> import datetime
>>> AddMonths(datetime.datetime(2010,8,25),1)
datetime.date(2010, 9, 25)
>>> AddMonths(datetime.datetime(2010,8,25),4)
datetime.date(2010, 12, 25)
>>> AddMonths(datetime.datetime(2010,8,25),5)
datetime.date(2011, 1, 25)
>>> AddMonths(datetime.datetime(2010,8,25),13)
datetime.date(2011, 9, 25)
>>> AddMonths(datetime.datetime(2010,8,25),24)
datetime.date(2012, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-1)
datetime.date(2010, 7, 25)
>>> AddMonths(datetime.datetime(2010,8,25),0)
datetime.date(2010, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-12)
datetime.date(2009, 8, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-8)
datetime.date(2009, 12, 25)
>>> AddMonths(datetime.datetime(2010,8,25),-7)
datetime.date(2010, 1, 25)>>>
``` |
How do I calculate the date six months from the current date using the datetime Python module? | 546,321 | 143 | 2009-02-13T15:16:25Z | 4,406,260 | 410 | 2010-12-10T06:22:36Z | [
"python",
"datetime"
] | I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. | I found this solution to be good. (This uses the [python-dateutil extension](https://dateutil.readthedocs.org/en/latest/))
```
from datetime import date
from dateutil.relativedelta import relativedelta
six_months = date.today() + relativedelta(months=+6)
```
The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)
```
$ date(2010,12,31)+relativedelta(months=+1)
datetime.date(2011, 1, 31)
$ date(2010,12,31)+relativedelta(months=+2)
datetime.date(2011, 2, 28)
``` |
How do I calculate the date six months from the current date using the datetime Python module? | 546,321 | 143 | 2009-02-13T15:16:25Z | 5,643,283 | 7 | 2011-04-13T00:54:07Z | [
"python",
"datetime"
] | I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. | I know this was for 6 months, however the answer shows in google for "adding months in python" if you are adding one month:
```
import calendar
date = datetime.date.today() //Or your date
datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])
```
this would count the days in the current month and add them to the current date, using 365/12 would ad 1/12 of a year can causes issues for short / long months if your iterating over the date. |
How Do I Perform Introspection on an Object in Python 2.x? | 546,337 | 22 | 2009-02-13T15:22:50Z | 546,349 | 24 | 2009-02-13T15:27:23Z | [
"python",
"introspection",
"python-datamodel"
] | I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property.
Similarly, I'd like to get a list of methods for that object, as well, plus any other information I could find on that method, such as number of arguments and their respective types.
I have a feeling that I am simply missing the correct jargon in my Google searches. Not that I want to derail with specifics, but it's Active Directory, so that's always fun. | Well ... Your first stop will be a simple dir(object). This will show you all the object's members, both fields and methods. Try it in an interactive Python shell, and play around a little.
For instance:
```
> class Foo:
def __init__(self):
self.a = "bar"
self.b = 4711
> a=Foo()
> dir(a)
['__doc__', '__init__', '__module__', 'a', 'b']
``` |
How Do I Perform Introspection on an Object in Python 2.x? | 546,337 | 22 | 2009-02-13T15:22:50Z | 546,366 | 8 | 2009-02-13T15:31:19Z | [
"python",
"introspection",
"python-datamodel"
] | I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property.
Similarly, I'd like to get a list of methods for that object, as well, plus any other information I could find on that method, such as number of arguments and their respective types.
I have a feeling that I am simply missing the correct jargon in my Google searches. Not that I want to derail with specifics, but it's Active Directory, so that's always fun. | How about something like:
```
>>> o=object()
>>> [(a,type(o.__getattribute__(a))) for a in dir(o)]
[('__class__', <type 'type'>), ('__delattr__', <type 'method-wrapper'>),
('__doc__', <type 'str'>), ('__format__', <type 'builtin_function_or_method'>),
('__getattribute__', <type 'method-wrapper'>), ('__hash__', <type 'method-wrapper'>),
('__init__', <type 'method-wrapper'>),
('__new__', <type 'builtin_function_or_method'>),
('__reduce__', <type 'builtin_function_or_method'>),
('__reduce_ex__', <type 'builtin_function_or_method'>),
('__repr__', <type 'method-wrapper'>), ('__setattr__', <type 'method-wrapper'>),
('__sizeof__', <type 'builtin_function_or_method'>),
('__str__', <type 'method-wrapper'>),
('__subclasshook__', <type 'builtin_function_or_method'>)]
>>>
```
A more structured method will be to use the [inspect module](http://docs.python.org/library/inspect.html#module-inspect):
> The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback. |
Do OO design principles apply to Python? | 546,479 | 24 | 2009-02-13T16:00:06Z | 546,495 | 36 | 2009-02-13T16:04:41Z | [
"python",
"oop"
] | It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).
Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)? | The biggest differences are that Python is duck typed, meaning that you won't need to plan out class hierarchies in as much detail as in Java, and has first class functions. The strategy pattern, for example, becomes much simpler and more obvious when you can just pass a function in, rather than having to make interfaces, etc. just to simulate higher order functions. More generally, Python has syntactic sugar for a lot of common design patterns, such as the iterator and the aforementioned strategy. It might be useful to understand these patterns (I've read Head First and found it pretty useful), but think about Pythonic ways to implement them rather than just doing things the same way you would in Java. |
Do OO design principles apply to Python? | 546,479 | 24 | 2009-02-13T16:00:06Z | 546,515 | 12 | 2009-02-13T16:07:07Z | [
"python",
"oop"
] | It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).
Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)? | Python has it's own design idioms. Some of the standard patterns apply, others don't. Something like strategy or factories have in-language support that make them transparent.
For instance, with first-class types anything can be a factory. There's no need for a factory type, you can use the class directly to construct any object you want.
Basically, Python has its own design idioms that are somewhat different largely because it's so dynamic and has incredible introspection capabilities.
Example:
```
x = list
my_list = x(range(0,5)) #creates a new list by invoking list's constructor
```
By assigning the class-type to a callable object you can essentially remove any 'factory' types in your code. You are only left with callables that produce objects that should conform to some given conventions.
Furthermore, there are design patterns in Python that just can't be represented in other statically-typed languages efficiently. Metaclasses and function decorators are good examples of this. |
How can I split a file in python? | 546,508 | 8 | 2009-02-13T16:06:29Z | 546,561 | 13 | 2009-02-13T16:17:41Z | [
"python"
] | Is it possible to split a file? For example you have huge wordlist, I want to split it so that it becomes more than one file. How is this possible? | This one splits a file up by newlines and writes it back out. You can change the delimiter easily. This can also handle uneven amounts as well, if you don't have a multiple of splitLen lines (20 in this example) in your input file.
```
splitLen = 20 # 20 lines per file
outputBase = 'output' # output.1.txt, output.2.txt, etc.
# This is shorthand and not friendly with memory
# on very large files (Sean Cavanagh), but it works.
input = open('input.txt', 'r').read().split('\n')
at = 1
for lines in range(0, len(input), splitLen):
# First, get the list slice
outputData = input[lines:lines+splitLen]
# Now open the output file, join the new slice with newlines
# and write it out. Then close the file.
output = open(outputBase + str(at) + '.txt', 'w')
output.write('\n'.join(outputData))
output.close()
# Increment the counter
at += 1
``` |
How can I split a file in python? | 546,508 | 8 | 2009-02-13T16:06:29Z | 13,345,290 | 8 | 2012-11-12T14:15:35Z | [
"python"
] | Is it possible to split a file? For example you have huge wordlist, I want to split it so that it becomes more than one file. How is this possible? | A better loop for sli's example, not hogging memory :
```
splitLen = 20 # 20 lines per file
outputBase = 'output' # output.1.txt, output.2.txt, etc.
input = open('input.txt', 'r')
count = 0
at = 0
dest = None
for line in input:
if count % splitLen == 0:
if dest: dest.close()
dest = open(outputBase + str(at) + '.txt', 'w')
at += 1
dest.write(line)
count += 1
``` |
Python using result of function for Regular Expression Substitution | 547,798 | 5 | 2009-02-13T21:38:30Z | 547,817 | 14 | 2009-02-13T21:45:58Z | [
"python",
"regex"
] | I have a block of text, and for every regex match, I want to substitute that match with the return value from another function. The argument to this function is of course the matched text.
I have been having trouble trying to come up with a one pass solution to this problem. It feels like it should be pretty simple. | Right from [the documentation](http://docs.python.org/library/re.html#re.sub):
```
>>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
``` |
How to dynamically load a Python class | 547,829 | 74 | 2009-02-13T21:49:04Z | 547,867 | 109 | 2009-02-13T22:02:57Z | [
"python",
"reflection",
"python-import"
] | Given a string of a Python class, e.g. `my_package.my_module.MyClass`, what is the best possible way to load it?
In other words I am looking for a equivalent `Class.forName()` in Java, function in Python. It needs to work on Google App Engine.
Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:
```
my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
``` | From the python documentation, here's the function you want:
```
def my_import(name):
components = name.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
```
The reason a simple `__import__` won't work is because any import of anything past the first dot in a package string is an attribute of the module you're importing. Thus, something like this won't work:
```
__import__('foo.bar.baz.qux')
```
You'd have to call the above function like so:
```
my_import('foo.bar.baz.qux')
```
Or in the case of your example:
```
klass = my_import('my_package.my_module.my_class')
some_object = klass()
```
**EDIT**: I was a bit off on this. What you're basically wanting to do is this:
```
from my_package.my_module import my_class
```
The above function is only necessary if you have a *empty* fromlist. Thus, the appropriate call would be like this:
```
mod = __import__('my_package.my_module', fromlist=['my_class'])
klass = getattr(mod, 'my_class')
``` |
How to dynamically load a Python class | 547,829 | 74 | 2009-02-13T21:49:04Z | 8,255,024 | 23 | 2011-11-24T09:49:03Z | [
"python",
"reflection",
"python-import"
] | Given a string of a Python class, e.g. `my_package.my_module.MyClass`, what is the best possible way to load it?
In other words I am looking for a equivalent `Class.forName()` in Java, function in Python. It needs to work on Google App Engine.
Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:
```
my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
``` | ```
def import_class(cl):
d = cl.rfind(".")
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
``` |
How to dynamically load a Python class | 547,829 | 74 | 2009-02-13T21:49:04Z | 19,228,066 | 28 | 2013-10-07T14:55:19Z | [
"python",
"reflection",
"python-import"
] | Given a string of a Python class, e.g. `my_package.my_module.MyClass`, what is the best possible way to load it?
In other words I am looking for a equivalent `Class.forName()` in Java, function in Python. It needs to work on Google App Engine.
Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:
```
my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
``` | ```
import importlib
module = importlib.import_module('my_package.my_module')
my_class = getattr(module, 'MyClass')
my_instance = my_class()
``` |
How to dynamically load a Python class | 547,829 | 74 | 2009-02-13T21:49:04Z | 24,815,361 | 44 | 2014-07-17T23:52:06Z | [
"python",
"reflection",
"python-import"
] | Given a string of a Python class, e.g. `my_package.my_module.MyClass`, what is the best possible way to load it?
In other words I am looking for a equivalent `Class.forName()` in Java, function in Python. It needs to work on Google App Engine.
Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:
```
my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
``` | If you don't want to roll your own, there is a function available in the `pydoc` module that does exactly this:
```
from pydoc import locate
my_class = locate('my_package.my_module.MyClass')
```
The advantage of this approach over the others listed here is that `locate` will find *any* python object at the provided dotted path, not just an object directly within a module. e.g. `my_package.my_module.MyClass.attr`.
If you're curious what their recipe is, here's the function:
```
def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
if nextmodule: module, n = nextmodule, n + 1
else: break
if module:
object = module
else:
object = __builtin__
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
```
It relies on `pydoc.safeimport` function. Here are the docs for that:
```
"""Import a module; handle errors; return None if the module isn't found.
If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised. Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning. If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""
``` |
SQLAlchemy and empty columns | 548,952 | 9 | 2009-02-14T11:14:06Z | 548,958 | 12 | 2009-02-14T11:26:35Z | [
"python",
"database-design",
"sqlalchemy"
] | When I try to insert a new record into the database using SQLAlchemy and I don't fill out all values, it tries to insert them as "None" (instead of omitting them). It then complains about "can't be null" errors. Is there a way to have it just omit columns from the sql query if I also omitted them when declaring the instance? | This is a database schema issue, not an SQLAlchemy issue. If your database schema has a column which cannot be NULL, you must put something (i.e. not None) into there. Or change your schema to allow NULL in those columns.
Wikipedia has an article [about NULL](http://en.wikipedia.org/wiki/Null_(SQL)) and an article which describes [non-NULL constraints](http://en.wikipedia.org/wiki/Check_Constraint#NOT_NULL_Constraint) |
SQLAlchemy and empty columns | 548,952 | 9 | 2009-02-14T11:14:06Z | 549,022 | 25 | 2009-02-14T12:11:20Z | [
"python",
"database-design",
"sqlalchemy"
] | When I try to insert a new record into the database using SQLAlchemy and I don't fill out all values, it tries to insert them as "None" (instead of omitting them). It then complains about "can't be null" errors. Is there a way to have it just omit columns from the sql query if I also omitted them when declaring the instance? | To add to the answer from Ali A, this means you need to have `nullable=True` in your column definition, so that NULL is allowed in the column. For example:
```
email_address = Column(String, nullable=True)
```
[SQLAlchemy docs for Tables and Columns](http://sqlalchemy.readthedocs.org/en/rel_1_0/core/metadata.html#accessing-tables-and-columns) |
Skipping Iterations in Python | 549,674 | 42 | 2009-02-14T19:48:04Z | 549,680 | 10 | 2009-02-14T19:50:18Z | [
"python",
"iteration",
"skip"
] | I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my `except:` clause to just skip the rest of the current iteration? | Something like this?
```
for i in xrange( someBigNumber ):
try:
doSomethingThatMightFail()
except SomeException, e:
continue
doSomethingWhenNothingFailed()
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.