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
split a string into a list of tuples
2,908,308
2
2010-05-25T20:32:31Z
2,908,318
11
2010-05-25T20:34:48Z
[ "python" ]
If i have a string like: ``` "user1:type1,user2:type2,user3:type3" ``` and I want to convert this to a list of tuples like so: ``` [('user1','type1'),('user2','type2'),('user3','type3')] ``` how would i go about doing this? I'm fairly new to python but couldn't find a good example in the documentation to do this. ...
``` >>> s = "user1:type1,user2:type2,user3:type3" >>> [tuple(x.split(':')) for x in s.split(',')] [('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')] ```
How to append a tag after a link with BeautifulSoup
2,908,362
3
2010-05-25T20:39:45Z
2,909,136
7
2010-05-25T23:03:39Z
[ "python", "beautifulsoup" ]
Starting from an Html input like this: ``` <p> <a href="http://www.foo.com">this if foo</a> <a href="http://www.bar.com">this if bar</a> </p> ``` using BeautifulSoup, i would like to change this Html in: ``` <p> <a href="http://www.foo.com">this if foo</a><b>OK</b> <a href="http://www.bar.com">this if bar</a><b>OK</...
You can use BeautifulSoup's [insert](http://www.crummy.com/software/BeautifulSoup/documentation.html#Adding%20a%20Brand%20New%20Element) to add the element in the right place: ``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html) for link_tag in soup.findAll('a'): link_tag_idx = link_tag.parent.c...
what does "from MODULE import _" do in python?
2,908,444
7
2010-05-25T20:53:51Z
2,908,541
11
2010-05-25T21:07:32Z
[ "python", "import" ]
In the Getting things gnome code base I stumbled upon this import statement ``` from GTG import _ ``` and have no idea what it means, never seen this in the documentation and a quick so / google search didn't turn anything up.
`from GTG import _` imports the `_` function from the `GTG` module into the "current" namespace. Usually, the `_` function is an alias for [`gettext.gettext()`](http://docs.python.org/library/gettext.html#gettext.gettext), a function that shows the localized version of a given message. The documentation gives a pictur...
append versus resize for numpy array
2,908,672
14
2010-05-25T21:30:11Z
2,908,771
7
2010-05-25T21:46:35Z
[ "python", "arrays", "numpy" ]
I would like to append a value at the end of my `numpy.array`. I saw `numpy.append` function but this performs an exact copy of the original array adding at last my new value. I would like to avoid copies since my arrays are big. I am using `resize` method and then set the last index available to the new value. Can yo...
My simple timing experiment of append vs. resizing showed that resizing is about 3x faster and its the fastest way that I can think of to do this. Also, the answer to [this question](http://stackoverflow.com/questions/1730080?tab=votes#tab-top) seems to imply that resizing the array is the way to go because it is in-pl...
Python: What's a correct and good way to implement __hash__()?
2,909,106
70
2010-05-25T22:56:46Z
2,909,119
78
2010-05-25T22:59:52Z
[ "python", "hashtable", "hashcode", "dictionary" ]
What's a correct and good way to implement `__hash__()`? I am talking about the function that returns a hashcode that is then used to insert objects into hashtables aka dictionaries. As `__hash__()` returns an integer and is used for "binning" objects into hashtables I assume that the values of the returned integer s...
An easy, correct way to implement `__hash__()` is to use a key tuple. It won't be as fast as a specialized hash, but if you need that then you should probably implement the type in C. Here's an example of using a key for hash and equality: ``` class A(object): def __key(self): return (self.attr_a, self.at...
Python: What's a correct and good way to implement __hash__()?
2,909,106
70
2010-05-25T22:56:46Z
2,909,572
14
2010-05-26T01:05:53Z
[ "python", "hashtable", "hashcode", "dictionary" ]
What's a correct and good way to implement `__hash__()`? I am talking about the function that returns a hashcode that is then used to insert objects into hashtables aka dictionaries. As `__hash__()` returns an integer and is used for "binning" objects into hashtables I assume that the values of the returned integer s...
Paul Larson of Microsoft Research studied a wide variety of hash functions. He told me that ``` for c in some_string: hash = 101 * hash + ord(c) ``` worked surprisingly well for a wide variety of strings. I've found that similar polynomial techniques work well for computing a hash of disparate subfields.
Python: What's a correct and good way to implement __hash__()?
2,909,106
70
2010-05-25T22:56:46Z
19,073,010
11
2013-09-29T00:03:34Z
[ "python", "hashtable", "hashcode", "dictionary" ]
What's a correct and good way to implement `__hash__()`? I am talking about the function that returns a hashcode that is then used to insert objects into hashtables aka dictionaries. As `__hash__()` returns an integer and is used for "binning" objects into hashtables I assume that the values of the returned integer s...
John Millikin proposed a solution similar to this: ``` class A(object): def __init__(self, a, b, c): self._a = a self._b = b self._c = c def __eq__(self, othr): return ((self._a, self._b, self._c) == (othr._a, othr._b, othr._c)) def __hash__(self): ...
Is it bad practice to use python's getattr extensively?
2,909,423
7
2010-05-26T00:21:50Z
2,909,734
19
2010-05-26T02:07:55Z
[ "python", "shell", "performance", "getattr" ]
I'm creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making use of the fact that functions are first class objects in python. For flexibility's sake (mostly for parsing commands), I'm thinking of changing my ...
The difference between direct attribute access and using getattr() should be fairly negligible. You can tell the difference between the two versions' bytecodes by using Python's `dis` module to compare the two approaches: ``` >>> import dis >>> dis.dis(lambda x: x.foo) 1 0 LOAD_FAST 0 (x) ...
Paramiko and Pseudo-tty Allocation
2,909,481
18
2010-05-26T00:38:45Z
2,909,781
13
2010-05-26T02:24:46Z
[ "python", "ssh", "paramiko" ]
I'm trying to use Paramiko to connect to a remote host and execute a number of text file substitutions. ``` i, o, e = client.exec_command("perl -p -i -e 's/" + initial + "/" + replaced + "/g'" + conf); ``` Some of these commands need to be run as sudo, which results in: > sudo: sorry, ...
I think you want the `invoke_shell` method of the `SSHClient` object (I'd love to give a URL but the paramiko docs at [lag.net](http://www.lag.net/paramiko/docs/) are frame-heavy and just won't show me a specific URL for a given spot in the docs) -- it gives you a `Channel`, on which you can do `exec_command` and the l...
Paramiko and Pseudo-tty Allocation
2,909,481
18
2010-05-26T00:38:45Z
7,613,010
19
2011-09-30T15:58:29Z
[ "python", "ssh", "paramiko" ]
I'm trying to use Paramiko to connect to a remote host and execute a number of text file substitutions. ``` i, o, e = client.exec_command("perl -p -i -e 's/" + initial + "/" + replaced + "/g'" + conf); ``` Some of these commands need to be run as sudo, which results in: > sudo: sorry, ...
The following code works for me: ``` #!/usr/bin/env python import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('localhost',username='root',password='secret') chan = ssh.get_transport().open_session() chan.get_pty() chan.exec_command('tty') print(chan.recv(1...
Paramiko and Pseudo-tty Allocation
2,909,481
18
2010-05-26T00:38:45Z
28,310,421
20
2015-02-03T22:58:57Z
[ "python", "ssh", "paramiko" ]
I'm trying to use Paramiko to connect to a remote host and execute a number of text file substitutions. ``` i, o, e = client.exec_command("perl -p -i -e 's/" + initial + "/" + replaced + "/g'" + conf); ``` Some of these commands need to be run as sudo, which results in: > sudo: sorry, ...
Actually it's quite simple. Just: ``` stdin, stdout, stderr = client.exec_command(command, get_pty=True) ```
How to sort a list by the 2nd tuple element in python and C#
2,909,652
9
2010-05-26T01:33:38Z
2,909,666
13
2010-05-26T01:38:19Z
[ "c#", "python", "sorting" ]
I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this: ``` sorted(myList, key=lambda x: x[1]) ``` which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I kn...
Another way to do it in python is this ``` from operator import itemgetter sorted(myList, key=itemgetter(1)) ```
Python list directory, subdirectory, and files
2,909,975
28
2010-05-26T03:38:04Z
2,909,998
72
2010-05-26T03:46:18Z
[ "python", "file", "path" ]
I'm trying to make a script to list all directory, subdirectory, and files in a given directory. I tried this: ``` import sys,os root = "/home/patate/directory/" path = os.path.join(root, "targetdirectory") for r,d,f in os.walk(path): for file in f: print os.path.join(root,file) ``` Unfortunatly it do...
Use `os.path.join` to concatenate the *directory* and file *name*: ``` for path, subdirs, files in os.walk(root): for name in files: print os.path.join(path, name) ``` Note the usage of `path` and not `root` in the concatenation, since using `root` would be incorrect. --- In Python 3.4, the [pathlib](ht...
Python list directory, subdirectory, and files
2,909,975
28
2010-05-26T03:38:04Z
13,214,966
10
2012-11-04T00:38:36Z
[ "python", "file", "path" ]
I'm trying to make a script to list all directory, subdirectory, and files in a given directory. I tried this: ``` import sys,os root = "/home/patate/directory/" path = os.path.join(root, "targetdirectory") for r,d,f in os.walk(path): for file in f: print os.path.join(root,file) ``` Unfortunatly it do...
Just in case... Getting all files in the directory and subdirectories matching some pattern (\*.py for example): ``` import os from fnmatch import fnmatch root = '/some/directory' pattern = "*.py" for path, subdirs, files in os.walk(root): for name in files: if fnmatch(name, pattern): print o...
How can I login to a website with Python?
2,910,221
38
2010-05-26T05:17:17Z
2,910,309
36
2010-05-26T05:38:59Z
[ "python", "website", "httpclient" ]
How can I do it? I was trying to enter some specified link (with urllib), but to do it, I need to log in. I have this source from the site: ``` <form id="login-form" action="auth/login" method="post"> <div> <!--label for="rememberme">Remember me</label><input type="checkbox" class="remember" checked="checked"...
Maybe you want to use [twill](http://twill.idyll.org/) (it's based on [mechanize](http://wwwsearch.sourceforge.net/mechanize/)). It's quite easy to use and should be able to do what you want. It will look like the following: ``` from twill.commands import * go('http://mysite.org') fv("1", "email-email", "blabla.com"...
How can I login to a website with Python?
2,910,221
38
2010-05-26T05:17:17Z
2,910,487
12
2010-05-26T06:18:24Z
[ "python", "website", "httpclient" ]
How can I do it? I was trying to enter some specified link (with urllib), but to do it, I need to log in. I have this source from the site: ``` <form id="login-form" action="auth/login" method="post"> <div> <!--label for="rememberme">Remember me</label><input type="checkbox" class="remember" checked="checked"...
``` import cookielib import urllib import urllib2 url = 'http://www.someserver.com/auth/login' values = {'email-email' : 'john@example.com', 'password-clear' : 'Combination', 'password-password' : 'mypassword' } data = urllib.urlencode(values) cookies = cookielib.CookieJar() opener = urllib2.buil...
How can I login to a website with Python?
2,910,221
38
2010-05-26T05:17:17Z
2,910,491
18
2010-05-26T06:19:05Z
[ "python", "website", "httpclient" ]
How can I do it? I was trying to enter some specified link (with urllib), but to do it, I need to log in. I have this source from the site: ``` <form id="login-form" action="auth/login" method="post"> <div> <!--label for="rememberme">Remember me</label><input type="checkbox" class="remember" checked="checked"...
Typically you'll need cookies to log into a site, which means cookielib, urllib and urllib2. Here's a class which I wrote back when I was playing Facebook web games: ``` import cookielib import urllib import urllib2 # set these to whatever your fb account is fb_username = "your@facebook.login" fb_password = "secretpa...
How can I login to a website with Python?
2,910,221
38
2010-05-26T05:17:17Z
28,628,514
16
2015-02-20T12:01:34Z
[ "python", "website", "httpclient" ]
How can I do it? I was trying to enter some specified link (with urllib), but to do it, I need to log in. I have this source from the site: ``` <form id="login-form" action="auth/login" method="post"> <div> <!--label for="rememberme">Remember me</label><input type="checkbox" class="remember" checked="checked"...
Let me try to make it simple, suppose URL of the site is www.example.com and you need to sign up by filling username and password, so we go to the login page say <http://www.example.com/login.php> now and view it's source code and search for the action URL it will be in form tag something like ``` <form name="loginfo...
Python/YACC Lexer: Token priority?
2,910,338
7
2010-05-26T05:45:59Z
10,422,943
10
2012-05-02T23:04:10Z
[ "python", "parsing", "nlp", "yacc" ]
I'm trying to use reserved words in my grammar: ``` reserved = { 'if' : 'IF', 'then' : 'THEN', 'else' : 'ELSE', 'while' : 'WHILE', } tokens = [ 'DEPT_CODE', 'COURSE_NUMBER', 'OR_CONJ', 'ID', ] + list(reserved.values()) t_DEPT_CODE = r'[A-Z]{2,}' t_COURSE_NUMBER = r'[0-9]{4}' t_OR_CONJ = r'or' t_ign...
## Mystery Solved! Ok, i ran into this issue on my own today and looked for solution - did not find it on S/O - but found it in the manual: <http://www.dabeaz.com/ply/ply.html#ply_nn6> > When building the master regular expression, rules are added in the > following order: > > * All tokens defined by functions are ad...
Including a Django app's url.py is resulting in a 404
2,910,714
9
2010-05-26T06:58:35Z
2,910,796
16
2010-05-26T07:13:27Z
[ "python", "django", "url-routing", "http-status-code-404", "django-urls" ]
I have the following code in the urls.py in mysite project. **/mysite/urls.py** ``` from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^gallery/$', include('mysite.gallery.urls')), ) ``` This results in a 404 page when I try to access a url set in gallery/urls.py. **/mysite/gallery/urls.py** ...
Remove the `$` from the regex of main `urls.py` ``` urlpatterns = patterns('', (r'^gallery/', include('mysite.gallery.urls')), ) ``` You don't need `gallery` in the included Urlconf. ``` urlpatterns = patterns('', (r'^browse/$', 'mysite.gallery.views.browse'), (r'^photo/$', 'mysite.gallery.views.photo'...
In Python How can I declare a Dynamic Array
2,910,864
6
2010-05-26T07:24:29Z
2,910,944
45
2010-05-26T07:37:23Z
[ "python", "listbox" ]
I want to declare an Array and all items present in the ListBox Should Be deleted irrespective of the Group name present in the ListBox. can any body help me coding in Python. I am using WINXP OS & Python 2.6.
In Python, a `list` is a dynamic array. You can create one like this: ``` lst = [] # Declares an empty list named lst ``` Or you can fill it with items: ``` lst = [1,2,3] ``` You can add items using "append": ``` lst.append('a') ``` You can iterate over elements of the list using the `for` loop: ``` for item in ...
How to upload binary file with ftplib in Python?
2,911,754
5
2010-05-26T09:44:33Z
2,911,937
20
2010-05-26T10:10:31Z
[ "python", "ftplib" ]
My python2 script uploads files nicely using this method but python3 is presenting problems and I'm stuck as to where to go next (googling hasn't helped). ``` from ftplib import FTP ftp = FTP(ftp_host, ftp_user, ftp_pass) ftp.storbinary('STOR myfile.txt', open('myfile.txt')) ``` The error I get is ``` Traceback (mos...
The issue is not with the command argument, but with the the file object. Since you're storing binary you need to open file with `'rb'` flag: ``` >>> ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb')) '226 File receive OK.' ```
Injecting raw TCP packets with Python
2,912,123
4
2010-05-26T10:38:35Z
2,914,000
10
2010-05-26T14:45:40Z
[ "python", "tcp" ]
What would be a suitable way to inject a raw TCP packet with Python? For example, I have the payload consisting of hexadecimal numbers and I want to send that sequence of hexadecimal numbers to a network daemon: so that if I choose to send 'abcdef', I see 'abcdef' on the wire too. But not '6162636566' as in the case of...
Try [scapy](http://www.secdev.org/projects/scapy/), a powerful interactive packet manipulation program. Example: ``` %> sudo scapy >>> packet1 = IP(dst='127.0.0.1')/TCP(dport=9999) >>> packet1.payload = 'abcdef' >>> send(packet1) . Sent 1 packets. >>> packet1.show() ###[ IP ]### version= 4 ihl= None tos= 0x0 ...
Is there a clever way to pass the key to defaultdict's default_factory?
2,912,231
35
2010-05-26T10:55:14Z
2,912,455
57
2010-05-26T11:28:08Z
[ "python" ]
A class has a constructor which takes one parameter: ``` class C(object): def __init__(self, v): self.v = v ... ``` Somewhere in the code, it is useful for values in a dict to know their keys. I want to use a defaultdict with the key passed to newborn default values: ``` d = defaultdict(lambda ...
It hardly qualifies as *clever* - but subclassing is your friend: ``` class keydefaultdict(defaultdict): def __missing__(self, key): if self.default_factory is None: raise KeyError( key ) else: ret = self[key] = self.default_factory(key) return ret d = keydefaul...
How to iterate over function arguments
2,912,615
16
2010-05-26T11:48:44Z
2,912,627
12
2010-05-26T11:50:05Z
[ "python", "arguments" ]
I have a Python function accepting several string arguments `def foo(a, b, c):` and concatenating them in a string. I want to iterate over all function arguments to check they are not None. How it can be done? Is there a quick way to convert None to ""? Thanks.
``` def func(*args): ' '.join(i if i is not None else '' for i in args) ``` if you're joining on an empty string, you could just do `''.join(i for i in args if i is not None)`
How to iterate over function arguments
2,912,615
16
2010-05-26T11:48:44Z
2,912,884
21
2010-05-26T12:28:40Z
[ "python", "arguments" ]
I have a Python function accepting several string arguments `def foo(a, b, c):` and concatenating them in a string. I want to iterate over all function arguments to check they are not None. How it can be done? Is there a quick way to convert None to ""? Thanks.
[`locals()`](http://docs.python.org/library/functions.html#locals) may be your friend here if you call it first thing in your function. **Example 1**: ``` >>> def fun(a, b, c): ... d = locals() ... e = d ... print e ... print locals() ... >>> fun(1, 2, 3) {'a': 1, 'c': 3, 'b': 2} {'a': 1, 'c': 3, 'b'...
Python Source Formatter/Pretty Printer
2,913,324
13
2010-05-26T13:23:49Z
2,913,427
10
2010-05-26T13:36:27Z
[ "python", "pretty-print" ]
Is there an online or offline utility that will format/pretty-print Python source code?
<http://pypi.python.org/pypi/PythonTidy> is an excellent, simple script. I've found that PyLint and other code analysis tools all choke on pyrex, twisted and other modules. If you want formatting, just use ***PythonTidy***.
Python read multiline JSON
2,913,554
13
2010-05-26T13:52:08Z
2,913,637
20
2010-05-26T14:03:04Z
[ "python", "json" ]
I have been trying to use JSON to store settings for a program. I can't seem to get Python 2.6 's JSON Decoder to decode multi-line JSON strings... Here is example input: ``` .settings file: """ {\ 'user':'username',\ 'password':'passwd',\ }\ """ ``` I have tried a couple other syntaxes for this file, which I wi...
Get rid of all of the backslashes and all of the "Pythonic" quoting in the settings file. Works fine if the file is just: ``` { "user":"username", "password":"passwd" } ``` Note also that JSON strings are quoted with double quotes, not single quotes. See JSON spec here: <http://www.json.org/>
How should I correctly handle exceptions in Python3
2,913,819
12
2010-05-26T14:24:19Z
2,913,895
24
2010-05-26T14:33:53Z
[ "python", "exception", "logging" ]
I can't understand what sort of exceptions I should handle 'here and now', and what sort of exceptions I should re-raise or just don't handle here, and what to do with them later (on higher tier). For example: I wrote client/server application using python3 with ssl communication. Client is supposed to verify files on ...
In general, you should "catch" the exceptions that you expect to happen (because they may be caused by user error, or other environmental problems outside of your program's control), especially if you know what your code might be able to do about them. Just giving more details in an error report is a marginal issue, th...
varargs in lambda functions in Python
2,914,883
17
2010-05-26T16:26:29Z
2,914,933
25
2010-05-26T16:32:48Z
[ "python", "lambda", "varargs" ]
Is it possible a lambda function to have variable number of arguments? For example, I want to write a metaclass, which creates a method for every method of some other class and this newly created method returns the opposite value of the original method and has the same number of arguments. And I want to do this with la...
There is no problem using varargs in lambda functions. The issue here is different: The problem is that the the lambda refrences the loop variable `v`. But by the time the lambda is called, the value of `v` has changed and the lambda calls the wrong function. This is always something to watch out for when you define a...
varargs in lambda functions in Python
2,914,883
17
2010-05-26T16:26:29Z
2,914,938
10
2010-05-26T16:33:01Z
[ "python", "lambda", "varargs" ]
Is it possible a lambda function to have variable number of arguments? For example, I want to write a metaclass, which creates a method for every method of some other class and this newly created method returns the opposite value of the original method and has the same number of arguments. And I want to do this with la...
Yes. ``` >>> l = lambda *x: print(x) >>> l(1,2,3) (1, 2, 3) ```
How do I abort a socket.recv() from another thread in Python
2,915,160
7
2010-05-26T17:04:46Z
6,403,690
11
2011-06-19T16:39:36Z
[ "python", "multithreading", "sockets", "recv" ]
I have a main thread that waits for connection. It spawns client threads that will echo the response from the client (telnet in this case). But say that I want to close down all sockets and all threads after some time, like after 1 connection. How would I do? If I do clientSocket.close() from the main thread, it won't ...
I know this is an old thread and that Samuel probably fixed his issue a long time ago. However, I had the same problem and came across this post while google'ing. Found a solution and think it is worthwhile to add. You can use the shutdown method on the socket class. It can prevent further sends, receives or both. > ...
Install a Python package into a different directory using pip?
2,915,471
194
2010-05-26T17:55:48Z
2,916,320
188
2010-05-26T19:59:36Z
[ "python", "pip" ]
I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that. So how do I modify the command ``` pip install package_name ``` to make `pip` install the package somewhere other than the default `site-packages`?
Use: ``` pip install --install-option="--prefix=$PREFIX_PATH" package_name ``` You might also want to use `--ignore-installed` to force all dependencies to be reinstalled using this new prefix. You can use `--install-option` to multiple times to add any of the options you can use with `python setup.py install` (`--pr...
Install a Python package into a different directory using pip?
2,915,471
194
2010-05-26T17:55:48Z
11,017,307
36
2012-06-13T14:39:44Z
[ "python", "pip" ]
I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that. So how do I modify the command ``` pip install package_name ``` to make `pip` install the package somewhere other than the default `site-packages`?
Installing a Python package often only includes some pure Python files. If the package includes data, scripts and or executables, these are installed in different directories from the pure Python files. Assuming your package has no data/scripts/executables, and that you want your Python files to go into `/python/packa...
Install a Python package into a different directory using pip?
2,915,471
194
2010-05-26T17:55:48Z
19,404,371
168
2013-10-16T13:10:54Z
[ "python", "pip" ]
I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that. So how do I modify the command ``` pip install package_name ``` to make `pip` install the package somewhere other than the default `site-packages`?
The [--target](http://www.pip-installer.org/en/latest/reference/pip_install.html#cmdoption-t) switch is the thing you're looking for: > pip install --target=d:\somewhere\other\than\the\default package\_name But you still need to add `d:\somewhere\other\than\the\default` to `PYTHONPATH` to actually use them from that ...
Install a Python package into a different directory using pip?
2,915,471
194
2010-05-26T17:55:48Z
27,627,022
8
2014-12-23T19:46:39Z
[ "python", "pip" ]
I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that. So how do I modify the command ``` pip install package_name ``` to make `pip` install the package somewhere other than the default `site-packages`?
Just add one point to @Ian Bicking's answer: Using the `--user` option to specify the installed directory also work if one wants to install some Python package into one's home directory (without sudo user right) on remote server. E.g., ``` pip install --user python-memcached ``` The command will install the package...
Install a Python package into a different directory using pip?
2,915,471
194
2010-05-26T17:55:48Z
29,103,053
24
2015-03-17T15:24:41Z
[ "python", "pip" ]
I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that. So how do I modify the command ``` pip install package_name ``` to make `pip` install the package somewhere other than the default `site-packages`?
Instead of the `--target` option or the `--install-options` option, I have found that the following works well (from discussion on a bug regarding this very thing at <https://github.com/pypa/pip/issues/446>): ``` PYTHONUSERBASE=/path/to/install/to pip install --user ``` (Or set the `PYTHONUSERBASE` directory in your ...
How to import * with __import__
2,916,374
12
2010-05-26T20:08:31Z
2,916,810
12
2010-05-26T21:06:54Z
[ "python", "import" ]
What's the best approach to execute the following using `__import__` so that I may dynamically specify the module? ``` from module import * ```
The only way I found: ``` module = __import__(module, globals(), locals(), ['*']) for k in dir(module): locals()[k] = getattr(module, k) ```
SMTP through Exchange using Integrated Windows Authentication (NTLM) using Python
2,916,396
9
2010-05-26T20:10:45Z
2,916,435
10
2010-05-26T20:16:07Z
[ "python", "smtp", "ntlm", "pywin32" ]
I want to use the credentials of the logged-in Windows user to authenticate an SMTP connection to an Exchange server using NTLM. I'm aware of the [python-ntlm](http://code.google.com/p/python-ntlm/) module and the [two](http://code.google.com/p/python-ntlm/issues/detail?id=14) [patches](http://code.google.com/p/python...
Although the solution below only uses the Python Win32 extensions (the sspi example code included with the Python Win32 extensions was very helpful), the python-ntlm IMAP & SMTP patches mentioned in the question also served as useful guides. ``` from smtplib import SMTPException, SMTPAuthenticationError import string ...
Non-global middleware in Django
2,916,966
25
2010-05-26T21:30:57Z
2,917,155
28
2010-05-26T22:03:51Z
[ "python", "django", "middleware", "django-middleware" ]
In Django there is a settings file that defines the middleware to be run on each request. This middleware setting is global. Is there a way to specify a set of middleware on a per-view basis? I want to have specific urls use a set of middleware different from the global set.
You want [`decorator_from_middleware`](https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.decorators.decorator_from_middleware). ``` from django.utils.decorators import decorator_from_middleware @decorator_from_middleware(MyMiddleware) def view_function(request): #blah blah ``` It doesn't apply to URL...
Python: What is the hard recursion limit for Linux, Mac and Windows?
2,917,210
26
2010-05-26T22:12:42Z
2,918,118
26
2010-05-27T02:30:14Z
[ "python", "recursion", "platform" ]
Python's `sys` module [provides a function](http://docs.python.org/library/sys.html#sys.setrecursionlimit) `setrecursionlimit` that lets you change Python's maximum recursion limit. The docs say: > The highest possible limit is platform-dependent. My question is: What is the highest possible limits for various platfo...
On Windows (at least), `sys.setrecursionlimit` isn't the full story. The hard limit is on a per-thread basis and you need to call `threading.stack_size` and create a new thread once you reach a certain limit. (I think 1MB, but not sure) I've used this approach to increase it to a 64MB stack. ``` import sys import thre...
In Django/python, how do I set the memcache to infinite time?
2,917,290
8
2010-05-26T22:27:44Z
2,917,352
10
2010-05-26T22:40:47Z
[ "python", "django", "memcached" ]
``` cache.set(key, value, 9999999) ``` But this is not infinite time...
``` def _get_memcache_timeout(self, timeout): """ Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout. """ timeout = timeout or self.default_timeout if timeout > 2592000: # 60*60*24*30, 30 days # See http://code.goog...
In Django/python, how do I set the memcache to infinite time?
2,917,290
8
2010-05-26T22:27:44Z
13,689,243
9
2012-12-03T18:15:58Z
[ "python", "django", "memcached" ]
``` cache.set(key, value, 9999999) ``` But this is not infinite time...
From [the docs](http://code.google.com/p/memcached/wiki/NewProgramming#Expiration): > Expiration times can be set from 0, meaning "never expire", to 30 > days. Any time higher than 30 days is interpreted as a unix timestamp > date So, to set a key to never expire, set the timeout to 0.
How to search a list of tuples in Python
2,917,372
64
2010-05-26T22:45:13Z
2,917,386
8
2010-05-26T22:47:19Z
[ "python", "search", "list", "tuples" ]
So I have a list of tuples such as this: ``` [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")] ``` I want this list for a tuple whose number value is equal to something. So that if I do `search(53)` it will return the index value of `2` Is there an easy way to do this?
Hmm... well, the simple way that comes to mind is to convert it to a dict ``` d = dict(thelist) ``` and access `d[53]`. *EDIT*: Oops, misread your question the first time. It sounds like you actually want to get the index where a given number is stored. In that case, try ``` dict((t[0], i) for i, t in enumerate(the...
How to search a list of tuples in Python
2,917,372
64
2010-05-26T22:45:13Z
2,917,388
59
2010-05-26T22:47:33Z
[ "python", "search", "list", "tuples" ]
So I have a list of tuples such as this: ``` [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")] ``` I want this list for a tuple whose number value is equal to something. So that if I do `search(53)` it will return the index value of `2` Is there an easy way to do this?
``` [i for i, v in enumerate(L) if v[0] == 53] ```
How to search a list of tuples in Python
2,917,372
64
2010-05-26T22:45:13Z
2,917,399
45
2010-05-26T22:48:27Z
[ "python", "search", "list", "tuples" ]
So I have a list of tuples such as this: ``` [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")] ``` I want this list for a tuple whose number value is equal to something. So that if I do `search(53)` it will return the index value of `2` Is there an easy way to do this?
You can use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` >>> a = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")] >>> [x[0] for x in a] [1, 22, 53, 44] >>> [x[0] for x in a].index(53) 2 ```
How to search a list of tuples in Python
2,917,372
64
2010-05-26T22:45:13Z
2,917,408
23
2010-05-26T22:49:53Z
[ "python", "search", "list", "tuples" ]
So I have a list of tuples such as this: ``` [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")] ``` I want this list for a tuple whose number value is equal to something. So that if I do `search(53)` it will return the index value of `2` Is there an easy way to do this?
Your tuples are basically key-value pairs--a python `dict`--so: ``` l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")] val = dict(l)[53] ``` Edit -- aha, you say you want the index value of (53, "xuxa"). If this is *really* what you want, you'll have to iterate through the original list, or perhaps make a more ...
How to search a list of tuples in Python
2,917,372
64
2010-05-26T22:45:13Z
10,865,345
17
2012-06-02T19:36:40Z
[ "python", "search", "list", "tuples" ]
So I have a list of tuples such as this: ``` [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")] ``` I want this list for a tuple whose number value is equal to something. So that if I do `search(53)` it will return the index value of `2` Is there an easy way to do this?
# tl;dr A [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions) is probably the most performant and simple solution to your problem: ``` l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")] result = next((i for i, v in enumerate(l) if v[0] == 53), None) # 2 ``` # Explan...
Django URL resolving infrastructure stops working
2,917,687
2
2010-05-27T00:03:28Z
2,957,239
7
2010-06-02T11:33:44Z
[ "python", "django", "fastcgi", "django-urls" ]
We recently launched a new Django-powered website, and we are experiencing the oddest bug: The site is running under Apache with mod\_fastcgi. Everything works fine for a while, and then the URL tag and reverse() functionality stops working. Instead of returning the expected URL, they return "". We haven't noticed an...
This has happened to me before. Normally it's due to a 'broken' urls.py file. There are two things that make this kind of bug really hard to fix: * It could be the urls.py file in *any* of the apps that breaks the reverse() function, so knowing that reverse() breaks for app X doesn't mean the error is in that particul...
how do simple SQLAlchemy relationships work?
2,917,866
22
2010-05-27T01:00:13Z
2,918,384
35
2010-05-27T04:03:46Z
[ "python", "database-design", "sqlalchemy" ]
I'm no database expert -- I just know the basics, really. I've picked up SQLAlchemy for a small project, and I'm using the declarative base configuration rather than the "normal" way. This way seems a lot simpler. However, while setting up my database schema, I realized I don't understand some database relationship co...
Yes, you need `user_id = Column(Integer, ForeignKey('users.id'))` or `user_id = Column(Integer, ForeignKey('users.id'), nullable=False)` if it's mandatory. This is directly translated to FOREIGN KEY in underlying database schema, no magic. The simple way to declare relationship is `user = relationship(Users)` in `Open...
writing string to a file on a new line everytime?
2,918,362
61
2010-05-27T03:56:12Z
2,918,367
36
2010-05-27T03:58:56Z
[ "python" ]
I want to append a newline to my string every time I call `file.write()`. What's the easiest way to do this in Python?
You can do this in two ways: ``` f.write("text to write\n") ``` or, depending on your Python version (2 or 3): ``` print >>f, "text to write" # Python 2.x print("text to write", file=f) # Python 3.x ```
writing string to a file on a new line everytime?
2,918,362
61
2010-05-27T03:56:12Z
2,918,370
67
2010-05-27T03:59:28Z
[ "python" ]
I want to append a newline to my string every time I call `file.write()`. What's the easiest way to do this in Python?
Use "\n": ``` file.write("My String\n"); ``` See [the Python manual](http://docs.python.org/tutorial/inputoutput.html) for reference.
writing string to a file on a new line everytime?
2,918,362
61
2010-05-27T03:56:12Z
2,918,375
26
2010-05-27T04:00:44Z
[ "python" ]
I want to append a newline to my string every time I call `file.write()`. What's the easiest way to do this in Python?
Maybe can you use ``` file.write(your_string + '\n') ```
writing string to a file on a new line everytime?
2,918,362
61
2010-05-27T03:56:12Z
24,183,884
10
2014-06-12T12:02:35Z
[ "python" ]
I want to append a newline to my string every time I call `file.write()`. What's the easiest way to do this in Python?
If you use it extensively (a lot of written lines), you can subclass 'file': ``` class cfile(file): #subclass file to have a more convienient use of writeline def __init__(self, name, mode = 'r'): self = file.__init__(self, name, mode) def wl(self, string): self.writelines(string + '\n') ...
problem with f.readline()?
2,918,572
2
2010-05-27T04:55:01Z
2,918,597
7
2010-05-27T05:02:37Z
[ "python", "file-io" ]
I am reading one line at a time from a file, but at the end of each line it adds a `'\n'`. Example: The file has: `094 234 hii` but my input is: `094 234 hii\n` I want to read line by line but I don't need to keep the newlines... My goal is to read a list from every line: I need `['094','234','hii']`, not `['094...
1. It's not that it adds a `'\n'` so much as that there's really one there. Use `line = line.rstrip()` to get the line sans newline (or something similar to it depending on *exactly* what you need). 2. Don't use the `readline` method for reading a file line by line. Just use `for line in f:`. Files already iterate over...
Prevent Python from caching the imported modules
2,918,898
23
2010-05-27T06:16:17Z
2,918,951
17
2010-05-27T06:28:50Z
[ "python", "import", "ipython", "python-module", "python-import" ]
While developing a largeish project (split in several files and folders) in Python with IPython, I run into the trouble of cached imported modules. The problem is that instructions `import module` only reads the module once, even if that module has changed! So each time I change something in my package, I have to quit...
`import` checks to see if the module is in `sys.modules`, and if it is, it returns it. If you want import to load the module fresh from disk, you can delete the appropriate key in `sys.modules` first. There is the `reload` builtin function which will, given a module object, reload it from disk and that will get placed...
What host do I have to bind a listening socket to?
2,919,068
3
2010-05-27T06:55:27Z
2,919,075
7
2010-05-27T06:56:34Z
[ "python", "networking", "sockets", "network-programming" ]
I used python's socket module and tried to open a listening socket using ``` import socket import sys def getServerSocket(host, port): for r in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = r...
Try 0.0.0.0. That's what's mostly used.
GWT on Python App Engine
2,919,608
6
2010-05-27T08:40:17Z
2,919,675
7
2010-05-27T08:50:04Z
[ "python", "json", "google-app-engine", "gwt", "rpc" ]
I have a python app engine code (matured backend) - and we are now planning to have a front end for that code. I was wondering whether it is possible to implement GWT as the front end. Even though Alex Martelli in this post [1] mentions it is not possible, a comment to that post suggests that it is indeed possible us...
I use GWT with Python quite a bit - the JSON interface works perfectly well. Your GWT front-end is still written in a java-like syntax, and you still need the Java toolchain to actually compile it down to HTML/Javascript, but it doesn't care what language the backend is written in. As for how this is accomplished - th...
How do I type a floating point infinity literal in python
2,919,754
47
2010-05-27T09:04:24Z
2,919,800
43
2010-05-27T09:11:28Z
[ "python", "floating-point", "portability", "numerical" ]
How do I type a floating point infinity literal in python? I have heard ``` inf = float('inf') ``` is non portable. Thus, I have had the following recommended: ``` inf = 1e400 ``` Is either of these standard, or portable? What is best practice?
In [python 2.6](http://docs.python.org/whatsnew/2.6.html) it is portable if the CPU supports it > The float() function will now turn the > string nan into an IEEE 754 Not A > Number value, and +inf and -inf into > positive or negative infinity. This > works on any platform with IEEE 754 > semantics.
How do I type a floating point infinity literal in python
2,919,754
47
2010-05-27T09:04:24Z
2,919,814
8
2010-05-27T09:13:13Z
[ "python", "floating-point", "portability", "numerical" ]
How do I type a floating point infinity literal in python? I have heard ``` inf = float('inf') ``` is non portable. Thus, I have had the following recommended: ``` inf = 1e400 ``` Is either of these standard, or portable? What is best practice?
`float('inf')` is non portable as in not portable back to Python 2.5 when the string output varies between platforms. From 2.6 and onwards `float('inf')` is guaranteed to work on IEEE-754-compliance platforms (ref: <http://www.python.org/dev/peps/pep-0754/>). (And the recommendation seems to be in the range 1e30000, n...
How do I type a floating point infinity literal in python
2,919,754
47
2010-05-27T09:04:24Z
2,919,884
7
2010-05-27T09:23:36Z
[ "python", "floating-point", "portability", "numerical" ]
How do I type a floating point infinity literal in python? I have heard ``` inf = float('inf') ``` is non portable. Thus, I have had the following recommended: ``` inf = 1e400 ``` Is either of these standard, or portable? What is best practice?
Perhaps you could do something like this ``` try: inf = float('inf') except: # check for a particular exception here? inf = 1e30000 ```
Calling a non python program from python?
2,919,783
4
2010-05-27T09:08:46Z
2,919,822
10
2010-05-27T09:14:48Z
[ "python", "system-calls" ]
I am currently struggling to call a non python program from a python script. I have a ~1000 files that when passed through this C++ program will generate ~1000 outputs. Each output file must have a distinct name. The command I wish to run is of the form: ``` program_name -input -output -o1 -o2 -o3 ``` To date I hav...
You can use [subprocess](http://docs.python.org/library/subprocess.html#module-subprocess) for that purpose: ``` import os import subprocess cwd = os.getcwd() for i in os.listdir(cwd): if i.endswith('.ttp'): o = i + "-out" p = subprocess.call(["program_name", "-input", i, "-output", o]) ```
Difference between list, sequence and slice in Python?
2,920,619
18
2010-05-27T11:24:52Z
2,921,465
25
2010-05-27T13:23:09Z
[ "python", "list", "definition", "sequence", "slice" ]
What are the differences between these built-in Python data types: *list*, *sequence* and *slice*? As I see it, all three essentially represent what C++ and Java call *array*.
You're mixing very different things in your question, so I'll just answer a different question ;-P You are now asking about one of the most important interface in Python: `iterable` - it's basically anything you can use like `for elem in iterable`. `iterable` has three descendants: `sequence`, `generator` and `mappin...
Is there anything for Python that is like readability.js?
2,921,237
12
2010-05-27T12:53:27Z
6,374,482
9
2011-06-16T15:34:21Z
[ "javascript", "python", "html-content-extraction", "heuristics" ]
I'm looking for a package / module / function etc. that is approximately the Python equivalent of Arc90's readability.js <http://lab.arc90.com/experiments/readability> <http://lab.arc90.com/experiments/readability/js/readability.js> so that I can give it some input.html and the result is cleaned up version of that h...
Please try my fork <https://github.com/buriy/python-readability> which is fast and has all features of latest javascript version.
Fast matrix transposition in Python
2,921,681
3
2010-05-27T13:50:25Z
2,921,713
16
2010-05-27T13:54:52Z
[ "python", "algorithm", "matrix" ]
Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).? Say, if I have an array ``` X=[ [1,2,3], [4,5,6] ] ``` I need an array Y which should be a transposed version of X, so ``` Y=[ [1,4], [2,5], [3,6] ] ```
Simple: **Y=zip(\*X)** ``` >>> X=[[1,2,3], [4,5,6]] >>> Y=zip(*X) >>> Y [(1, 4), (2, 5), (3, 6)] ``` **EDIT:** to answer questions in the comments about what does zip(\*X) mean, here is an example from python manual: ``` >>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>...
Include a text file *as is* in (Python) Sphinx Docs
2,921,724
9
2010-05-27T13:56:04Z
2,922,004
9
2010-05-27T14:27:48Z
[ "python", "python-sphinx" ]
(using Python-Sphinx Documentation tool) I have a `.txt` log file I'd like to build into `_build/html` *unaltered*. What do I need to alter in `conf.py`, `index.rst`, etc. Here is the layout: ``` src/ index.rst some_doc.rst somefile.txt ``` How do I get `somefile.txt` into the html build? I tried adding...
I think you can include an external document fragment, as described here: <http://docutils.sourceforge.net/docs/ref/rst/directives.html#including-an-external-document-fragment> From that text, something like this should do it: ``` .. include:: inclusion.txt :literal: ```
Include a text file *as is* in (Python) Sphinx Docs
2,921,724
9
2010-05-27T13:56:04Z
2,932,149
8
2010-05-28T20:12:54Z
[ "python", "python-sphinx" ]
(using Python-Sphinx Documentation tool) I have a `.txt` log file I'd like to build into `_build/html` *unaltered*. What do I need to alter in `conf.py`, `index.rst`, etc. Here is the layout: ``` src/ index.rst some_doc.rst somefile.txt ``` How do I get `somefile.txt` into the html build? I tried adding...
The correct answer is the [`:download:` role](http://sphinx.pocoo.org/markup/inline.html#referencing-downloadable-files). Cf: [Georg's answer on the Sphinx Mailing List](http://groups.google.com/group/sphinx-dev/browse_thread/thread/2d9cdbf30940a12b/103091de78357514?lnk=gst&q=include#103091de78357514)
What is faster when looking in lists of strings? "In" or "index"?
2,922,072
2
2010-05-27T14:36:10Z
2,922,122
12
2010-05-27T14:42:20Z
[ "python", "performance", "string", "search", "list" ]
I have a bunch of lists of strings and I need to know if an string is in any of them so I have to look for the string in the first list, if not found, in the second, if not found, in the third... and so on. My question is: What is faster? ``` if (string in stringList1): return True else: if (string in stringL...
1. **`in` is the correct way to determine whether something is or is not in a container.** Don't worry about speed microoptimization until you have tested your app, found it to be slow, [profiled](http://docs.python.org/library/profile.html), and found what's causing it. At that point, optimize by testing (the timeit m...
python os.mkfifo() for Windows
2,922,185
3
2010-05-27T14:51:31Z
2,922,849
11
2010-05-27T16:17:34Z
[ "python", "subprocess", "pipe", "mkfifo" ]
Short version (if you can answer the short version it does the job for me, the rest is mainly for the benefit of other people with a similar task): In python in Windows, I want to create 2 file objects, attached to the same file (it doesn't have to be an actual file on the hard-drive), one for reading and one for writ...
Following the two answers above, I accidentally bumped into the answer. os.pipe() does the job. Thank you for your answers. I'm posting the complete code in case someone else is looking for this: ``` import subprocess from threading import Thread import time import sys import logging import tempfile import os import...
Calculating the pixel size of a string with Python
2,922,295
20
2010-05-27T15:05:39Z
2,949,546
17
2010-06-01T12:02:17Z
[ "python", "fonts", "cross-platform", "size", "tkinter" ]
I have a Python script which needs to calculate the exact size of arbitrary strings displayed in arbitrary fonts in order to generate simple diagrams. I can easily do it with Tkinter. ``` import Tkinter as tk import tkFont root = tk.Tk() canvas = tk.Canvas(root, width=300, height=200) canvas.pack() (x,y) = (5,5) text ...
You have two problems. Let's tackle them one at a time 1: the difference between python 2.5 and 2.6 on the same platform with the same font These two versions of python use different versions of tk. On my mac box, 2.5 uses tk version 8.4.19 and 2.6 uses 8.5.7. In version 8.5.2 of tk were some changes to the font meas...
What are simple instructions for creating a Python package structure and egg?
2,922,498
10
2010-05-27T15:31:44Z
2,922,635
27
2010-05-27T15:49:20Z
[ "python", "packages", "egg" ]
I just completed my first (minor) Python project, and my boss wants me to package it nicely so that it can be distributed and called from other programs easily. He suggested I look into eggs. I've been googling and reading, but I'm just getting confused. Most of the sites I'm looking at explain how to use Python eggs t...
All you need is read this: [The Hitchhiker's Guide to Packaging](http://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/creation.html) or install PasteScript using pip or easy\_install, then ``` paster create your_package_name ``` and you'll get a template for your python package
Obtain Latitude and Longitude from a GeoTIFF File
2,922,532
22
2010-05-27T15:36:49Z
2,923,066
7
2010-05-27T16:45:46Z
[ "python", "math", "geolocation", "tiff", "gdal" ]
Using GDAL in Python, how do you get the latitude and longitude of a GeoTIFF file? GeoTIFF's do not appear to store any coordinate information. Instead, they store the XY Origin coordinates. However, the XY coordinates do not provide the latitude and longitude of the top left corner and bottom left corner. It appears...
I don't know if this is a full answer, but [this site](http://home.gdal.org/~warmerda/gdal_opendap_design.html) says: > The x/y map dimensions are called easting and northing. For datasets in a geographic coordinate system these would hold the longitude and latitude. For projected coordinate systems they would normall...
Obtain Latitude and Longitude from a GeoTIFF File
2,922,532
22
2010-05-27T15:36:49Z
2,926,097
47
2010-05-28T01:14:52Z
[ "python", "math", "geolocation", "tiff", "gdal" ]
Using GDAL in Python, how do you get the latitude and longitude of a GeoTIFF file? GeoTIFF's do not appear to store any coordinate information. Instead, they store the XY Origin coordinates. However, the XY coordinates do not provide the latitude and longitude of the top left corner and bottom left corner. It appears...
To get the coordinates of the corners of your geotiff do the following: ``` from osgeo import gdal ds = gdal.Open('path/to/file') width = ds.RasterXSize height = ds.RasterYSize gt = ds.GetGeoTransform() minx = gt[0] miny = gt[3] + width*gt[4] + height*gt[5] maxx = gt[0] + width*gt[1] + height*gt[2] maxy = gt[3] ``` ...
Python time objects with more than 24 hours
2,922,735
5
2010-05-27T16:02:48Z
2,922,812
8
2010-05-27T16:13:31Z
[ "python", "time", "timedelta" ]
I have a time out of Linux that is in hh:mm:sec, but the hh can be greater than 24 hours. So if the time is 1 day 12 hours, it would be 36:00:00. Is there a way to take this format and easily make a time object? What I would really like to do is take the the required time i.e. 36:00:00, and the time that it has been r...
What you need is the timedelta object: <http://docs.python.org/library/datetime.html#timedelta-objects> 36 hours: ``` d = timedelta(hours=36) ```
Python time objects with more than 24 hours
2,922,735
5
2010-05-27T16:02:48Z
2,923,346
8
2010-05-27T17:24:35Z
[ "python", "time", "timedelta" ]
I have a time out of Linux that is in hh:mm:sec, but the hh can be greater than 24 hours. So if the time is 1 day 12 hours, it would be 36:00:00. Is there a way to take this format and easily make a time object? What I would really like to do is take the the required time i.e. 36:00:00, and the time that it has been r...
[timedelta](http://docs.python.org/library/datetime.html#timedelta-objects) is indeed what you want. Here is a more complete example that does what you asked. ``` >>> import datetime >>> a = datetime.timedelta(hours=36) >>> b = datetime.timedelta(hours=4, minutes=46, seconds=23) >>> c = a - b >>> print c 1 day, 7:13:3...
How do you walk through the directories using python?
2,922,783
10
2010-05-27T16:08:29Z
2,922,878
33
2010-05-27T16:21:52Z
[ "python" ]
I have a folder called notes, naturally they will be categorized into folders, and within those folders there will also be sub-folders for sub categories. Now my problem is I have a function that walks through 3 levels of sub directories: ``` def obtainFiles(path): list_of_files = {} for element in os.list...
Based on your short descriptions, something like this should work: ``` list_of_files = {} for (dirpath, dirnames, filenames) in os.walk(path): for filename in filenames: if filename.endswith('.html'): list_of_files[filename] = os.sep.join([dirpath, filename]) ```
How to stream an HttpResponse with Django
2,922,874
47
2010-05-27T16:21:20Z
2,923,091
40
2010-05-27T16:48:55Z
[ "python", "django", "streaming" ]
I'm trying to get the 'hello world' of streaming responses working for Django (1.2). I figured out how to use a generator and the `yield` function. But the response still not streaming. I suspect there's a middleware that's mucking with it -- maybe ETAG calculator? But I'm not sure how to disable it. Can somebody pleas...
You can disable the ETAG middleware using the [condition decorator](http://docs.djangoproject.com/en/1.2/topics/conditional-view-processing/). That will get your response to stream back over HTTP. You can confirm this with a command-line tool like `curl`. But it probably won't be enough to get your browser to show the ...
How to stream an HttpResponse with Django
2,922,874
47
2010-05-27T16:21:20Z
13,429,719
30
2012-11-17T10:33:44Z
[ "python", "django", "streaming" ]
I'm trying to get the 'hello world' of streaming responses working for Django (1.2). I figured out how to use a generator and the `yield` function. But the response still not streaming. I suspect there's a middleware that's mucking with it -- maybe ETAG calculator? But I'm not sure how to disable it. Can somebody pleas...
A lot of the django middleware will prevent you from streaming content. Much of this middleware needs to be enabled if you want to use the django admin app, so this can be an annoyance. Luckily this has been resolved in the [django 1.5 release](https://docs.djangoproject.com/en/1.5/releases/1.5/#explicit-streaming-resp...
What is a simple fuzzy string matching algorithm in Python?
2,923,420
13
2010-05-27T17:34:53Z
2,923,517
27
2010-05-27T17:50:42Z
[ "python" ]
I'm trying to find some sort of a good, fuzzy string matching algorithm. Direct matching doesn't work for me — this isn't too good because unless my strings are a 100% similar, the match fails. The [Levenshtein](http://en.wikipedia.org/wiki/Levenshtein_distance) method doesn't work too well for strings as it works on...
I like [Drew's answer](http://stackoverflow.com/questions/2923420/fuzzy-string-matching-algorithm-in-python/2923488#2923488). You can use [difflib](http://docs.python.org/library/difflib.html) to find the longest match: ``` >>> a = 'The quick brown fox.' >>> b = 'The quick brown fox jumped over the lazy dog.' >>> imp...
What is a simple fuzzy string matching algorithm in Python?
2,923,420
13
2010-05-27T17:34:53Z
6,636,996
11
2011-07-09T19:28:58Z
[ "python" ]
I'm trying to find some sort of a good, fuzzy string matching algorithm. Direct matching doesn't work for me — this isn't too good because unless my strings are a 100% similar, the match fails. The [Levenshtein](http://en.wikipedia.org/wiki/Levenshtein_distance) method doesn't work too well for strings as it works on...
Take a look at this python library, which SeatGeek open-sourced yesterday. Obviously most of these kinds of problems are very context dependent, but it might help you. ``` from fuzzywuzzy import fuzz s1 = "the quick brown fox" s2 = "the quick brown fox jumped over the lazy dog" s3 = "the fast fox jumped over the hard...
python class attribute
2,923,579
12
2010-05-27T18:00:14Z
2,923,674
32
2010-05-27T18:11:58Z
[ "python", "class", "attributes" ]
i have a question about class attribute in python. ``` class base : def __init__ (self): pass derived_val = 1 t1 = base() t2 = base () t2.derived_val +=1 t2.__class__.derived_val +=2 print t2.derived_val # its value is 2 print t2.__class__.derived_val # its value is 3 ``` The results a...
There are class attributes, and instance attributes. When you say ``` class base : derived_val = 1 ``` You are defining a class attribute. `derived_val` becomes a key in `base.__dict__`. ``` t2=base() print(base.__dict__) # {'derived_val': 1, '__module__': '__main__', '__doc__': None} print(t2.__dict__) # {} ```...
What's a good equivalent to python's subprocess.check_call that returns the contents of stdout?
2,924,310
7
2010-05-27T19:39:35Z
2,924,457
20
2010-05-27T20:01:32Z
[ "python", "subprocess" ]
I'd like a good method that matches the interface of `subprocess.check_call` -- ie, it throws `CalledProcessError` when it fails, is synchronous, &c -- but instead of returning the return code of the command (if it even does that) returns the program's output, either only stdout, or a tuple of (stdout, stderr). Does s...
### Python 2.7+ ``` from subprocess import check_output as qx ``` ### Python < 2.7 From [subprocess.py](http://hg.python.org/cpython/file/2.7/Lib/subprocess.py): ``` import subprocess def check_output(*popenargs, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be...
numpy array C api
2,924,827
7
2010-05-27T20:53:25Z
2,925,014
9
2010-05-27T21:18:50Z
[ "python", "c", "vector", "numpy", "python-c-api" ]
I have a C++ function returning a std::vector and I want to use it in python, so I'm using the C numpy api: ``` static PyObject * py_integrate(PyObject *self, PyObject *args){ ... std::vector<double> integral; cpp_function(integral); // This changes integral npy_intp size = {integral.size()}; PyOb...
Your `std::vector` object appears to be local to that function. `PyArray_SimpleNewFromData` does not make a copy of the data you pass it. It just keeps a pointer. So once your py\_integrate function returns, the vector is deallocated. The print works the first time because nothing has written over the freed memory yet,...
Get "2:35pm" instead of "02:35PM" from Python date/time?
2,925,230
23
2010-05-27T21:48:08Z
2,925,280
16
2010-05-27T21:54:59Z
[ "python", "datetime", "time", "formatting" ]
I'm still a bit slow with Python, so I haven't got this figured out beyond what's obviously in the docs, etc. I've worked with Django a bit, where they've added some datetime formatting options via template tags, but in regular python code **how can I get the 12-hour *hour* without a leading zero?** Is there a straig...
Nothing built-in to `datetime` will do it. You'll need to use something like: ``` datetime.time(1).strftime('%I:%M%p').lstrip('0') ``` ### Addendum As @naktinis points out, this is tailored to the use of this particular `strftime` parameter. Unfortunately, there is no generic solution if the content of the `strftime...
Get "2:35pm" instead of "02:35PM" from Python date/time?
2,925,230
23
2010-05-27T21:48:08Z
2,929,710
7
2010-05-28T14:08:24Z
[ "python", "datetime", "time", "formatting" ]
I'm still a bit slow with Python, so I haven't got this figured out beyond what's obviously in the docs, etc. I've worked with Django a bit, where they've added some datetime formatting options via template tags, but in regular python code **how can I get the 12-hour *hour* without a leading zero?** Is there a straig...
While I'm partial to [Mike DeSimone's answer](http://stackoverflow.com/questions/2925230/get-235pm-instead-of-0235pm-from-python-date-time/2925280#2925280), for voting purposes I think this might be a worthwhile contribution... The Django project contains a "PHP Compatible" date formatting class in [django/utils/datef...
Get "2:35pm" instead of "02:35PM" from Python date/time?
2,925,230
23
2010-05-27T21:48:08Z
12,483,430
10
2012-09-18T19:10:19Z
[ "python", "datetime", "time", "formatting" ]
I'm still a bit slow with Python, so I haven't got this figured out beyond what's obviously in the docs, etc. I've worked with Django a bit, where they've added some datetime formatting options via template tags, but in regular python code **how can I get the 12-hour *hour* without a leading zero?** Is there a straig...
This question has already been answered but you can technically get "2:35pm" directly from a Python datetime with `.strftime("%-I:%M%P")` on linux platforms that use glibc because [Python's `strftime()` uses the c library's `strftime()`](http://linux.die.net/man/3/strftime). ``` >>> import datetime >>> now = datetime....
Place image over PDF
2,925,484
4
2010-05-27T22:29:28Z
5,322,168
8
2011-03-16T07:24:08Z
[ "python", "pdf" ]
How can I place an image over an existing PDF file at an specific coordinate location. The pdf represents a drawing sheet with one page. The image will be scaled. I'm checking ReportLab but can't find the answer. Thanks.
<http://pybrary.net/pyPdf/>: ``` from pyPdf import PdfFileWriter, PdfFileReader output = PdfFileWriter() input1 = PdfFileReader(file("document1.pdf", "rb")) watermark = PdfFileReader(file("watermark.pdf", "rb")) page4.mergePage(watermark.getPage(0)) # finally, write "output" to document-output.pdf outputStream = fi...
Fixing color in scatter plots in matplotlib
2,925,806
18
2010-05-27T23:50:02Z
2,931,472
34
2010-05-28T18:14:41Z
[ "python", "colors", "matplotlib", "scatter-plot" ]
I want to fix the color range on multiple scatter plots and add in a colorbar to each plot (which will be the same in each figure). Essentially, I'm fixing all aspects of the axes and colorspace etc. so that the plots are directly comparable by eye. For the life of me, I can't seem to figure out all the various ways o...
Setting vmin and vmax should do this. Here's an example: ``` import matplotlib.pyplot as plt xyc = range(20) plt.subplot(121) plt.scatter(xyc[:13], xyc[:13], c=xyc[:13], s=35, vmin=0, vmax=20) plt.colorbar() plt.xlim(0, 20) plt.ylim(0, 20) plt.subplot(122) plt.scatter(xyc[8:20], xyc[8:20], c=xyc[8:20], s=35, vmin=...
wxPython TreeCtrl without showing root while still showing arrows
2,925,971
3
2010-05-28T00:33:13Z
2,994,121
8
2010-06-08T00:43:10Z
[ "python", "tree", "wx", "treecontrol", "root-node" ]
I am making a python tree visualizer using wxPython. It would be used like so: ``` show_tree([ 'A node with no children', ('A node with children', 'A child node', ('A child node with children', 'Another child')) ]) ``` It worked fine but it shows a root with a value of "Tree". I made it so that it would create multip...
Note: When I posted this I did not realize you were able to apply multiple styles to trees. After trying everything, I realized that it was a combination of TR\_HIDE\_ROOT and TR\_HAS\_BUTTONS that does the trick of hiding the root while still showing arrows on the left side that allow you to collapse and hide nodes ...
Counting vowels
2,926,383
7
2010-05-28T02:52:10Z
2,926,391
8
2010-05-28T02:54:39Z
[ "python" ]
Can anyone please tell me what is wrong with this script. I am a python newb but i cant seem to figure out what might be causing it not to function. ``` def find_vowels(sentence): """ >>> find_vowels(test) 1 """ count = 0 vowels = "aeiuoAEIOU" for letter in sentence: if letter in...
You're printing `count` (a number), but your test expects the letter `e`. Also, the more Pythonic way to count the vowels would be a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` >>> len([letter for letter in 'test' if letter in vowels]) 1 ``` Want to *see* the vo...
Counting vowels
2,926,383
7
2010-05-28T02:52:10Z
2,926,393
7
2010-05-28T02:55:13Z
[ "python" ]
Can anyone please tell me what is wrong with this script. I am a python newb but i cant seem to figure out what might be causing it not to function. ``` def find_vowels(sentence): """ >>> find_vowels(test) 1 """ count = 0 vowels = "aeiuoAEIOU" for letter in sentence: if letter in...
Besides the fact that you're returning a count but expecting a string of vowels, as others have said, you must also change the line ``` >>> find_vowels(test) ``` to ``` >>> find_vowels('test') ``` You forgot the quotes!
Potential Django Bug In QuerySet.query?
2,926,483
7
2010-05-28T03:27:36Z
2,929,399
9
2010-05-28T13:34:28Z
[ "python", "django" ]
Disclaimer: I'm still learning Django, so I might be missing something here, but I can't see what it would be... I'm running Python 2.6.1 and Django 1.2.1. ``` (InteractiveConsole) >>> from myproject.myapp.models import * >>> qs = Identifier.objects.filter(Q(key="a") | Q(key="b")) >>> print qs.query SELECT `app_ident...
Ok, I just figured it out. It's not a bug. Browsing the source of django/db/models/sql/query.py: ``` 160 def __str__(self): 161 """ 162 Returns the query as a string of SQL with the parameter values 163 substituted in. 164 165 Parameter values won't necessarily be quoted correctly,...
Why does Python's 'for ... in' work differently on a list of values vs. a list of dictionaries?
2,926,580
6
2010-05-28T04:03:52Z
2,926,687
16
2010-05-28T04:43:39Z
[ "python", "iteration" ]
I'm wondering about some details of how for ... in works in Python. My understanding is `for var in iterable` on each iteration creates a variable, var, bound to the current value of iterable. So, if you do `for c in cows; c = cows[whatever]`, but changing c within the loop does not affect the original value. However,...
It helps to picture what happens to the reference held by `c` in each iteration: ``` [ 0, 1, 2, 3, 4, 5 ] ^ | c ``` c holds a reference pointing to the first element in the list. When you do `c += 2` (i.e., `c = c + 2`, the temporary variable `c` is reassigned a new value. This new value is `2`, and `c` is rebo...
Python finding n consecutive numbers in a list
2,927,213
3
2010-05-28T07:07:55Z
2,927,234
9
2010-05-28T07:13:19Z
[ "python" ]
I want to know how to find if there is a certain amount of consecutive numbers in a row in my list e.g. For example if I am looking for two 1's then: ``` list = [1, 1, 1, 4, 6] #original list list = ["true", "true", 1, 4, 6] #after my function has been through the list. ``` If I am looking for three 1's then: ``` l...
It is a bad idea to assign to `list`. Use a different name. To find the largest number of consecutive equal values you can use [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) ``` >>> import itertools >>> l = [1, 1, 1, 4, 6] >>> max(len(list(v)) for g,v in itertools.groupby(l)) ...
Python urllib2 > HTTP Proxy > HTTPS request
2,927,831
9
2010-05-28T09:20:39Z
3,248,895
15
2010-07-14T17:43:05Z
[ "python", "proxy", "https", "urllib2" ]
This work fine: ``` import urllib2 opener = urllib2.build_opener( urllib2.HTTPHandler(), urllib2.HTTPSHandler(), urllib2.ProxyHandler({'http': 'http://user:pass@proxy:3128'})) urllib2.install_opener(opener) print urllib2.urlopen('http://www.google.com').read() ``` But,...
Change this line: ``` urllib2.ProxyHandler({'http': 'http://user:pass@proxy:3128'})) ``` to this: ``` urllib2.ProxyHandler({'https': 'http://user:pass@proxy:3128'})) ``` It works fine for me.
Where are the python modules stored?
2,927,993
3
2010-05-28T09:46:42Z
2,928,020
11
2010-05-28T09:52:33Z
[ "python", "directory", "module" ]
I have recently started learning Python and I have 2 questions relating to modules. 1. Is there a way to obtain a list of Python modules available (i.e. installed) on a machine? 2. I am using Ubuntu Karmic and Synaptic for package management. I have just installed a python module.Where is the module code actually stor...
> 1) Is there a way to obtain a list of > Python modules available (i.e. > installed) on a mchine? This works for me: ``` help('modules') ``` . > 2) Where is the module code actually > stored on my machine? Usually in `/lib/site-packages` in your Python folder. (At least, on Windows.) You can use `sys.path` to fi...
How to print unsorted dictionary in python?
2,928,686
3
2010-05-28T11:52:12Z
2,928,707
10
2010-05-28T11:55:29Z
[ "python", "dictionary" ]
I have this dict in python; ``` d={} d['b']='beta' d['g']='gamma' d['a']='alpha' ``` when i print the dict; ``` for k,v in d.items(): print k ``` i get this; ``` a b g ``` it seems like python sorts the dict automatically! how can i get the original unsorted list? Gath
[Dicts don't work like that](http://docs.python.org/library/stdtypes.html#dict): > **CPython implementation detail**: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. You could use a list ...
How to print unsorted dictionary in python?
2,928,686
3
2010-05-28T11:52:12Z
2,929,007
10
2010-05-28T12:41:56Z
[ "python", "dictionary" ]
I have this dict in python; ``` d={} d['b']='beta' d['g']='gamma' d['a']='alpha' ``` when i print the dict; ``` for k,v in d.items(): print k ``` i get this; ``` a b g ``` it seems like python sorts the dict automatically! how can i get the original unsorted list? Gath
As has been mentioned, dicts don't order or unorder the items you put in. It's "magic" as to how it's ordered when you retrieve it. If you want to keep an order -sorted or not- you need to also bind a list or tuple. This will give you the same dict result with a list that retains order: ``` greek = ['beta', 'gamma', ...
Python - from file to data structure?
2,928,883
2
2010-05-28T12:22:59Z
2,928,943
13
2010-05-28T12:30:37Z
[ "python", "string" ]
I have large file comprising ~100,000 lines. Each line corresponds to a cluster and each entry within each line is a reference i.d. for another file (protein structure in this case), e.g. ``` 1hgn 1dju 3nmj 8kfn 9opu 7gfb 4bui ``` I need to read in the file as a list of lists where each line is a sublist, thus prese...
Super simple: ``` with open('myfile', 'r') as f: data = [line.split() for line in f] ```
Doubling binary digits
2,928,886
8
2010-05-28T12:23:26Z
2,928,973
11
2010-05-28T12:35:47Z
[ "python", "algorithm", "math", "binary" ]
How to double a number of binary digits in an integer? For example, if bin(x)="1001" then bin(y) must be "11000011". Is there any smart and fast algorithm ? UPDATE: Here is an elegant solution: ``` ''.join([''.join(i) for i in zip(X,X)]) ``` where X is bin(int\_x)[2:] However, I am interested in a more faster way a...
The straightforward solution just using integer arithmetic would be: ``` def doubledigits(n): result = 0 power = 1 while n > 0: if n%2==1: result += 3*power power *= 4 n //= 2 return result ```