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 aesth... |
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... | 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... |
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 d... | [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 t... | ```
#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 (g... |
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 t... | 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;
};
... |
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 t... | 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 t... | 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)
);
```
Th... |
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 t... | 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",... |
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 =... |
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 typ... | 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 typ... | 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 x... |
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 typ... | 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*10... |
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 i... | 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.
`<ES... |
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 i... | 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... |
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 ... | 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):
... |
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'
face... | 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'
face... | 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 imp... |
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'
face... | 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 divisi... |
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'
face... | python supports ***arbitrarily*** large ***integers*** naturally:
example:
> **>>>** 10\*\*1000 100000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000000000000000000000000000... |
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... | ```
>>> 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 second... |
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... | 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... | 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
... |
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... | 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 va... |
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... | ```
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),
... |
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... | 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))... |
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... | 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 re... |
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(... | ```
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.s... | 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 url... |
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.s... | 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'l... |
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);
}
```
Yo... | 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 (arg... |
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 = ['johndoe@somedomain.com']
sender = 'me@mydomain.com'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
```
Th... | 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('... |
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 = ['johndoe@somedomain.com']
sender = 'me@mydomain.com'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
```
Th... | 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_fr... |
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... | 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 ... |
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 = []... | 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-... |
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 = []... | 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 nee... |
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 = []... | ```
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 ... |
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 mor... | 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 mor... | 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://stack... |
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 mor... | `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... |
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 i... | 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 getMan... |
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 Softwa... |
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 cha... | 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 ... |
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 supp... | 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 supp... | 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 ra... |
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 se... | 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/l94WhP2v8F3OG... | 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/54... |
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/l94WhP2v8F3OG... | 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
nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ... |
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 ,'.',marker... | 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... |
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/... |
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,... |
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... |
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 fi... | ```
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 fi... | ```
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 fi... | 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(fil... |
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 fi... | 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 (GSSAP... |
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).
... | 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 t... |
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).
... | * 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 | ... |
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(objec... | 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 desig... |
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(objec... | 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):
... |
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 t... | 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. [pi... |
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 o... | 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 i... |
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 o... | [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 o... | 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 o... | ```
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 o... | 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 % ... |
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 o... | 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 is... |
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 o... | 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 ... |
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 informatio... | 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__', '__in... |
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 informatio... | 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 ... |
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 interfac... |
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... |
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, out... |
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(o... |
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... | 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 p... |
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... | ```
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... | ```
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... | 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 d... |
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 ins... | 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 whi... |
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 ins... | 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#acc... |
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:` c... | 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.