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
how to get the number of elements in a python list?
4,706,989
23
2011-01-16T17:51:14Z
7,582,875
14
2011-09-28T11:58:15Z
[ "python", "list", "count" ]
I'm new to python. i've the following code: ``` liste = 'asdfasfasd:asdfafaergasde' # example, how the string looks like liste = str.split(':'); if liste.count()>2 : print "NOT YET SUPPORTED!" ``` According to the doc <http://docs.python.org/library/stdtypes.html> , python can just return number of i‘s for which...
`len()` gets the length of the list. It actually does not get the number of elements in the list. There could be spaces that are empty and they are still part of the list.
Django: How to build a custom form widget?
4,707,192
35
2011-01-16T18:27:04Z
4,708,481
33
2011-01-16T22:20:11Z
[ "python", "django", "forms" ]
I am having a difficult time finding documentation on how to write a custom widget. My questions are: * If I build a custom widget, can it be used equivalently for the admin interface or for normal forms? * If I want to allow the user to edit a list of items, what widget should I subclass? What methods of the widget ...
You're right in that Django doesn't supply documentation on this specific topic. I advise you to look at the builtin widgets in [`django.forms.widgets`](https://github.com/django/django/blob/master/django/forms/widgets.py) (I'll reference classes from that module below). > If I build a custom widget, can it be used eq...
Ways to avoid MySQLdb's "Commands out of sync; you can't run this command now" (2014) exception
4,707,957
14
2011-01-16T20:50:20Z
4,708,157
9
2011-01-16T21:21:38Z
[ "python", "mysql" ]
Following code, using python 2.6.6 and MySQLdb 1.2.2 causes *Commands out of sync; you can't run this command now* MySQLdb exception: ``` import MySQLdb conn = MySQLdb.connect( db="test", user="root" ) cursor = conn.cursor( MySQLdb.cursors.DictCursor ) cursor.execute( "BEGIN; CREATE TABLE t1 ( t1_id INT PRIMARY KEY ...
DB-API tries to handle transactions on its own, starting a transaction on the first command and having its own API call to commit it, so: ``` cursor.execute( "CREATE TABLE t1 ( t1_id INT PRIMARY KEY AUTO_INCREMENT )" ) cursor.commit() cursor.execute( "CREATE TABLE t2 ( t2_id INT PRIMARY KEY AUTO_INCREMENT )" ) cursor....
How to connect PyQt slot from background thread to gui thread
4,708,436
7
2011-01-16T22:14:03Z
4,710,910
18
2011-01-17T07:29:04Z
[ "python", "pyqt" ]
I wish to connect up a signal in the background thread to a slot in the GUI thread in a pythonic way. I have the following code snippet. ``` from PyQt4.QtCore import * class CompanyPresenter(QObject): fieldChangeSignal = pyqtSignal(str, str) def __init__(self,model,view): self.model = model # ...
you forgot this: ``` def __init__(self,model,view): super(CompanyPresenter, self).__init__() # this!!!!!!!!! ``` add this will work.(tested)
Python: What does _("str") do?
4,708,595
7
2011-01-16T22:43:22Z
4,708,625
15
2011-01-16T22:47:29Z
[ "python", "syntax" ]
I see this in the Django source code: ``` description = _("Comma-separated integers") description = _("Date (without time)") ``` What does it do? I try it in Python 3.1.3 and it fails: ``` >>> foo = _("bar") Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> foo = _("bar") NameError: na...
The name `_` is an ordinary name like any other. The syntax `_(x)` is calling the function called `_` with the argument `x`. In this case it is used as an alias for `ugettext`, which is defined by Django. This function is used for translation of strings. From the [documentation](http://docs.djangoproject.com/en/dev/top...
Cython float division PyExc_ZeroDivisionError checking
4,709,285
7
2011-01-17T01:27:20Z
4,709,456
12
2011-01-17T02:06:21Z
[ "python", "cython" ]
I'm doing some loop-intensive calculations and converted the code into Cython. I did profiling with cython -a option, and inspected the .html file, and it seems whenever I do the float division, there is somewhat yellow line and it does something like the following: ``` if (unlikely(__pyx_t_37 == 0)) { PyErr_F...
You need to add `@cython.cdivision(True)` to avoid the exception checking. ``` import cython cdef double pydivision(): cdef int i cdef double k, j k = 2.0 j = 0.0 for i in range(10): j += i/k # Generated code: Python exception checking # /* "checksum.pyx":9 # * j = 0.0 # * for i in range(10)...
Difficulty with Django and jQuery (why is $ undefined in the admin app?)
4,709,298
7
2011-01-17T01:29:28Z
4,715,844
15
2011-01-17T17:11:42Z
[ "javascript", "python", "django" ]
It's been a while since I worked with jQuery; I think I'm making a stupid mistake. Here is a Django widget: ``` class FooWidget(Widget): # ... class Media: js = ('js/foowidget.js',) ``` Here is the .js file: ``` alert("bar"); $(document).ready(function() { alert("omfg"); $('.foo-widget').clic...
Adding this to the top of my .js file fixes it: ``` var $ = django.jQuery; ``` I'm not sure how to remove the jquery.init.js file, given that my project doesn't contain any scripts that use `$` for something other than jQuery.
Installing OpenCV on Windows 7 for Python 2.7
4,709,301
27
2011-01-17T01:30:45Z
4,709,781
39
2011-01-17T03:27:07Z
[ "python", "opencv" ]
am trying desperately to get OpenCV to work on Windows 7. I download and installed it, and it didn't work, I got ``` ImportError: No module named opencv ``` when I tried to run one of the samples. I google my problem and got only random solutions that don't work. Can anybody guide me in installing it, or know where i...
As of OpenCV 2.2.0, the package name for the Python bindings is "cv".The old bindings named "opencv" are not maintained any longer. You might have to adjust your code. See <http://opencv.willowgarage.com/wiki/PythonInterface>. The official OpenCV installer does not install the Python bindings into your Python director...
Installing OpenCV on Windows 7 for Python 2.7
4,709,301
27
2011-01-17T01:30:45Z
10,859,845
34
2012-06-02T04:42:34Z
[ "python", "opencv" ]
am trying desperately to get OpenCV to work on Windows 7. I download and installed it, and it didn't work, I got ``` ImportError: No module named opencv ``` when I tried to run one of the samples. I google my problem and got only random solutions that don't work. Can anybody guide me in installing it, or know where i...
I have posted a very simple method to install OpenCV 2.4 for Python in Windows here : [Install OpenCV in Windows for Python](http://opencvpython.blogspot.com/2012/05/install-opencv-in-windows-for-python.html) It is just as simple as copy and paste. Hope it will be useful for future viewers. 1. Download Python, Numpy,...
Python string formatting: reference one argument multiple times
4,709,310
20
2011-01-17T01:32:27Z
4,709,329
28
2011-01-17T01:38:25Z
[ "python", "string-formatting" ]
If I have a string like: ``` "{0} {1} {1}" % ("foo", "bar") ``` and I want: ``` "foo bar bar" ``` What do the replacement tokens have to be? (I know that my example above is incorrect; I'm just trying to express my goal.)
``` "{0} {1} {1}".format("foo", "bar") ```
itertools product speed up
4,709,510
9
2011-01-17T02:20:48Z
4,714,857
10
2011-01-17T15:29:31Z
[ "python", "numpy", "itertools" ]
I use itertools.product to generate all possible variations of 4 elements of length 13. The 4 and 13 can be arbitrary, but as it is, I get 4^13 results, which is a lot. I need the result as a Numpy array and currently do the following: ``` c = it.product([1,-1,np.complex(0,1), np.complex(0,-1)], repeat=length) sen...
The NumPy equivalent of `itertools.product()` is `numpy.indices()`, but it will only get you the product of ranges of the form 0,...,k-1: ``` numpy.rollaxis(numpy.indices((2, 3, 3)), 0, 4) array([[[[0, 0, 0], [0, 0, 1], [0, 0, 2]], [[0, 1, 0], [0, 1, 1], [0, 1, 2]], ...
Python regex match date
4,709,652
18
2011-01-17T03:02:29Z
4,709,669
25
2011-01-17T03:06:17Z
[ "python", "regex" ]
What regular expression in Python do i use to match dates like this: "11/12/98"?
You could search for digits separated by forward-slashes: ``` In [146]: import re In [152]: match=re.search(r'(\d+/\d+/\d+)','The date is 11/12/98') In [153]: match.group(1) Out[153]: '11/12/98' ``` Of course, invalid dates will also match: ``` In [154]: match=re.search(r'(\d+/\d+/\d+)','The date is 99/99/99') In ...
how to output every line in a file python
4,709,655
2
2011-01-17T03:03:34Z
4,709,680
11
2011-01-17T03:07:53Z
[ "python", "file", "input" ]
``` if data.find('!masters') != -1: f = open('masters.txt') lines = f.readline() for line in lines: print lines sck.send('PRIVMSG ' + chan + " " + str(lines) + '\r\n') f.close() ``` masters.txt has a list of nicknames, how can I print every l...
Firstly, as @l33tnerd said, `f.close` should be outside the for loop. Secondly, you are only calling `readline` once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you o...
Convert a string to a dictionary in Python?
4,709,737
2
2011-01-17T03:19:33Z
4,709,746
9
2011-01-17T03:21:12Z
[ "python", "json", "twitter" ]
I am pulling data from twitter, which is in the structure of a python dictionary, but the data is held in a string variable. How can I convert this string variable to a dictionary in Python? Thanks for the help! EDIT: [Here](https://docs.google.com/document/pub?id=1SkDTIV95_KPBnOxmoWx4n5uhvSBSayJ_RjXzpgY0sEc) is an ...
You are probably looking for the [json](http://docs.python.org/library/json.html#module-json) module. For example, ``` In [165]: json.loads('{"a": 0, "c": 0, "b": 0}') Out[165]: {u'a': 0, u'b': 0, u'c': 0} ```
Find the most recent file in a directory without reading all the contents of it
4,709,968
4
2011-01-17T04:07:18Z
4,709,985
7
2011-01-17T04:16:33Z
[ "python", "c", "unix" ]
I'm trying to find out the latest file in a huge filesystem. One way to do this is to go through all directories - one at a time, read its contents, select the latest file etc. The obvious drawback is I have to get *all* the files in a specific directory. I was wondering whether there was a 'magic' call in Python [1] ...
Have you considered using [pyinotify](http://pyinotify.sourceforge.net/) which can watch a directory and subdirectories? This might require your code to be threaded, say, a watcher thread that records the latest changes for the main thread to poll. Alternatively, you could use popen and get the result of 'ls -t | he...
Deleting a specific line in a file (python)
4,710,067
50
2011-01-17T04:38:55Z
4,710,090
88
2011-01-17T04:44:37Z
[ "python", "file", "input" ]
Lets say I have a text file full of nicknames, how can I delete a specific nickname from that file?
Assuming your file is in the format of one nickname per line, use this. First, open the file: ``` f = open("yourfile.txt","r") ``` Next, get all your lines from the file: ``` lines = f.readlines() ``` Now you can close the file: ``` f.close() ``` And reopen it in write mode: ``` f = open("yourfile.txt","w") ```...
Deleting a specific line in a file (python)
4,710,067
50
2011-01-17T04:38:55Z
28,057,753
33
2015-01-21T00:42:08Z
[ "python", "file", "input" ]
Lets say I have a text file full of nicknames, how can I delete a specific nickname from that file?
Solution to this problem with only a single open: ``` f = open("target.txt","r+") d = f.readlines() f.seek(0) for i in d: if i != "line you want to remove...": f.write(i) f.truncate() f.close() ``` This solution opens the file in r/w mode ("r+") and makes use of seek to reset the f-pointer then truncate t...
Can Python's unittest test in parallel, like nose can?
4,710,142
26
2011-01-17T04:57:39Z
4,721,103
14
2011-01-18T06:26:50Z
[ "python", "unit-testing" ]
Python's NOSE testing framework has the concept of [running multiple tests in parallel](http://packages.python.org/nose/plugins/multiprocess.html). The purpose of this is not to test concurrency in the code, but to make tests for code that has "no side-effects, no ordering issues, and no external dependencies" run fas...
Python unittest's builtin testrunner does not run tests in parallel. It probably wouldn't be too hard write one that did. I've written my own just to reformat the output and time each test. That took maybe 1/2 a day. I think you can swap out the TestSuite class that is used with a derived one that uses multiprocess wit...
Can Python's unittest test in parallel, like nose can?
4,710,142
26
2011-01-17T04:57:39Z
17,059,844
14
2013-06-12T07:23:39Z
[ "python", "unit-testing" ]
Python's NOSE testing framework has the concept of [running multiple tests in parallel](http://packages.python.org/nose/plugins/multiprocess.html). The purpose of this is not to test concurrency in the code, but to make tests for code that has "no side-effects, no ordering issues, and no external dependencies" run fas...
The [testtools](http://pypi.python.org/pypi/testtools) package is an extension of unittest which supports running tests concurrently. It can be used with your old test classes that inherit `unittest.TestCase`. For example: ``` import unittest import testtools class MyTester(unittest.TestCase): # Tests... suite ...
Python 3, Are there any known security holes in ast.literal_eval(node_or_string)?
4,710,247
16
2011-01-17T05:24:24Z
7,689,085
36
2011-10-07T15:01:51Z
[ "python", "security", "abstract-syntax-tree" ]
Are there any known ways for [ast.literal\_eval(node\_or\_string)](http://docs.python.org/py3k/library/ast.html#ast-helpers)'s evaluation to not actually be safe? If yes, are patches available for them? (I already know about PyPy[sandbox], which is presumably more secure, but unless the answers are yes then no, my ne...
The [documentation](http://docs.python.org/py3k/library/ast.html#ast.literal_eval) states it is safe, and there is no bug relative to security of literal\_eval in the [bug tracker](http://bugs.python.org/issue?@columns=id,activity,title,creator,assignee,status,type&@sort=-activity&@filter=status&@action=searchid&ignore...
Python:When to use Threads vs. Multiprocessing
4,710,433
26
2011-01-17T06:07:34Z
4,710,649
13
2011-01-17T06:46:39Z
[ "python" ]
What are some good guidelines to follow when deciding to use threads or multiprocessing when speaking in terms of efficiency and code clarity?
Many of the differences between threading and multiprocessing are not really Python-specific, and some differences are specific to a certain Python implementation. For CPython, I would use the `multiprocessing` module in either fo the following cases: * I need to make use of multiple cores simultaneously for performa...
Scrapy and proxies
4,710,483
19
2011-01-17T06:17:01Z
4,710,544
27
2011-01-17T06:29:08Z
[ "python", "scrapy" ]
How do you utilize proxy support with the python web-scraping framework Scrapy?
From the [Scrapy FAQ](http://scrapy.readthedocs.org/en/latest/faq.html#does-scrapy-work-with-http-proxies), > ### Does Scrapy work with HTTP proxies? > > Yes. Support for HTTP proxies is provided (since Scrapy 0.8) through the HTTP Proxy downloader middleware. See [`HttpProxyMiddleware`](http://scrapy.readthedocs.org/...
Scrapy and proxies
4,710,483
19
2011-01-17T06:17:01Z
14,401,562
8
2013-01-18T14:58:29Z
[ "python", "scrapy" ]
How do you utilize proxy support with the python web-scraping framework Scrapy?
that would be: > export http\_proxy=http://user:password@proxy:port
Scrapy and proxies
4,710,483
19
2011-01-17T06:17:01Z
20,608,483
15
2013-12-16T10:25:22Z
[ "python", "scrapy" ]
How do you utilize proxy support with the python web-scraping framework Scrapy?
**Single Proxy** 1. Enable `HttpProxyMiddleware` in your `settings.py`, like this: ``` DOWNLOADER_MIDDLEWARES = { 'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 1, } ``` 2. pass proxy to request via `request.meta`: ``` request = Request(url="http://example.com") request....
Scrapy and proxies
4,710,483
19
2011-01-17T06:17:01Z
29,716,179
8
2015-04-18T10:46:02Z
[ "python", "scrapy" ]
How do you utilize proxy support with the python web-scraping framework Scrapy?
1-Create a new file called “middlewares.py” and save it in your scrapy project and add the following code to it. ``` import base64 class ProxyMiddleware(object): # overwrite process request def process_request(self, request, spider): # Set the location of the proxy request.meta['proxy'] = "http://YOUR_PROX...
Any tips on writing testing-friendly code?
4,710,621
5
2011-01-17T06:43:24Z
4,710,719
10
2011-01-17T06:55:57Z
[ "python", "unit-testing" ]
Are there any guidelines for writing test-friendly Python code? What I believe: * One method does one thing. * Don't use side-effects. Any other suggestions?
## TDD The best tip I can give you to write test friendly code is to write the tests first. Then write the production code (TDD). Uncle Bob devised three simple rules to write [TDD](http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd): > 1. You are not allowed to write any production code unless it is to make...
Is boolean logic possible in django templates?
4,711,627
8
2011-01-17T09:26:37Z
4,711,664
20
2011-01-17T09:31:44Z
[ "python", "django", "templates", "boolean" ]
I want to do something like: ``` {% if ("view_video" in video_perms) OR purchase_override %} ``` Is that possible?
[Django docs on boolean operators](https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#boolean-operators) Gives you: ``` {% if user in users %} If users is a QuerySet, this will appear if user is an instance that belongs to the QuerySet. {% endif %} ``` and ``` {% if a == b or c == d and e %} ``` Be...
How to use SQLite 3's vacuum command in Python
4,712,929
11
2011-01-17T12:03:20Z
4,713,249
21
2011-01-17T12:39:45Z
[ "python", "sqlite3" ]
I cannot find any example on the net of how the SQLite 3 vacuum command is done on a database.
Just open a connection and execute the VACUUM command; ``` conn=sqlite3.connect(SQLITE_FILE) conn.execute("VACUUM") conn.close() ```
Decorate \ delegate a File object to add functionality
4,713,932
12
2011-01-17T13:55:12Z
4,838,875
11
2011-01-29T19:11:20Z
[ "python", "design-patterns", "logging", "subprocess" ]
I've been writing a small Python script that executes some shell commands using the `subprocess` module and a helper function: ``` import subprocess as sp def run(command, description): """Runs a command in a formatted manner. Returns its return code.""" start=datetime.datetime.now() sys.stderr.write('%-65...
1 and 2 are reasonable solutions, but overriding write() won't be enough. The problem is that Popen needs file handles to attach to the process, so Python file objects doesn't work, they have to be OS level. To solve that you have to have a Python object that has a os level file handle. The only way I can think of sol...
Python - how to implement virtual methods?
4,714,136
31
2011-01-17T14:14:53Z
4,714,147
29
2011-01-17T14:16:21Z
[ "python", "virtual-method" ]
I know virtual methods from php or java. How can be implemeted this method in python? Or I have to define empty method in abstract class and rewrite it?
Python methods are always virtual.
Python - how to implement virtual methods?
4,714,136
31
2011-01-17T14:14:53Z
4,714,172
52
2011-01-17T14:19:31Z
[ "python", "virtual-method" ]
I know virtual methods from php or java. How can be implemeted this method in python? Or I have to define empty method in abstract class and rewrite it?
Sure, and you don't even have to define a method in the base class. In Python methods are better than virtual - they're completely dynamic, as the typing in Python is *duck typing*. ``` class Dog: def say(self): print "hau" class Cat: def say(self): print "meow" pet = Dog() pet.say() # prints "hau" anoth...
Python - how to implement virtual methods?
4,714,136
31
2011-01-17T14:14:53Z
19,316,077
13
2013-10-11T10:36:48Z
[ "python", "virtual-method" ]
I know virtual methods from php or java. How can be implemeted this method in python? Or I have to define empty method in abstract class and rewrite it?
Actually, in version 2.6 python provides sth called abstract base classes and you can explicitly set virtual methods like this: ``` from abc import ABCMeta from abc import abstractmethod ... class C: __metaclass__ = ABCMeta @abstractmethod def my_abstract_method(self, ...): ``` It works very well, provide...
Why 'NoneType' is returned in Python?
4,714,764
2
2011-01-17T15:21:07Z
4,714,778
14
2011-01-17T15:22:26Z
[ "python" ]
I have a code that basically solves one of the problem in Project Euler and aims to find out LCM of first 20 natural numbers. ``` def GCD(a, b): #Euclid's algorithim if (b == 0): return a else: GCD(b, a % b) def LCM(a, b): #LCM(a,b) = a*b/GCD(a,b) x = GCD(a, b) ...
Try ``` def GCD(a, b): #Euclid's algorithim if (b == 0): return a else: return GCD(b, a % b) ``` You have to return the value returned by the recursive call. `RFIND` has a similar problem.
What version of python can I use with Twisted/Zope?
4,715,357
3
2011-01-17T16:21:17Z
4,715,383
7
2011-01-17T16:24:41Z
[ "python", "twisted", "zope" ]
I noticed that Twisted has a dependency on Zope. I found that when I tried to install Zope, after running, ./configure it tells me I need to use python2.4 (not python 2.5+ which I would like to be using). However, I have seen some tutorials and guides that suggested using python 2.5 for Twisted. So I'm just generally ...
Twisted doesn't have a dependency on full `zope`. It's just [`zope.interface`](http://pypi.python.org/pypi/zope.interface), which is a small pure-python module packaged separately from all zope. You can download the `.tar.gz` version and run the usual `python setup.py install`, that should work. Or if your operational...
Django-South introspection rule doesn't work
4,715,964
13
2011-01-17T17:24:27Z
4,716,156
17
2011-01-17T17:49:55Z
[ "python", "django", "migration", "django-south" ]
I'm using `Django 1.2.3` and `South 0.7.3`. I am trying to convert my app (named `core`) to use *Django-South*. I have a custom model/field that I'm using, named `ImageWithThumbsField`. It's basically just the ol' `django.db.models.ImageField` with some attributes such as height, weight, etc. While trying to `./manag...
I got it! :) I changed this: `["^core/.fields/.ImageWithThumbsField",]` To this: `["^lib\.thumbs\.ImageWithThumbsField",]` This whole line is a *regular-expression* of python paths of **Django field types** (read this again, long sentence). *South* stumbled upon a field name `ImageWithThumbsField` that was declared...
Django - how can I find the distance between two locations?
4,716,017
8
2011-01-17T17:31:12Z
4,718,833
17
2011-01-17T23:02:55Z
[ "python", "django", "google-maps", "geodjango" ]
I have some users registered in my Django app and I want to simply be able to figure out the distance, geographically, between two users based on their zip code and then sort a list based on that. I would imagine this functionality isn't built into Django. I was looking at some options and stumbled across geodjango whi...
This is a big fat comment on the code posted in the (currently-accepted) answer by @Sven Marnach. Original code from zip project website, with indentation edited by me: ``` from math import * def calcDist(lat_A, long_A, lat_B, long_B): distance = (sin(radians(lat_A)) * sin(radians(lat_B)) + cos(ra...
Accessing the user's request in a post_save signal
4,716,330
13
2011-01-17T18:10:37Z
4,716,440
9
2011-01-17T18:22:07Z
[ "python", "django", "signals" ]
I have done the below post\_save signal in my project. ``` from django.db.models.signals import post_save from django.contrib.auth.models import User # CORE - SIGNALS # Core Signals will operate based on post def after_save_handler_attr_audit_obj(sender, **kwargs): print User.get_profile() if hasattr(kwargs...
Can't be done. The current user is only available via the request, which is not available when using purely model functionality. Access the user in the view somehow.
Accessing the user's request in a post_save signal
4,716,330
13
2011-01-17T18:10:37Z
9,104,767
7
2012-02-01T23:08:47Z
[ "python", "django", "signals" ]
I have done the below post\_save signal in my project. ``` from django.db.models.signals import post_save from django.contrib.auth.models import User # CORE - SIGNALS # Core Signals will operate based on post def after_save_handler_attr_audit_obj(sender, **kwargs): print User.get_profile() if hasattr(kwargs...
Look at [django-contrib-requestprovider](http://pypi.python.org/pypi/django-contrib-requestprovider), probably you can use it.
How to attach debugger to a python subproccess?
4,716,533
18
2011-01-17T18:32:12Z
4,721,432
9
2011-01-18T07:20:24Z
[ "python", "debugging", "subprocess", "multiprocessing" ]
I need to debug a child process spawned by `multiprocessing.Process()`. The `pdb` degugger seems to be unaware of forking and unable to attach to already running processes. Are there any smarter python debuggers which can be attached to a subprocess?
[Winpdb](http://winpdb.org/about/) is pretty much the definition of a smarter Python debugger. It explicitly supports [going down a fork](http://winpdb.org/docs/handling-a-fork/), not sure it works nicely with multiprocessing.Process() but it's worth a try. For a list of candidates to check for support of your use cas...
How to attach debugger to a python subproccess?
4,716,533
18
2011-01-17T18:32:12Z
23,654,936
27
2014-05-14T12:34:48Z
[ "python", "debugging", "subprocess", "multiprocessing" ]
I need to debug a child process spawned by `multiprocessing.Process()`. The `pdb` degugger seems to be unaware of forking and unable to attach to already running processes. Are there any smarter python debuggers which can be attached to a subprocess?
I've been searching for a simple to solution for this problem and came up with this: ``` import sys import pdb class ForkedPdb(pdb.Pdb): """A Pdb subclass that may be used from a forked multiprocessing child """ def interaction(self, *args, **kwargs): _stdin = sys.stdin try: ...
Indexing one-dimensional numpy.array as matrix
4,716,647
7
2011-01-17T18:45:15Z
4,716,704
9
2011-01-17T18:51:59Z
[ "python", "numpy" ]
I am trying to index a *numpy.array* with varying dimensions during runtime. To retrieve e.g. the first row of a n\*m array `a`, you can simply do ``` a[0,:] ``` However, in case a happens to be a *1xn* vector, this code above returns an index error: > IndexError: too many indices As the code needs to be executed a...
Just use `a[0]` instead of `a[0,:]`. It will return the first line for a matrix and the first entry for a vector. Is this what you are looking for? If you want to get the whole vector in the one-dimensional case instead, you can use `numpy.atleast_2d(a)[0]`. It won't copy your vector -- it will just access it as a two...
Can you register multiple ModelAdmins for a Model? Alternatives?
4,716,880
8
2011-01-17T19:12:51Z
4,717,354
10
2011-01-17T20:07:11Z
[ "python", "django", "django-models", "django-admin" ]
Say I have the Django model class: ``` class Foo(models.Model): bar = models.CharField() baz = models.CharField() ``` and the ModelAdmins: ``` class Foo_Admin_1(admin.ModelAdmin): list_display = ['id','bar'] class Foo_Admin_2(admin.ModelAdmin): list_display = ['id','baz'] ``` is there any way to register both ...
Create an empty proxy subclass and register it instead: ``` class Foo(models.Model): bar = models.CharField() baz = models.CharField() # admin.py class FooProxy(Foo): class Meta: proxy=True admin.site.register(Foo, FooAdmin1) admin.site.register(FooProxy, FooAdmin2) ```
Is python exception handling more efficient than PHP and/or other languages?
4,717,484
20
2011-01-17T20:22:53Z
4,717,604
7
2011-01-17T20:34:14Z
[ "php", "python", "exception", "programming-languages" ]
I have it drilled into my head that (at least in PHP) it is badbadmojo to use `try... catch` blocks for flow control. What I've learned is to use them only to handle *unexpected errors*, not determine the logic flow of the program, because `catch` blocks are expensive. Now that I'm learning python, I see a lot of exce...
I don't believe that the EAFP encourages the use of exceptions for flow control. Rather, it tells us that we needn't bother checking for the existence of a particular key in a dictionary or property of an object before we reference it. Throwing exceptions as an alternative to `if` statements or having correct `while` ...
Is python exception handling more efficient than PHP and/or other languages?
4,717,484
20
2011-01-17T20:22:53Z
4,718,382
11
2011-01-17T22:00:54Z
[ "php", "python", "exception", "programming-languages" ]
I have it drilled into my head that (at least in PHP) it is badbadmojo to use `try... catch` blocks for flow control. What I've learned is to use them only to handle *unexpected errors*, not determine the logic flow of the program, because `catch` blocks are expensive. Now that I'm learning python, I see a lot of exce...
Historically, in languages like C++, exceptions have been very slow compared to other forms of flow control *in the same language*. In C++, there are two things at work: * Throwing an exception is very complex. The stack needs to be unwound, and doing so in native code is *much* harder than in a high-level VM-based l...
How can I run my python script from the terminal in Mac OS X without having to type the full path?
4,718,071
6
2011-01-17T21:25:23Z
4,718,135
12
2011-01-17T21:32:07Z
[ "python", "osx", "path", "terminal" ]
I'm on Mac OS 10.6 Snow Leopard and I'm trying to add a directory to my PATH variable so I can run a tiny script I wrote by just typing: python alarm.py at the terminal prompt. I put the path in my .profile file and it seems to show up when I echo $PATH, but python still can't find script the that I've put in that dir...
PATH is only for executables, not for python scripts. Add the following to the beginning of your Python script: ``` #!/usr/bin/env python ``` and run ``` sudo chmod a+x /Users/tobylieven/Documents/my_scripts/alarm.py ``` Then, you can type just `alarm.py` to execute your program.
How to enable Python support in gVim on Windows?
4,718,122
36
2011-01-17T21:31:05Z
4,718,183
33
2011-01-17T21:37:50Z
[ "python", "vim" ]
I'm trying to get Python support in gVim on Windows. Is there a way to accomplish that? I'm using: * Windows XP SP3 * gVim v. 7.3 * Python 2.7.13 (ActivePython through Windows Installer binaries)
Usually, python support is built in the official gvim distribution. You will need to install python though: [Python 2.7.9 Windows installer for X86](http://python.org/ftp/python/2.7.9/python-2.7.9.msi) to check if vim supports python: ``` :echo has("python") ```
How to enable Python support in gVim on Windows?
4,718,122
36
2011-01-17T21:31:05Z
9,953,565
9
2012-03-31T06:21:43Z
[ "python", "vim" ]
I'm trying to get Python support in gVim on Windows. Is there a way to accomplish that? I'm using: * Windows XP SP3 * gVim v. 7.3 * Python 2.7.13 (ActivePython through Windows Installer binaries)
If you have installed Python via one of the Windows installers it is probably compiled with Python 2.7 support. You can verify this by running: ``` :version ``` It will spit out all the options Vim was compiled with. Yours should say something like ``` +python/dyn +python3\dyn ``` This means you have support for py...
How to enable Python support in gVim on Windows?
4,718,122
36
2011-01-17T21:31:05Z
12,643,966
23
2012-09-28T16:35:10Z
[ "python", "vim" ]
I'm trying to get Python support in gVim on Windows. Is there a way to accomplish that? I'm using: * Windows XP SP3 * gVim v. 7.3 * Python 2.7.13 (ActivePython through Windows Installer binaries)
I encountered this problem on Windows 7 64-bit. I realized I was using 64-bit Python 2.7.3 and 32-bit vim 7.3-46. I reinstalled both as 32-bit versions and then restarted the computer. Now it works.
How to enable Python support in gVim on Windows?
4,718,122
36
2011-01-17T21:31:05Z
17,963,884
17
2013-07-31T07:12:40Z
[ "python", "vim" ]
I'm trying to get Python support in gVim on Windows. Is there a way to accomplish that? I'm using: * Windows XP SP3 * gVim v. 7.3 * Python 2.7.13 (ActivePython through Windows Installer binaries)
I had the same issue, but on Windows 7, and a restart didn't fix it. I already had gVim 7.3 installed. At the time of writing the current Python version was 3.3, so I installed that. But :has ("python") and :has ("python3") still returned 0. After much trial and error, I determined that: * If gVim is 32-bit, and it ...
Converting Django project from MySQL to Mongo, any major pitfalls?
4,718,580
2
2011-01-17T22:22:32Z
4,718,924
9
2011-01-17T23:16:06Z
[ "python", "django", "mongodb", "mongoengine" ]
I want to try Mongodb w/ mongoengine. I'm new to Django and databases and I'm having a fit with Foreign Keys, Joins, Circular Imports (you name it). I know I could eventually work through these issues but Mongo just seems like a simpler solution for what I am doing. My question is I'm using a lot of pluggable apps (Ima...
There's no reason why you can't use one of the standard RDBMSs for all the standard Django apps, and then Mongo for your app. You'll just have to replace all the standard ways of processing things from the Django ORM with doing it the Mongo way. So you can keep urls.py and its neat pattern matching, views will still g...
How to add commas / delimiters for all list items except last?
4,719,103
3
2011-01-17T23:38:47Z
4,719,166
7
2011-01-17T23:47:10Z
[ "python", "html", "css", "django" ]
Say I have a for loop, which lists a bunch of Users. There might be 0-n Users in the loop. I want to put commas after each User name except the last one. So for: ``` <p> {% for u in users %} {{u.name}}, {% endfor } </p> ``` I get: ``` Sam, Neil, Bob, ``` I want: ``` Sam, Neil, Bob ```
I agree join is a good approach. If you want to do it with for, try ``` {% for u in users %} {{u.name}}{% if not forloop.last %},{% endif %} {% endfor } ```
Python and sqlite3 - importing and exporting databases
4,719,159
9
2011-01-17T23:45:44Z
4,719,184
13
2011-01-17T23:50:19Z
[ "python", "sql", "django", "sqlite", "sqlite3" ]
I'm trying to write a script to import a database file. I wrote the script to export the file like so: import sqlite3 ``` con = sqlite3.connect('../sqlite.db') with open('../dump.sql', 'w') as f: for line in con.iterdump(): f.write('%s\n' % line) ``` Now I want to be able to import that database. I tried:...
``` sql = f.read() # watch out for built-in `str` cur.executescript(sql) ``` [Documentation](http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executescript).
string manipulation in python
4,719,244
3
2011-01-18T00:02:02Z
4,719,261
7
2011-01-18T00:04:47Z
[ "python" ]
I have a python file like this ``` import urllib2 try: data = urllib2.urlopen('http:....').read() except urllib2.HTTPError, e: print "HTTP error: %d" % e.code except urllib2.URLError, e: print "Network error: %s" % e.reason.args[1] print data1 ``` the output looks like this ``` >>> 15.95 >>> ``` I ne...
Perhaps you just need to strip whitespace from your variable? Use `data1.strip()`. Read up on [str.strip()](http://docs.python.org/library/stdtypes.html#str.strip) for more information. By the way, to see the whitespace explicitly, use `print repr(data1)`.
Implementing offsetof() for structures in Python ctypes
4,719,357
3
2011-01-18T00:22:43Z
4,719,452
13
2011-01-18T00:43:16Z
[ "python", "c", "padding", "ctypes", "ffi" ]
I cannot seem to implement offsetof for a structure in ctypes. I have seen the [FAQ for ctypes](http://wiki.python.org/moin/ctypes), but either it doesn't work, or I cannot figure out the details. ``` Python 2.6.4 (r264:75706, Dec 19 2010, 13:04:47) [C] on sunos5 Type "help", "copyright", "credits" or "license" for mo...
``` class Dog(Structure): _fields_ = [('name', c_char_p), ('weight', c_int)] Dog.name.offset # 0 Dog.weight.offset # 4 (on my 32-bit system) ``` The task of turning this into a method is left to the reader :)
Editing specific line in text file in python
4,719,438
23
2011-01-18T00:41:03Z
4,719,562
41
2011-01-18T01:02:53Z
[ "python", "io" ]
Let's say I have a text file containing: ``` Dan Warrior 500 1 0 ``` Is there a way I can edit a specific line in that text file? Right now I have this: ``` #!/usr/bin/env python import io myfile = open('stats.txt', 'r') dan = myfile.readline() print dan print "Your name: " + dan.split('\n')[0] try: myfile = o...
You want to do something like this: ``` # with is like your try .. finally block in this case with open('stats.txt', 'r') as file: # read a list of lines into data data = file.readlines() print data print "Your name: " + data[0] # now change the 2nd line, note that you have to add a newline data[1] = 'Mage\n...
Editing specific line in text file in python
4,719,438
23
2011-01-18T00:41:03Z
4,719,576
7
2011-01-18T01:06:06Z
[ "python", "io" ]
Let's say I have a text file containing: ``` Dan Warrior 500 1 0 ``` Is there a way I can edit a specific line in that text file? Right now I have this: ``` #!/usr/bin/env python import io myfile = open('stats.txt', 'r') dan = myfile.readline() print dan print "Your name: " + dan.split('\n')[0] try: myfile = o...
``` def replace_line(file_name, line_num, text): lines = open(file_name, 'r').readlines() lines[line_num] = text out = open(file_name, 'w') out.writelines(lines) out.close() ``` And then: ``` replace_line('stats.txt', 0, 'Mage') ```
Editing specific line in text file in python
4,719,438
23
2011-01-18T00:41:03Z
4,719,629
7
2011-01-18T01:17:58Z
[ "python", "io" ]
Let's say I have a text file containing: ``` Dan Warrior 500 1 0 ``` Is there a way I can edit a specific line in that text file? Right now I have this: ``` #!/usr/bin/env python import io myfile = open('stats.txt', 'r') dan = myfile.readline() print dan print "Your name: " + dan.split('\n')[0] try: myfile = o...
you can use fileinput to do in place editing ``` import fileinput for line in fileinput.FileInput("myfile", inplace=1): if line .....: print line ```
List of References in Google App Engine for Python
4,719,700
18
2011-01-18T01:29:49Z
4,730,415
13
2011-01-18T23:57:42Z
[ "python", "google-app-engine" ]
In Google App Engine, there is such a thing as a ListProperty that allows you to hold a list (array) of items. You may also specify the type of the item being held, for instance string, integer, or whatever. Google App Engine also allows you to have a ReferenceProperty. A ReferenceProperty "contains" a reference to an...
Step one: Use db.ListProperty(db.Key) to create the relationship. You want the ListProp to be on the Entity that will have the fewer references in the Many to Many relationship. This will also give you a back reference. So: ``` class Spam prop1 = db.String eggs = db.List class Eggs prop1 = db.string @propert...
Python and sqlite3 - adding thousands of rows
4,719,836
6
2011-01-18T02:01:26Z
4,719,931
11
2011-01-18T02:24:11Z
[ "python", "sql", "django", "sqlite", "sqlite3" ]
I have a .sql file containing thousands of individual insert statements. It takes forever to do them all. I am trying to figure out a way to do this more efficiently. In python the sqlite3 library can't do things like ".read" or ".import" but executescript is too slow for that many inserts. I installed the sqlite3.exe...
Are you using transactions ? SQLite will create a transaction for every [insert statement individually by default](http://docs.python.org/library/sqlite3.html), which slows things way down. > By default, the sqlite3 module opens > transactions implicitly before a Data > Modification Language (DML) statement > (i.e. IN...
SOAP suds and the dreaded schema Type Not Found error
4,719,854
15
2011-01-18T02:06:39Z
5,969,234
11
2011-05-11T18:59:41Z
[ "python", "soap", "suds" ]
I'm using the latest version of suds (<https://fedorahosted.org/suds/>) for the first time and I'm getting stalled at step one. ``` suds.TypeNotFound: Type not found: '(schema, http://www.w3.org/2001/XMLSchema, )' ``` Now, I know this is well covered ground in the suds world (<https://fedorahosted.org/suds/wiki/TipsA...
We got it working and I hope you did as well, even though it is a bit quirky. Perhaps an explicit location or filter will help. E.g.: ``` imp = Import('http://schemas.xmlsoap.org/soap/encoding/', location='http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add('http://ws.client.com/Members.asmx') client = Client(u...
SOAP suds and the dreaded schema Type Not Found error
4,719,854
15
2011-01-18T02:06:39Z
16,683,005
15
2013-05-22T03:27:42Z
[ "python", "soap", "suds" ]
I'm using the latest version of suds (<https://fedorahosted.org/suds/>) for the first time and I'm getting stalled at step one. ``` suds.TypeNotFound: Type not found: '(schema, http://www.w3.org/2001/XMLSchema, )' ``` Now, I know this is well covered ground in the suds world (<https://fedorahosted.org/suds/wiki/TipsA...
I was banging my head for a while on this one. I finally resolved the issue by using the following syntax: ``` from suds.xsd.doctor import ImportDoctor, Import url = 'http://somedomain.com/filename.php?wsdl' imp = Import('http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add('http://some/namespace/A') doctor = I...
python -> time a while loop has been running
4,720,073
6
2011-01-18T02:52:36Z
4,720,164
8
2011-01-18T03:13:55Z
[ "python", "loops", "time", "permutation", "while-loop" ]
i have a loop that runs for up to a few hours at a time. how could I have it tell me how long it has been at a set interval? just a generic...question EDIT: it's a while loop that runs permutations, so can i have it print the time running every 10 seconds?
Instead of checking the time on every loop, you can use a Timer object ``` import time from threading import Timer def timeout_handler(timeout=10): print time.time() timer = Timer(timeout, timeout_handler) timer.start() timeout_handler() while True: print "loop" time.sleep(1) ```
Using Python and Mechanize to submit form data and authenticate
4,720,470
13
2011-01-18T04:24:54Z
4,727,364
18
2011-01-18T17:59:35Z
[ "python", "networking", "screen-scraping", "mechanize" ]
I want to submit login to the website Reddit.com, navigate to a particular area of the page, and submit a comment. I don't see what's wrong with this code, but it is not working in that no change is reflected on the Reddit site. ``` import mechanize import cookielib def main(): #Browser br = mechanize.Browser() #...
I would definitely suggest trying to use the API if possible, but this works for me (not for your example post, which has been deleted, but for any active one): ``` #!/usr/bin/env python import mechanize import cookielib import urllib import logging import sys def main(): br = mechanize.Browser() cj = cooki...
Fastest way to download 3 million objects from a S3 bucket
4,720,735
20
2011-01-18T05:20:23Z
4,721,264
25
2011-01-18T06:51:08Z
[ "python", "linux", "amazon-s3", "boto", "eventlet" ]
I've tried using Python + boto + multiprocessing, S3cmd and J3tset but struggling with all of them. Any suggestions, perhaps a ready-made script you've been using or another way I don't know of? **EDIT:** eventlet+boto is a worthwhile solution as mentioned below. Found a good eventlet reference article here <http://...
Okay, I figured out a solution based on @Matt Billenstien's hint. It uses eventlet library. The first step is most important here (monkey patching of standard IO libraries). Run this script in the background with nohup and you're all set. ``` from eventlet import * patcher.monkey_patch(all=True) import os, sys, time...
Google app engine Channel API for COMET on non Javascript clients
4,721,205
6
2011-01-18T06:40:11Z
4,740,220
8
2011-01-19T20:14:25Z
[ "python", "google-app-engine", "channel-api" ]
How to use Google app engine [Channel API](http://code.google.com/intl/it-IT/appengine/docs/python/channel/overview.html) for COMET on non JavaScript clients. I shall be writing a client in python or any other language, and can do HTTP or Socks from client. How shall I proceed, I want to know what is happening in bac...
The asynchronous message passing is done by embedding a hidden iframe in the page, then using the goog.net.CrossPageChannel classes from the Google Closure javascript library to send messages from the iframe to the host page. The Closure CrosspageChannel code is documented here: <http://closure-library.googlecode.com/...
error: Setup script exited with error: command 'gcc' failed with exit status 1
4,721,385
19
2011-01-18T07:13:34Z
4,724,061
7
2011-01-18T12:29:49Z
[ "python", "mysql-python", "mysql" ]
I get the following error when I try to install MySQL-python-1.2.3 under Python 2.6 in Fedora 14. Fedora 14 comes with Python 2.7 by default and I am working in a project which runs in Python 2.6, So I am not in a position to update Python from 2.6 to 2.7. ``` _mysql.c:35:23: fatal error: my_config.h: No such file or...
Solved this issue in the following way 1. Copy `MySQLdb` folder from site-packages directory of Python2.7 to Python2.6. 2. Also copy the following files from site-packages directory of Python2.7 to Python2.6. `_mysql.so` `_mysql_exceptions.py` `_mysql_exceptions.pyc` `_mysql_exceptions.pyo` Now try th...
error: Setup script exited with error: command 'gcc' failed with exit status 1
4,721,385
19
2011-01-18T07:13:34Z
6,615,594
35
2011-07-07T18:50:21Z
[ "python", "mysql-python", "mysql" ]
I get the following error when I try to install MySQL-python-1.2.3 under Python 2.6 in Fedora 14. Fedora 14 comes with Python 2.7 by default and I am working in a project which runs in Python 2.6, So I am not in a position to update Python from 2.6 to 2.7. ``` _mysql.c:35:23: fatal error: my_config.h: No such file or...
you need to install MySQL Development package ``` yum install mysql-devel ``` :D
error: Setup script exited with error: command 'gcc' failed with exit status 1
4,721,385
19
2011-01-18T07:13:34Z
11,479,036
12
2012-07-13T22:11:26Z
[ "python", "mysql-python", "mysql" ]
I get the following error when I try to install MySQL-python-1.2.3 under Python 2.6 in Fedora 14. Fedora 14 comes with Python 2.7 by default and I am working in a project which runs in Python 2.6, So I am not in a position to update Python from 2.6 to 2.7. ``` _mysql.c:35:23: fatal error: my_config.h: No such file or...
Install python-devel. That should help
custom signals in django
4,722,255
2
2011-01-18T09:07:17Z
4,722,294
7
2011-01-18T09:10:31Z
[ "python", "django" ]
am having problem with django custom signals not being able to see signals across application. I made a simple call in my core/signals.py ``` from django.dispatch.dispatcher import Signal # Signal-emitting code... emits whenever a file upload is received # -------------------------------------------------------------...
You haven't imported the `upload_recieved` name into your admin.py.
Can I do custom complicated group by in a Django QuerySet?
4,722,605
3
2011-01-18T09:46:50Z
4,722,941
8
2011-01-18T10:24:15Z
[ "python", "django", "django-queryset" ]
I need to do a sum of a certain column grouped by date and month. In SQL (postgres), it would look something like this: ``` select sum(amount) from somewhere group by extract(year from date), extract(month from date) ``` Can this be expressed as a Django `QuerySet`? Seems to me like it can't, but I don't really want ...
You can use the `extra` method to add in the year and date values before doing the aggregation. ``` Somewhere.objects.extra(select={'year': 'EXTRACT(year FROM date)', 'month': 'EXTRACT(month FROM date)'} ).values_list('year', 'month').annotate(Sum('amount')) ```
Logging between classes in python
4,722,745
10
2011-01-18T10:02:56Z
4,723,380
23
2011-01-18T11:12:29Z
[ "python", "logging" ]
I have three classes in python and they run in different threads. I would like to have output to the same file from all classes. Right now I created output method in main class and passing it through constructors to other classes. Is there way to handle it better? How I can pass the logger between classes except using ...
``` import logging log = logging.getLogger("mylog") log.setLevel(logging.DEBUG) formatter = logging.Formatter( "%(asctime)s %(threadName)-11s %(levelname)-10s %(message)s") # Alternative formatting available on python 3.2+: # formatter = logging.Formatter( # "{asctime} {threadName:>11} {levelname} {message}", ...
Parsing an XML file using Element Tree
4,722,794
4
2011-01-18T10:06:58Z
4,726,192
8
2011-01-18T16:04:32Z
[ "python", "xml", "parsing", "elementtree" ]
I have a large number of .xml files (about 70) and i need to extract some co-ordinates from them. Apparently the best way to do this is to parse the xml file using element tree. I am new to python (very very new!) and am having a difficult time understanding all of the documentation which comes with element tree! I was...
ElementTree can be tricky when namespaces are involved. The element you are looking for are named `<gml:lowerCorner>` and `<gml:upperCorner>`. Searching higher in the XML data, `gml` is defined as an XML namespace: `xmlns:gml="http://www.opengis.net/gml"`. The way to find a subelement of the XML tree is as follows: ``...
Python: Regular expression to match alpha-numeric not working?
4,722,998
10
2011-01-18T10:31:13Z
4,723,028
17
2011-01-18T10:34:25Z
[ "python", "regex" ]
I am looking to match a string that is inputted from a website to check if is alpha-numeric and possibly contains an underscore. My code: ``` if re.match('[a-zA-Z0-9_]',playerName): # do stuff ``` For some reason, this matches with crazy chars for example: nIg○▲ ☆ ★ ◇ ◆ I only want regular A-...
Your regex only matches one character. Try this instead: ``` if re.match('^[a-zA-Z0-9_]+$',playerName): ```
Python: Regular expression to match alpha-numeric not working?
4,722,998
10
2011-01-18T10:31:13Z
4,723,154
21
2011-01-18T10:46:21Z
[ "python", "regex" ]
I am looking to match a string that is inputted from a website to check if is alpha-numeric and possibly contains an underscore. My code: ``` if re.match('[a-zA-Z0-9_]',playerName): # do stuff ``` For some reason, this matches with crazy chars for example: nIg○▲ ☆ ★ ◇ ◆ I only want regular A-...
Python has a special sequence `\w` for matching alphanumeric and underscore when the `LOCALE` and `UNICODE` flags are not specified. So you can modify your pattern as, `pattern = '^\w+$'`
split text into lines by the number of characters
4,725,249
5
2011-01-18T14:33:44Z
4,725,276
16
2011-01-18T14:36:05Z
[ "python", "string" ]
I have some text for example: ``` 'This is a line of text over 10 characters' ``` That I need to be broken into lines consisting of no more than 10 characters without breaking words unless I need to (for example a line with work containing more than 10 characters). The line above would turn into: ``` 'This is a\nli...
You need [`textwrap`](http://docs.python.org/library/textwrap.html) ``` >>> import textwrap >>> s = 'This is a line of text over 10 characters' >>> textwrap.fill(s, width=10) 'This is a\nline of\ntext over\n10\ncharacters' ```
Wrap text in a table reportlab?
4,726,011
11
2011-01-18T15:46:24Z
10,244,769
14
2012-04-20T10:48:51Z
[ "python", "reportlab" ]
I use a table but, I draw in in a canvas to control the position of the flowables, this because I have a template in a pdf, an I merge with pyPDF. The wrap is done in a table but the text go up, not down that's what I hope. c is the canvas **Code** ``` from reportlab.pdfgen import canvas from reportlab.lib.pagesize...
The description text went up as you wrap it in a styles["Normal"] You can try to wrap your text in a styles["BodyText"] This will allow your text to align themselves according to the width of the cell you specify. You could also include formatting which is similar to HTML text formatting. Then use TableStyle to format...
Parsing command line input for numbers
4,726,168
8
2011-01-18T16:01:52Z
4,726,287
12
2011-01-18T16:13:25Z
[ "python", "parsing", "command-line" ]
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example: ``` $ myapp -n 3,4,5,6 ``` or ``` $ myapp -n 3-6 ``` I would like my app to put these into a Python list e.g., [3, 4, 5, 6] I'm using `optparse`, but am not sure how to cr...
``` import argparse def parse_range(astr): result = set() for part in astr.split(','): x = part.split('-') result.update(range(int(x[0]), int(x[-1]) + 1)) return sorted(result) parser = argparse.ArgumentParser() parser.add_argument('-n', type=parse_range) args = parser.parse_args() print(a...
I/O intensive serial port application: Porting from Threading, Queue based design to Asynchronous (ala Twisted)
4,726,391
4
2011-01-18T16:24:38Z
4,726,591
7
2011-01-18T16:42:27Z
[ "python", "multithreading", "serial-port", "twisted" ]
So, I've been working on an application for a client that communicates with wireless devices via a Serial (RS-232) "Master". I've currently written the core of the app using threading (below). I've been noticing on #python that the consensus seems to be to *NOT* use threads and to use Twisted's asynchronous communicati...
It is very difficult (if not impossible) to write a direct one-to-one mapping program between threading/queue approach and one that uses twisted. I would suggest that, get a hang of twisted and its reactor way it's use of Protocol and the protocol specific methods. Think about it as as all the asynchronous things that...
Creating objects during runtime in Python
4,726,501
3
2011-01-18T16:35:10Z
4,726,554
7
2011-01-18T16:39:51Z
[ "python", "oop", "concept" ]
I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person() What I have trouble understanding now is how I would design a model that creat...
Things like lists or dictionaries are great for storing dynamically generated sets of values/objects: ``` class Person(object): def __init__(self, name): self.name = name def __repr__(self): print "A person named %s" % self.name people = {} while True: print "Enter a name:", a_name = r...
Python elegant assignment based on True/False values
4,726,949
28
2011-01-18T17:16:58Z
4,727,000
29
2011-01-18T17:20:57Z
[ "python", "if-statement", "boolean" ]
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs: ``` if a and b and c: name = 'first' elif a and b and not c: name = 'second' elif a and not b and c: name = 'third' elif a and not b and not c: name...
How about using a dict? ``` name = {(True, True, True): "first", (True, True, False): "second", (True, False, True): "third", (True, False, False): "fourth", (False, True, True): "fifth", (False, True, False): "sixth", (False, False, True): "seventh", (False, False, False): "eighth"} print nam...
Python elegant assignment based on True/False values
4,726,949
28
2011-01-18T17:16:58Z
4,727,012
50
2011-01-18T17:22:12Z
[ "python", "if-statement", "boolean" ]
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs: ``` if a and b and c: name = 'first' elif a and b and not c: name = 'second' elif a and not b and c: name = 'third' elif a and not b and not c: name...
You can think of a, b, and c as three bits that when put together form a number between 0 and 7. Then, you can have an array of the values ['first', 'second', ... 'eighth'] and use the bit value as an offset into the array. This would just be two lines of code (one to assemble the bits into a value from 0-7, and one to...
Python elegant assignment based on True/False values
4,726,949
28
2011-01-18T17:16:58Z
4,727,017
11
2011-01-18T17:22:27Z
[ "python", "if-statement", "boolean" ]
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs: ``` if a and b and c: name = 'first' elif a and b and not c: name = 'second' elif a and not b and c: name = 'third' elif a and not b and not c: name...
Maybe not much better, but how about ``` results = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth'] name = results[((not a) << 2) + ((not b) << 1) + (not c)] ```
Django: Filter for get_foo_display in a Queryset
4,727,327
8
2011-01-18T17:55:41Z
4,727,398
16
2011-01-18T18:03:10Z
[ "python", "django", "filter", "django-queryset", "choicefield" ]
I've been trying to filter a queryset on a simple model but with no luck so far. Here is my model: ``` class Country(models.Model): COUNTRY_CHOICES = ( ('FR', _(u'France')), ('VE', _(u'Venezuela')), ) code = models.CharField(max_length=2, choices=COUNTRY_CHOICES) def __unicode__(self...
You can't do this. `filter` works at the database level, and the database doesn't know anything about your long names. If you want to do filtering on a value, you need to store that value in the database. An alternative is to translate the value back into the code, and filter on that: ``` country_reverse = dict((v, k...
What is the difference between an expression and a statement in Python?
4,728,073
165
2011-01-18T19:19:58Z
4,728,147
120
2011-01-18T19:27:48Z
[ "python", "expression" ]
In Python, what is the difference between expressions and statements?
[Expressions](http://docs.python.org/reference/expressions.html) only contain [identifiers](http://docs.python.org/release/2.5.2/ref/identifiers.html), [literals](http://docs.python.org/release/2.5.2/ref/literals.html) and [operators](http://docs.python.org/release/2.5.2/ref/operators.html), where operators include ari...
What is the difference between an expression and a statement in Python?
4,728,073
165
2011-01-18T19:19:58Z
4,728,162
26
2011-01-18T19:29:26Z
[ "python", "expression" ]
In Python, what is the difference between expressions and statements?
Though this isn't related to Python: An `expression` evaluates to a value. A `statement` does something. ``` >>> x = 1 >>> y = x + 1 # an expression >>> print y # a statement (in 2.x) 2 ```
What is the difference between an expression and a statement in Python?
4,728,073
165
2011-01-18T19:19:58Z
4,730,559
64
2011-01-19T00:25:13Z
[ "python", "expression" ]
In Python, what is the difference between expressions and statements?
**Expression** -- from my dictionary: > expression: *Mathematics* a collection > of symbols that jointly express a > quantity : the expression for the > circumference of a circle is 2πr. In gross general terms: **Expressions produce at least one value.** In Python, expressions are covered extensively in the [Python...
Modulo and order of operation in Python
4,729,025
3
2011-01-18T21:08:07Z
4,729,083
19
2011-01-18T21:12:40Z
[ "python", "modulo", "order-of-operations" ]
In Zed Shaw's [Learn Python the Hard Way](http://learnpythonthehardway.org) (page 15-16), he has an example exercise ``` 100 - 25 * 3 % 4 ``` the result is 97 (try it!) I cannot see the order of operations that could do this.. 100 - 25 = 75 3 % 4 = 0 or (100-25\*3) =225 % 4 = ??? but anyhow not 97 I don't thin...
For the first example: `*` and `%` take precedence over `-`, so we first evaluate `25 * 3 % 4`. `*` and `%` have the same priority and associativity from left to right, so we evaluate from left to right, starting with `25 * 3`. This yields `75`. Now we evaluate `75 % 4`, yielding `3`. Finally, `100 - 3` is `97`.
Exception Passing In Python
4,730,435
9
2011-01-19T00:01:11Z
4,730,456
9
2011-01-19T00:04:13Z
[ "python", "exception-handling" ]
I have a bit of code that does some functional exception handling and everything works well, exceptions are raised when I want them to be, but when I'm debugging, the line-traces don't always do quite what I want them to. Example A: ``` >>> 3/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
When you re-raise an exception that you caught, such as ``` except Exception as e: raise e ``` it resets the stack trace. It's just like re-raising a new exception. What you want is this: ``` except Exception as e: raise ```
Python import MySQLdb error - Mac 10.6
4,730,787
10
2011-01-19T01:09:07Z
4,731,333
11
2011-01-19T02:52:40Z
[ "python", "mysql", "osx" ]
I downloaded and followed the install instructions for MySQL 5.5.8 (http://dev.mysql.com/downloads/mysql/) and for the MySQLdb python plugin. (http://sourceforge.net/projects/mysql-python/) When I attempt to import MySQLdb to a python terminal, I get the below error: ``` Safira:~ yanigisawa$ python --version Python 2...
You could try running otool to find out exactly what library paths the `MySQLdb` C extension, `_mysql.so` is looking for: ``` $ otool -L /Users/yanigisawa/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so ``` and then the installed library name of the MySQL library file: ``` $ otool -DX /...
Python import MySQLdb error - Mac 10.6
4,730,787
10
2011-01-19T01:09:07Z
6,162,965
49
2011-05-28T16:41:24Z
[ "python", "mysql", "osx" ]
I downloaded and followed the install instructions for MySQL 5.5.8 (http://dev.mysql.com/downloads/mysql/) and for the MySQLdb python plugin. (http://sourceforge.net/projects/mysql-python/) When I attempt to import MySQLdb to a python terminal, I get the below error: ``` Safira:~ yanigisawa$ python --version Python 2...
In my case, I solved by adding a couple of symbolic links as in <http://ageekstory.blogspot.com/2011/04/installing-massive-coupon-on-mac-os-10.html> as following: > sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib > > sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql
Cython's calculations are incorrect
4,730,898
7
2011-01-19T01:30:13Z
4,730,931
17
2011-01-19T01:36:22Z
[ "python", "cython", "pi" ]
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version: ``` from __future__ import division pi = 0 l = 1 x = True while True: if x: pi += 4/l else: pi -= 4/l x = not x l += 2 print str(pi) ``` The Cython ver...
You are using `float` in the Cython version -- that's [single precision](http://en.wikipedia.org/wiki/Single_precision)! Use `double` instead, which corresponds to Python's `float` (funnily enough). The C type `float` only has about 8 significant decimal digits, whereas `double` or Python's `float` have about 16 digits...
How do I do simple user input in python?
4,730,949
2
2011-01-19T01:39:34Z
4,730,961
10
2011-01-19T01:41:50Z
[ "python", "input", "user-input" ]
I'm just playing with input and variables. I'm trying to run a simple function: ``` slope = (y2-y1)/(x2-x1) ``` I'd like to prompt the user to enter `y2`, `y1`, `x2` and `x1`. What is the simplest, cleanest way to do this?
Use `raw_input()` on Python 2 series: ``` x1 = float(raw_input("x1: ")) y1 = float(raw_input("y1: ")) x2 = float(raw_input("x2: ")) y2 = float(raw_input("y2: ")) ``` On Python 3 series, use, `input()`.
python key in dict.keys() performance for large dictionaries
4,730,993
7
2011-01-19T01:46:57Z
4,731,079
29
2011-01-19T02:01:39Z
[ "python" ]
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better. I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that...
Don't do this: ``` value.key in dict.keys() ``` That--in Python 2, at least--creates a list containing every key. That gets more and more expensive as the dictionary gets larger, and performs an O(n) search on the list to find the key, which defeats the purpose of using a dict. Instead, just do: ``` value.key in di...
Worst Case Analysis for Regular Expressions
4,731,104
48
2011-01-19T02:06:07Z
4,731,245
22
2011-01-19T02:35:22Z
[ "python", "regex", "perl", "optimization", "analysis" ]
Are there any tools that will take a particular regular expression and return the worst case scenario in terms of the number of operations required for a certain number of characters that the regular expression is matched against? So for example, given a `(f|a)oo.*[ ]baz`, how many steps might the engine possibly go t...
[Regexbuddy's](http://www.regexbuddy.com/) debugger shows how many steps engine would take to conclude match or not on a given sample. More information on [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html) and [debugging regular expressions](http://www.regexbuddy.com/debug.html). ![cata...
Worst Case Analysis for Regular Expressions
4,731,104
48
2011-01-19T02:06:07Z
6,631,538
11
2011-07-08T23:20:00Z
[ "python", "regex", "perl", "optimization", "analysis" ]
Are there any tools that will take a particular regular expression and return the worst case scenario in terms of the number of operations required for a certain number of characters that the regular expression is matched against? So for example, given a `(f|a)oo.*[ ]baz`, how many steps might the engine possibly go t...
Note that it depends on the *engine*. While regex theory is based on straight automata theory, most of the engines are not strict translations of those theories. For this reason, for instance, some engines incur in exponential time while strict NFA processing would not.
Worst Case Analysis for Regular Expressions
4,731,104
48
2011-01-19T02:06:07Z
6,631,563
7
2011-07-08T23:23:33Z
[ "python", "regex", "perl", "optimization", "analysis" ]
Are there any tools that will take a particular regular expression and return the worst case scenario in terms of the number of operations required for a certain number of characters that the regular expression is matched against? So for example, given a `(f|a)oo.*[ ]baz`, how many steps might the engine possibly go t...
You might get what you're looking for something like using `re.compile` with `re.DEBUG`. See this [excellent answer](http://stackoverflow.com/questions/101268/hidden-features-of-python/143636#143636) from the [Python Hidden Features](http://stackoverflow.com/q/101268/172322) Community wiki for an extensive explanation.
Django counter in loop to index list
4,731,572
7
2011-01-19T03:54:16Z
4,731,596
9
2011-01-19T03:58:36Z
[ "python", "django" ]
I'm passing two lists to a template. Normally if I was iterating over a list I would do something like this ``` {% for i in list %} ``` but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list. My thought was to loop over one list and access an...
You can't. The simple way is to preprocess you data in a [zipped list](http://docs.python.org/library/functions.html#zip), like this In your view ``` x = [1, 2, 3] y = [4, 5, 6] zipped = zip(x, y) ``` Then in you template : ``` {% for x, y in zipped %} {{ x }} - {{ y }} {% endfor %} ```
pycairo "ImportError: DLL load failed: The specified module could not be found." even after DLLs installed
4,731,786
9
2011-01-19T04:38:09Z
4,731,796
20
2011-01-19T04:40:23Z
[ "python", "windows-7", "igraph", "pycairo" ]
I'm following the pycairo installation instructions here : <http://www.cs.rhul.ac.uk/home/tamas/development/igraph/tutorial/install.html> to install pycairo for use with igraph. However, even after running the installer and unzipping/copying all DLL's into the site-packages cairo directory according to the instruction...
Open \_cairo.pyd in [Dependency Walker](http://www.dependencywalker.com/) and figure out what it's missing.
Continuing in Python's unittest when an assertion fails
4,732,827
43
2011-01-19T07:38:08Z
4,733,120
8
2011-01-19T08:23:38Z
[ "python", "unit-testing" ]
EDIT: switched to a better example, and clarified why this is a real problem. I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example: ``` class Car(object): def __init__(self, make, model): self.make = make se...
It is considered an anti-pattern to have multiple asserts in a single unit test. A single unit test is expected to test only one thing. Perhaps you are testing too much. Consider splitting this test up into multiple tests. This way you can name each test properly. Sometimes however, it is okay to check multiple things...
Continuing in Python's unittest when an assertion fails
4,732,827
43
2011-01-19T07:38:08Z
5,028,110
21
2011-02-17T11:06:30Z
[ "python", "unit-testing" ]
EDIT: switched to a better example, and clarified why this is a real problem. I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example: ``` class Car(object): def __init__(self, make, model): self.make = make se...
Another way to have non-fatal assertions is to capture the assertion exception and store the exceptions in a list. Then assert that that list is empty as part of the tearDown. ``` import unittest class Car(object): def __init__(self, make, model): self.make = make self.model = make # Copy and paste error: ...