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 |
|---|---|---|---|---|---|---|---|---|---|
Add to python path mac os x | 3,387,695 | 31 | 2010-08-02T12:23:58Z | 3,387,737 | 42 | 2010-08-02T12:28:01Z | [
"python",
"osx",
"add",
"pythonpath"
] | I thought
```
import sys
sys.path.append("/home/me/mydir")
```
is appending a dir to my pythonpath
if I print sys.path my dir is in there.
Then I open a new command and it is not there anymore.
But somehow Python cant import modules I saved in that dir.
What Am I doing wrong?
I read .profile or .bash\_profile wi... | Modifications to `sys.path` only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the `PYTHONPATH` environment variable:
```
PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH
```
Note that `PATH` is the system path for executables, which is completely sep... |
Check if a package is installed | 3,387,961 | 12 | 2010-08-02T12:58:35Z | 24,517,783 | 8 | 2014-07-01T19:21:53Z | [
"python",
"debian"
] | Is there an elegant and more Python-like way to check if a package is installed on Debian?
In a bash script, I'd do:
```
dpkg -s packagename | grep Status
```
Suggestions to do the same in a Python script?
Thanks, | This is a pythonic way:
```
import apt
cache = apt.Cache()
if cache['package-name'].is_installed:
print "YES it's installed"
else:
print "NO it's NOT installed"
``` |
Python - difference between os.access and os.path.exists? | 3,388,223 | 16 | 2010-08-02T13:31:58Z | 3,388,286 | 14 | 2010-08-02T13:38:46Z | [
"python",
"operating-system",
"module"
] | ```
def CreateDirectory(pathName):
if not os.access(pathName, os.F_OK):
os.makedirs(pathName)
```
versus:
```
def CreateDirectory(pathName):
if not os.path.exists(pathName):
os.makedirs(pathName)
```
I understand that os.access is a bit more flexible since you can check for RWE attributes as ... | Better to just catch the exception rather than try to prevent it. There are a zillion reasons that makedirs can fail
```
def CreateDirectory(pathName):
try:
os.makedirs(pathName)
except OSError, e:
# could be that the directory already exists
# could be permission error
# could ... |
Django model group by datetime's date | 3,388,559 | 6 | 2010-08-02T14:12:43Z | 3,388,626 | 8 | 2010-08-02T14:19:56Z | [
"python",
"django",
"django-models"
] | Hello
Assume I have a such model:
```
class Entity(models.Model):
start_time = models.DateTimeField()
```
I want to regroup them as **list of lists** which each list of lists contains Entities from the same date (same day, time should be ignored).
How can this be achieved in a pythonic way ?
Thanks | Create a small function to extract just the date:
```
def extract_date(entity):
'extracts the starting date from an entity'
return entity.start_time.date()
```
Then you can use it with [`itertools.groupby`](http://docs.python.org/library/itertools#itertools.groupby):
```
from itertools import groupby
entiti... |
What's wrong with the "or" in my "if" statement? | 3,388,788 | 2 | 2010-08-02T14:39:07Z | 3,388,802 | 17 | 2010-08-02T14:40:48Z | [
"python"
] | I've tried Google, but I can't find the answer to this simple question.
I hate myself for not being able to figure this out, but here we go.
How do I write an if statement with `or` in it?
For example:
```
if raw_input=="dog" or "cat" or "small bird":
print "You can have this animal in your house"
else:
prin... | You can put the allowed animals into a [`tuple`](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences) then use `in` to search for a match
```
if raw_input() in ("dog", "cat", "small bird"):
print "You can have this animal in your house"
else:
print "I'm afraid you can't have this animal in... |
What's wrong with the "or" in my "if" statement? | 3,388,788 | 2 | 2010-08-02T14:39:07Z | 3,388,813 | 11 | 2010-08-02T14:41:44Z | [
"python"
] | I've tried Google, but I can't find the answer to this simple question.
I hate myself for not being able to figure this out, but here we go.
How do I write an if statement with `or` in it?
For example:
```
if raw_input=="dog" or "cat" or "small bird":
print "You can have this animal in your house"
else:
prin... | If you want to use `or`, you need to repeat the whole expression each time:
```
if raw_input == "dog" or raw_input == "cat" or raw_input == "small bird":
```
But a better way to do this particular comparison is with `in`:
```
if raw_input in ("dog", "cat", "small bird"):
``` |
How to silent/quiet HTTPServer and BasicHTTPRequestHandler's stderr output? | 3,389,305 | 27 | 2010-08-02T15:39:28Z | 3,389,505 | 63 | 2010-08-02T16:03:44Z | [
"python",
"httpserver",
"basehttpserver"
] | I am writing a simple http server as part of my project. Below is a skeleton of my script:
```
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class MyHanlder(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self... | This will probably do it:
```
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<html><body><p>OK</p></b... |
Check if multiple strings exist in another string | 3,389,574 | 126 | 2010-08-02T16:10:20Z | 3,389,611 | 250 | 2010-08-02T16:15:25Z | [
"python",
"arrays",
"string",
"exists"
] | How can I check if any of the strings in an array exists in another string?
Like:
```
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
```
That code doesn't work, it's just to show what I want to achieve. | You can use [**`any`**](http://docs.python.org/library/functions.html#any):
```
if any(x in str for x in a):
```
Similarly to check if *all* the strings from the list are found, use [**`all`**](http://docs.python.org/library/functions.html#all) instead of `any`. |
Check if multiple strings exist in another string | 3,389,574 | 126 | 2010-08-02T16:10:20Z | 3,390,918 | 19 | 2010-08-02T19:04:58Z | [
"python",
"arrays",
"string",
"exists"
] | How can I check if any of the strings in an array exists in another string?
Like:
```
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
```
That code doesn't work, it's just to show what I want to achieve. | You should be careful if the strings in `a` or `str` gets longer. The straightforward solutions take O(S\*(A^2)), where `S` is the length of `str` and A is the sum of the lenghts of all strings in `a`. For a faster solution, look at [Aho-Corasick](http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algori... |
Check if multiple strings exist in another string | 3,389,574 | 126 | 2010-08-02T16:10:20Z | 37,401,376 | 7 | 2016-05-23T22:10:00Z | [
"python",
"arrays",
"string",
"exists"
] | How can I check if any of the strings in an array exists in another string?
Like:
```
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
```
That code doesn't work, it's just to show what I want to achieve. | `any()` is by far the best approach if all you want is `True` or `False`, but if you want to know specifically which string/strings match, you can use a couple things.
If you want the first match (with `False` as a default):
```
match = next((x for x in a if x in str), False)
```
If you want to get all matches (incl... |
Why does this do what it does? | 3,390,310 | 9 | 2010-08-02T17:43:51Z | 3,390,359 | 10 | 2010-08-02T17:48:51Z | [
"python",
"syntax"
] | I found this interesting item in a blog today:
```
def abc():
try:
return True
finally:
return False
print "abc() is", abc()
```
Can anyone tell why it does what it does?
Thanks,
KR | If the finally block contains a `return` or `break` statement the result from the try
block is discarded
it's explained in detail in the [python docu](http://docs.python.org/reference/compound_stmts.html) |
Python - Hashlib MD5 differs between linux/windows | 3,390,484 | 11 | 2010-08-02T18:07:06Z | 3,390,602 | 22 | 2010-08-02T18:21:43Z | [
"python"
] | I have a python app in which I am creating packages in windows to be used and later compared in a linux python app. I am creating an md5 for a file in windows to be checked later in linux. The problem is that the same code on the same file gives different Md5 hash results in each environment. Below is the method I use ... | Change `open(filePath)` to `open(filePath, 'rb')`, where the `b` is for binary mode. You're currently opening in text mode, which can cause portability issues. |
Python introspection: description of the parameters a function takes | 3,391,013 | 6 | 2010-08-02T19:16:56Z | 3,391,122 | 9 | 2010-08-02T19:33:08Z | [
"python",
"introspection"
] | Is there is a tool similar to `dir()` for modules that will tell me what parameters a given function takes? For instance, I would like to do something like `dir(os.rename)` and have it tell me what parameters are documented so that I can avoid checking the documentation online, and instead use only the Python scripting... | I realize that you're more interested in `help(thing)` or `thing.__doc__`, but if you're trying to do programmatic introspection (instead of human-readable documentation) to find out about calling a function, then you can use the [`inspect` module](http://docs.python.org/library/inspect.html), as discussed in [this que... |
Repeat string to certain length | 3,391,076 | 86 | 2010-08-02T19:26:44Z | 3,391,105 | 23 | 2010-08-02T19:30:35Z | [
"string",
"python",
"repeat"
] | What is an efficient way to repeat a string to a certain length? Eg: `repeat('abc', 7) -> 'abcabca'`
Here is my current code:
```
def repeat(string, length):
cur, old = 1, string
while len(string) < length:
string += old[cur-1]
cur = (cur+1)%len(old)
return string
```
Is there a better (m... | ```
def repeat_to_length(string_to_expand, length):
return (string_to_expand * ((length/len(string_to_expand))+1))[:length]
``` |
Repeat string to certain length | 3,391,076 | 86 | 2010-08-02T19:26:44Z | 3,391,106 | 336 | 2010-08-02T19:30:44Z | [
"string",
"python",
"repeat"
] | What is an efficient way to repeat a string to a certain length? Eg: `repeat('abc', 7) -> 'abcabca'`
Here is my current code:
```
def repeat(string, length):
cur, old = 1, string
while len(string) < length:
string += old[cur-1]
cur = (cur+1)%len(old)
return string
```
Is there a better (m... | Repeating a string a fixed number of times is a built-in operation:
```
'abc' * 7
```
So, just calculate the number of repeats you need to reach the length you want, and put that on the RHS. You'll then need to trim it to the right length.
(It appears that this is what the other answer does, but a little bit more ex... |
Repeat string to certain length | 3,391,076 | 86 | 2010-08-02T19:26:44Z | 3,391,161 | 13 | 2010-08-02T19:39:18Z | [
"string",
"python",
"repeat"
] | What is an efficient way to repeat a string to a certain length? Eg: `repeat('abc', 7) -> 'abcabca'`
Here is my current code:
```
def repeat(string, length):
cur, old = 1, string
while len(string) < length:
string += old[cur-1]
cur = (cur+1)%len(old)
return string
```
Is there a better (m... | ```
from itertools import cycle, islice
def srepeat(string, n):
return ''.join(islice(cycle(string), n))
``` |
Repeat string to certain length | 3,391,076 | 86 | 2010-08-02T19:26:44Z | 3,391,233 | 22 | 2010-08-02T19:50:43Z | [
"string",
"python",
"repeat"
] | What is an efficient way to repeat a string to a certain length? Eg: `repeat('abc', 7) -> 'abcabca'`
Here is my current code:
```
def repeat(string, length):
cur, old = 1, string
while len(string) < length:
string += old[cur-1]
cur = (cur+1)%len(old)
return string
```
Is there a better (m... | ```
def rep(s, m):
a, b = divmod(m, len(s))
return s * a + s[:b]
``` |
Repeat string to certain length | 3,391,076 | 86 | 2010-08-02T19:26:44Z | 19,934,971 | 22 | 2013-11-12T16:45:49Z | [
"string",
"python",
"repeat"
] | What is an efficient way to repeat a string to a certain length? Eg: `repeat('abc', 7) -> 'abcabca'`
Here is my current code:
```
def repeat(string, length):
cur, old = 1, string
while len(string) < length:
string += old[cur-1]
cur = (cur+1)%len(old)
return string
```
Is there a better (m... | This is pretty pythonic:
```
newstring = 'abc'*5
print newstring[0:6]
``` |
How to transform negative elements to zero without a loop? | 3,391,843 | 21 | 2010-08-02T21:18:23Z | 3,391,887 | 41 | 2010-08-02T21:24:53Z | [
"python",
"numpy"
] | If I have an array like
```
a = np.array([2, 3, -1, -4, 3])
```
I want to set all the negative elements to zero: `[2, 3, 0, 0, 3]`. How to do it with numpy without an explicit for? I need to use the modified `a` in a computation, for example
```
c = a * b
```
where `b` is another array with the same length of the o... | ```
a = a.clip(min=0)
``` |
How to transform negative elements to zero without a loop? | 3,391,843 | 21 | 2010-08-02T21:18:23Z | 3,391,916 | 7 | 2010-08-02T21:27:53Z | [
"python",
"numpy"
] | If I have an array like
```
a = np.array([2, 3, -1, -4, 3])
```
I want to set all the negative elements to zero: `[2, 3, 0, 0, 3]`. How to do it with numpy without an explicit for? I need to use the modified `a` in a computation, for example
```
c = a * b
```
where `b` is another array with the same length of the o... | I would do this:
```
a[a < 0] = 0
```
If you want to keep the original `a` and only set the negative elements to zero in a copy, you can copy the array first:
```
c = a.copy()
c[c < 0] = 0
``` |
Pydoc is not working (Windows XP) | 3,391,998 | 6 | 2010-08-02T21:38:34Z | 5,746,282 | 7 | 2011-04-21T15:27:51Z | [
"python",
"windows-xp",
"pydoc"
] | Using Windows XP and Python 2.7 I tried to run "pydoc" through the terminal. unfortunately it doesn't work.
Since I'm not allowed to post a screenshot (Newbie). Here is what it says (white on black)
What I type:
```
"C:\Python27>pydoc raw_input /"pydoc raw_input"
```
My result (It's German an it roughly translates... | for me
```
% python -m pydoc <params here>
```
worked. python will look for `pydoc.py` in the right directories without further ado. |
python: append values to a set | 3,392,354 | 106 | 2010-08-02T22:40:05Z | 3,392,370 | 142 | 2010-08-02T22:43:15Z | [
"python"
] | i have a set like this:
```
keep = set(generic_drugs_mapping[drug] for drug in drug_input)
```
how do i add values `[0,1,2,3,4,5,6,7,8,9,10]` in to this set? | ```
keep.update(yoursequenceofvalues)
```
e.g, `keep.update(xrange(11))` for your specific example. Or, if you *have* to produce the values in a loop for some other reason,
```
for ...whatever...:
onemorevalue = ...whatever...
keep.add(onemorevalue)
```
But, of course, doing it in bulk with a single `.update` ca... |
python: append values to a set | 3,392,354 | 106 | 2010-08-02T22:40:05Z | 3,392,372 | 27 | 2010-08-02T22:43:46Z | [
"python"
] | i have a set like this:
```
keep = set(generic_drugs_mapping[drug] for drug in drug_input)
```
how do i add values `[0,1,2,3,4,5,6,7,8,9,10]` in to this set? | use `update` like
`keep.update(newvalues)` |
python: append values to a set | 3,392,354 | 106 | 2010-08-02T22:40:05Z | 25,163,489 | 42 | 2014-08-06T14:47:43Z | [
"python"
] | i have a set like this:
```
keep = set(generic_drugs_mapping[drug] for drug in drug_input)
```
how do i add values `[0,1,2,3,4,5,6,7,8,9,10]` in to this set? | You can also use the `|` operator to concatenate two sets (**union** in set theory):
```
>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}
```
Or a shorter form using `|=`:
```
>>> my_set |= {2}
>>> my_set
{1, 2}
```
**Note:** In versions prior to Python 2.7, use `set([...])` instead of `{...}`. |
python: append values to a set | 3,392,354 | 106 | 2010-08-02T22:40:05Z | 31,972,583 | 33 | 2015-08-12T18:17:48Z | [
"python"
] | i have a set like this:
```
keep = set(generic_drugs_mapping[drug] for drug in drug_input)
```
how do i add values `[0,1,2,3,4,5,6,7,8,9,10]` in to this set? | Define set
```
a = set()
```
Use add to append single values
```
a.add(1)
a.add(2)
```
Use update to append iterable values
```
a.update([3,4])
```
Check your collection
```
a
Out[*n*]: {1, 2, 3, 4}
```
That's it - remember, *update* if it is iterable (aka list or tuple) or *add* if not. Happy coding! |
python: how do i always start from the second row in csv? | 3,392,397 | 7 | 2010-08-02T22:50:11Z | 3,392,412 | 11 | 2010-08-02T22:53:10Z | [
"python",
"csv"
] | b holds the contents of a csv file
i need to go through every row of b; however, since it has a header, i dont want to pay attention to the header. how do i start from the second row?
```
for row in b (starting from the second row!!):
``` | Prepend a `next(b)` (in every recent version of Python; `b.next()` in older ones) to skip the first row (if `b` is an iterator; if it is, instead, a list, `for row in b[1:]:`, of course). |
Do dictionaries have a has key method? I'm checking for 'None' and I'm having issues | 3,392,637 | 2 | 2010-08-02T23:48:57Z | 3,392,647 | 11 | 2010-08-02T23:50:45Z | [
"python",
"dictionary"
] | I have 2 dictionaries, and I want to check if a key is in either of the dictionaries.
I am trying:
```
if dic1[p.sku] is not None:
```
I wish there was a hasKey method, anyhow.
I am getting an error if the key isn't found, why is that? | Use the `in` operator:
```
if p.sku in dic1:
...
```
(Incidentally, you can also use the [has\_key](http://docs.python.org/library/stdtypes.html#dict.has_key) method, but the use of `in` is preferred.) |
python s3 using boto, says 'attribute error: 'str' object has no attribute 'connection' | 3,392,843 | 3 | 2010-08-03T00:38:39Z | 10,288,472 | 10 | 2012-04-23T21:17:56Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto"
] | I have a connection that works as I can list buckets, but having issues when trying to add a object.
```
conn = S3Connection(awskey, awssecret)
key = Key(mybucket)
key.key = p.sku
key.set_contents_from_filename(fullpathtofile)
```
I get the error:
```
'attribute error: 'str' object has no attribute 'connection'
``... | Just replace:
```
key = Key(mybucket)
```
with:
```
mybucket = "foo"
bucketobj = conn.get_bucket(mybucket)
mykey = Key(bucketobj)
```
Expanding on sth's comment, you can't pass a string, it needs to be a bucket object. |
Lazy Evaluation for iterating through NumPy arrays | 3,392,877 | 4 | 2010-08-03T00:50:47Z | 3,392,998 | 9 | 2010-08-03T01:25:56Z | [
"python",
"memory-management",
"numpy",
"lazy-evaluation"
] | I have a Python program that processes fairly large NumPy arrays (in the hundreds of megabytes), which are stored on disk in pickle files (one ~100MB array per file). When I want to run a query on the data I load the entire array, via pickle, and then perform the query (so that from the perspective of the Python progra... | [PyTables](http://www.pytables.org/moin) is designed to solve this problem for you. |
How to counting not 0 elements in an iterable? | 3,393,431 | 11 | 2010-08-03T03:40:33Z | 3,393,470 | 15 | 2010-08-03T03:51:06Z | [
"python",
"iterator",
"list-comprehension"
] | I'm looking for a better/more Pythonic solution for the following snippet
```
count = sum(1 for e in iterable if e)
``` | ```
len(filter(None, iterable))
```
Using `None` as the predicate for `filter` just says to use the truthiness of the items. (maybe clearer would be `len(filter(bool, iterable))`) |
Python check first and last index of a list | 3,394,687 | 8 | 2010-08-03T08:09:09Z | 3,394,724 | 10 | 2010-08-03T08:13:16Z | [
"python",
"list"
] | Assuming I have object\_list list which contains objects.
I want to check if my current iteration is is at the first or the last.
```
for object in object_list:
do_something
if first_indexed_element:
do_something_else
if last_indexed_element:
do_another_thing
```
How can this be achieved?... | You can use [`enumerate()`](http://docs.python.org/library/functions.html#enumerate):
```
for i, obj in enumerate(object_list):
do_something
if i == 0:
do_something_else
if i == len(object_list) - 1:
do_another_thing
```
But instead of checking in every iteration which object you are deali... |
Python check first and last index of a list | 3,394,687 | 8 | 2010-08-03T08:09:09Z | 3,394,821 | 12 | 2010-08-03T08:26:07Z | [
"python",
"list"
] | Assuming I have object\_list list which contains objects.
I want to check if my current iteration is is at the first or the last.
```
for object in object_list:
do_something
if first_indexed_element:
do_something_else
if last_indexed_element:
do_another_thing
```
How can this be achieved?... | ```
li = iter(object_list)
obj = next(li)
do_first_thing_with(obj)
while True:
try:
do_something_with(obj)
obj = next(li)
except StopIteration:
do_final_thing_with(obj)
break
``` |
What are good programming questions to exercise the use of "if ... else" in Python? | 3,394,757 | 9 | 2010-08-03T08:16:41Z | 3,394,792 | 7 | 2010-08-03T08:22:49Z | [
"python",
"if-statement"
] | What would be a good set of programming exercises that would help Python newbies to learn the use of the "if ... else" construct? I could cook up the following, do you know of any more?
1. Find the largest/smallest of three numbers.
2. Given a date (year, month, day), find the next date.
Most of the intended audience... | "Figure out whether a given year is a leap year" springs to mind almost immediately. Just give 'em the rules and turn 'em loose.
Other possibilities (albeit with stuff other than `if` statements):
* Hunt the Wumpus (you may have to google for this one, I'm showing my age).
* The perennial "detect a win in a Tic Tac T... |
Using multiple arguments for string formatting in Python (e.g., '%s ... %s') | 3,395,138 | 85 | 2010-08-03T09:19:07Z | 3,395,158 | 78 | 2010-08-03T09:22:55Z | [
"python",
"string",
"syntax"
] | I have a string that looks like `'%s in %s'` and I want to know how to seperate the arguments so that they are two different %s. My mind coming from Java came up with this:
```
'%s in %s' % unicode(self.author), unicode(self.publication)
```
But this doesn't work so how does it look in Python? | If you're using more than one argument it has to be in a tuple (note the extra parentheses):
```
'%s in %s' % (unicode(self.author), unicode(self.publication))
```
As [EOL points out](#3395666), the `unicode()` function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to e... |
Using multiple arguments for string formatting in Python (e.g., '%s ... %s') | 3,395,138 | 85 | 2010-08-03T09:19:07Z | 3,395,177 | 32 | 2010-08-03T09:26:20Z | [
"python",
"string",
"syntax"
] | I have a string that looks like `'%s in %s'` and I want to know how to seperate the arguments so that they are two different %s. My mind coming from Java came up with this:
```
'%s in %s' % unicode(self.author), unicode(self.publication)
```
But this doesn't work so how does it look in Python? | ### On a tuple/mapping object for multiple argument `format`
The following is excerpt from the documentation:
> Given `format % values`, `%` conversion specifications in `format` are replaced with zero or more elements of `values`. The effect is similar to the using `sprintf()` in the C language.
>
> If `format` requ... |
Using multiple arguments for string formatting in Python (e.g., '%s ... %s') | 3,395,138 | 85 | 2010-08-03T09:19:07Z | 3,395,185 | 97 | 2010-08-03T09:27:19Z | [
"python",
"string",
"syntax"
] | I have a string that looks like `'%s in %s'` and I want to know how to seperate the arguments so that they are two different %s. My mind coming from Java came up with this:
```
'%s in %s' % unicode(self.author), unicode(self.publication)
```
But this doesn't work so how does it look in Python? | Mark Cidade's answer is right - you need to supply a tuple.
However from Python 2.6 onwards you can use [`format`](http://docs.python.org/library/stdtypes.html#str.format) instead of `%`:
```
'{0} in {1}'.format(unicode(self.author,'utf-8'), unicode(self.publication,'utf-8'))
```
Usage of `%` for formatting strings... |
Using multiple arguments for string formatting in Python (e.g., '%s ... %s') | 3,395,138 | 85 | 2010-08-03T09:19:07Z | 3,395,666 | 8 | 2010-08-03T10:33:32Z | [
"python",
"string",
"syntax"
] | I have a string that looks like `'%s in %s'` and I want to know how to seperate the arguments so that they are two different %s. My mind coming from Java came up with this:
```
'%s in %s' % unicode(self.author), unicode(self.publication)
```
But this doesn't work so how does it look in Python? | There is a significant problem with some of the answers posted so far: `unicode()` decodes from the default encoding, which is often ASCII; in fact, `unicode()` tries to make "sense" of the bytes it is given by converting them into characters. Thus, the following code, which is essentially what is recommended by previo... |
Aggregating save()s in Django? | 3,395,236 | 18 | 2010-08-03T09:33:55Z | 3,397,586 | 37 | 2010-08-03T14:37:43Z | [
"python",
"sql",
"django",
"sqlite"
] | I'm using Django with an sqlite backend, and write performance is a problem. I may graduate to a "proper" db at some stage, but for the moment I'm stuck with sqlite. I think that my write performance problems are probably related to the fact that I'm creating a large number of rows, and presumably each time I `save()` ... | Actually this is easier to do then you think. You can use [transactions](http://docs.djangoproject.com/en/dev/topics/db/transactions/) in Django. These batch database operations (specifically save, insert and delete) into one operation. I've found the easiest one to use is `commit_on_success`. Essentially you wrap your... |
Aggregating save()s in Django? | 3,395,236 | 18 | 2010-08-03T09:33:55Z | 29,216,436 | 21 | 2015-03-23T17:20:53Z | [
"python",
"sql",
"django",
"sqlite"
] | I'm using Django with an sqlite backend, and write performance is a problem. I may graduate to a "proper" db at some stage, but for the moment I'm stuck with sqlite. I think that my write performance problems are probably related to the fact that I'm creating a large number of rows, and presumably each time I `save()` ... | New as of Django 1.6 is [atomic, a simple API to control DB transactions](https://docs.djangoproject.com/en/1.7/topics/db/transactions/#django.db.transaction.atomic). Copied verbatim from the docs:
atomic is usable both as a [decorator](http://docs.python.org/glossary.html#term-decorator):
```
from django.db import t... |
How can I get the object count for a model in Django's templates? | 3,395,863 | 21 | 2010-08-03T11:05:23Z | 3,396,090 | 45 | 2010-08-03T11:39:52Z | [
"python",
"django",
"django-models"
] | I'm my Django application I'm fetching all the objects for a particular model like so:
```
secs = Sections.objects.filter(order__gt = 5)
```
I pass this varbiles to my templates and i can access all the properties of the Model like `section.name`, `section.id`, etc.
There is a model called `Books` which has a FK to ... | If `Books` has a ForeignKey to `Sections`, then Django will automatically create a reverse relationship from Sections back to Books, which will be called `books_set`. This is a Manager, which means you can use `.filter()`, `.get()` and `.count()` on it - and you can use these in your template.
```
{{ sec.books_set.cou... |
How can I get the object count for a model in Django's templates? | 3,395,863 | 21 | 2010-08-03T11:05:23Z | 10,008,017 | 9 | 2012-04-04T09:02:13Z | [
"python",
"django",
"django-models"
] | I'm my Django application I'm fetching all the objects for a particular model like so:
```
secs = Sections.objects.filter(order__gt = 5)
```
I pass this varbiles to my templates and i can access all the properties of the Model like `section.name`, `section.id`, etc.
There is a model called `Books` which has a FK to ... | Additionally to what Daniel said, Django creates reverse relationships automatically (as Daniel said above) unless you override their names with the related\_name argument. In your particular case, you would have something like:
```
class Book(models.Model):
section = models.ForeignKey(Section, related_name="books... |
enumerate()-ing a generator in Python | 3,396,279 | 33 | 2010-08-03T12:08:17Z | 3,396,313 | 41 | 2010-08-03T12:14:41Z | [
"python",
"iterator",
"generator",
"enumerate"
] | I'd like to know what happens when I pass the result of a generator function to python's enumerate(). Example:
```
def veryBigHello():
i = 0
while i < 10000000:
i += 1
yield "hello"
numbered = enumerate(veryBigHello())
for i, word in numbered:
print i, word
```
Is the enumeration iterated... | It's lazy. It's fairly easy to prove that's the case:
```
>>> def abc():
... letters = ['a','b','c']
... for letter in letters:
... print letter
... yield letter
...
>>> numbered = enumerate(abc())
>>> for i, word in numbered:
... print i, word
...
a
0 a
b
1 b
c
2 c
``` |
enumerate()-ing a generator in Python | 3,396,279 | 33 | 2010-08-03T12:08:17Z | 3,396,321 | 8 | 2010-08-03T12:15:23Z | [
"python",
"iterator",
"generator",
"enumerate"
] | I'd like to know what happens when I pass the result of a generator function to python's enumerate(). Example:
```
def veryBigHello():
i = 0
while i < 10000000:
i += 1
yield "hello"
numbered = enumerate(veryBigHello())
for i, word in numbered:
print i, word
```
Is the enumeration iterated... | Since you can call this function without getting out of memory exceptions it definitly is lazy
```
def veryBigHello():
i = 0
while i < 1000000000000000000000000000:
yield "hello"
numbered = enumerate(veryBigHello())
for i, word in numbered:
print i, word
``` |
enumerate()-ing a generator in Python | 3,396,279 | 33 | 2010-08-03T12:08:17Z | 3,396,639 | 16 | 2010-08-03T12:55:01Z | [
"python",
"iterator",
"generator",
"enumerate"
] | I'd like to know what happens when I pass the result of a generator function to python's enumerate(). Example:
```
def veryBigHello():
i = 0
while i < 10000000:
i += 1
yield "hello"
numbered = enumerate(veryBigHello())
for i, word in numbered:
print i, word
```
Is the enumeration iterated... | It's even easier to tell than either of the previous suggest:
```
$ python
Python 2.5.5 (r255:77872, Mar 15 2010, 00:43:13)
[GCC 4.3.4 20090804 (release) 1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> abc = (letter for letter in 'abc')
>>> abc
<generator object at 0x7ff29d8c>
>... |
How to read a raw image using PIL? | 3,397,157 | 23 | 2010-08-03T13:52:35Z | 3,397,322 | 7 | 2010-08-03T14:11:16Z | [
"python",
"image",
"image-processing",
"python-imaging-library"
] | I have a raw image where each pixel corresponds to a 16 bits unsigned integer. I am trying to read using the PIL Image.fromstring() function as in the following code:
```
if __name__ == "__main__":
if (len(sys.argv) != 4):
print 'Error: missing input argument'
sys.exit()
file = open(sys.argv[1... | > Image.frombuffer(mode, size, data) => image
>
> (New in PIL 1.1.4). Creates an image memory from pixel data in a string or buffer object, using the standard "raw" decoder. For some modes, the image memory will share memory with the original buffer (this means that changes to the original buffer object are reflected i... |
How to read a raw image using PIL? | 3,397,157 | 23 | 2010-08-03T13:52:35Z | 3,397,465 | 17 | 2010-08-03T14:25:43Z | [
"python",
"image",
"image-processing",
"python-imaging-library"
] | I have a raw image where each pixel corresponds to a 16 bits unsigned integer. I am trying to read using the PIL Image.fromstring() function as in the following code:
```
if __name__ == "__main__":
if (len(sys.argv) != 4):
print 'Error: missing input argument'
sys.exit()
file = open(sys.argv[1... | The specific documentation is at <http://effbot.org/imagingbook/concepts.htm>:
> ## Mode
>
> The mode of an image defines the type
> and depth of a pixel in the image. The
> current release supports the following
> standard modes:
>
> * 1 (1-bit pixels, black and white, stored with one pixel per byte)
> * L (8-bit pix... |
How to get started with a bare-bones Eclipse + PyDev | 3,397,343 | 6 | 2010-08-03T14:13:26Z | 3,397,734 | 8 | 2010-08-03T14:53:31Z | [
"python",
"eclipse",
"pydev",
"barebones"
] | I am planning to move from SPE to Eclipse + PyDev for better code completion. I think SPE's code completion is rather weird.
Anyway, how should I get started with Eclipse + PyDev? I browsed <http://www.eclipse.org> and I found that Eclipse is made up of some base/core system and plugins are added for more functionalit... | The leanest Eclipse installation is the [Platform Runtime Binary](http://download.eclipse.org/eclipse/downloads/drops4/R-4.4.2-201502041700/) at around 50MB (look for it in the middle of the page). Install it and then once in eclipse go to Help->Install New Software... and use <http://pydev.org/updates> as link to inst... |
In Django, how to get django-storages, boto and easy_thumbnail to work nicely? | 3,397,599 | 5 | 2010-08-03T14:38:50Z | 5,262,932 | 14 | 2011-03-10T16:46:45Z | [
"python",
"django",
"amazon-s3",
"thumbnails"
] | I'm making a website where files are uploaded through the admin and this will then store them on Amazon S3. I'm using django-storages and boto for this, and it seems to be working just fine.
Thing is, I'm used to use my easy\_thumbnails (the new sorl.thumbnail) on the template side to create thumbnails on the fly. I p... | easy\_thumbnails will do S3-based image thumbnailing for you - you just need to set `settings.THUMBNAIL_DEFAULT_STORAGE`, so that easy\_thumbnails knows which storage to use (in your case, you probably want to set it to the same storage you're using for your ImageFields). |
copy multiple files in python | 3,397,752 | 30 | 2010-08-03T14:54:57Z | 3,397,772 | 7 | 2010-08-03T14:57:22Z | [
"python",
"file",
"copy"
] | How to copy all the files in one directory to another in python.
I have the source path and the destination path in a string. | Look at [shutil in the Python docs](http://docs.python.org/library/shutil.html), specifically the [copytree](https://docs.python.org/2/library/shutil.html#shutil.copytree) command. |
copy multiple files in python | 3,397,752 | 30 | 2010-08-03T14:54:57Z | 3,398,331 | 8 | 2010-08-03T15:56:32Z | [
"python",
"file",
"copy"
] | How to copy all the files in one directory to another in python.
I have the source path and the destination path in a string. | If you don't want to copy the whole tree (with subdirs etc), use or `glob.glob("path/to/dir/*.*")` to get a list of all the filenames, loop over the list and use `shutil.copy` to copy each file.
```
for filename in glob.glob(os.path.join(source_dir, '*.*')):
shutil.copy(filename, dest_dir)
``` |
copy multiple files in python | 3,397,752 | 30 | 2010-08-03T14:54:57Z | 3,399,299 | 47 | 2010-08-03T17:59:51Z | [
"python",
"file",
"copy"
] | How to copy all the files in one directory to another in python.
I have the source path and the destination path in a string. | You can use [os.listdir()](http://docs.python.org/library/os.html#os.listdir) to get the files in the source directory, [os.path.isfile()](http://docs.python.org/library/os.path.html#os.path.isfile) to see if they are regular files (including symbolic links on \*nix systems), and [shutil.copy](http://docs.python.org/li... |
python: get number without decimal places | 3,398,410 | 2 | 2010-08-03T16:05:05Z | 3,398,433 | 10 | 2010-08-03T16:08:34Z | [
"python"
] | ```
a=123.45324
```
is there a function that will return just `123`? | [`int`](http://docs.python.org/library/functions.html#int) will always truncate towards zero:
```
>>> a = 123.456
>>> int(a)
123
>>> a = 0.9999
>>> int(a)
0
>>> int(-1.5)
-1
```
The difference between `int` and [`math.floor`](http://docs.python.org/library/math.html#math.floor) is that `math.floor` returns the number... |
Sorting a list of lists in Python | 3,398,589 | 6 | 2010-08-03T16:30:01Z | 3,398,649 | 13 | 2010-08-03T16:36:34Z | [
"python",
"list",
"sorting"
] | ```
c2=[]
row1=[1,22,53]
row2=[14,25,46]
row3=[7,8,9]
c2.append(row2)
c2.append(row1)
c2.append(row3)
```
`c2` is now:
```
[[14, 25, 46], [1, 22, 53], [7, 8, 9]]
```
how do i sort `c2` in such a way that for example:
```
for row in c2:
sort on row[2]
```
the result would be:
```
[[7,8,9],[14,25,46],[1,22,53]]
`... | [The `key` argument to `sort`](http://docs.python.org/library/stdtypes.html#mutable-sequence-types) specifies a function of one argument that is used to extract a comparison key from each list element. So we can create a simple `lambda` that returns the last element from each row to be used in the sort:
```
c2.sort(ke... |
using python, Remove HTML tags/formatting from a string | 3,398,852 | 8 | 2010-08-03T17:02:55Z | 3,398,894 | 22 | 2010-08-03T17:09:10Z | [
"python",
"regex"
] | I have a string that contains html markup like links, bold text, etc.
I want to strip all the tags so I just have the raw text.
What's the best way to do this? regex? | If you are going to use regex:
```
import re
def striphtml(data):
p = re.compile(r'<.*?>')
return p.sub('', data)
>>> striphtml('<a href="foo.com" class="bar">I Want This <b>text!</b></a>')
'I Want This text!'
``` |
using python, Remove HTML tags/formatting from a string | 3,398,852 | 8 | 2010-08-03T17:02:55Z | 3,398,951 | 11 | 2010-08-03T17:17:16Z | [
"python",
"regex"
] | I have a string that contains html markup like links, bold text, etc.
I want to strip all the tags so I just have the raw text.
What's the best way to do this? regex? | AFAIK using regex is a bad idea for parsing HTML, you would be better off
using a HTML/XML parser like [beautiful soup](http://www.crummy.com/software/BeautifulSoup/). |
How do I maximize efficiency with numpy arrays? | 3,399,361 | 7 | 2010-08-03T18:05:50Z | 3,399,529 | 9 | 2010-08-03T18:24:25Z | [
"python",
"performance",
"numpy"
] | I am just getting to know numpy, and I am impressed by its claims of C-like efficiency with memory access in its ndarrays. I wanted to see the differences between these and pythonic lists for myself, so I ran a quick timing test, performing a few of the same simple tasks with numpy without it. Numpy outclassed regular ... | `a2` is a NumPy array, right? One possible reason it might be taking so long in NumPy (if other processes' activity don't account for it as Wayne Werner suggested) is that you're iterating over the array using a Python loop. At every step of the iteration, Python has to fetch a single value out of the NumPy array and c... |
Why is it not possible to create a practical Perl to Python source code converter? | 3,399,781 | 4 | 2010-08-03T18:50:59Z | 3,399,795 | 7 | 2010-08-03T18:52:57Z | [
"python",
"perl"
] | It would be nice if there existed a program that automatically transforms Perl code to Python code, making the resultant Python program as readable and maintainable as the original one, let alone working the same way.
The most obvious solution would just invoke `perl` via Python utils:
```
#!/usr/bin/python
os.exec("... | It is not impossible, it would just take a lot of work.
By the way, there is [Perthon](http://perthon.sourceforge.net/), a Python-to-Perl translator. It just seems like nobody is willing to make one that goes the other way.
EDIT: I think I might I've found the reason why a Python to Perl translator is much easier to ... |
Why is it not possible to create a practical Perl to Python source code converter? | 3,399,781 | 4 | 2010-08-03T18:50:59Z | 3,399,878 | 25 | 2010-08-03T19:02:20Z | [
"python",
"perl"
] | It would be nice if there existed a program that automatically transforms Perl code to Python code, making the resultant Python program as readable and maintainable as the original one, let alone working the same way.
The most obvious solution would just invoke `perl` via Python utils:
```
#!/usr/bin/python
os.exec("... | Why Perl is not Python.
1. Perl has statements which Python more-or-less totally lacks. While you can probably contrive matching statements, the syntax will be so utterly unlike Perl as to make it difficult to call it a "translation". You'd really have to cook up some fancy Python stuff to make it as terse as the orig... |
Why is it not possible to create a practical Perl to Python source code converter? | 3,399,781 | 4 | 2010-08-03T18:50:59Z | 3,400,239 | 34 | 2010-08-03T19:47:54Z | [
"python",
"perl"
] | It would be nice if there existed a program that automatically transforms Perl code to Python code, making the resultant Python program as readable and maintainable as the original one, let alone working the same way.
The most obvious solution would just invoke `perl` via Python utils:
```
#!/usr/bin/python
os.exec("... | Your best Perl to Python converter is probably 23 years old, just graduated university and is looking for a job. |
Why is it not possible to create a practical Perl to Python source code converter? | 3,399,781 | 4 | 2010-08-03T18:50:59Z | 3,400,756 | 16 | 2010-08-03T21:07:37Z | [
"python",
"perl"
] | It would be nice if there existed a program that automatically transforms Perl code to Python code, making the resultant Python program as readable and maintainable as the original one, let alone working the same way.
The most obvious solution would just invoke `perl` via Python utils:
```
#!/usr/bin/python
os.exec("... | Just to expand on some of the other lists here, these are a few Perl constructs that are probably very clumsy in python (if possible).
* dynamic scope (via the `local` keyword)
* typeglob manipulation (multiple variables with the same name)
* formats (they have a syntax all their own)
* closures over mutable variables... |
Python UTF-8 comparison | 3,400,171 | 16 | 2010-08-03T19:39:49Z | 3,400,320 | 26 | 2010-08-03T20:00:16Z | [
"python",
"unicode",
"utf-8",
"python-2.x"
] | ```
a = {"a":"çö"}
b = "çö"
a['a']
>>> '\xc3\xa7\xc3\xb6'
b.decode('utf-8') == a['a']
>>> False
```
What is going in there?
edit= I'm sorry, it was my mistake. It is still False. I'm using Python 2.6 on Ubuntu 10.04. | ## Possible solutions
Either write like this:
```
a = {"a": u"çö"}
b = "çö"
b.decode('utf-8') == a['a']
```
Or like this (you may also skip the `.decode('utf-8')` on both sides):
```
a = {"a": "çö"}
b = "çö"
b.decode('utf-8') == a['a'].decode('utf-8')
```
Or like this (my recommendation):
```
a = {"a": u"... |
Calling a python script from command line without typing "python" first | 3,400,381 | 6 | 2010-08-03T20:08:34Z | 3,400,399 | 24 | 2010-08-03T20:10:07Z | [
"python",
"linux",
"shell",
"command-line"
] | Question: In command line, how do I call a python script without having to type `python` in front of the script's name? Is this even possible?
---
Info:
I wrote a handy script for accessing sqlite databases from command line, but I kind of don't like having to type "python SQLsap args" and would rather just type "SQ... | You can prepend a shebang on the first line of the script:
```
#!/usr/bin/env python
```
This will tell your current shell which command to feed the script into. |
Global Variable from a different file Python | 3,400,525 | 13 | 2010-08-03T20:28:55Z | 3,400,652 | 23 | 2010-08-03T20:46:49Z | [
"python"
] | So I have two different files somewhat like this:
file1.py
```
from file2 import *
foo = "bar";
test = SomeClass();
```
file2.py
```
class SomeClass :
def __init__ (self):
global foo;
print foo;
```
However I cannot seem to get file2 to recognize variables from file1 even though its imported in... | Importing `file2` in `file1.py` makes the global (i.e., module level) names bound in `file2` available to following code in `file1` -- the only such name is `SomeClass`. It does **not** do the reverse: names defined in `file2` are not made available to code in `file1` when `file2` imports `file1`. This would be the cas... |
How to get an isoformat datetime string including the default timezone? | 3,401,428 | 26 | 2010-08-03T23:13:02Z | 3,401,661 | 24 | 2010-08-04T00:05:32Z | [
"python",
"datetime",
"datetime-format"
] | I need to produce a time string that matches the iso format `yyyy-mm-ddThh:mm:ss.ssssss-ZO:NE`. The `now()` and `utcnow()` class methods almost do what I want.
```
>>> import datetime
>>> #time adjusted for current timezone
>>> datetime.datetime.now().isoformat()
'2010-08-03T03:00:00.000000'
>>> #unadjusted UTC time
>... | You need to make your datetime objects timezone aware. from the [datetime docs](http://docs.python.org/library/datetime.html#module-datetime):
> There are two kinds of date and time objects: ânaiveâ and âawareâ. This distinction refers to whether the object has any notion of time zone, daylight saving time, or... |
How to get an isoformat datetime string including the default timezone? | 3,401,428 | 26 | 2010-08-03T23:13:02Z | 28,164,131 | 16 | 2015-01-27T05:58:31Z | [
"python",
"datetime",
"datetime-format"
] | I need to produce a time string that matches the iso format `yyyy-mm-ddThh:mm:ss.ssssss-ZO:NE`. The `now()` and `utcnow()` class methods almost do what I want.
```
>>> import datetime
>>> #time adjusted for current timezone
>>> datetime.datetime.now().isoformat()
'2010-08-03T03:00:00.000000'
>>> #unadjusted UTC time
>... | To get the current time in UTC in Python 3.2+:
```
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2015-01-27T05:57:31.399861+00:00'
```
To get local time in Python 3.3+:
```
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).astimezone().isoformat()
'2... |
How to get an isoformat datetime string including the default timezone? | 3,401,428 | 26 | 2010-08-03T23:13:02Z | 29,698,242 | 7 | 2015-04-17T11:45:07Z | [
"python",
"datetime",
"datetime-format"
] | I need to produce a time string that matches the iso format `yyyy-mm-ddThh:mm:ss.ssssss-ZO:NE`. The `now()` and `utcnow()` class methods almost do what I want.
```
>>> import datetime
>>> #time adjusted for current timezone
>>> datetime.datetime.now().isoformat()
'2010-08-03T03:00:00.000000'
>>> #unadjusted UTC time
>... | With [arrow](https://arrow.readthedocs.org/en/latest/):
```
>>> import arrow
>>> arrow.now().isoformat()
'2015-04-17T06:36:49.463207-05:00'
>>> arrow.utcnow().isoformat()
'2015-04-17T11:37:17.042330+00:00'
``` |
python: how should I write very long lines of code? | 3,401,468 | 9 | 2010-08-03T23:21:13Z | 3,401,515 | 12 | 2010-08-03T23:29:43Z | [
"python",
"pep8"
] | if i have a very long line of a code, is it possible to continue it on the next line for example:
```
url='http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|'
+ '100,000|1,000,000&chxp=1,0&chxr=0,0,' +
max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1... | ## Where to look for help in future
Most syntax problems like this are dealt with in [PEP 8](http://www.python.org/dev/peps/pep-0008/). For the answer to this question, you can refer to the section "Code Layout".
## Preferred way : Use `()`, `{}` & `[]`
From PEP-8:
> The preferred way of wrapping long lines is by u... |
python: how should I write very long lines of code? | 3,401,468 | 9 | 2010-08-03T23:21:13Z | 3,401,545 | 20 | 2010-08-03T23:37:11Z | [
"python",
"pep8"
] | if i have a very long line of a code, is it possible to continue it on the next line for example:
```
url='http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|'
+ '100,000|1,000,000&chxp=1,0&chxr=0,0,' +
max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1... | I would write it like this
```
url=('http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|'
'100,000|1,000,000&chxp=1,0&chxr=0,0,%(max_freq)s300|1,0,3&chxs=0,676767'
',13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465'
'&cht=bvs&chco=A2C180&chds=0,300&chd=t:'%{'max_fre... |
Hyperlink in Tkinter Text widget? | 3,402,110 | 7 | 2010-08-04T02:12:02Z | 3,404,849 | 12 | 2010-08-04T11:00:49Z | [
"python",
"windows",
"tkinter",
"hyperlink"
] | I am re designing a portion of my current software project, and want to use *hyperlinks* instead of `Buttons`. I really didn't want to use a `Text` widget, but that is all I could find when I googled the subject. Anyway, I found an example of this, but keep getting this error:
```
TclError: bitmap "blue" not defined
`... | If you don't want to use a text widget, you don't need to. An alternative is to use a label and bind mouse clicks to it. Even though it's a label it still responds to events.
For example:
```
import tkinter as tk
class App:
def __init__(self, root):
self.root = root
for text in ("link1", "link2",... |
Permanently add a directory to PYTHONPATH | 3,402,168 | 164 | 2010-08-04T02:28:07Z | 3,402,176 | 223 | 2010-08-04T02:29:53Z | [
"python",
"windows",
"save",
"pythonpath",
"sys"
] | Whenever I use `sys.path.append`, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? | If you're using bash (on a Mac or GNU/Linux distro), add this to your `~/.bashrc`
```
export PYTHONPATH="${PYTHONPATH}:/my/other/path"
``` |
Permanently add a directory to PYTHONPATH | 3,402,168 | 164 | 2010-08-04T02:28:07Z | 3,402,193 | 71 | 2010-08-04T02:33:07Z | [
"python",
"windows",
"save",
"pythonpath",
"sys"
] | Whenever I use `sys.path.append`, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? | You need to add your new directory to the environment variable `PYTHONPATH`, separated by a colon from previous contents thereof. In any form of Unix, you can do that in a startup script appropriate to whatever shell you're using (`.profile` or whatever, depending on your favorite shell) with a command which, again, de... |
Permanently add a directory to PYTHONPATH | 3,402,168 | 164 | 2010-08-04T02:28:07Z | 3,402,196 | 10 | 2010-08-04T02:33:24Z | [
"python",
"windows",
"save",
"pythonpath",
"sys"
] | Whenever I use `sys.path.append`, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? | You could add the path via your pythonrc file, which defaults to ~/.pythonrc on linux. ie.
```
import sys
sys.path.append('/path/to/dir')
```
You could also set the `PYTHONPATH` environment variable, in a global rc file, such `~/.profile` on mac or linux, or via Control Panel -> System -> Advanced tab -> Environment ... |
Permanently add a directory to PYTHONPATH | 3,402,168 | 164 | 2010-08-04T02:28:07Z | 12,311,321 | 51 | 2012-09-07T03:28:30Z | [
"python",
"windows",
"save",
"pythonpath",
"sys"
] | Whenever I use `sys.path.append`, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? | Instead of manipulating `PYTHONPATH` you can also create a [path configuration file](http://docs.python.org/library/site.html). First find out in which directory Python searches for this information:
```
python -m site --user-site
```
For some reason this doesn't seem to work in Python 2.7. There you can use:
```
py... |
Permanently add a directory to PYTHONPATH | 3,402,168 | 164 | 2010-08-04T02:28:07Z | 12,429,896 | 16 | 2012-09-14T18:19:00Z | [
"python",
"windows",
"save",
"pythonpath",
"sys"
] | Whenever I use `sys.path.append`, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? | In case anyone is still confused - if you are on a Mac, do the following:
1. Open up Terminal
2. Type `open .bash_profile`
3. In the text file that pops up, add this line at the end:
`export PYTHONPATH=$PYTHONPATH:foo/bar`
4. Save the file, restart the Terminal, and you're done |
Permanently add a directory to PYTHONPATH | 3,402,168 | 164 | 2010-08-04T02:28:07Z | 15,709,523 | 7 | 2013-03-29T18:47:32Z | [
"python",
"windows",
"save",
"pythonpath",
"sys"
] | Whenever I use `sys.path.append`, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? | On linux you can create a symbolic link from your package to a directory of the PYTHONPATH without having to deal with the environment variables. Something like:
```
ln -s /your/path /usr/lib/pymodules/python2.7/
``` |
Permanently add a directory to PYTHONPATH | 3,402,168 | 164 | 2010-08-04T02:28:07Z | 30,728,643 | 10 | 2015-06-09T09:49:26Z | [
"python",
"windows",
"save",
"pythonpath",
"sys"
] | Whenever I use `sys.path.append`, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? | This works on Windows
1. On Windows, with Python 2.7 go to the Python setup folder.
2. Open Lib/site-packages.
3. Add an example.pth empty file to this folder.
4. Add the required path to the file, one per each line.
Then you'll be able to see all modules within those paths from your scripts. |
Is there a way to force lxml to parse Unicode strings that specify an encoding in a tag? | 3,402,520 | 8 | 2010-08-04T04:13:10Z | 3,403,962 | 12 | 2010-08-04T08:51:00Z | [
"python",
"lxml"
] | I have an XML file that specifies an encoding, and I use UnicodeDammit to convert it to unicode (for reasons of storage, I can't store it as a string). I later pass it to lxml but it refuses to ignore the encoding specified in the file and parse it as Unicode, and it raises an exception.
How can I force lxml to parse ... | You cannot parse from unicode strings AND have an encoding declaration in the string.
So, either you make it an encoded string (as you apparently can't store it as a string, you will have to re-encode it before parsing. Or you serialize the tree as unicode with lxml yourself: `etree.tostring(tree, encoding=unicode)`, W... |
identifying objects, why does the returned value from id(...) change? | 3,402,679 | 10 | 2010-08-04T04:51:20Z | 3,402,717 | 26 | 2010-08-04T05:00:45Z | [
"python"
] | > ### id(object)
>
> This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.
Can you explain this output? Why does `j`'s id change?
```
>>> i=10
>>> id(i)
6337824
>>> j=10
>>> id(j)
6337824
>>> j=j+1
>>> id(j)
6337800
>>> id(i)
633782... | Because integers are immutable, each integer value is a distinct object with a unique id. The integer `10` has a different id from `11`. Doing `j=j+1` doesn't change the value of an existing integer object, rather it changes `j` to point to the object for `11`.
Check out what happens when we independently create a new... |
Django urls straight to html template | 3,402,708 | 24 | 2010-08-04T04:58:21Z | 3,402,778 | 25 | 2010-08-04T05:13:07Z | [
"python",
"django"
] | Learning django & python.
Just set up a new site after doing the tutorial. Now for arguments sake say I want to add a bunch of About us, FAQ basic html pages with very limited dynamic elements do you go ahead and write a new line in my urls.py file for each page? or is their some neat way to say map all \* \*.html to ... | As long as there is some uniquely identifying section in the URL, you will not need to create an entry in urls.py for each direct-template url.
For example, you could say that all urls ending in ".html" are referencing a direct file from the templates.
```
urlpatterns = patterns('django.views.generic.simple',
(r'... |
Django urls straight to html template | 3,402,708 | 24 | 2010-08-04T04:58:21Z | 3,402,840 | 12 | 2010-08-04T05:26:40Z | [
"python",
"django"
] | Learning django & python.
Just set up a new site after doing the tutorial. Now for arguments sake say I want to add a bunch of About us, FAQ basic html pages with very limited dynamic elements do you go ahead and write a new line in my urls.py file for each page? or is their some neat way to say map all \* \*.html to ... | Write a url which grabs the static pages you're interested in
```
url(r'^(?P<page_name>about|faq|press|whatever)/$', 'myapp.staticpage', name='static-pages')
```
The `staticpage` view function in `myapp`
```
from django.views.generic.simple import direct_to_template
from django.http import Http404
def staticpage(re... |
Django urls straight to html template | 3,402,708 | 24 | 2010-08-04T04:58:21Z | 14,669,308 | 10 | 2013-02-03T03:47:59Z | [
"python",
"django"
] | Learning django & python.
Just set up a new site after doing the tutorial. Now for arguments sake say I want to add a bunch of About us, FAQ basic html pages with very limited dynamic elements do you go ahead and write a new line in my urls.py file for each page? or is their some neat way to say map all \* \*.html to ... | If you're using the [**class based views**](https://docs.djangoproject.com/en/dev/ref/class-based-views/) because `direct_to_template` has been [deprecated](https://docs.djangoproject.com/en/1.4/topics/generic-views-migration/), you can create a simple wrapper that renders your own templates directly:
```
from django.... |
Django urls straight to html template | 3,402,708 | 24 | 2010-08-04T04:58:21Z | 29,133,093 | 7 | 2015-03-18T21:30:42Z | [
"python",
"django"
] | Learning django & python.
Just set up a new site after doing the tutorial. Now for arguments sake say I want to add a bunch of About us, FAQ basic html pages with very limited dynamic elements do you go ahead and write a new line in my urls.py file for each page? or is their some neat way to say map all \* \*.html to ... | Currently the best way to do this is using TemplateView from generic class-based views:
```
url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),
``` |
Creating Instances of IronPython Classes From C# | 3,402,713 | 3 | 2010-08-04T04:59:41Z | 3,403,327 | 10 | 2010-08-04T07:09:31Z | [
"c#",
".net",
"python",
"ironpython",
"dynamic-language-runtime"
] | I want to create an instance of an IronPython class from C#, but my current attempts all seem to have failed.
This is my current code:
```
ConstructorInfo[] ci = type.GetConstructors();
foreach (ConstructorInfo t in from t in ci
where t.GetParameters().Length == 1
... | This code works with IronPython 2.6.1
```
static void Main(string[] args)
{
const string script = @"
class A(object) :
def __init__(self) :
self.a = 100
class B(object) :
def __init__(self, a, v) :
self.a = a
self.v = v
def run(self) :
return self.a.a + se... |
Fast replacement of values in a numpy array | 3,403,973 | 21 | 2010-08-04T08:52:55Z | 3,404,089 | 21 | 2010-08-04T09:09:48Z | [
"python",
"replace",
"numpy"
] | I have a very large numpy array (containing up to a million elements) like the one below:
```
[ 0 1 6 5 1 2 7 6 2 3 8 7 3 4 9 8 5 6 11 10 6 7 12 11 7
8 13 12 8 9 14 13 10 11 16 15 11 12 17 16 12 13 18 17 13 14 19 18 15 16
21 20 16 17 22 21 17 18 23 22 18 19 24 23]
```
and a small dictionary m... | I believe there's even more efficient method, but for now, try
```
from numpy import copy
newArray = copy(theArray)
for k, v in d.iteritems(): newArray[theArray==k] = v
```
---
Microbenchmark and test for correctness:
```
#!/usr/bin/env python2.7
from numpy import copy, random, arange
random.seed(0)
data = rando... |
Fast replacement of values in a numpy array | 3,403,973 | 21 | 2010-08-04T08:52:55Z | 3,404,401 | 14 | 2010-08-04T09:56:18Z | [
"python",
"replace",
"numpy"
] | I have a very large numpy array (containing up to a million elements) like the one below:
```
[ 0 1 6 5 1 2 7 6 2 3 8 7 3 4 9 8 5 6 11 10 6 7 12 11 7
8 13 12 8 9 14 13 10 11 16 15 11 12 17 16 12 13 18 17 13 14 19 18 15 16
21 20 16 17 22 21 17 18 23 22 18 19 24 23]
```
and a small dictionary m... | Assuming the values are between 0 and some maximum integer, one could implement a fast replace by using the numpy-array as `int->int` dict, like below
```
mp = numpy.arange(0,max(data)+1)
mp[replace.keys()] = replace.values()
data = mp[data]
```
where first
```
data = [ 0 1 6 5 1 2 7 6 2 3 8 7 3 4 9 8... |
Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work | 3,405,397 | 15 | 2010-08-04T12:19:01Z | 3,405,479 | 31 | 2010-08-04T12:31:29Z | [
"python",
"windows",
"process",
"multiprocessing"
] | I don't understand why this simple code
```
# file: mp.py
from multiprocessing import Process
import sys
def func(x):
print 'works ', x + 2
sys.stdout.flush()
p = Process(target= func, args= (2, ))
p.start()
p.join()
p.terminate()
print 'done'
sys.stdout.flush()
```
creates "pythonw.exe" processes continuou... | You need to [protect then entry point of the program by using `if __name__ == '__main__':`](http://docs.python.org/library/multiprocessing.html#windows).
This is a Windows specific problem. On Windows your module has to be imported into a new Python interpreter in order for it to access your target code. If you don't ... |
Elegant way to remove fields from nested dictionaries | 3,405,715 | 4 | 2010-08-04T12:58:47Z | 3,405,772 | 9 | 2010-08-04T13:05:56Z | [
"python",
"dictionary"
] | I had to remove some fields from a dictionary, the keys of this fields are on a list. So I write this function:
```
def delete_keys_from_dict(dict_del, lst_keys):
"""
Delete the keys present in the lst_keys from the dictionary.
Loops recursively over nested dictionaries.
"""
dict_foo = dict_del.cop... | ```
def delete_keys_from_dict(dict_del, lst_keys):
for k in lst_keys:
try:
del dict_del[k]
except KeyError:
pass
for v in dict_del.values():
if isinstance(v, dict):
delete_keys_from_dict(v, lst_keys)
return dict_del
``` |
Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting? | 3,405,794 | 7 | 2010-08-04T13:08:32Z | 3,405,828 | 13 | 2010-08-04T13:11:57Z | [
"functional-programming",
"python",
"list-comprehension",
"short-circuiting"
] | I wrote a simple script to solve a "logic puzzle", the type of puzzle from school where you are given a number of rules and then must be able to find the solution for problems like "There are five musicians named A, B, C, D, and E playing in a concert, each plays one after the other... if A goes before B, and D is not ... | Use a [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions):
```
rules = [ rule1, rule2, rule3, rule4, ... ]
rules_generator = ( r( solution ) for f in rules )
return all( rules_generator )
```
Syntactic sugar: you can omit the extra parentheses:
```
rules = [ rule1, rule2, ... |
Iteration order of sets in Python | 3,406,341 | 16 | 2010-08-04T14:08:15Z | 3,406,439 | 20 | 2010-08-04T14:21:21Z | [
"python",
"iteration",
"set"
] | If I have two identical sets, meaning `a == b` gives me `True`, will they have the same iteration order? I tried it, and it works:
```
>>> foo = set("abc")
>>> bar = set("abc")
>>> zip(foo, bar)
[('a', 'a'), ('c', 'c'), ('b', 'b')]
```
My question is, was I lucky, or is this behavior guaranteed? | It wasn't *just* a coincidence that they came out the same: the implementation happens to be deterministic, so creating the same set twice produces the same ordering. But Python does not guarantee that.
If you create the same set in two different ways:
```
n = set("abc")
print n
m = set("kabc")
m.remove("k")
print m... |
Parsing Snort Logs with PyParsing | 3,406,544 | 7 | 2010-08-04T14:31:40Z | 3,407,282 | 12 | 2010-08-04T15:45:56Z | [
"python",
"pyparsing",
"snort"
] | Having a problem with parsing Snort logs using the pyparsing module.
The problem is with separating the Snort log (which has multiline entries, separated by a blank line) and getting pyparsing to parse each entry as a whole chunk, rather than read in line by line and expecting the grammar to work with each line (obvio... | ```
import pyparsing as pyp
import itertools
integer = pyp.Word(pyp.nums)
ip_addr = pyp.Combine(integer+'.'+integer+'.'+integer+'.'+integer)
def snort_parse(logfile):
header = (pyp.Suppress("[**] [")
+ pyp.Combine(integer + ":" + integer + ":" + integer)
+ pyp.Suppress(pyp.SkipTo("[**]... |
Paranoia, excessive logging and exception handling on simple scripts dealing with files. Is this normal? | 3,406,627 | 6 | 2010-08-04T14:39:29Z | 3,406,958 | 8 | 2010-08-04T15:14:15Z | [
"python",
"exception",
"logging"
] | I find myself using python for a lot of file management scripts as the one below. While looking for examples on the net I am surprised about how little logging and exception handling is featured on the examples. Every time I write a new script my intention is not to end up as the one below but if it deals with files th... | Learning to let go (or how I learned to live with the bomb)...
Ask yourself this: what exactly are you afraid of, and how will you handle it if it happens? In the example that you provide you want to avoid data-loss. The way that you've handled it is by looking for every combination of conditions that you think is an ... |
How to delete all files in directory on remote server in python? | 3,406,734 | 2 | 2010-08-04T14:50:57Z | 3,407,755 | 7 | 2010-08-04T16:43:38Z | [
"python",
"paramiko"
] | I'd like to delete all the files in a given directory on a remote server that I'm already connected to using paramiko. I cannot explicitly give the file names, though, because these will vary depending on which version of file I had previously put there.
Here's what I'm trying to do... the line below the #TODO is the ... | A [Fabric](http://fabfile.org) routine could be as simple as this:
```
with cd(remoteArtifactPath):
run("rm *")
```
Fabric is great for executing shell commands on remote servers. Fabric actually uses Paramiko underneath, so you can use both if you need to. |
python sort without lambda expressions | 3,407,414 | 5 | 2010-08-04T16:00:44Z | 3,407,821 | 11 | 2010-08-04T16:51:25Z | [
"python",
"lambda",
"sorting"
] | I often do sorts in Python using lambda expressions, and although it works fine, I find it not very readable, and was hoping there might be a better way. Here is a typical use case for me.
I have a list of numbers, e.g., `x = [12, 101, 4, 56, ...]`
I have a separate list of indices: `y = range(len(x))`
I want to sor... | You can use the `__getitem__` method of the list x. This behaves the same as your lambda and will be much faster since it is implemented as a C function instead of a python function:
```
>>> x = [12, 101, 4, 56]
>>> y = range(len(x))
>>> sorted(y, key=x.__getitem__)
[2, 0, 3, 1]
``` |
python: what happens to opened file if i quit before it is closed? | 3,407,522 | 3 | 2010-08-04T16:15:22Z | 3,407,572 | 8 | 2010-08-04T16:21:01Z | [
"python"
] | i am opening a csv file:
```
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
header=data[0]
counter=collections.defaultdict(int)
for row in data:
counter[row[10]]+=1
return (data,counter,header)
```
does the file sta... | The operating system will automatically close any open file descriptors when your process terminates.
File data stored in memory (e.g. variables, Python buffers) will be lost. Data buffered in the operating system may be flushed to disk when the file is implicitly closed (checking the exact semantics of in-kernel dirt... |
Parsing files (ics/ icalendar) using Python | 3,408,097 | 37 | 2010-08-04T17:28:13Z | 3,408,488 | 48 | 2010-08-04T18:17:47Z | [
"python",
"icalendar"
] | I have a .ics file in the following format. What is the best way to parse it? I need to retrieve the Summary, Description, and Time for each of the entries.
```
BEGIN:VCALENDAR
X-LOTUS-CHARSET:UTF-8
VERSION:2.0
PRODID:-//Lotus Development Corporation//NONSGML Notes 8.0//EN
METHOD:PUBLISH
BEGIN:VTIMEZONE
TZID:India
BEG... | [The `icalendar` package](http://pypi.python.org/pypi/icalendar) looks nice.
For instance, to write a file:
```
from icalendar import Calendar, Event
from datetime import datetime
from pytz import UTC # timezone
cal = Calendar()
cal.add('prodid', '-//My calendar product//mxm.dk//')
cal.add('version', '2.0')
event =... |
Parsing files (ics/ icalendar) using Python | 3,408,097 | 37 | 2010-08-04T17:28:13Z | 6,470,135 | 11 | 2011-06-24T15:32:55Z | [
"python",
"icalendar"
] | I have a .ics file in the following format. What is the best way to parse it? I need to retrieve the Summary, Description, and Time for each of the entries.
```
BEGIN:VCALENDAR
X-LOTUS-CHARSET:UTF-8
VERSION:2.0
PRODID:-//Lotus Development Corporation//NONSGML Notes 8.0//EN
METHOD:PUBLISH
BEGIN:VTIMEZONE
TZID:India
BEG... | You could probably also use the `vobject` module for this: <http://pypi.python.org/pypi/vobject>
If you have a `sample.ics` file you can read it's contents like, so:
```
# read the data from the file
data = open("sample.ics").read()
# parse the top-level event with vobject
cal = vobject.readOne(data)
# Get Summary
... |
string to datetime with fractional seconds, on Google App Engine | 3,408,494 | 8 | 2010-08-04T18:18:35Z | 3,422,122 | 9 | 2010-08-06T08:30:32Z | [
"python",
"google-app-engine",
"datetime"
] | I need to convert a string to a datetime object, along with the fractional seconds. I'm running into various problems.
Normally, i would do:
```
>>> datetime.datetime.strptime(val, "%Y-%m-%dT%H:%M:%S.%f")
```
But errors and old docs showed me that python2.5's strptime does not have %f...
Investigating further, it s... | **Parsing**
Without the `%f` format support for `datetime.datetime.strptime()` you can still sufficiently easy enter it into a `datetime.datetime` object (randomly picking a value for your `val` here) using `datetime.datetime.replace()`), tested on 2.5.5:
```
>>> val = '2010-08-06T10:00:14.143896'
>>> nofrag, frag = ... |
How do I rotate a polygon in python on a Tkinter Canvas? | 3,408,779 | 6 | 2010-08-04T18:49:28Z | 3,409,039 | 8 | 2010-08-04T19:20:52Z | [
"python",
"vector",
"tkinter"
] | I am working to create a version of asteroids using Python and Tkinter. When the left or right arrow key is pressed the ship needs to rotate. The ship is a triangle on the Tkinter canvas. I am having trouble coming up with formula to adjust the coordinates for the triangle. I believe it has something to do with sin and... | First of all, you need to rotate around a center of the triangle. The centroid would probably work best for that. To find that, you can use the formula `C = (1/3*(x0 + x1 + x2), 1/3*(y0 + y1 + y2))`, as it's the average of all points in the triangle. Then you have to apply the rotation with that point as the center. So... |
Python 2.5 Windows Binaries? | 3,408,847 | 9 | 2010-08-04T18:57:39Z | 3,408,866 | 8 | 2010-08-04T19:00:09Z | [
"python",
"windows",
"python-2.5"
] | I need to test an issue that occurs on Windows with Python 2.5, but [the releases page](http://www.python.org/download/releases/) doesn't link to a binary for 2.5.
Is there anywhere I could find a copy? | It's on their FTP server still, it's just the link that's gone:
<http://www.python.org/ftp/python/2.5/>
You'll want one of the MSI files, depending on your Windows version (32-bits or 64-bits). |
How do I do conditional array arithmetic on a numpy array? | 3,409,255 | 8 | 2010-08-04T19:47:12Z | 3,409,349 | 22 | 2010-08-04T20:01:25Z | [
"python",
"numpy"
] | I'm trying to get a better grip on numpy arrays, so I have a sample question to ask about them:
Say I have a numpy array called a. I want to perform an operation on a that increments all the values inside it that are less than 0 and leaves the rest alone. for example, if I had:
```
a = np.array([1,2,3,-1,-2,-3])
```
... | ```
In [45]: a = np.array([1,2,3,-1,-2,-3])
In [46]: a[a<0]+=1
In [47]: a
Out[47]: array([ 1, 2, 3, 0, -1, -2])
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.