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 |
|---|---|---|---|---|---|---|---|---|---|
Easiest way to read/write a file's content in Python | 3,758,147 | 33 | 2010-09-21T07:29:50Z | 3,758,171 | 25 | 2010-09-21T07:33:14Z | [
"python"
] | In Ruby you can read from a file using `s = File.read(filename)`. The shortest and clearest I know in Python is
```
with file(filename) as f:
s = f.read()
```
Is there any other way to do it that makes it even shorter (preferably one line) and more readable?
Note: initially I phrased the question as "doing this ... | This is same as above but does not handle errors:
```
s = open(filename, 'r').read()
``` |
Easiest way to read/write a file's content in Python | 3,758,147 | 33 | 2010-09-21T07:29:50Z | 3,758,177 | 8 | 2010-09-21T07:33:33Z | [
"python"
] | In Ruby you can read from a file using `s = File.read(filename)`. The shortest and clearest I know in Python is
```
with file(filename) as f:
s = f.read()
```
Is there any other way to do it that makes it even shorter (preferably one line) and more readable?
Note: initially I phrased the question as "doing this ... | ```
contents = open(filename).read()
``` |
Easiest way to read/write a file's content in Python | 3,758,147 | 33 | 2010-09-21T07:29:50Z | 3,758,255 | 56 | 2010-09-21T07:45:42Z | [
"python"
] | In Ruby you can read from a file using `s = File.read(filename)`. The shortest and clearest I know in Python is
```
with file(filename) as f:
s = f.read()
```
Is there any other way to do it that makes it even shorter (preferably one line) and more readable?
Note: initially I phrased the question as "doing this ... | ```
with open('x.py') as f: s = f.read()
```
\*\*\*grins\*\*\* |
Setting window style in PyQT/PySide? | 3,758,648 | 5 | 2010-09-21T08:48:38Z | 3,761,216 | 10 | 2010-09-21T14:17:07Z | [
"python",
"pyqt",
"pyside"
] | I've been looking for how to do this and I've found places where the subject comes up, but none of the suggestions actually work for me, even though they seem to work out okay for the questioner (they don't even list what to `import`). I ran across `self.setWindowFlags(Qt.FramelessWindowHint)` but it doesn't seem to wo... | u need to import `QtCore`
so the code will look like this :
`self.setWindowFlags(QtCore.Qt.FramelessWindowHint)`
whenever you see `Qt.`something put in mind that they are talking about the Qt class inside QtCore module .
hope this helps |
What encoding looks exactly like ASCII but has NULL bytes before each byte? | 3,759,189 | 3 | 2010-09-21T10:02:02Z | 3,759,204 | 9 | 2010-09-21T10:03:54Z | [
"python",
"character-encoding"
] | I have a string that looks and behaves as follows (Python code provided). WTF?! What encoding is it in?
```
s = u'\x00Q\x00u\x00i\x00c\x00k'
>>> print s
Quick
>>>
>>> s == 'Quick'
False
>>>
>>> import re
>>> re.search('Quick', s)
>>>
>>> import chardet
>>> chardet.detect(s)
/usr/lib/pymodules/python2.6/chardet/univers... | UTF-16 big endian |
Get IP address of visitors using Python + Flask | 3,759,981 | 104 | 2010-09-21T11:49:37Z | 3,760,309 | 139 | 2010-09-21T12:37:17Z | [
"python",
"website",
"flask",
"ip-address",
"werkzeug"
] | I'm making a website where users can log on and download files, using the [Flask micro-framework](http://flask.pocoo.org/) (based on [Werkzeug](http://werkzeug.pocoo.org/)) which uses Python (2.6 in my case).
I need to get the IP address of users when they log on (for logging purposes).
Does anyone know how to do this... | See the documentation on [how to access the Request object](http://flask.pocoo.org/docs/quickstart/#accessing-request-data) and then get from this same Request object, the attribute `remote_addr`.
**Code example**
```
from flask import request
from flask import jsonify
@app.route("/get_my_ip", methods=["GET"])
def g... |
Get IP address of visitors using Python + Flask | 3,759,981 | 104 | 2010-09-21T11:49:37Z | 16,502,990 | 23 | 2013-05-12T00:21:33Z | [
"python",
"website",
"flask",
"ip-address",
"werkzeug"
] | I'm making a website where users can log on and download files, using the [Flask micro-framework](http://flask.pocoo.org/) (based on [Werkzeug](http://werkzeug.pocoo.org/)) which uses Python (2.6 in my case).
I need to get the IP address of users when they log on (for logging purposes).
Does anyone know how to do this... | The user's IP address can be retrieved using the following snippet:
```
from flask import request
print request.remote_addr
``` |
Get IP address of visitors using Python + Flask | 3,759,981 | 104 | 2010-09-21T11:49:37Z | 25,040,332 | 59 | 2014-07-30T15:05:14Z | [
"python",
"website",
"flask",
"ip-address",
"werkzeug"
] | I'm making a website where users can log on and download files, using the [Flask micro-framework](http://flask.pocoo.org/) (based on [Werkzeug](http://werkzeug.pocoo.org/)) which uses Python (2.6 in my case).
I need to get the IP address of users when they log on (for logging purposes).
Does anyone know how to do this... | Actually, what you will find is that when simply getting the following will get you the server's address:
```
request.remote_addr
```
If you want the clients IP address, then use the following:
```
request.environ['REMOTE_ADDR']
``` |
Get IP address of visitors using Python + Flask | 3,759,981 | 104 | 2010-09-21T11:49:37Z | 26,654,607 | 40 | 2014-10-30T13:41:48Z | [
"python",
"website",
"flask",
"ip-address",
"werkzeug"
] | I'm making a website where users can log on and download files, using the [Flask micro-framework](http://flask.pocoo.org/) (based on [Werkzeug](http://werkzeug.pocoo.org/)) which uses Python (2.6 in my case).
I need to get the IP address of users when they log on (for logging purposes).
Does anyone know how to do this... | Proxies can make this a little tricky, make sure to check out [ProxyFix](http://werkzeug.pocoo.org/docs/0.11/contrib/fixers/#werkzeug.contrib.fixers.ProxyFix) ([Flask docs](http://flask.pocoo.org/docs/0.10/deploying/wsgi-standalone/#proxy-setups)) if you are using one. Take a look at request.environ in your particular ... |
allow_none in twisted XML-RPC server | 3,760,043 | 6 | 2010-09-21T11:58:03Z | 3,760,388 | 7 | 2010-09-21T12:47:52Z | [
"python",
"twisted",
"xml-rpc"
] | I am building xml rpc service using twisted and I would like to use None just as it can be done in standard python lib. How can I pass allow\_none to the twisted version of xmlrpc server?
**EDIT**
```
In [28]: sock = rpc.ServerProxy('http://localhost:7080',allow_none=True)
In [29]: sock
Out[29]: <ServerProxy for loc... | [XMLRPC](http://twistedmatrix.com/documents/current/api/twisted.web.xmlrpc.XMLRPC.html) accepts `allowNone` as an argument to its initializer. So, pass `True` when instantiating your resources if you want to support `None`.
```
from twisted.web.xmlrpc import XMLRPC
resource = XMLRPC(allowNone=True)
``` |
Checking Version of Python Interpreter Upon Execution of Script With Invalid Syntax | 3,760,098 | 5 | 2010-09-21T12:07:28Z | 3,760,194 | 7 | 2010-09-21T12:20:13Z | [
"python",
"interpreter"
] | I have a Python script that uses Python version 2.6 syntax (Except *error* as *value*:) which version 2.5 complains about. So in my script I have included some code to check for the Python interpreter version before proceeding so that the user doesn't get hit with a nasty error, however, no matter where I place that co... | Create a wrapper script that checks the version and calls your real script -- this gives you a chance to check the version before the interpreter tries to syntax-check the real script. |
Converting domain names to idn in python | 3,760,338 | 5 | 2010-09-21T12:41:51Z | 3,760,386 | 12 | 2010-09-21T12:47:30Z | [
"python",
"unicode"
] | I have a long list of domain names which I need to generate some reports on. The list contains some IDN domains, and although I know how to convert them in python on the command line:
```
>>> domain = u"pfarmerü.com"
>>> domain
u'pfarmer\xfc.com'
>>> domain.encode("idna")
'xn--pfarmer-t2a.com'
>>>
```
I'm struggling... | you need to know in which encoding you file was saved. This would be something like 'utf-8' (which is NOT Unicode) or 'iso-8859-1' or 'cp1252' or alike.
Then you can do (assuming 'utf-8'):
```
infile = open(sys.argv[1])
for line in infile:
print line,
domain = line.strip().decode('utf-8')
print type(doma... |
How's Python GUI development today (Sep/2010)? | 3,760,714 | 7 | 2010-09-21T13:25:53Z | 3,760,999 | 7 | 2010-09-21T13:53:39Z | [
"python",
"user-interface"
] | Last time I saw, GUIs in Python were extremely ugly, how's it today?
(saw some beautiful images on google images, but I don't know if are really Python's) | Python 2.7 and 3.0 ships with the themed tk ("ttk") widgets which look much better than previous versions of Tk (though, honestly, any competent GUI developer can make even older Tk look good). Don't let the people who don't know much about Tk sway you from using it, it's still a very viable toolkit for many, many task... |
Using genfromtxt to import csv data with missing values in numpy | 3,761,103 | 5 | 2010-09-21T14:05:37Z | 3,761,256 | 8 | 2010-09-21T14:22:30Z | [
"python",
"numpy",
"genfromtxt"
] | I have a csv file that looks something like this (actual file has many more columns and rows):
```
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16
```
Say the name of the file is **info.csv**
If I try to import this using
```
data = numpy.genfromtxt('info.csv', delimiter = ',')
```
then I get the following error:
```
Value... | if you can ignore the 16 at the end of the file try using the
`invalid_raise` (**bool, optional**) parameter
if set to False it ignores all incomplete lines without throwing an exception
see here (its the last parameter before the examples)
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html> |
boost::python: Python list to std::vector | 3,761,391 | 15 | 2010-09-21T14:34:44Z | 3,761,526 | 17 | 2010-09-21T14:51:30Z | [
"python",
"boost",
"boost-python",
"stdvector"
] | Finally I'm able to use std::vector in python using the [] operator. The trick is to simple provide a container in the boost C++ wrapper which handles the internal vector stuff:
```
#include <boost/python.hpp>
#include <vector>
class world
{
std::vector<double> myvec;
void add(double n)
{
this->my... | To make your C++ method accept Python lists you should use `boost::python::list`
```
void massadd(boost::python::list& ns)
{
for (int i = 0; i < len(ns); ++i)
{
add(boost::python::extract<double>(ns[i]));
}
}
``` |
boost::python: Python list to std::vector | 3,761,391 | 15 | 2010-09-21T14:34:44Z | 19,092,051 | 10 | 2013-09-30T10:35:54Z | [
"python",
"boost",
"boost-python",
"stdvector"
] | Finally I'm able to use std::vector in python using the [] operator. The trick is to simple provide a container in the boost C++ wrapper which handles the internal vector stuff:
```
#include <boost/python.hpp>
#include <vector>
class world
{
std::vector<double> myvec;
void add(double n)
{
this->my... | Here's what I use:
```
#include <boost/python/stl_iterator.hpp>
namespace py = boost::python;
template< typename T >
inline
std::vector< T > to_std_vector( const py::object& iterable )
{
return std::vector< T >( py::stl_input_iterator< T >( iterable ),
py::stl_input_iterator< T >( ) ... |
Python not recognising directories os.path.isdir() | 3,761,473 | 5 | 2010-09-21T14:45:46Z | 3,761,494 | 18 | 2010-09-21T14:47:56Z | [
"python",
"file-io",
"path",
"directory"
] | I have the following Python code to remove files in a directory.
For some reason my .svn directories are not being recognised as directories.
And I get the following output:
> .svn not a dir
Any ideas would be appreciated.
```
def rmfiles(path, pattern):
pattern = re.compile(pattern)
for each in os.listdir(... | You need to create the full path name before checking:
```
if not os.path.isdir(os.path.join(path, each)):
...
``` |
How do you get the process ID of a program in Unix or Linux using Python? | 3,761,639 | 40 | 2010-09-21T15:05:24Z | 3,761,653 | 141 | 2010-09-21T15:07:13Z | [
"python"
] | I'm writing some monitoring scripts in Python and I'm trying to find the cleanest way to get the process ID of any random running program given the name of that program
something like
```
ps -ef | grep MyProgram
```
I could parse the output of that however I thought there might be a better way in python | [From the standard library](http://docs.python.org/library/os.html#os.getpid):
```
os.getpid()
``` |
How do you get the process ID of a program in Unix or Linux using Python? | 3,761,639 | 40 | 2010-09-21T15:05:24Z | 3,762,031 | 12 | 2010-09-21T15:48:37Z | [
"python"
] | I'm writing some monitoring scripts in Python and I'm trying to find the cleanest way to get the process ID of any random running program given the name of that program
something like
```
ps -ef | grep MyProgram
```
I could parse the output of that however I thought there might be a better way in python | If you are not limiting yourself to the standard library, I like [psutil](http://code.google.com/p/psutil/) for this. |
How do you get the process ID of a program in Unix or Linux using Python? | 3,761,639 | 40 | 2010-09-21T15:05:24Z | 3,762,129 | 7 | 2010-09-21T15:58:28Z | [
"python"
] | I'm writing some monitoring scripts in Python and I'm trying to find the cleanest way to get the process ID of any random running program given the name of that program
something like
```
ps -ef | grep MyProgram
```
I could parse the output of that however I thought there might be a better way in python | Try `pgrep`. Its output format is much simpler and therefore easier to parse. |
Python vs. C++ for an application that does sparse linear algebra | 3,761,994 | 4 | 2010-09-21T15:45:06Z | 3,762,815 | 7 | 2010-09-21T17:26:03Z | [
"c++",
"python",
"linear-algebra"
] | I'm writing an application where quite a bit of the computational time will be devoted to performing basic linear algebra operations (add, multiply, multiply by vector, multiply by scalar, etc.) on sparse matrices and vectors. Up to this point, we've built a prototype using C++ and the Boost matrix library.
I'm consid... | My advice is to fully test the algorithm in Python before translating it into any other language (otherwise you run the risk of optimizing prematurely a bad algorithm). Once you have clearly defined the best interface for your problems, you can factor it out to external code.
Let me explain.
Suppose your final algori... |
ETL using Python | 3,762,199 | 9 | 2010-09-21T16:04:57Z | 3,762,400 | 15 | 2010-09-21T16:29:15Z | [
"python",
"data-warehouse",
"etl"
] | I am working on a data warehouse and looking for an ETL solution that uses Python.
I have played with SnapLogic as an ETL, but I was wondering if there were any other solutions out there.
This data warehouse is just getting started. Ihave not brought any data over yet. It will easily be over 100 gigs with the initial ... | Yes. Just write Python using a DB-API interface to your database.
Most ETL programs provide fancy "high-level languages" or drag-and-drop GUI's that don't help much.
Python is just as expressive and just as easy to work with.
Eschew obfuscation. Just use plain-old Python.
We do it every day and we're very, very ple... |
Returning all characters before the first underscore | 3,762,420 | 6 | 2010-09-21T16:31:25Z | 3,762,437 | 16 | 2010-09-21T16:33:53Z | [
"python",
"regex",
"string"
] | Using `re` in Python, I would like to return all of the characters in a string that precede the first appearance of an underscore. In addition, I would like the string that is being returned to be in all uppercase and **without** any non-alpanumeric characters.
For example:
```
AG.av08_binloop_v6 = AGAV08
TL.av1_binl... | Even without `re`:
```
text.split('_', 1)[0].replace('.', '').upper()
``` |
How do I check if stdin has some data? | 3,762,881 | 25 | 2010-09-21T17:34:18Z | 3,763,257 | 33 | 2010-09-21T18:23:37Z | [
"python",
"redirect",
"stdout",
"stdin"
] | In Python, how do you check if `sys.stdin` has data or not?
I found that `os.isatty(0)` can not only check if stdin is connected to a TTY device, but also if there is data available.
But if someone uses code such as
```
sys.stdin = cStringIO.StringIO("ddd")
```
and after that uses `os.isatty(0)`, it still returns T... | On Unix systems you can do the following:
```
import sys
import select
if select.select([sys.stdin,],[],[],0.0)[0]:
print "Have data!"
else:
print "No data"
```
On Windows the select module may only be used with sockets though so you'd need to use an alternative mechanism. |
How do I check if stdin has some data? | 3,762,881 | 25 | 2010-09-21T17:34:18Z | 17,735,803 | 24 | 2013-07-18T23:39:06Z | [
"python",
"redirect",
"stdout",
"stdin"
] | In Python, how do you check if `sys.stdin` has data or not?
I found that `os.isatty(0)` can not only check if stdin is connected to a TTY device, but also if there is data available.
But if someone uses code such as
```
sys.stdin = cStringIO.StringIO("ddd")
```
and after that uses `os.isatty(0)`, it still returns T... | I've been using
```
if not sys.stdin.isatty()
```
Here's an example:
```
4 import sys
5
6 def main():
7 if not sys.stdin.isatty():
8 print "not sys.stdin.isatty"
9 else:
10 print "is sys.stdin.isatty"
>echo "asdf" | stdin.py
not sys.stdin.isatty
```
sys.stdin.isatty() returns false if ther... |
Calling Tcl procedures with Function pointers as argument from Python | 3,763,904 | 6 | 2010-09-21T19:50:11Z | 3,764,521 | 7 | 2010-09-21T21:13:35Z | [
"python",
"tkinter",
"tcl"
] | Is it possible to call Tcl procedures that have function pointers (or callback functions) from Python?
I am using Tkinter to call Tcl procedures from Python.
Python Snippet :
```
proc callbackFunc():
print "I am in callbackFunc"
cb = callbackFunc
Tkinter.Tk.call('tclproc::RetrieveInfo', cb)
```
Tcl Snippet :
`... | Yes, and your pseudocode is pretty close. You have to register your python code with the Tcl interpreter. This will create a tcl command that will call your python code. You then reference this new tcl command whenever you pass it to a Tcl procedure that expects a procedure name. It goes something like this:
```
impor... |
Checking network connection | 3,764,291 | 58 | 2010-09-21T20:39:15Z | 3,764,315 | 8 | 2010-09-21T20:42:17Z | [
"python",
"networking"
] | I want to see if I can access an online API, but for that I need to have Internet access.
How can I see if there's a connection available and active using Python? | You can just try to download data, and if connection fail you will know that somethings with connection isn't fine.
Basically you can't check if computer is connected to internet. There can be many reasons for failure, like wrong DNS configuration, firewalls, NAT. So even if you make some tests, you can't have guarant... |
Checking network connection | 3,764,291 | 58 | 2010-09-21T20:39:15Z | 3,764,660 | 74 | 2010-09-21T21:31:51Z | [
"python",
"networking"
] | I want to see if I can access an online API, but for that I need to have Internet access.
How can I see if there's a connection available and active using Python? | Perhaps you could use something like this:
```
import urllib2
def internet_on():
try:
response=urllib2.urlopen('http://216.58.192.142', timeout=1)
return True
except urllib2.URLError as err: pass
return False
```
Currently, 216.58.192.142 is one of the IP addresses for google.com. *Change... |
Checking network connection | 3,764,291 | 58 | 2010-09-21T20:39:15Z | 8,019,156 | 13 | 2011-11-05T08:56:25Z | [
"python",
"networking"
] | I want to see if I can access an online API, but for that I need to have Internet access.
How can I see if there's a connection available and active using Python? | Just to update what unutbu said for new code in Python 3.2
```
def check_connectivity(reference):
try:
urllib.request.urlopen(reference, timeout=1)
return True
except urllib.request.URLError:
return False
```
And, just to note, the input here (reference) is the url that you want to che... |
Checking network connection | 3,764,291 | 58 | 2010-09-21T20:39:15Z | 24,460,981 | 8 | 2014-06-27T21:25:39Z | [
"python",
"networking"
] | I want to see if I can access an online API, but for that I need to have Internet access.
How can I see if there's a connection available and active using Python? | As an alternative to ubutnu's/Kevin C answers, I use the `requests` package like this:
```
import requests
def connected_to_internet(url='http://www.google.com/', timeout=5):
try:
_ = requests.get(url, timeout=timeout)
return True
except requests.ConnectionError:
print("No internet con... |
Checking network connection | 3,764,291 | 58 | 2010-09-21T20:39:15Z | 33,117,579 | 17 | 2015-10-14T05:51:53Z | [
"python",
"networking"
] | I want to see if I can access an online API, but for that I need to have Internet access.
How can I see if there's a connection available and active using Python? | If we can connect to some Internet server, then we indeed have connectivity. However, for the fastest and most reliable approach, all solutions should comply with the following requirements, at the very least:
* Avoid DNS resolution (we will need an IP that is well-known and guaranteed to be available for most of the ... |
When __repr__() is called? | 3,764,360 | 8 | 2010-09-21T20:48:22Z | 3,764,365 | 17 | 2010-09-21T20:49:16Z | [
"python"
] | `print OBJECT` calls `OBJECT.__str__()`, then when `OBJECT.__repr__()` is called? I see that `print OBJECT` calls `OBJECT.__repr__()` when `OBJECT.__str__()` doesn't exist, but I expect that's not the only way to call `__repr__()`. | ```
repr(obj)
```
calls
```
obj.__repr__
```
the purpose of `__repr__` is that it provides a 'formal' representation of the object that is supposed to be a expression that can be `eval`ed to create the object. that is,
```
obj == eval(repr(obj))
```
*should*, but does not always in practice, yield `True`
I was as... |
How to make a .exe for Python with good graphics? | 3,764,410 | 3 | 2010-09-21T20:55:43Z | 3,764,488 | 7 | 2010-09-21T21:08:39Z | [
"python",
"graphics",
"wxpython",
"py2exe"
] | I have a Python application and I decided to do a .exe to execute it.
This is the code that I use to do the .exe:
```
# -*- coding: cp1252 -*-
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
windows = [{'script': "SoundLog.... | I assume you mean the visual style of the toolbar and buttons. You need to add a manifest file to the EXE file or as a separate file so that Windows applies the modern style of recent comctl32.dll versions.
Check out [Using Windows XP Visual Styles With Controls on Windows Forms](http://msdn.microsoft.com/en-us/librar... |
Adding Readline Functionality Without Recompiling Python | 3,764,730 | 6 | 2010-09-21T21:42:21Z | 3,764,744 | 8 | 2010-09-21T21:44:14Z | [
"python",
"readline"
] | I recently upgraded to Ubuntu 10.04 LTS and refreshed my Python environment. I installed Python 2.7 from source. Unfortunately, I didn't notice that Setup.dist has the readline line commented out by default - by default, there is no readline support installed. I'm now using the Python interpreter as a REPL enough that ... | There's a standalone [gnureadline package](https://pypi.python.org/pypi/gnureadline) available, you can install it using setuptools
```
$ easy_install readline
```
You might also consider using [ipython](http://ipython.scipy.org/) instead. |
Python: What does the use of [] mean here? | 3,764,858 | 5 | 2010-09-21T22:04:18Z | 3,764,863 | 13 | 2010-09-21T22:06:02Z | [
"python",
"list",
"syntax",
"brackets",
"variable-assignment"
] | What is the difference in these two statements in python?
```
var = foo.bar
```
and
```
var = [foo.bar]
```
I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?
For example: if foo.bar = [1, 2] would I get ... | `[]` is an empty list.
`[foo.bar]` is creating a new list (`[]`) with `foo.bar` as the first item in the list, which can then be referenced by its index:
```
var = [foo.bar]
var[0] == foo.bar # returns True
```
So your guess that your assignment of `foo.bar = [1,2]` is exactly right.
If you haven't already, I recom... |
Different behavior between re.finditer and re.findall | 3,765,024 | 7 | 2010-09-21T22:39:36Z | 3,766,824 | 17 | 2010-09-22T06:28:46Z | [
"python",
"regex"
] | I am using the following code:
```
CARRIS_REGEX=r'<th>(\d+)</th><th>([\s\w\.\-]+)</th><th>(\d+:\d+)</th><th>(\d+m)</th>'
pattern = re.compile(CARRIS_REGEX, re.UNICODE)
matches = pattern.finditer(mailbody)
findall = pattern.findall(mailbody)
```
But finditer and findall are finding different things. Findall indeed fin... | I can't reproduce this here. Have tried it with both Python 2.7 and 3.1.
One difference between `finditer` and `findall` is that the former returns regex match objects whereas the other returns a tuple of the matched capturing groups (or the entire match if there are no capturing groups).
So
```
import re
CARRIS_REG... |
Combine picture and plot with Python Matplotlib | 3,765,056 | 10 | 2010-09-21T22:46:19Z | 3,796,404 | 11 | 2010-09-26T02:44:12Z | [
"python",
"matplotlib"
] | I have a plot which has timestamps on the x-axis and some signal data on the y-axis. As a documentation I want to put timestamped pictures in relation to specific points in the plot. Is it possible to draw a line in a plot to a picture in a sequence of pictures below the plot? | [This](http://matplotlib.sourceforge.net/examples/pylab_examples/demo_annotation_box.html) demo from the matplotlib gallery shows how to insert pictures, draw lines to them, etc. I'll post the image from the gallery, and you can follow the [link](http://matplotlib.sourceforge.net/examples/pylab_examples/demo_annotation... |
Combine picture and plot with Python Matplotlib | 3,765,056 | 10 | 2010-09-21T22:46:19Z | 3,796,448 | 12 | 2010-09-26T03:04:39Z | [
"python",
"matplotlib"
] | I have a plot which has timestamps on the x-axis and some signal data on the y-axis. As a documentation I want to put timestamped pictures in relation to specific points in the plot. Is it possible to draw a line in a plot to a picture in a sequence of pictures below the plot? | If I understand the question correctly, then perhaps this may help:
```
import scipy
import pylab
fig = pylab.figure()
axplot = fig.add_axes([0.07,0.25,0.90,0.70])
axplot.plot(scipy.randn(100))
numicons = 8
for k in range(numicons):
axicon = fig.add_axes([0.07+0.11*k,0.05,0.1,0.1])
axicon.imshow(scipy.rand(4,4... |
Running python on a Windows machine vs Linux | 3,765,178 | 7 | 2010-09-21T23:17:45Z | 3,765,219 | 9 | 2010-09-21T23:27:15Z | [
"python",
"windows"
] | I am interested in learning python but my linux skills suck. i would like to develop a medium to large scale web application using python and django but afraid the software may not work well on a windows box. Is there a performance difference in running python on linux vs windows. Is there anything that I should watch ... | Don't tell anybody this, but I've run python/django on windows. It works all right and the performance hit isn't any worse than you would expect from windows. I used MySQL and it installed without a problem. I had to grope around to find out how to manage it (no good ol' `sudo /etc/init.d/mysql restart` but i eventuall... |
Running python on a Windows machine vs Linux | 3,765,178 | 7 | 2010-09-21T23:17:45Z | 3,765,742 | 10 | 2010-09-22T01:36:33Z | [
"python",
"windows"
] | I am interested in learning python but my linux skills suck. i would like to develop a medium to large scale web application using python and django but afraid the software may not work well on a windows box. Is there a performance difference in running python on linux vs windows. Is there anything that I should watch ... | > but afraid the software may not work well on a windows box.
Your software will work. The Windows OS may not work as you hope. But that's Windows, not Python.
We develop 100% on Windows. We completely test: Unit test, integration test and user acceptance test on Windows. 100%.
We deploy for production 0% on Windows... |
Monkey-patch Python class | 3,765,222 | 33 | 2010-09-21T23:28:22Z | 3,765,237 | 45 | 2010-09-21T23:30:30Z | [
"python",
"monkeypatching"
] | I've got a class, located in a separate module, which I can't change.
```
from module import MyClass
class ReplaceClass(object)
...
MyClass = ReplaceClass
```
This doesn't change MyClass anywhere else but this file. However if I'll add a method like this
```
def bar():
print 123
MyClass.foo = bar
```
this w... | ```
import module
class ReplaceClass(object):
....
module.MyClass = ReplaceClass
``` |
Monkey-patch Python class | 3,765,222 | 33 | 2010-09-21T23:28:22Z | 3,765,252 | 22 | 2010-09-21T23:33:25Z | [
"python",
"monkeypatching"
] | I've got a class, located in a separate module, which I can't change.
```
from module import MyClass
class ReplaceClass(object)
...
MyClass = ReplaceClass
```
This doesn't change MyClass anywhere else but this file. However if I'll add a method like this
```
def bar():
print 123
MyClass.foo = bar
```
this w... | Avoid the `from ... import` (horrid;-) way to get barenames when what you need most often are **qualified** names. Once you do things the right Pythonic way:
```
import module
class ReplaceClass(object): ...
module.MyClass = ReplaceClass
```
This way, you're monkeypatching the **module** object, which is what you n... |
Monkey-patch Python class | 3,765,222 | 33 | 2010-09-21T23:28:22Z | 7,830,208 | 8 | 2011-10-20T01:38:56Z | [
"python",
"monkeypatching"
] | I've got a class, located in a separate module, which I can't change.
```
from module import MyClass
class ReplaceClass(object)
...
MyClass = ReplaceClass
```
This doesn't change MyClass anywhere else but this file. However if I'll add a method like this
```
def bar():
print 123
MyClass.foo = bar
```
this w... | I am but an egg . . . . Perhaps it is obvious to not-newbies, but I needed the `from some.package.module import module` idiom.
I had to modify one method of GenerallyHelpfulClass. This failed:
```
import some.package.module
class SpeciallyHelpfulClass(some.package.module.GenerallyHelpfulClass):
def general_meth... |
Python Array with String Indices | 3,765,533 | 18 | 2010-09-22T00:44:43Z | 3,765,543 | 50 | 2010-09-22T00:46:14Z | [
"python",
"arrays",
"list",
"dictionary"
] | Is it possible to use strings as indices in an array in python?
For example:
```
myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]
``` | What you want is called an [associative array](http://en.wikipedia.org/wiki/Associative_array). In python these are called [dictionaries](http://docs.python.org/tutorial/datastructures.html#dictionaries).
> Dictionaries are sometimes found in other languages as âassociative memoriesâ or âassociative arraysâ. U... |
How to sort with lambda in Python | 3,766,633 | 52 | 2010-09-22T05:46:41Z | 3,766,636 | 105 | 2010-09-22T05:48:56Z | [
"python",
"lambda"
] | In Python, I am trying to sort by date with lambda. I can't understand which lambda my error message is referring to. The message is:
```
<lambda>() takes exactly 1 argument (2 given)
```
The 2 instructions are
```
a = A.proximity_fetch(A.all().filter("modified >", timeline).filter("published =", True).filter("modif... | Use
```
a = sorted(a, key=lambda x: x.modified, reverse=True)
# ^^^^
```
On Python 2.x, the `sorted` function takes its arguments in this order:
```
sorted(iterable, cmp=None, key=None, reverse=False)
```
so without the `key=`, the function you pass in will be considered a `cmp` function which takes 2 a... |
Python: Advanced Nested List Comprehension Syntax | 3,766,711 | 32 | 2010-09-22T06:07:19Z | 3,766,765 | 30 | 2010-09-22T06:18:40Z | [
"python",
"syntax",
"scope",
"list-comprehension"
] | I was playing around with list comprehensions to get a better understanding of them and I ran into some unexpected output that I am not able to explain. I haven't found this question asked before, but if it /is/ a repeat question, I apologize.
I was essentially trying to write a generator which generated generators. A... | you need to use some parentheses:
```
((x for x in range(10) if x%2==i) for i in range(2))
```
> This didn't make sense to me, so I
> thought it best to try something
> simpler first. So I went back to lists
> and tried:
>
> [>>> [x for x in range(10) if x%2==i for i in range(2)]
> [1, 1, 3, 3, 5, 5, 7, 7, 9, 9]
Tha... |
Python text validation: a-z and comma (",") | 3,767,210 | 2 | 2010-09-22T07:39:49Z | 3,767,239 | 14 | 2010-09-22T07:43:29Z | [
"python",
"regex",
"validation"
] | I need to check that some text only contains lower-case letters a-z and a comma (",").
What is the best way to do this in Python? | ```
import string
allowed = set(string.lowercase + ',')
if set(text) - allowed:
# you know it has forbidden characters
else:
# it doesn't have forbidden characters
```
Doing it with sets will be faster than doing it with for loops (especially if you want to check more than one text) and is all together cleaner ... |
Python text validation: a-z and comma (",") | 3,767,210 | 2 | 2010-09-22T07:39:49Z | 3,767,294 | 15 | 2010-09-22T07:53:24Z | [
"python",
"regex",
"validation"
] | I need to check that some text only contains lower-case letters a-z and a comma (",").
What is the best way to do this in Python? | ```
import re
def matches(s):
return re.match("^[a-z,]*$", s) is not None
```
Which gives you:
```
>>> matches("tea and cakes")
False
>>> matches("twiddledee,twiddledum")
True
```
You can optimise a bit with re.compile:
```
import re
matcher = re.compile("^[a-z,]*$")
def matches(s):
return matcher.match(s) ... |
'invalid value encountered in double_scalars' warning, possibly numpy | 3,767,409 | 25 | 2010-09-22T08:11:21Z | 3,767,475 | 23 | 2010-09-22T08:22:22Z | [
"python",
"numpy",
"warnings",
"matplotlib"
] | As I run my code I get these warnings, always in groups of four, sporadically. I have tried to locate the source by placing debug messages before and after certain statements to pin-point its origin.
```
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
Warning: ... | It looks like a floating-point calculation error. Check the [numpy.seterr](http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html) function to get more information about where it happens. |
'invalid value encountered in double_scalars' warning, possibly numpy | 3,767,409 | 25 | 2010-09-22T08:11:21Z | 4,126,333 | 8 | 2010-11-08T17:30:53Z | [
"python",
"numpy",
"warnings",
"matplotlib"
] | As I run my code I get these warnings, always in groups of four, sporadically. I have tried to locate the source by placing debug messages before and after certain statements to pin-point its origin.
```
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
Warning: ... | Sometimes NaNs or null values in data will generate this error with Numpy. If you are ingesting data from say, a CSV file or something like that, and then operating on the data using numpy arrays, the problem could have originated with your data ingest. You could try feeding your code a small set of data with known val... |
'invalid value encountered in double_scalars' warning, possibly numpy | 3,767,409 | 25 | 2010-09-22T08:11:21Z | 4,424,235 | 17 | 2010-12-12T21:47:25Z | [
"python",
"numpy",
"warnings",
"matplotlib"
] | As I run my code I get these warnings, always in groups of four, sporadically. I have tried to locate the source by placing debug messages before and after certain statements to pin-point its origin.
```
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
Warning: ... | In my case i found out it was division by zero |
Namespaces in C# vs imports in Java and Python | 3,767,910 | 10 | 2010-09-22T09:28:28Z | 3,767,961 | 7 | 2010-09-22T09:35:19Z | [
"c#",
"java",
"python",
"namespaces",
"packages"
] | In the Java and Python world, you look at a source file and know where all the imports come from (i.e. you know in which file the imported classes are defined). For example:
In Java:
```
import javafoo.Bar;
public class MyClass {
private Bar myBar = new Bar();
}
```
You immediately see that the Bar-class is imp... | 1) Well, you can do the same thing in Java too:
```
import java.util.*;
import java.io.*;
...
InputStream x = ...;
```
Does `InputStream` come from `java.util` or `java.io`? Of course, you can choose not to use that feature.
Now, in *theory* I realise this means when you're looking with a text editor, you can't te... |
Python lists and list item matches - can my code/reasoning be improved? | 3,768,702 | 2 | 2010-09-22T11:23:48Z | 3,768,809 | 8 | 2010-09-22T11:38:57Z | [
"python",
"list",
"while-loop"
] | query level: beginner
As part of a learning exercise I have written code that must check if a string (as it is build up through raw\_input) matches the beginning of any list item and if it equals any list item.
```
wordlist = ['hello', 'bye']
handlist = []
letter = raw_input('enter letter: ')
handlist.append(lette... | Firstly, you don't need the `handlist` variable; you can just concatenate the value of `raw_input` with `hand`.
You can save the first `raw_input` by starting the `while` loop with `hand` as an empty string since every string has `startswith("")` as `True`.
Finally, we need work out best way to see if any of the item... |
How to make a class JSON serializable | 3,768,895 | 311 | 2010-09-22T11:52:19Z | 3,768,975 | 243 | 2010-09-22T12:02:18Z | [
"python",
"json",
"serialization"
] | How to make a Python class serializable?
A simple class:
```
class FileItem:
def __init__(self, fname):
self.fname = fname
```
What should I do to be able to get output of:
```
json.dumps()
```
Without an error (`FileItem instance at ... is not JSON serializable`) | Do you have an idea about the expected output? For e.g. will this do?
```
>>> f = FileItem("/foo/bar")
>>> magic(f)
'{"fname": "/foo/bar"}'
```
In that case you can merely call `json.dumps(f.__dict__)`.
If you want more customized output then you will have to subclass [`JSONEncoder`](https://docs.python.org/2/libra... |
How to make a class JSON serializable | 3,768,895 | 311 | 2010-09-22T11:52:19Z | 8,614,096 | 54 | 2011-12-23T09:11:09Z | [
"python",
"json",
"serialization"
] | How to make a Python class serializable?
A simple class:
```
class FileItem:
def __init__(self, fname):
self.fname = fname
```
What should I do to be able to get output of:
```
json.dumps()
```
Without an error (`FileItem instance at ... is not JSON serializable`) | For more complex classes you could consider the tool [**jsonpickle**](http://jsonpickle.github.com/):
> jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON.
>
> The standard Python libraries for encoding Python into JSON, such as the stdlibâs json, simplejs... |
How to make a class JSON serializable | 3,768,895 | 311 | 2010-09-22T11:52:19Z | 11,062,658 | 14 | 2012-06-16T10:30:13Z | [
"python",
"json",
"serialization"
] | How to make a Python class serializable?
A simple class:
```
class FileItem:
def __init__(self, fname):
self.fname = fname
```
What should I do to be able to get output of:
```
json.dumps()
```
Without an error (`FileItem instance at ... is not JSON serializable`) | Another case is to wrap JSON dumping in the own class:
```
import json
class FileItem:
def __init__(self, fname):
self.fname = fname
def __repr__(self):
return json.dumps(self.__dict__)
```
Or even subclassing FileItem class from a JSONSerializable class:
```
import json
class JSONSerializ... |
How to make a class JSON serializable | 3,768,895 | 311 | 2010-09-22T11:52:19Z | 15,538,391 | 261 | 2013-03-21T02:26:08Z | [
"python",
"json",
"serialization"
] | How to make a Python class serializable?
A simple class:
```
class FileItem:
def __init__(self, fname):
self.fname = fname
```
What should I do to be able to get output of:
```
json.dumps()
```
Without an error (`FileItem instance at ... is not JSON serializable`) | Here is a simple solution for a simple feature:
## `.toJSON()` Method
Instead of a JSON serializable class, implement a serializer method:
```
import json
class Object:
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
```
So you just call it... |
How to make a class JSON serializable | 3,768,895 | 311 | 2010-09-22T11:52:19Z | 28,174,796 | 13 | 2015-01-27T16:04:36Z | [
"python",
"json",
"serialization"
] | How to make a Python class serializable?
A simple class:
```
class FileItem:
def __init__(self, fname):
self.fname = fname
```
What should I do to be able to get output of:
```
json.dumps()
```
Without an error (`FileItem instance at ... is not JSON serializable`) | I like [Onur's answer](http://stackoverflow.com/a/15538391/44330) but would expand to include an optional `toJSON()` method for objects to serialize themselves:
```
def dumper(obj):
try:
return obj.toJSON()
except:
return obj.__dict__
print json.dumps(some_big_object, default=dumper, indent=2)
... |
How to make a class JSON serializable | 3,768,895 | 311 | 2010-09-22T11:52:19Z | 31,207,881 | 11 | 2015-07-03T13:22:25Z | [
"python",
"json",
"serialization"
] | How to make a Python class serializable?
A simple class:
```
class FileItem:
def __init__(self, fname):
self.fname = fname
```
What should I do to be able to get output of:
```
json.dumps()
```
Without an error (`FileItem instance at ... is not JSON serializable`) | Most of the answers involve changing the call to **json.dumps()**, which is not always possible or desirable (it may happen inside a framework component for example).
If you want to be able to call **json.dumps(obj)** as is, then a simple solution is inheriting from **dict**:
```
class FileItem(dict):
def __init_... |
How to make a class JSON serializable | 3,768,895 | 311 | 2010-09-22T11:52:19Z | 35,483,750 | 8 | 2016-02-18T14:10:51Z | [
"python",
"json",
"serialization"
] | How to make a Python class serializable?
A simple class:
```
class FileItem:
def __init__(self, fname):
self.fname = fname
```
What should I do to be able to get output of:
```
json.dumps()
```
Without an error (`FileItem instance at ... is not JSON serializable`) | I came across this problem the other day and implemented a more general version of an Encoder for Python objects that can **handle nested objects** and **inherited fields**:
```
import json
import inspect
class ObjectEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, "to_json"):
... |
Django getting executable raw sql for a QuerySet | 3,769,093 | 4 | 2010-09-22T12:18:01Z | 3,769,153 | 8 | 2010-09-22T12:24:26Z | [
"python",
"sql",
"django",
"orm"
] | I know that you can get the SQL of a given QuerySet using
```
print query.query
```
but as we know from a previous question ( <http://stackoverflow.com/questions/2926483/potential-django-bug-in-queryset-query> ) the returned SQL is not properly quoted. See <http://code.djangoproject.com/browser/django/trunk/django/db... | Django never creates the raw sql, so no. To prevent SQL injection, django passes the parameters separately to the database drivers at the last step. The best way to get the actual SQL is to look at your query log, which you cannot do before you execute the query. |
Are there tools that can spot errors like this one? | 3,769,196 | 16 | 2010-09-22T12:30:05Z | 3,769,310 | 7 | 2010-09-22T12:45:53Z | [
"python"
] | I found the following mistake in my code this week:
```
import datetime
d = datetime.date(2010,9,24)
if d.isoweekday == 5:
pass
```
Yes, it should be d.isoweekday() instead.
I know, if I had had a test-case for this I would have been saved.
Comparing a function with 5 is not very useful. Oh, I'm not blaming Pyt... | As an *alternative*, most Python projects are **unit tested** and system tested. If you have both (or even just unit tests) you'll find your problem along with pretty much any other issue.
As *dekomote* said, this is syntaxically valid. Python is *not* statically typed so this cannot be caught as an error. At most it ... |
How to create an email and send it to specific mailbox with imaplib | 3,769,701 | 3 | 2010-09-22T13:28:49Z | 3,769,857 | 7 | 2010-09-22T13:44:22Z | [
"python",
"imaplib"
] | I am trying to use python's imaplib to create an email and send it to a mailbox with specific name, e.g. INBOX. Anyone has some great suggestion :). | The IMAP protocol is not designed to send emails. It is designed to manipulate mailboxes.
To create an email and send it you can use SMTP, as in [smtplib](http://docs.python.org/library/smtplib.html#smtp-example).
To move an email that is already in a mailbox from one folder to another, you can copy the mail to the n... |
How to safely open/close files in python 2.4 | 3,770,348 | 52 | 2010-09-22T14:37:41Z | 3,770,375 | 89 | 2010-09-22T14:40:52Z | [
"python",
"file",
"io"
] | I'm currently writing a small script for use on one of our servers using Python. The server only has Python 2.4.4 installed.
I didn't start using Python until 2.5 was out, so I'm used to the form:
```
with open('file.txt', 'r') as f:
# do stuff with f
```
However, there is no `with` statement before 2.5, and I'm... | Use `try/finally`:
```
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
```
This ensures that even if `# do stuff with f` raises an exception, `f` will still be closed properly.
Note that `open` should appear *outside* of the `try`. If `open` itself raises an exception, the file wasn't op... |
How to safely open/close files in python 2.4 | 3,770,348 | 52 | 2010-09-22T14:37:41Z | 28,673,892 | 13 | 2015-02-23T12:31:18Z | [
"python",
"file",
"io"
] | I'm currently writing a small script for use on one of our servers using Python. The server only has Python 2.4.4 installed.
I didn't start using Python until 2.5 was out, so I'm used to the form:
```
with open('file.txt', 'r') as f:
# do stuff with f
```
However, there is no `with` statement before 2.5, and I'm... | In the above solution, repeated here:
```
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
```
if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:
```
f = None
try:
f = open('file.txt... |
Python os.walk + follow symlinks | 3,771,696 | 19 | 2010-09-22T16:57:00Z | 3,771,705 | 29 | 2010-09-22T16:58:55Z | [
"python",
"symlink",
"traversal",
"directory-traversal",
"symlink-traversal"
] | How do I get this piece to follow symlinks in python 2.6?
```
def load_recursive(self, path):
for subdir, dirs, files in os.walk(path):
for file in files:
if file.endswith('.xml'):
file_path = os.path.join(subdir, file)
try:
do_stuff(file_path... | Set `followlinks` to `True`. This is the fourth argument to the `os.walk` method, reproduced below:
```
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
```
This option was added in Python 2.6. |
Ambiguous tab completion not working in iPython on Windows | 3,771,837 | 6 | 2010-09-22T17:15:02Z | 4,126,854 | 9 | 2010-11-08T18:36:44Z | [
"python",
"ipython",
"tab-completion"
] | I am running IPython on Windows 7 x64 with pyreadline installed. If I start a new session and type:
```
import numpy
nu<TAB>
```
Then `nu` autocompletes to `numpy`. However, if I start a new session and try this:
```
import numpy
n<TAB>
```
Then nothing happens. I would expect it to cycle through all of the possibl... | You have to copy config file for pyreadline to your HOME folder (C:\Users\< username >).
Open Command line and execute that:
```
copy "C:\Program Files (x86)\Python26\Lib\site-packages\pyreadline\configuration\pyreadlineconfig.ini" %HOMEPATH%
``` |
Python multiprocessing Pool.map is calling aquire? | 3,771,875 | 12 | 2010-09-22T17:19:08Z | 3,775,154 | 7 | 2010-09-23T02:56:39Z | [
"python",
"profiling",
"multiprocessing"
] | I have a numpy.array of 640x480 images, each of which is 630 images long.
The total array is thus 630x480x640.
I want to generate an average image, as well as compute the standard deviation for
each pixel across all 630 images.
This is easily accomplished by
```
avg_image = numpy.mean(img_array, axis=0)
std_image = n... | I believe the problem is that the amount of CPU time it takes to process each chunk is small relative to the amount of time it takes to copy the input and output to and from the worker processes. I modified your example code to split the output into 16 even chunks and to print out the difference in CPU time (`time.cloc... |
How to reload modules in django shell? | 3,772,260 | 42 | 2010-09-22T18:02:49Z | 3,816,813 | 20 | 2010-09-28T20:32:49Z | [
"python",
"django",
"ipython"
] | I am working with Django and use Django shell all the time. The annoying part is that while the Django server reloads on code changes, the shell does not, so every time I make a change to a method I am testing, I need to quit the shell and restart it, re-import all the modules I need, reinitialize all the variables I n... | It seems that the general consensus on this topic, is that python reload() sucks and there is no good way to do this. |
How to reload modules in django shell? | 3,772,260 | 42 | 2010-09-22T18:02:49Z | 16,745,520 | 35 | 2013-05-25T01:17:48Z | [
"python",
"django",
"ipython"
] | I am working with Django and use Django shell all the time. The annoying part is that while the Django server reloads on code changes, the shell does not, so every time I make a change to a method I am testing, I need to quit the shell and restart it, re-import all the modules I need, reinitialize all the variables I n... | look at the manage.py shell\_plus command provided by the [django-extensions](https://github.com/django-extensions/django-extensions) project. It will load all your model files on shell startup. and autoreload your any modify but do not need exit, you can direct call there |
How to reload modules in django shell? | 3,772,260 | 42 | 2010-09-22T18:02:49Z | 20,513,519 | 13 | 2013-12-11T07:55:27Z | [
"python",
"django",
"ipython"
] | I am working with Django and use Django shell all the time. The annoying part is that while the Django server reloads on code changes, the shell does not, so every time I make a change to a method I am testing, I need to quit the shell and restart it, re-import all the modules I need, reinitialize all the variables I n... | I recommend using the django-extensions project like stated above by dongweiming. But instead of just 'shell\_plus' management command, use:
```
manage.py shell_plus --notebook
```
This will open a IPython notebook on your web browser. Write your code there in a cell, your imports etc. and run it.
When you change yo... |
How to reload modules in django shell? | 3,772,260 | 42 | 2010-09-22T18:02:49Z | 26,771,173 | 16 | 2014-11-06T03:20:20Z | [
"python",
"django",
"ipython"
] | I am working with Django and use Django shell all the time. The annoying part is that while the Django server reloads on code changes, the shell does not, so every time I make a change to a method I am testing, I need to quit the shell and restart it, re-import all the modules I need, reinitialize all the variables I n... | My solution to it is I write the code and save to a file and then use:
> python manage.py shell < test.py
So I can make the change, save and run that command again till I fix whatever I'm trying to fix. |
How to use Scrapy | 3,773,035 | 3 | 2010-09-22T19:46:14Z | 3,774,129 | 7 | 2010-09-22T22:35:19Z | [
"python",
"web-crawler",
"scrapy"
] | I would like to know how can I start a crawler based on Scrapy. I installed the tool via apt-get install and I tried to run an example:
```
/usr/share/doc/scrapy/examples/googledir/googledir$ scrapy list
directory.google.com
/usr/share/doc/scrapy/examples/googledir/googledir$ scrapy crawl
```
I hacked the code from ... | EveryBlock.com released some [quality scraping code](http://code.google.com/p/ebcode/) using lxml, urllib2 and Django as their stack.
[Scraperwiki.com](http://scraperwiki.com/) is inspirational, full of examples of python scrapers.
Simple example with cssselect:
```
from lxml.html import fromstring
dom = fromstring... |
How to use Scrapy | 3,773,035 | 3 | 2010-09-22T19:46:14Z | 3,775,311 | 7 | 2010-09-23T03:36:50Z | [
"python",
"web-crawler",
"scrapy"
] | I would like to know how can I start a crawler based on Scrapy. I installed the tool via apt-get install and I tried to run an example:
```
/usr/share/doc/scrapy/examples/googledir/googledir$ scrapy list
directory.google.com
/usr/share/doc/scrapy/examples/googledir/googledir$ scrapy crawl
```
I hacked the code from ... | You missed the spider name in the crawl command. Use:
```
$ scrapy crawl directory.google.com
```
Also, I suggest you copy the example project to your home, instead of working in the `/usr/share/doc/scrapy/examples/` directory, so you can modify it and play with it:
```
$ cp -r /usr/share/doc/scrapy/examples/googled... |
Pythonic way to perform a large case/switch | 3,773,079 | 2 | 2010-09-22T19:52:19Z | 3,773,090 | 7 | 2010-09-22T19:53:56Z | [
"python"
] | I'm pretty sure this is a really fundamental concept in Python, I'd love it if someone could help me understand how to do the following in a pythonic/clean way. I'm really new to coding so I will just show an example. I think it will be obvious what I am trying to do.
```
for textLine in textLines:
foo = re.match('... | For the specific code you're showing, the pythonic thing would be to replace the entire if-ladder with:
```
item = list[int(thing)-1]
```
Of course, it's possible that your real code doesn't lend itself to collapsing like this. |
Pythonic way to perform a large case/switch | 3,773,079 | 2 | 2010-09-22T19:52:19Z | 3,773,096 | 11 | 2010-09-22T19:54:58Z | [
"python"
] | I'm pretty sure this is a really fundamental concept in Python, I'd love it if someone could help me understand how to do the following in a pythonic/clean way. I'm really new to coding so I will just show an example. I think it will be obvious what I am trying to do.
```
for textLine in textLines:
foo = re.match('... | Why not just do this
```
item = list[int(thing) - 1]
```
In more complex cases, you should use a dictionary mapping inputs to outputs. |
Python vs Lua for embedded scripting/text processing engine | 3,774,108 | 15 | 2010-09-22T22:30:44Z | 3,774,150 | 17 | 2010-09-22T22:39:13Z | [
"c++",
"python",
"scripting",
"lua",
"embedded-language"
] | For a project I'm currently working on, I'm looking to embed a scripting engine into my C++ code to allow for some extensibility down the line. The application will require a fair amount of text processing and the use of regular expressions within these scripts.
I know Lua is generally the industry darling when it com... | if you need specifically what is commonly known as 'regular expressions' (which aren't regular at all), then you have two choices:
1. go with Python. it's included regexp is similar enough to Perl's and sed/grep
2. use Lua and an external [PCRE library](http://www.t2-project.org/packages/lua-pcre.html)
if, on the oth... |
Python vs Lua for embedded scripting/text processing engine | 3,774,108 | 15 | 2010-09-22T22:30:44Z | 3,774,209 | 7 | 2010-09-22T22:54:05Z | [
"c++",
"python",
"scripting",
"lua",
"embedded-language"
] | For a project I'm currently working on, I'm looking to embed a scripting engine into my C++ code to allow for some extensibility down the line. The application will require a fair amount of text processing and the use of regular expressions within these scripts.
I know Lua is generally the industry darling when it com... | Python and C++ integration is greatly helped with [boost.python](http://www.boost.org/doc/libs/1_44_0/libs/python/doc/index.html). You may find this much more convenient if those familiar with your C++ source are primarily the ones writing scripts.
Even if the scripters aren't familiar with your particular source, if ... |
Given an AST, is there a working library for getting the source? | 3,774,162 | 9 | 2010-09-22T22:41:44Z | 3,794,251 | 7 | 2010-09-25T14:48:30Z | [
"python",
"abstract-syntax-tree"
] | Is there a way to convert a given Python abstract syntax tree (AST) to a source code?
[Here](http://www.dalkescientific.com/writings/diary/archive/2010/02/22/instrumenting_the_ast.html) is a good example of how to use Python's `ast` module, specifically a `NodeTransformer`. I was looking for a way to convert the resul... | The Python source tree contains an implementation of this: unparse.py in the Demo/parser directory: <http://svn.python.org/projects/python/trunk/Demo/parser/unparse.py> |
What do we call this (new?) higher-order function? | 3,774,247 | 9 | 2010-09-22T23:03:38Z | 3,775,293 | 17 | 2010-09-23T03:29:47Z | [
"python",
"haskell",
"functional-programming",
"theory",
"higher-order-functions"
] | I am trying to name what I think is a new idea for a higher-order function. To the important part, here is the code in Python and Haskell to demonstrate the concept, which will be explained afterward.
Python:
```
>>> def pleat(f, l):
return map(lambda t: f(*t), zip(l, l[1:]))
>>> pleat(operator.add, [0, 1, 2, ... | Hmm... a counterpoint.
```
(`ap` tail) . zipWith
```
doesn't deserve a name.
BTW, quicksilver says:
```
zip`ap`tail
```
The Aztec god of consecutive numbers |
Implementing use of 'with object() as f' in custom class in python | 3,774,328 | 14 | 2010-09-22T23:18:34Z | 3,774,396 | 17 | 2010-09-22T23:31:17Z | [
"python",
"file-io",
"with-statement"
] | I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I'm getting weird errors though and I think it has to do w... | Those methods are pretty much all you need for making the object work with `with` statement.
In `__enter__` you have to return the file object after opening it and setting it up.
In `__exit__` you have to close the file object. The code for writing to it will be in the `with` statement body.
```
class Meter():
d... |
Implementing use of 'with object() as f' in custom class in python | 3,774,328 | 14 | 2010-09-22T23:18:34Z | 3,774,934 | 7 | 2010-09-23T02:06:38Z | [
"python",
"file-io",
"with-statement"
] | I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I'm getting weird errors though and I think it has to do w... | Easiest may be to use standard Python library module [contextlib](http://docs.python.org/library/contextlib.html):
```
import contextlib
@contextlib.contextmanager
def themeter(name):
theobj = Meter(name)
yield theobj
theobj.close() # or whatever you need to do at exit
```
This doesn't make `Meter` itse... |
Get data from the meta tags using BeautifulSoup | 3,774,571 | 13 | 2010-09-23T00:17:33Z | 3,774,887 | 32 | 2010-09-23T01:51:32Z | [
"python",
"beautifulsoup"
] | I am trying to read the description from the meta tag and this is what I used
```
soup.findAll(name="description")
```
but it does not work, however, the code below works just fine
```
soup.findAll(align="center")
```
How do I read the description from the meta tag in the head of a document? | Yep, `name` can't be used in keyword-argument form to designate an attribute named `name` because the name `name` is already used by `BeautifulSoup` itself. So use instead:
```
soup.findAll(attrs={"name":"description"})
```
That's what the `attrs` argument is **for**: passing as a dict those attribute constraints for... |
What is the Perl version of a Python iterator? | 3,775,413 | 39 | 2010-09-23T04:14:09Z | 3,775,460 | 7 | 2010-09-23T04:29:41Z | [
"python",
"perl",
"iterator"
] | I am learning Perl at my work and enjoying it. I usually do my work in Python but boss wants Perl.
Most of the concepts in Python and Perl match nicely: Python dictionary=Perl hash; Python tuple=Perl list; Python list=Perl array; etc.
Question: Is there a Perl version of the Python form of an [Iterator](http://docs.p... | There is a similar method to produce a Iterator / Generator, but it is not a "first class citizen" as it is on Python.
In Perl, if you do not see what you want (after a **MANDATORY** trip to [CPAN](http://search.cpan.org/search?query=iterator&mode=all) **FIRST**!), you can roll your own that is similar to a Python ite... |
What is the Perl version of a Python iterator? | 3,775,413 | 39 | 2010-09-23T04:14:09Z | 3,775,484 | 29 | 2010-09-23T04:38:11Z | [
"python",
"perl",
"iterator"
] | I am learning Perl at my work and enjoying it. I usually do my work in Python but boss wants Perl.
Most of the concepts in Python and Perl match nicely: Python dictionary=Perl hash; Python tuple=Perl list; Python list=Perl array; etc.
Question: Is there a Perl version of the Python form of an [Iterator](http://docs.p... | The concept of an iterator is a little different in Perl. You basically want to return a one-use subroutine "closed" over the persistent variables.
```
use bigint;
use strict;
use warnings;
sub fibonacci {
my $limit = 10**( shift || 0 );
my ( $a, $b ) = ( 0, 1 );
return sub {
return if $a > $limi... |
What is the Perl version of a Python iterator? | 3,775,413 | 39 | 2010-09-23T04:14:09Z | 3,775,687 | 14 | 2010-09-23T05:40:24Z | [
"python",
"perl",
"iterator"
] | I am learning Perl at my work and enjoying it. I usually do my work in Python but boss wants Perl.
Most of the concepts in Python and Perl match nicely: Python dictionary=Perl hash; Python tuple=Perl list; Python list=Perl array; etc.
Question: Is there a Perl version of the Python form of an [Iterator](http://docs.p... | The excellent [Higher-Order Perl](http://hop.perl.plover.com/book/) book (available for free at the specified link) contains a lot of information on related topics, and in particular has a whole chapter on iterators. By "higher order" the author implies using Perl's abilities as a functional language with first-class f... |
What is the Perl version of a Python iterator? | 3,775,413 | 39 | 2010-09-23T04:14:09Z | 3,775,818 | 32 | 2010-09-23T06:13:00Z | [
"python",
"perl",
"iterator"
] | I am learning Perl at my work and enjoying it. I usually do my work in Python but boss wants Perl.
Most of the concepts in Python and Perl match nicely: Python dictionary=Perl hash; Python tuple=Perl list; Python list=Perl array; etc.
Question: Is there a Perl version of the Python form of an [Iterator](http://docs.p... | For an even more flexible solution than Python's generators, I have written the module [List::Gen](http://search.cpan.org/perldoc?List%3a%3aGen) on CPAN which provides random access lazy generator arrays:
```
use List::Gen;
my $fib; $fib = cache gen {$_ < 2 ? $_ : $$fib[$_ - 1] + $$fib[$_ - 2]};
say "@$fib[0 .. 15]... |
google app engine blob store creation | 3,776,208 | 2 | 2010-09-23T07:31:07Z | 3,776,252 | 7 | 2010-09-23T07:38:22Z | [
"python",
"image",
"google-app-engine",
"blobstore"
] | In order to save precious bandwidth, the image serving app (a minor, but important part of the total app) tries to serve only thumbnails or reduced size previews of possibly large photos or illustrations. Storing the original image in the BlobStore is simple enough, and generating the thumbnails is also simple using th... | You don't need to create thumbnails from images in BlobStore at all - use `get_serving_url` function instead (see <http://code.google.com/appengine/docs/python/images/functions.html>).
This function generates and caches thumbnails from large images in the fly and doesn't even cost you any CPU (see [this post](http://g... |
How to add key,value pair to dictionary? | 3,776,275 | 19 | 2010-09-23T07:43:11Z | 3,776,287 | 41 | 2010-09-23T07:45:32Z | [
"python"
] | How to add key,value pair to dictionary?.Below i have mentioned following format?
```
{'1_somemessage': [[3L,
1L,
u'AAA',
1689544L,
datetime.datetime(2010, 9, 21, 22, 30),
u'gffggf'],
[3L,
... | Add a key, value pair to dictionary
```
aDict = {}
aDict[key] = value
```
What do you mean by dynamic addition. |
Writing a module for both Python 2.x and 3.x | 3,776,665 | 8 | 2010-09-23T08:47:32Z | 3,776,824 | 9 | 2010-09-23T09:06:15Z | [
"python",
"python-3.x",
"python-2.x"
] | I've written a pure-Python module for Python 3.0/3.1 which I'd also like to make it compatible with 2.x (probably just 2.6/2.7) in order to make it available to the widest possible audience.
The module is concerned with reading and writing a set of related file formats, so the differences between 2.x and 3.x versions ... | Write your code entirely against 2.x, targeting the most recent version in the 2.x series. In this case, it's probably going to remain 2.7. Run it through `2to3`, and if it doesn't pass all of its unit tests, fix the 2.x version until the generated 3.x version works.
Eventually, when you want to drop 2.x support, you ... |
How to call a shell script from python code? | 3,777,301 | 88 | 2010-09-23T10:12:57Z | 3,777,308 | 102 | 2010-09-23T10:13:45Z | [
"python"
] | how to call a shell script from python code? | The [subprocess](http://docs.python.org/library/subprocess.html) module will help you out.
Here is a decent [tutorial](http://jimmyg.org/blog/2009/working-with-python-subprocess.html).
Blatantly trivial example:
```
>>> import subprocess
>>> subprocess.call(['./test.sh']) # Thanks @Jim Dennis for suggesting the []
0... |
How to call a shell script from python code? | 3,777,301 | 88 | 2010-09-23T10:12:57Z | 3,777,320 | 19 | 2010-09-23T10:15:06Z | [
"python"
] | how to call a shell script from python code? | There is some ways using `os.popen()` (deprecated) or whole `subprocess` module, but [`os.system(command)`](http://docs.python.org/py3k/library/os.html#os.system) is one of the easiest. |
How to call a shell script from python code? | 3,777,301 | 88 | 2010-09-23T10:12:57Z | 3,777,351 | 12 | 2010-09-23T10:19:35Z | [
"python"
] | how to call a shell script from python code? | Use the subprocess module as mentioned above.
I use it like this:
```
subprocess.call(["notepad"])
``` |
How to call a shell script from python code? | 3,777,301 | 88 | 2010-09-23T10:12:57Z | 31,995,784 | 11 | 2015-08-13T18:26:41Z | [
"python"
] | how to call a shell script from python code? | In case you want to pass some parameters to your shell script, you can use the method [shlex.split()](https://docs.python.org/2/library/shlex.html#shlex.split):
```
import subprocess
import shlex
subprocess.call(shlex.split('./test.sh param1 param2'))
```
with `test.sh` in the same folder:
```
#!/bin/sh
echo $1
echo... |
What is a good place to store configuration in Google AppEngine (python) | 3,777,367 | 12 | 2010-09-23T10:22:03Z | 3,778,155 | 10 | 2010-09-23T12:04:47Z | [
"python",
"google-app-engine",
"configuration-files"
] | I am making a Google AppEngine application and am doubting were I should store (sensitive) configuration data like credentials.
Should I make a single bigtable entity for configuration, or is there another advised way to store it. | Store them in a module. You can go simple, like having a `config.py` module with, say:
```
AMAZON_KEY = 'XXXX'
```
Then use:
```
import config
service = my_amazon_service(config.AMAZON_KEY)
```
Or have a slightly more sophisticated config object that allows you to have sensible defaults for your app, namespaced con... |
What is a good place to store configuration in Google AppEngine (python) | 3,777,367 | 12 | 2010-09-23T10:22:03Z | 3,778,576 | 14 | 2010-09-23T12:57:59Z | [
"python",
"google-app-engine",
"configuration-files"
] | I am making a Google AppEngine application and am doubting were I should store (sensitive) configuration data like credentials.
Should I make a single bigtable entity for configuration, or is there another advised way to store it. | If you're okay with embedding them in your source, you can do that, but if you need it to be dynamically configurable, the datastore is the way to go. You can avoid fetching the settings on every request by caching them in local memory. Here's a helper class for that:
```
class Configuration(db.Model):
_INSTANCE = N... |
setting y-axis limit in matplotlib | 3,777,861 | 107 | 2010-09-23T11:32:39Z | 3,780,536 | 65 | 2010-09-23T16:32:39Z | [
"python",
"matplotlib"
] | I need help with setting the limits of y-axis on matplotlib. Here is the code that I tried, unsuccessfully.
```
import matplotlib.pyplot as plt
plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
aPlot = plt.subplot(321, axisbg = 'w', title = "Year 1")
ax.append(aPlot)
plt.plot(paramValues,plotDataPr... | Your code works also for me. However, another workaround can be to get the plot's axis and then change only the y-values:
`x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))` |
setting y-axis limit in matplotlib | 3,777,861 | 107 | 2010-09-23T11:32:39Z | 25,421,861 | 132 | 2014-08-21T08:43:02Z | [
"python",
"matplotlib"
] | I need help with setting the limits of y-axis on matplotlib. Here is the code that I tried, unsuccessfully.
```
import matplotlib.pyplot as plt
plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
aPlot = plt.subplot(321, axisbg = 'w', title = "Year 1")
ax.append(aPlot)
plt.plot(paramValues,plotDataPr... | Try this . Works for subplots too .
```
axes = plt.gca()
axes.set_xlim([xmin,xmax])
axes.set_ylim([ymin,ymax])
``` |
Django Form validation including the use of session data | 3,778,148 | 2 | 2010-09-23T12:03:54Z | 3,782,919 | 9 | 2010-09-23T22:17:07Z | [
"python",
"django",
"django-forms"
] | The use case I am try to address is a requirement for a user to have downloaded a file before being permitted to proceed to the next stage in a form process.
In order to achieve this, I have a Django Form to capture the user's general information which POSTS to Django view 'A'. The Form is displayed using a template w... | You could override the `__init__` method for your form so that it takes `request` as an argument.
```
class MyForm(forms.Form):
def __init__(self, request, *args, **kwargs)
self.request = request
super(MyForm, self).__init__(*args, **kwargs)
def clean(self):
if not self.request.session... |
What Vim script you recommend for checking Python syntax on the fly? | 3,778,486 | 8 | 2010-09-23T12:46:27Z | 3,858,239 | 7 | 2010-10-04T18:56:47Z | [
"python",
"vim",
"syntax"
] | I have visited Vim website , script section and found several synthax checkers for python. But which one to choose ? I would prefer something that supports python 3 as well, even though I code in python 2.6 currently.
Do all these checkers need a module like pychecker and pyflakes ?
I could install the most popular f... | These two websites really boosted my Vim productivity with all languages:
<http://nvie.com/posts/how-i-boosted-my-vim/>
<http://stevelosh.com/blog/2010/09/coming-home-to-vim/> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.