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
Why doesn't print work in a lambda?
2,970,858
100
2010-06-04T00:58:26Z
2,970,872
22
2010-06-04T01:03:44Z
[ "python", "printing", "lambda", "python-2.x" ]
Why doesn't this work? ``` lambda: print "x" ``` Is this not a single statement, or is it something else? The documentation seems a little sparse on what is allowed in a lambda...
what you've written is equivalent to ``` def anon(): return print "x" ``` which also results in a SyntaxError, python doesn't let you assign a value to print in 2.xx; in python3 you could say ``` lambda: print('hi') ``` and it would work because they've changed print to be a function instead of a statement.
Why doesn't print work in a lambda?
2,970,858
100
2010-06-04T00:58:26Z
2,970,886
9
2010-06-04T01:06:56Z
[ "python", "printing", "lambda", "python-2.x" ]
Why doesn't this work? ``` lambda: print "x" ``` Is this not a single statement, or is it something else? The documentation seems a little sparse on what is allowed in a lambda...
The body of a lambda has to be an expression that returns a value. `print`, being a statement, doesn't return anything, not even `None`. Similarly, you can't assign the result of `print` to a variable: ``` >>> x = print "hello" File "<stdin>", line 1 x = print "hello" ^ SyntaxError: invalid syntax ``...
Why doesn't print work in a lambda?
2,970,858
100
2010-06-04T00:58:26Z
2,970,891
119
2010-06-04T01:08:56Z
[ "python", "printing", "lambda", "python-2.x" ]
Why doesn't this work? ``` lambda: print "x" ``` Is this not a single statement, or is it something else? The documentation seems a little sparse on what is allowed in a lambda...
A `lambda`'s body has to be a *single expression*. In Python 2.x, `print` is a statement. However, in Python 3, `print` is a *function* (and a function application is an expression, so it will work in a lambda). You can (and should, for forward compatibility :) use the back-ported print function if you are using the la...
Why doesn't print work in a lambda?
2,970,858
100
2010-06-04T00:58:26Z
6,125,151
16
2011-05-25T13:24:09Z
[ "python", "printing", "lambda", "python-2.x" ]
Why doesn't this work? ``` lambda: print "x" ``` Is this not a single statement, or is it something else? The documentation seems a little sparse on what is allowed in a lambda...
In cases where I am using this for simple stubbing out I use this: ``` fn = lambda x: sys.stdout.write(str(x) + "\n") ``` which works perfectly.
Why doesn't print work in a lambda?
2,970,858
100
2010-06-04T00:58:26Z
23,066,051
8
2014-04-14T17:05:39Z
[ "python", "printing", "lambda", "python-2.x" ]
Why doesn't this work? ``` lambda: print "x" ``` Is this not a single statement, or is it something else? The documentation seems a little sparse on what is allowed in a lambda...
You can do something like this. **Create a function to transform print statement into a function:** ``` def printf(text): print text ``` **And print it:** ``` lambda: printf("Testing") ```
django and netbeans?
2,971,309
11
2010-06-04T03:25:45Z
3,060,182
9
2010-06-17T08:51:25Z
[ "python", "django", "netbeans", "ide" ]
I use netbeans for all of my Linux development (C/C++, Php, Python, Symfony). I am now learning django, and wondered if I could use netbeans as the IDE. I cant seem to find a Django plugin for netbeans. Is there one?. If no when is one planned? Worst case scenario, I'll have to use another IDE (I really dont want to ...
There is Python and Django support from the [built-in **Python** plug-in](http://wiki.netbeans.org/PythonInstall) (in short simply get *any* NetBeans 6.9 or more recent, go to menu Update... > Search "Python" > Install). There is also a [NetBeans-Django](http://code.google.com/p/netbeans-django/) additional project go...
How to maximize performance in Python when doing many I/O bound operations?
2,971,381
8
2010-06-04T03:46:37Z
2,971,453
13
2010-06-04T04:08:16Z
[ "python" ]
I have a situation where I'm downloading a lot of files. Right now everything runs on one main Python thread, and downloads as many as 3000 files every few minutes. The problem is that the time it takes to do this is too long. I realize Python has no true multi-threading, but is there a better way of doing this? I was ...
Multithreading is just fine for the specific purpose of speeding up I/O on the net (although asynchronous programming would give even greater performance). CPython's multithreading is quite "true" (native OS threads) -- what you're probably thinking of is the GIL, the global interpreter lock that stops different thread...
Creating an empty list in Python
2,972,212
88
2010-06-04T07:26:02Z
2,972,226
144
2010-06-04T07:29:11Z
[ "python", "performance", "coding-style", "timeit" ]
What is the best way to create a new empty list in Python? ``` l = [] ``` or ``` l = list() ``` I am asking this because of two reasons: 1. Technical reasons, as to which is faster. (creating a class causes overhead?) 2. Code readability - which one is the standard convention.
Here is how you can test which piece of code is faster: ``` % python -mtimeit "l=[]" 10000000 loops, best of 3: 0.0711 usec per loop % python -mtimeit "l=list()" 1000000 loops, best of 3: 0.297 usec per loop ``` However, in practice, this initialization is most likely an extremely small part of your program, so wo...
Creating an empty list in Python
2,972,212
88
2010-06-04T07:26:02Z
2,972,369
61
2010-06-04T07:59:11Z
[ "python", "performance", "coding-style", "timeit" ]
What is the best way to create a new empty list in Python? ``` l = [] ``` or ``` l = list() ``` I am asking this because of two reasons: 1. Technical reasons, as to which is faster. (creating a class causes overhead?) 2. Code readability - which one is the standard convention.
list() is inherently slower than [], because a) there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!), b) there is function invocation, c) then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none ...
Creating an empty list in Python
2,972,212
88
2010-06-04T07:26:02Z
2,972,414
8
2010-06-04T08:06:08Z
[ "python", "performance", "coding-style", "timeit" ]
What is the best way to create a new empty list in Python? ``` l = [] ``` or ``` l = list() ``` I am asking this because of two reasons: 1. Technical reasons, as to which is faster. (creating a class causes overhead?) 2. Code readability - which one is the standard convention.
I use `[]`. 1. It's faster because the list notation is a short circuit. 2. Creating a list *with* items should look about the same as creating a list without, why should there be a difference?
Is there any thorough, broad documentation of Twisted that is better than the official site?
2,972,703
14
2010-06-04T08:59:34Z
2,976,401
7
2010-06-04T17:28:35Z
[ "python", "twisted" ]
I've been looking at twisted for a while now. It looks interesting - it seems like a good way to leverage a lot of power when writing servers. Unfortunately, in spite of writing a few web servers using twisted.web (from reading other people's source and an extremely dated O'Reilly book) I've never really felt like I ha...
The [Twisted Intro](http://krondo.com/blog/?page_id=1327) by [Dave Peticolas](http://krondo.com) is an *amazing* overview of Twisted from the ground up. It starts simple and then starts getting deeper and deeper while explaining everything along the way. I've been using Twisted for years and found this intro to fill i...
Is there any thorough, broad documentation of Twisted that is better than the official site?
2,972,703
14
2010-06-04T08:59:34Z
2,979,264
15
2010-06-05T05:16:33Z
[ "python", "twisted" ]
I've been looking at twisted for a while now. It looks interesting - it seems like a good way to leverage a lot of power when writing servers. Unfortunately, in spite of writing a few web servers using twisted.web (from reading other people's source and an extremely dated O'Reilly book) I've never really felt like I ha...
I'm going to repeat what some of the answerers here have said (they're all good answers) in the hopes of providing an answer that is somewhat comprehensive. 1. While the included documentation is spotty in places, [the core documentation](http://twistedmatrix.com/documents/10.0.0/core/howto/index.html) contains severa...
Available disk space on an SMB share, via Python
2,973,480
2
2010-06-04T11:03:21Z
2,974,830
8
2010-06-04T14:04:02Z
[ "python", "windows", "samba" ]
Does anyone know a way to get the amount of space available on a Windows (Samba) share via Python 2.6 with its standard library? (also running on Windows) e.g. ``` >>> os.free_space("\\myshare\folder") # return free disk space, in bytes 1234567890 ```
If [PyWin32](http://sourceforge.net/projects/pywin32/) is available: ``` free, total, totalfree = win32file.GetDiskFreeSpaceEx(r'\\server\share') ``` Where *free* is a amount of free space available to the current user, and *totalfree* is amount of free space total. Relevant documentation: [PyWin32 docs](http://docs....
Is Python's logging module thread safe?
2,973,900
17
2010-06-04T12:06:48Z
2,973,911
21
2010-06-04T12:09:01Z
[ "python" ]
If you call the same logging handler from two different python threads, is there a need for locking?
The logging module is thread-safe; it handles the locking for you. See [the docs](http://docs.python.org/2/library/logging.html#thread-safety).
Python - making counters, making loops?
2,973,926
2
2010-06-04T12:11:08Z
2,973,969
9
2010-06-04T12:17:03Z
[ "python", "loops", "counter" ]
I am having some trouble with a piece of code below: Input: li is a nested list as below: ``` li = [['>0123456789 mouse gene 1\n', 'ATGTTGGGTT/CTTAGTTG\n', 'ATGGGGTTCCT/A\n'], ['>9876543210 mouse gene 2\n', 'ATTTGGTTTCCT\n', 'ATTCAATTTTAAGGGGGGGG\n']] ``` Using the function below, my desired output is simply the 2...
Your indentation is possibly wrong, you should check `count > 1` within the `for j in i` loop, not within the one that checks every single character in `j[1:]`. Also, here's a much easier way to do the same thing: ``` def count_slashes(items): return sum(item.count('/') for item in items) for item in li: if ...
Python - making counters, making loops?
2,973,926
2
2010-06-04T12:11:08Z
2,974,476
8
2010-06-04T13:16:48Z
[ "python", "loops", "counter" ]
I am having some trouble with a piece of code below: Input: li is a nested list as below: ``` li = [['>0123456789 mouse gene 1\n', 'ATGTTGGGTT/CTTAGTTG\n', 'ATGGGGTTCCT/A\n'], ['>9876543210 mouse gene 2\n', 'ATTTGGTTTCCT\n', 'ATTCAATTTTAAGGGGGGGG\n']] ``` Using the function below, my desired output is simply the 2...
Tamás has suggested a good solution, although it uses a very different style of coding than you do. Still, since your question was "I am having some trouble with a piece of code below", I think something more is called for. **How to avoid these problems in the future** You've made several mistakes in your approach t...
Is it possible to assign the same value to multiple keys in a dict object at once?
2,974,022
13
2010-06-04T12:23:08Z
2,974,082
21
2010-06-04T12:31:10Z
[ "python", "syntax", "dictionary" ]
In Python, I need a dictionary object which looks like: ``` {'a': 10, 'b': 20, 'c': 10, 'd': 10, 'e': 20} ``` I've been able to get this successfully by combining the `dict.update()` and `dict.fromkeys()` functions like so: ``` myDict = {} myDict.update(dict.fromkeys(['a', 'b', 'c'], 10)) myDict.update(dict.fromkeys...
I would say what you have is *very* simple, you could slightly improve it to be: ``` my_dict = dict.fromkeys(['a', 'b', 'c'], 10) my_dict.update(dict.fromkeys(['b', 'e'], 20)) ``` If your keys are tuple you could do: ``` >>> my_dict = {('a', 'c', 'd'): 10, ('b', 'e'): 20} >>> next(v for k, v in my_dict.items() if 'c...
Does Python copy value or reference upon object instantiation?
2,974,679
10
2010-06-04T13:47:11Z
2,974,689
13
2010-06-04T13:48:27Z
[ "python", "object", "language-design", "instantiation" ]
A simple question, perhaps, but I can't quite phrase my Google query to find the answer here. I've had the habit of making copies of objects when I pass them into object constructors, like so: ``` ... def __init__(self, name): self._name = name[:] ... ``` However, when I ran the following test code, it appears to...
It is because strings are **immutable**. The operator `+=`, rather confusingly, actually *reassigns* the variable it is applied to, if the object is immutable: ``` s = 'a' ids = id(s) s += 'b' ids == id(s) # False, because s was reassigned to a new object ``` So, in your case, in the beginning, both `flav` and `a.fl...
How to run a Python script in the background even after I logout SSH?
2,975,624
38
2010-06-04T15:39:39Z
2,975,645
73
2010-06-04T15:41:50Z
[ "python", "service", "cron" ]
I have Python script `bgservice.py` and I want it to run all the time, because it is part of the web service I build. How can I make it run continuously even after I logout SSH?
Run `nohup python bgservice.py &` to get the script to ignore the hangup signal and keep running. Output will be put in `nohup.out`. Ideally, you'd run your script with something like [`supervise`](http://cr.yp.to/daemontools/supervise.html) so that it can be restarted if (when) it dies.
How to run a Python script in the background even after I logout SSH?
2,975,624
38
2010-06-04T15:39:39Z
2,975,657
14
2010-06-04T15:42:44Z
[ "python", "service", "cron" ]
I have Python script `bgservice.py` and I want it to run all the time, because it is part of the web service I build. How can I make it run continuously even after I logout SSH?
You could also use [GNU screen](http://www.gnu.org/software/screen/) which just about every Linux/Unix system should have. If you are on Ubuntu/Debian, its enhanced variant [byobu](http://byobu.co) is rather nice too.
How to run a Python script in the background even after I logout SSH?
2,975,624
38
2010-06-04T15:39:39Z
2,975,852
14
2010-06-04T16:07:29Z
[ "python", "service", "cron" ]
I have Python script `bgservice.py` and I want it to run all the time, because it is part of the web service I build. How can I make it run continuously even after I logout SSH?
If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it. `Ctrl+Z` (suspend the process) `bg` (restart the process in the background `disown %1` (assuming this is job #1, use `jobs` to determine)
How to run a Python script in the background even after I logout SSH?
2,975,624
38
2010-06-04T15:39:39Z
9,494,044
7
2012-02-29T05:31:49Z
[ "python", "service", "cron" ]
I have Python script `bgservice.py` and I want it to run all the time, because it is part of the web service I build. How can I make it run continuously even after I logout SSH?
You might consider turning your python script into a proper python daemon, as described [here](http://stackoverflow.com/a/9047339/482352). [python-daemon](https://pypi.python.org/pypi/python-daemon/) is a good tool that can be used to run python scripts as a background daemon process rather than a forever running scri...
Call another classes method in Python
2,976,840
3
2010-06-04T18:42:05Z
2,976,917
11
2010-06-04T18:53:03Z
[ "python" ]
I'm tying to create a class that holds a reference to another classes method. I want to be able to call the method. It is basically a way to do callbacks. My code works until I try to access a class var. When I run the code below, I get the error What am I doing wrong? Brian ``` import logging class yRunMethod(obje...
I think you're making this **WAY** too hard on yourself (which is easy to do ;-). Methods of classes and instances are first-class objects in Python. You can pass them around and call them like anything else. Digging into a method's instance variables is something that should almost never be done. A simple example to a...
Checkstyle for Python
2,977,866
11
2010-06-04T21:21:34Z
2,978,289
14
2010-06-04T22:51:25Z
[ "java", "python", "coding-style" ]
Is there an application similar to Java's [Checkstyle](http://checkstyle.sourceforge.net/) for Python? By which I mean, a tool that analyzes Python code and can be run as part of continuous integration (e.g. CruiseControl or Hudson). After analyzing, it should produce an online accessible report which outlines any pro...
There are actually a lot of tools: as other have said * pylint : very very strict (imho too much), yet customizable * pep-8 : very good * pychecker * pyflakes: extremely fast, perfect when used in emacs with flymake. To format your code according to pep8 I can suggest you [PythonTidy](http://pypi.python.org/pypi/Pyth...
Django Models / SQLAlchemy are bloated! Any truly Pythonic DB models out there?
2,978,138
5
2010-06-04T22:13:11Z
2,978,783
9
2010-06-05T01:44:16Z
[ "database", "nosql", "python" ]
"***Make things as simple as possible, but no simpler.***" Can we find the solution/s that fix the Python database world? **Update: [A 'lustdb' prototype has been written by Alex Martelli](http://groups.google.com/group/lustdb) - if you know any somewhat lightweight, high-level database libraries with multiple backen...
What you request cannot be done in Python 2.*whatever*, for a very specific reason. You want to write: ``` class Task(model): title = '' isDone = False ``` In Python 2.*anything*, **whatever** `model` may possibly be, this cannot **ever** allow you to predict any "ordering" for the two fields, because the se...
Is there a more efficient way to organize random outcomes by size in Python?
2,978,317
5
2010-06-04T23:03:08Z
2,978,328
8
2010-06-04T23:06:01Z
[ "python", "random", "numbers", "reorganize" ]
(sorry if this is a dumb question, I'm still learning) I'm making a program that, for part of the prog, rolls four dice and subtracts the lowest dice from the outcome. The code I'm using is ``` die1 = random.randrange(6) + 1 die2 = random.randrange(6) + 1 die3 = random.randrange(6) + 1 die4 = random.randrange(6) + 1 ...
Put the dice in a list, sort the list using [**`sorted`**](http://docs.python.org/library/functions.html#sorted) and remove the smallest element using a slice: ``` >>> import random >>> dice = [random.randint(1, 6) for x in range(4)] >>> sum(sorted(dice)[1:]) 13 ``` Or an alternative that is simpler and will also be ...
Pass parameter one time, but use more times
2,978,362
4
2010-06-04T23:18:48Z
2,978,376
10
2010-06-04T23:22:46Z
[ "python", "parameters", "string-formatting", "repeat" ]
I'm trying to do this: > commands = { 'py': 'python %s', 'md': 'markdown "%s" > "%s.html"; gnome-open "%s.html"', } > > commands['md'] % 'file.md' But like you see, the commmands['md'] uses the parameter 3 times, but the commands['py'] just use once. How can I repeat the parameter without changing the last line (so, ...
Note: The accepted answer, while it does work for both older and newer versions of Python, is discouraged in newer versions of Python. > Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.forma...
DatabaseError: current transaction is aborted, commands ignored until end of transaction block
2,979,369
150
2010-06-05T06:05:19Z
2,979,389
100
2010-06-05T06:16:39Z
[ "python", "django", "postgresql", "psycopg2", "psycopg" ]
I got a lot of errors with the message : ``` "DatabaseError: current transaction is aborted, commands ignored until end of transaction block" ``` after changed from python-psycopg to python-psycopg2 as Django project's database engine. The code remains the same, just dont know where those errors are from.
This is what postgres does when a query produces an error and you try to run another query without first rolling back the transaction. To fix it, you'll want to figure out where in the code that bad query is being executed. It might be helpful to use the [log\_statement](http://www.postgresql.org/docs/current/static/ru...
DatabaseError: current transaction is aborted, commands ignored until end of transaction block
2,979,369
150
2010-06-05T06:05:19Z
7,717,916
46
2011-10-10T19:54:22Z
[ "python", "django", "postgresql", "psycopg2", "psycopg" ]
I got a lot of errors with the message : ``` "DatabaseError: current transaction is aborted, commands ignored until end of transaction block" ``` after changed from python-psycopg to python-psycopg2 as Django project's database engine. The code remains the same, just dont know where those errors are from.
So, I ran into this same issue. The problem I was having here was that my database wasn't properly synced. Simple problems always seem to cause the most angst... To sync your django db, from within your app directory, within terminal, type: ``` $ python manage.py syncdb ``` Edit: Note that if you are using django-so...
DatabaseError: current transaction is aborted, commands ignored until end of transaction block
2,979,369
150
2010-06-05T06:05:19Z
10,437,521
26
2012-05-03T18:47:43Z
[ "python", "django", "postgresql", "psycopg2", "psycopg" ]
I got a lot of errors with the message : ``` "DatabaseError: current transaction is aborted, commands ignored until end of transaction block" ``` after changed from python-psycopg to python-psycopg2 as Django project's database engine. The code remains the same, just dont know where those errors are from.
In my experience, these errors happen this way: ``` try: code_that_executes_bad_query() # transaction on DB is now bad except: pass # transaction on db is still bad code_that_executes_working_query() # raises transaction error ``` There nothing wrong with the second query, but since the real error was ca...
DatabaseError: current transaction is aborted, commands ignored until end of transaction block
2,979,369
150
2010-06-05T06:05:19Z
11,366,092
16
2012-07-06T16:23:33Z
[ "python", "django", "postgresql", "psycopg2", "psycopg" ]
I got a lot of errors with the message : ``` "DatabaseError: current transaction is aborted, commands ignored until end of transaction block" ``` after changed from python-psycopg to python-psycopg2 as Django project's database engine. The code remains the same, just dont know where those errors are from.
I think the pattern priestc mentions is more likely to be the usual cause of this issue when using PostgreSQL. However I feel there are valid uses for the pattern and I don't think this issue should be a reason to always avoid it. For example: ``` try: profile = user.get_profile() except ObjectDoesNotExist: p...
DatabaseError: current transaction is aborted, commands ignored until end of transaction block
2,979,369
150
2010-06-05T06:05:19Z
13,007,379
108
2012-10-22T08:16:06Z
[ "python", "django", "postgresql", "psycopg2", "psycopg" ]
I got a lot of errors with the message : ``` "DatabaseError: current transaction is aborted, commands ignored until end of transaction block" ``` after changed from python-psycopg to python-psycopg2 as Django project's database engine. The code remains the same, just dont know where those errors are from.
To get rid of the error, **roll back the last (erroneous) transaction** after you've fixed your code: ``` from django.db import transaction transaction.rollback() ``` You can use try-except to prevent the error from occurring: ``` from django.db import transaction, DatabaseError try: a.save() except DatabaseErro...
More pythonic way to iterate
2,980,031
3
2010-06-05T10:48:42Z
2,980,048
11
2010-06-05T10:54:31Z
[ "refactoring", "iterator", "python" ]
I am using a module that is part of a commercial software API. The good news is there is a python module - the bad news is that its pretty unpythonic. To iterate over rows, the follwoing syntax is used: ``` cursor = gp.getcursor(table) row = cursor.next() while row: #do something with row row = cursor.next()...
Assuming that one of Next and next is a typo and they're both the same, you can use the not-so-well-known variant of the built-in iter function: ``` for row in iter(cursor.next, None): <do something> ```
Change|Assign parent for the Model instance on Google App Engine Datastore
2,980,196
6
2010-06-05T11:47:38Z
2,980,697
9
2010-06-05T14:18:24Z
[ "python", "google-app-engine", "gae-datastore", "gae-ds-transactions" ]
Is it possible to change or assign new parent to the Model instance that already in datastore? For example I need something like this ``` task = db.get(db.Key(task_key)) project = db.get(db.Key(project_key)) task.parent = project task.put() ``` but it doesn't works this way because `task.parent` is built-in method. I...
According to [the docs](http://code.google.com/appengine/docs/python/datastore/keysandentitygroups.html#Entity_Groups_Ancestors_and_Paths), no: > The parent of an entity is defined > when the entity is created, and cannot > be changed later. > > ... > > The complete key of an entity, > including the path, the kind and...
python and overflowing byte?
2,980,213
9
2010-06-05T11:52:32Z
2,980,422
8
2010-06-05T12:59:10Z
[ "python", "variables", "overflow" ]
I need to make a variable with similar behaviour like in C lanquage. I need byte or unsigned char with range 0-255. This variable should overflow, that means... ``` myVar = 255 myVar += 1 print myVar #!!myVar = 0!! ```
I see lots of good answers here. However, if you want to create your own type as you mentioned, you could look at the [Python Data model documentation](http://docs.python.org/reference/datamodel.html#data-model). It explains how to make classes that have customized behaviours, for example [emulating numeric types](http...
Python, Draw a circle with PIL
2,980,366
9
2010-06-05T12:46:04Z
2,980,931
9
2010-06-05T15:26:35Z
[ "python", "python-imaging-library" ]
I am looking for a command that will draw a circle on an existing image with PIL. ``` im = Image.open(path) ``` I want a function that will draw a colored circle with radius `r` and center `(x,y)`
``` image = Image.open("x.png") draw = ImageDraw.Draw(image) draw.ellipse((x-r, y-r, x+r, y+r), fill=(255,0,0,0)) ```
Python ctypes: loading DLL from from a relative path
2,980,479
15
2010-06-05T13:16:00Z
2,980,501
15
2010-06-05T13:21:45Z
[ "python", "ctypes" ]
I have a Python module, `wrapper.py`, that wraps a C DLL. The DLL lies in the same folder as the module. Therefore, I use the following code to load it: ``` myDll = ctypes.CDLL("MyCDLL.dll") ``` This works if I execute `wrapper.py` from its own folder. If, however, I run it from elsewhere, it fails. That's because ct...
You can use `os.path.dirname(__file__)` to get the directory where the Python source file is located.
Google App Engine: get_or_create()?
2,981,630
5
2010-06-05T18:58:32Z
2,981,725
7
2010-06-05T19:22:43Z
[ "python", "django", "google-app-engine" ]
Does Google App Engine have an equivalent of Django's [get\_or\_create()](http://www.djangoproject.com/documentation/models/get_or_create/)?
There is no full equivalent, but [get\_or\_insert](http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_or_insert) is something similar. The main differences is that `get_or_insert` accepts `key_name` as lookup against filters set in `get_or_create`.
Writing header with DictWriter from Python's csv module
2,982,023
64
2010-06-05T20:41:26Z
2,982,117
82
2010-06-05T21:09:45Z
[ "python", "csv" ]
Assume I have a csv.DictReader object and I want to write it out as a CSV file. How can I do this? I know that I can write the *rows* like this: ``` dr = csv.DictReader(open(f), delimiter='\t') # process my dr object # ... # write out object output = csv.DictWriter(open(f2, 'w'), delimiter='\t') for item in dr: out...
Edit: In 2.7 / 3.2 there is [a new `writeheader()` method](http://docs.python.org/dev/library/csv.html#csv.DictWriter.writeheader). Also, John Machin's answer provides a simpler method of writing the header row. Simple example of using the `writeheader()` method now available in 2.7 / 3.2: ``` from collections imp...
Writing header with DictWriter from Python's csv module
2,982,023
64
2010-06-05T20:41:26Z
2,982,499
22
2010-06-05T23:18:20Z
[ "python", "csv" ]
Assume I have a csv.DictReader object and I want to write it out as a CSV file. How can I do this? I know that I can write the *rows* like this: ``` dr = csv.DictReader(open(f), delimiter='\t') # process my dr object # ... # write out object output = csv.DictWriter(open(f2, 'w'), delimiter='\t') for item in dr: out...
A few options: (1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance. (2) The documentation mentions "the underlying `writer` instance" ... so just use it (example at the end). ``` dw.writer.wri...
Writing header with DictWriter from Python's csv module
2,982,023
64
2010-06-05T20:41:26Z
13,496,970
8
2012-11-21T15:51:38Z
[ "python", "csv" ]
Assume I have a csv.DictReader object and I want to write it out as a CSV file. How can I do this? I know that I can write the *rows* like this: ``` dr = csv.DictReader(open(f), delimiter='\t') # process my dr object # ... # write out object output = csv.DictWriter(open(f2, 'w'), delimiter='\t') for item in dr: out...
Another way to do this would be to add before adding lines in your output, the following line : ``` output.writerow(dict(zip(dr.fieldnames, dr.fieldnames))) ``` The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.
Output being printed in the same line, Py3k
2,982,295
5
2010-06-05T22:09:10Z
2,982,306
7
2010-06-05T22:12:57Z
[ "python", "py2to3" ]
In Python 2.x, I'd write... ``` for i in range(5): print i, ``` ...to get integers from 0 to 4 printed in the same row. How to do that in Python 3.x, since print is a function now?
Use `print(x, end = ' ')`: From the [release notes](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function): ``` Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline ```
Should I use Python or Assembly for a super fast copy program
2,982,829
18
2010-06-06T01:54:06Z
2,982,837
43
2010-06-06T01:58:09Z
[ "python", "assembly" ]
As a maintenance issue I need to routinely (3-5 times per year) copy a repository that is now has over 20 million files and exceeds 1.5 terabytes in total disk space. I am currently using RICHCOPY, but have tried others. RICHCOPY seems the fastest but I do not believe I am getting close to the limits of the capabilitie...
Copying files is an I/O bound process. It is unlikely that you will see any speed up from rewriting it in assembly, and even multithreading may just cause things to go slower as different threads requesting different files at the same time will result in more disk seeks. Using a standard tool is probably the best way ...
Should I use Python or Assembly for a super fast copy program
2,982,829
18
2010-06-06T01:54:06Z
2,982,847
8
2010-06-06T02:02:27Z
[ "python", "assembly" ]
As a maintenance issue I need to routinely (3-5 times per year) copy a repository that is now has over 20 million files and exceeds 1.5 terabytes in total disk space. I am currently using RICHCOPY, but have tried others. RICHCOPY seems the fastest but I do not believe I am getting close to the limits of the capabilitie...
There are 2 places for slowdown: * Per-file copy is MUCH slower than a disk copy (where you literally clone 100% of each sector's data). Especially for 20mm files. You can't fix that one with the most tuned assembly, **unless you switch from cloning files to cloning raw disk data. In the latter case, yes, Assembly is ...
Should I use Python or Assembly for a super fast copy program
2,982,829
18
2010-06-06T01:54:06Z
2,982,899
8
2010-06-06T02:31:23Z
[ "python", "assembly" ]
As a maintenance issue I need to routinely (3-5 times per year) copy a repository that is now has over 20 million files and exceeds 1.5 terabytes in total disk space. I am currently using RICHCOPY, but have tried others. RICHCOPY seems the fastest but I do not believe I am getting close to the limits of the capabilitie...
As the other answers mention (+1 to mark), when copying files, disk i/o is the bottleneck. The language you use won't make much of a difference. How you've laid out your files will make a difference, how you're transferring data will make a difference. You mentioned copying to a DROBO. How is your DROBO connected? Che...
plotting results of hierarchical clustering ontop of a matrix of data in python
2,982,929
41
2010-06-06T02:50:24Z
3,011,894
73
2010-06-10T05:40:19Z
[ "python", "cluster-analysis", "machine-learning", "matplotlib", "scipy" ]
How can I plot a dendrogram right on top of a matrix of values, reordered appropriately to reflect the clustering, in Python? An example is in the bottom of the following figure: <http://www.coriell.org/images/microarray.gif> I use scipy.cluster.dendrogram to make my dendrogram and perform hierarchical clustering on ...
The question does not define *matrix* very well: "matrix of values", "matrix of data". I assume that you mean a *distance matrix*. In other words, element D\_ij in the symmetric nonnegative N-by-N *distance matrix* D denotes the distance between two feature vectors, x\_i and x\_j. Is that correct? If so, then try this...
plotting results of hierarchical clustering ontop of a matrix of data in python
2,982,929
41
2010-06-06T02:50:24Z
23,046,142
7
2014-04-13T17:48:06Z
[ "python", "cluster-analysis", "machine-learning", "matplotlib", "scipy" ]
How can I plot a dendrogram right on top of a matrix of values, reordered appropriately to reflect the clustering, in Python? An example is in the bottom of the following figure: <http://www.coriell.org/images/microarray.gif> I use scipy.cluster.dendrogram to make my dendrogram and perform hierarchical clustering on ...
If in addition to the matrix and dendrogram it is required to show the labels of the elements, the following code can be used, that shows all the labels rotating the x labels and changing the font size to avoid overlapping on the x axis. It requires moving the colorbar to have space for the y labels: ``` axmatrix.set_...
Getting logging.debug() to work on Google App Engine/Python
2,982,959
20
2010-06-06T03:01:10Z
2,983,074
27
2010-06-06T04:18:16Z
[ "python", "debugging", "google-app-engine" ]
I'm just getting started on building a Python app for Google App Engine. In the localhost environment (on a Mac) I'm trying to send debug info to the GoogleAppEngineLauncher Log Console via `logging.debug()`, but it isn't showing up. However, anything sent through, say, `logging.info()` or `logging.error()` *does* sho...
I believe the only way to get debug messages to show up in the dev server is to pass --debug. dev\_appserver itself uses this same logger, though, so be prepared to see debug messages from the server as well as your own code.
Getting logging.debug() to work on Google App Engine/Python
2,982,959
20
2010-06-06T03:01:10Z
17,550,812
8
2013-07-09T14:25:39Z
[ "python", "debugging", "google-app-engine" ]
I'm just getting started on building a Python app for Google App Engine. In the localhost environment (on a Mac) I'm trying to send debug info to the GoogleAppEngineLauncher Log Console via `logging.debug()`, but it isn't showing up. However, anything sent through, say, `logging.info()` or `logging.error()` *does* sho...
In case someone is using the Windows Google Application Launcher. The argument for debug can be set under Edit > Application Settings In the Extra Command Line Flags, add --log\_level=debug
Copy call signature to decorator
2,982,974
11
2010-06-06T03:10:44Z
2,997,432
9
2010-06-08T12:57:25Z
[ "python", "decorator" ]
If I do the following ``` def mydecorator(f): def wrapper(*args, **kwargs): f(*args, **kwargs) wrapper.__doc__ = f.__doc__ wrapper.__name__ = f.__name__ return wrapper @mydecorator def myfunction(a,b,c): '''My docstring''' pass ``` And then type `help myfunction`, I get: ``` Help on ...
Here is an example using Michele Simionato's [decorator module](http://pypi.python.org/pypi/decorator) to fix the signature: ``` import decorator @decorator.decorator def mydecorator(f,*args, **kwargs): return f(*args, **kwargs) @mydecorator def myfunction(a,b,c): '''My docstring''' pass help(myfunction...
Unresolved import: models
2,983,088
16
2010-06-06T04:27:54Z
2,983,096
15
2010-06-06T04:34:41Z
[ "python", "django", "eclipse", "pydev" ]
I'm doing my VERY first project using python/django/eclipse/pydev following this guide <http://docs.djangoproject.com/en/dev/intro/tutorial01/> My only addition is the use of Eclipse/pydev. I'm getting many errors related to "Unresolved imports". I can remove the errors using "remove error markers" and my site runs ...
Check your pythonpath. You need to include the parent directory of django, usually Lib/site-packages.
assign operator to variable in python?
2,983,139
16
2010-06-06T04:55:04Z
2,983,144
30
2010-06-06T04:57:02Z
[ "python", "compiler-construction", "operators" ]
Usual method of applying mathematics to variables is ``` a * b ``` Is it able to calculate and manipulate two operands like this? ``` a = input('enter a value') b = input('enter a value') op = raw_input('enter a operand') ``` Then how do i connect op and two variables `a` and `b`? I know I can compare op to `+`,...
You can use the operator module and a dictionary: ``` import operator ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} op_char = raw_input('enter a operand') op_func = ops[op_char] result = op_func(a, b) ```
Splitting a list in python
2,983,959
5
2010-06-06T11:05:56Z
2,983,967
8
2010-06-06T11:11:06Z
[ "python", "list", "parsing" ]
I'm writing a parser in Python. I've converted an input string into a list of tokens, such as: `['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')', '/', '3', '.', 'x', '^', '2']` I want to be able to split the list into multiple lists, like the `str.split('+')` function. But there doesn't seem to be a w...
You can write your own split function for lists quite easily by using yield: ``` def split_list(l, sep): current = [] for x in l: if x == sep: yield current current = [] else: current.append(x) yield current ``` An alternative way is to use `list.index` ...
Google Application Engine slow in case of Python
2,984,444
3
2010-06-06T14:06:39Z
2,984,506
8
2010-06-06T14:21:45Z
[ "python", "google-app-engine" ]
I am reading a "table" in Python in GAE that has 1000 rows and the program stops because the time limit is reached. (So it takes at least 20 seconds.)( Is that possible that GAE is that slow? Is there a way to fix that? Is this because I use free service and I do not pay for it? Thank you. The code itself is this: `...
GAE is slow when used inefficiently. Like any framework, sometimes you have to know a little bit about how it works in order to efficiently use it. Luckily, I think there is an easy improvement that will help your code a lot. It is faster to use `fetch()` explicitly instead of using the iterator. The iterator causes e...
Check if file has a CSV format with Python
2,984,888
10
2010-06-06T16:16:50Z
2,985,005
19
2010-06-06T16:55:05Z
[ "python", "csv" ]
Could someone provide an effective way to check if a file has CSV format using Python ?
You could try something like the following, but just because you get a dialect back from [`csv.Sniffer`](http://docs.python.org/library/csv.html#csv.Sniffer) really won't be sufficient for guaranteeing you have a valid CSV document. ``` csv_fileh = open(somefile, 'rb') try: dialect = csv.Sniffer().sniff(csv_fileh....
Decorators vs. classes in python web development
2,985,014
10
2010-06-06T16:56:56Z
2,985,268
10
2010-06-06T18:05:56Z
[ "python", "django", "pylons", "tornado", "bottle" ]
I've noticed three main ways Python web frameworks deal request handing: decorators, controller classes with methods for individual requests, and request classes with methods for GET/POST. I'm curious about the virtues of these three approaches. Are there major advantages or disadvantages to any of these approaches? T...
There's actually a reason for each of the three methods you listed, specific to each project. * Bottle tries to keep things as simple/straightforward as possible for the programmer. With decorators for routes you don't have to worry about the developer understanding OOP. * Pylons development goal is to make ...
Order of execution and style of coding in Python
2,985,047
11
2010-06-06T17:09:07Z
2,985,085
14
2010-06-06T17:17:13Z
[ "python" ]
I am new to Python so please don't flame me if the question is too basic :) I have read that Python is executed from top - to - bottom. If this is the case, why do programs go like this: ``` def func2(): pass def func1(): func2() def func(): func1() if __name__ == '__main__': func() ``` So from ...
Python is executed from top to bottom, but executing a "def" block doesn't immediately execute the contained code. Instead it creates a function object with the given name in the current scope. Consider a Python file much like your example: ``` def func2(): print "func2" def func1(): func2() def func(): ...
Order of execution and style of coding in Python
2,985,047
11
2010-06-06T17:09:07Z
2,985,145
10
2010-06-06T17:32:49Z
[ "python" ]
I am new to Python so please don't flame me if the question is too basic :) I have read that Python is executed from top - to - bottom. If this is the case, why do programs go like this: ``` def func2(): pass def func1(): func2() def func(): func1() if __name__ == '__main__': func() ``` So from ...
The `def`s are just creating the functions. No code is executed, other than to parse the syntax and tie functions to those names. The `if` is the first place code is actually executed. If you put it first, and call a function before it is defined, the result is a NameError. Therefore, you need to put it after the func...
Moving to an arbitrary position in a file in Python
2,985,725
8
2010-06-06T20:08:39Z
2,985,778
15
2010-06-06T20:24:19Z
[ "python", "file", "python-3.x" ]
Let's say that I routinely have to work with files with an unknown, but large, number of lines. Each line contains a set of integers (space, comma, semicolon, or some non-numeric character is the delimiter) in the closed interval [0, R], where R can be arbitrarily large. The number of integers on each line can be varia...
Python's `seek` goes to a *byte* offset in a file, not to a *line* offset, simply because that's the way modern operating systems and their filesystems work -- the OS/FS just don't record or remember "line offsets" in any way whatsoever, and there's no way for Python (or any other language) to just magically guess them...
Tips for making a fraction calculator code more optimized (faster and using less memory)
2,985,797
6
2010-06-06T20:30:49Z
2,985,805
9
2010-06-06T20:34:34Z
[ "python", "performance", "optimization" ]
Basicly, what I need for the program to do is to act a as simple fraction calculator (for addition, subtraction, multiplication and division) for the a single line of input, for example: -input: `1/7 + 3/5` -output: `26/35` My initial code: ``` import sys def euclid(numA, numB): while numB != 0: numR...
Probably the biggest improvement you could make would be to use Python (2.6)'s [`fractions`](http://docs.python.org/library/fractions.html) library: ``` >>> import fractions >>> fractions.Fraction(1,7) + fractions.Fraction("3/5") Fraction(26, 35) ```
python floating number
2,986,150
9
2010-06-06T22:22:33Z
2,986,161
12
2010-06-06T22:26:05Z
[ "python", "floating-point", "numerical", "floating-accuracy" ]
i am kind of confused why python add some additional decimal number in this case, please help to explain ``` >>> mylist = ["list item 1", 2, 3.14] >>> print mylist ['list item 1', 2, 3.1400000000000001] ```
Floating point numbers are an approximation, they cannot store decimal numbers exactly. Because they try to represent a very large range of numbers in only 64 bits, they must approximate to some extent. It is very important to be aware of this, because it results in some weird side-effects. For example, you might very...
Python: what modules have been imported in my process?
2,986,419
3
2010-06-06T23:53:16Z
2,986,426
11
2010-06-06T23:56:17Z
[ "python", "python-module" ]
How can I get a list of the modules that have been imported into my process?
`sys.modules.values()` ... if you really need the **names** of the modules, use sys.modules.keys() `dir()` is not what you want. ``` >>> import re >>> def foo(): ... import csv ... fubar = 0 ... print dir() ... >>> foo() ['csv', 'fubar'] # 're' is not in the current scope >>> ```
django app organization
2,986,659
5
2010-06-07T01:44:16Z
2,987,352
7
2010-06-07T05:53:31Z
[ "python", "django" ]
I have been reading some django tutorial and it seems like all the view functions have to go in a file called "views.py" and all the models go in "models.py". I fear that I might end up with a lot of view functions in my view.py file and the same is the case with models.py. Is my understanding of django apps correct? ...
First, large files are pretty common in python. Python is not java, which has one class per file, rather one module per file. Next, `views`, even as the standard used, is a *python module*. A module need not be a single file. It can be a directory containing many files, and `__init__.py` And then, `views.py` is only ...
Counting entries in a list of dictionaries: for loop vs. list comprehension with map(itemgetter)
2,986,929
4
2010-06-07T03:31:30Z
2,986,955
11
2010-06-07T03:40:19Z
[ "python", "dictionary", "map", "loops", "list-comprehension" ]
In a Python program I'm writing I've compared using a `for` loop and increment variables versus list comprehension with `map(itemgetter)` and `len()` when counting entries in dictionaries which are in a list. It takes the same time using a each method. Am I doing something wrong or is there a better approach? Here is ...
I think you're measuring incorrectly by swamping the code to be measured in a lot of overhead (running at top module level instead of in a function, doing output). Putting the two snippets into functions named `forloop` and `withmap`, and adding a `* 100` to the list's definition (after the closing `]`) to make the mea...
How to obtain ports that a process in listening on?
2,987,168
11
2010-06-07T05:04:02Z
3,015,077
18
2010-06-10T14:00:20Z
[ "python", "linux", "sockets", "port" ]
How do I get the ports that a process is listening on using python? The pid of the process is known.
There are two parts to my answer: **1. Getting the information in the shell** For the first part, `netstat` would work, but I prefer using `lsof`, since it can be used to extract a more informative and concise list. The exact options to use may vary based on your OS, kernel and compilation options, but I believe you ...
How to obtain ports that a process in listening on?
2,987,168
11
2010-06-07T05:04:02Z
6,244,347
8
2011-06-05T16:49:59Z
[ "python", "linux", "sockets", "port" ]
How do I get the ports that a process is listening on using python? The pid of the process is known.
You can use [psutil](https://github.com/giampaolo/psutil): ``` >>> import psutil >>> p = psutil.Process(2549) >>> p.name() 'proftpd: (accepting connections)' >>> p.connections() [connection(fd=1, family=10, type=1, local_address=('::', 21), remote_address=(), status='LISTEN')] ``` ...To filter for listening sockets: ...
Any high-level languages that can use c libraries?
2,987,524
3
2010-06-07T06:42:36Z
2,987,542
9
2010-06-07T06:47:08Z
[ "c++", "python", "c" ]
I know this question could be in vain, but it's just out of curiosity, and I'm still much a newb^^ Anyways I've been loving python for some time while learning it. My problem is obviously speed issues. I'd like to get into indie game creation, and for the short future, 2d and pygame will work. But I'd eventually lik...
Python can call functions in dynamically loaded C libraries (.so in unix, .dll in Windows) using the ctypes module. There is also [cython](http://www.cython.org/) - a variation of python that compiles to C and can call C libraries directly. You can mix modules written in pure Python and cython. You may also want to l...
How is the 'is' keyword implemented in Python?
2,987,958
47
2010-06-07T08:17:54Z
2,987,975
89
2010-06-07T08:21:44Z
[ "python", "python-datamodel", "builtins" ]
... the `is` keyword that can be used for equality in strings. ``` >>> s = 'str' >>> s is 'str' True >>> s is 'st' False ``` I tried both `__is__()` and `__eq__()` but they didn't work. ``` >>> class MyString: ... def __init__(self): ... self.s = 'string' ... def __is__(self, s): ... return self.s == s ....
Testing strings with `is` only works when the strings are interned. Unless you really know what you're doing and explicitly [interned](http://en.wikipedia.org/wiki/String_interning) the strings you should *never* use `is` on strings. `is` tests for *identity*, not *equality*. That means Python simply compares the memo...
How is the 'is' keyword implemented in Python?
2,987,958
47
2010-06-07T08:17:54Z
2,987,999
11
2010-06-07T08:27:04Z
[ "python", "python-datamodel", "builtins" ]
... the `is` keyword that can be used for equality in strings. ``` >>> s = 'str' >>> s is 'str' True >>> s is 'st' False ``` I tried both `__is__()` and `__eq__()` but they didn't work. ``` >>> class MyString: ... def __init__(self): ... self.s = 'string' ... def __is__(self, s): ... return self.s == s ....
The `is` operator is equivalent to comparing `id(x)` values. `id` is currently implemented to use pointers as the comparison. So you can't overload `is` itself, and AFAIK you can't overload `id` either. So, you can't. Unusual in python, but there it is.
How is the 'is' keyword implemented in Python?
2,987,958
47
2010-06-07T08:17:54Z
2,988,000
8
2010-06-07T08:27:41Z
[ "python", "python-datamodel", "builtins" ]
... the `is` keyword that can be used for equality in strings. ``` >>> s = 'str' >>> s is 'str' True >>> s is 'st' False ``` I tried both `__is__()` and `__eq__()` but they didn't work. ``` >>> class MyString: ... def __init__(self): ... self.s = 'string' ... def __is__(self, s): ... return self.s == s ....
The Python `is` keyword tests object identity. You should NOT use it to test for string equality. It may seem to work frequently because Python implementations, like those of many very high level languages, performs "interning" of strings. That is to say that string literals and values are internally kept in a hashed l...
Parallelism in Python
2,987,980
18
2010-06-07T08:22:40Z
2,988,030
11
2010-06-07T08:35:19Z
[ "python", "multithreading", "parallel-processing", "message-passing" ]
What are the options for achieving parallelism in Python? I want to perform a bunch of CPU bound calculations over some very large rasters, and would like to parallelise them. Coming from a C background, I am familiar with three approaches to parallelism: 1. Message passing processes, possibly distributed across a clu...
Generally, you describe a CPU bound calculation. This is not Python's forte. Neither, historically, is multiprocessing. Threading in the mainstream Python interpreter has been ruled by a dreaded global lock. The new [multiprocessing](http://docs.python.org/library/multiprocessing.html) API works around that and gives ...
How to read a single character at a time from a file in Python?
2,988,211
30
2010-06-07T09:11:31Z
2,988,275
8
2010-06-07T09:19:30Z
[ "python", "file-io", "character" ]
Can anyone tell me how can I do this?
Python itself can help you with this, in interactive mode: ``` >>> help(file.read) Help on method_descriptor: read(...) read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data t...
How to read a single character at a time from a file in Python?
2,988,211
30
2010-06-07T09:11:31Z
2,988,278
45
2010-06-07T09:19:44Z
[ "python", "file-io", "character" ]
Can anyone tell me how can I do this?
``` with open(filename) as f: while True: c = f.read(1) if not c: print "End of file" break print "Read a character:", c ```
How to read a single character at a time from a file in Python?
2,988,211
30
2010-06-07T09:11:31Z
20,775,396
9
2013-12-25T17:52:42Z
[ "python", "file-io", "character" ]
Can anyone tell me how can I do this?
first open a file: ``` with open("filename") as fileobj: for word in fileobj: for ch in word: print ch ```
Overriding initial value in ModelForm
2,988,548
15
2010-06-07T10:04:35Z
2,988,630
34
2010-06-07T10:18:50Z
[ "python", "django", "django-forms" ]
in my Django (1.2) project, I want to prepopulate a field in a modelform, but my new value is ignored. This is the snippet: ``` class ArtefactForm(ModelForm): material = CharField(widget=AutoCompleteWidget('material', force_selection=False)) def __init__(self, *args, **kwargs): super(ArtefactForm, sel...
Try this: ``` def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) initial['material'] = 'Test' kwargs['initial'] = initial super(ArtefactForm, self).__init__(*args, **kwargs) ```
Overriding initial value in ModelForm
2,988,548
15
2010-06-07T10:04:35Z
27,212,260
8
2014-11-30T10:30:11Z
[ "python", "django", "django-forms" ]
in my Django (1.2) project, I want to prepopulate a field in a modelform, but my new value is ignored. This is the snippet: ``` class ArtefactForm(ModelForm): material = CharField(widget=AutoCompleteWidget('material', force_selection=False)) def __init__(self, *args, **kwargs): super(ArtefactForm, sel...
Old question but adding a descriptive answer as I believe it would be helpful for some new developer. > I also tried with `self`.`base_fields`, but no effect: there is always the database-value displaying in the form. Any ideas? If a form is "initialized" form, either:- 1. using `initial` argument (eg. `YourModelFro...
OverflowError: math range error
2,988,634
6
2010-06-07T10:19:48Z
2,988,641
16
2010-06-07T10:20:57Z
[ "python", "math" ]
``` >>> import math >>> math.pow(2, 3000) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: math range error ``` How can I fix it? thanx.
Use the built-in operator. ``` 2**3000 ```
How to show why "try" failed in python
2,988,751
8
2010-06-07T10:39:07Z
2,988,764
9
2010-06-07T10:41:21Z
[ "python", "error-handling" ]
is there anyway to show why a "try" failed, and skipped to "except", without writing out all the possible errors by hand, and without ending the program? example: ``` try: 1/0 except: someway to show "Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 1/0 ZeroD...
Try: ``` >>> try: ... 1/0 ... except Exception, e: ... print e ... integer division or modulo by zero ``` There are other syntactical variants, e.g.: ``` >>> try: ... 1/0 ... except Exception as e: ... print e ... integer division or modulo by zero ``` More information can be found in the [errors tu...
How to show why "try" failed in python
2,988,751
8
2010-06-07T10:39:07Z
2,988,948
7
2010-06-07T11:14:12Z
[ "python", "error-handling" ]
is there anyway to show why a "try" failed, and skipped to "except", without writing out all the possible errors by hand, and without ending the program? example: ``` try: 1/0 except: someway to show "Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 1/0 ZeroD...
I often use `traceback` to log such exception to log or show on stderr: ``` import traceback import sys try: print 1/0 except Exception: s = traceback.format_exc() serr = "there were errors:\n%s\n" % (s) sys.stderr.write(serr) ``` Output will show info about line is source where exception occured: `...
How to TRUNCATE TABLE using Django's ORM?
2,988,997
31
2010-06-07T11:24:56Z
2,989,049
40
2010-06-07T11:34:04Z
[ "python", "sql", "django" ]
To empty a database table, I use this SQL Query: ``` TRUNCATE TABLE `books` ``` How to I truncate a table using Django's models and ORM? I've tried this, but it doesn't work: ``` Book.objects.truncate() ```
The closest you'll get with the ORM is `Book.objects.all().delete()`. There are differences though: truncate will likely be faster, but the ORM will also chase down foreign key references and delete objects in other tables.
How to TRUNCATE TABLE using Django's ORM?
2,988,997
31
2010-06-07T11:24:56Z
2,989,122
24
2010-06-07T11:46:48Z
[ "python", "sql", "django" ]
To empty a database table, I use this SQL Query: ``` TRUNCATE TABLE `books` ``` How to I truncate a table using Django's models and ORM? I've tried this, but it doesn't work: ``` Book.objects.truncate() ```
You can do this in a fast and lightweight way, but not using Django's ORM. You may execute raw SQL with a Django connection cursor: ``` from django.db import connection cursor = connection.cursor() cursor.execute("TRUNCATE TABLE `books`") ```
How to TRUNCATE TABLE using Django's ORM?
2,988,997
31
2010-06-07T11:24:56Z
7,911,423
18
2011-10-27T03:26:13Z
[ "python", "sql", "django" ]
To empty a database table, I use this SQL Query: ``` TRUNCATE TABLE `books` ``` How to I truncate a table using Django's models and ORM? I've tried this, but it doesn't work: ``` Book.objects.truncate() ```
You can use the model's \_meta property to fill in the database table name: ``` from django.db import connection cursor = connection.cursor() cursor.execute('TRUNCATE TABLE "{0}"'.format(MyModel._meta.db_table)) ``` Note: This does not work for inherited models as they span multiple tables!
How to TRUNCATE TABLE using Django's ORM?
2,988,997
31
2010-06-07T11:24:56Z
15,680,612
8
2013-03-28T11:29:10Z
[ "python", "sql", "django" ]
To empty a database table, I use this SQL Query: ``` TRUNCATE TABLE `books` ``` How to I truncate a table using Django's models and ORM? I've tried this, but it doesn't work: ``` Book.objects.truncate() ```
In addition to Ned Batchelder's answer and refering to Bernhard Kircher's comment: In my case I needed to empty a very large database using the webapp: ``` Book.objects.all().delete() ``` Which, in the development SQLlite environment, returned: ``` too many SQL variables ``` So I added a little workaround. It mayb...
How can I find all the possible combinations of a list of lists (in Python)?
2,990,003
15
2010-06-07T13:43:31Z
2,990,027
14
2010-06-07T13:48:17Z
[ "python" ]
I have the following structure in Python: ``` letters = [['a', 'b', 'c'], ['p', 'q', 'r', 's'], ['j', 'k', 'l']] ``` I would like to find all the possible combinations of letters in the order that they currently exist. For the example above this would be: ``` apj apk apl aqj aqk aql ... csk csl ``` This seems like ...
In Python 2.6 or newer you can use [**`itertools.product`**](http://docs.python.org/library/itertools.html#itertools.product): ``` >>> import itertools >>> map(''.join, itertools.product(*letters)) apj apk apl aqj aqk aql ...etc... csk csl ```
How to define a new type (class) in Python using C API?
2,990,487
8
2010-06-07T14:46:35Z
2,990,560
14
2010-06-07T14:57:47Z
[ "python", "c", "class" ]
I am trying to use the Python C API to define a new class inside a module that would expose certain functionality written in C to Python code. I specifically want to have it in the form of a class and not a set of module functions. However, I can't find anything regarding this particular task in the official documenta...
The [Python/C API Reference Manual](http://docs.python.org/c-api/) explains it, in particular [Defining New Types](http://docs.python.org/extending/newtypes.html).
How to define a new type (class) in Python using C API?
2,990,487
8
2010-06-07T14:46:35Z
2,990,563
7
2010-06-07T14:58:06Z
[ "python", "c", "class" ]
I am trying to use the Python C API to define a new class inside a module that would expose certain functionality written in C to Python code. I specifically want to have it in the form of a class and not a set of module functions. However, I can't find anything regarding this particular task in the official documenta...
[This part](http://docs.python.org/c-api/typeobj.html) of the docs (and surrounding ones) should give you most of the info you need. The [xxsubtype.c](http://svn.python.org/view/python/trunk/Modules/xxsubtype.c?revision=81029&view=markup) sources provide one example module that defines a new class (as a subclass of `li...
How to test a regex password in Python?
2,990,654
10
2010-06-07T15:10:30Z
2,990,682
17
2010-06-07T15:13:41Z
[ "python", "regex", "passwords" ]
Using a regex in Python, how can I verify that a user's password is: * At least 8 characters * Must be restricted to, though does not specifically require any of: + uppercase letters: A-Z + lowercase letters: a-z + numbers: 0-9 + any of the special characters: @#$%^&+= Note, all the letter/number/special char...
``` import re password = raw_input("Enter string to test: ") if re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', password): # match else: # no match ``` The `{8,}` means "at least 8". The `.match` function requires the entire string to match the entire regex, not just a portion.
python str.strip strange behavior
2,990,973
3
2010-06-07T15:50:05Z
2,990,997
7
2010-06-07T15:52:33Z
[ "python", "string" ]
``` >>> t1 = "abcd.org.gz" >>> t1 'abcd.org.gz' >>> t1.strip("g") 'abcd.org.gz' >>> t1.strip("gz") 'abcd.org.' >>> t1.strip(".gz") 'abcd.or' ``` Why does the 'g' of '.org' is gone?
`strip` removes any of the characters `.`, `g` and `z` from the beginning and end of the string.
python str.strip strange behavior
2,990,973
3
2010-06-07T15:50:05Z
2,991,003
8
2010-06-07T15:52:53Z
[ "python", "string" ]
``` >>> t1 = "abcd.org.gz" >>> t1 'abcd.org.gz' >>> t1.strip("g") 'abcd.org.gz' >>> t1.strip("gz") 'abcd.org.' >>> t1.strip(".gz") 'abcd.or' ``` Why does the 'g' of '.org' is gone?
[`x.strip(y)` will remove all characters that appear in `y` from the beginning and end of `x`.](http://docs.python.org/library/stdtypes.html#str.strip) That means ``` 'foo42'.strip('1234567890') == 'foo' ``` becuase `'4'` and `'2'` both appear in `'1234567890'`. --- Use [`os.path.splitext`](http://docs.python.org/...
How to auto insert the current user when creating an object in django admin?
2,991,365
13
2010-06-07T16:40:04Z
2,992,150
21
2010-06-07T18:39:09Z
[ "python", "django", "django-admin" ]
I have a database of articles with a ``` submitter = models.ForeignKey(User, editable=False) ``` Where `User` is imported as follows: ``` from django.contrib.auth.models import User. ``` I would like to auto insert the current active user to the submitter field when a particular user submits the article. Anyone ha...
Just in case anyone is looking for an answer, here is the solution i've found here: <http://demongin.org/blog/806/> To summarize: He had an Essay table as follows: ``` from django.contrib.auth.models import User class Essay(models.Model): title = models.CharField(max_length=666) body = models.TextField() ...
Python + PostgreSQL + strange ascii = UTF8 encoding error
2,991,660
5
2010-06-07T17:22:16Z
2,994,258
11
2010-06-08T01:30:50Z
[ "python", "postgresql", "unicode", "encoding", "utf-8" ]
I have ascii strings which contain the character `"\x80"` to represent the euro symbol: ``` >>> print "\x80" € ``` When inserting string data containing this character into my database, I get: ``` psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0x80 HINT: This error can also happen if the byte sequ...
The question starts with a false premise: > I have ascii strings which contain the character "\x80" to represent the euro symbol. ASCII characters are in the range "\x00" to "\x7F" inclusive. **The previously-accepted now-deleted answer operated under two gross misapprehensions** (1) that locale == encoding (2) that...
Calculating the null space of a matrix
2,992,947
9
2010-06-07T20:34:19Z
2,993,030
9
2010-06-07T20:47:12Z
[ "python", "math", "linear-algebra", "svd", "least-squares" ]
I'm attempting to solve a set of equations of the form Ax = 0. A is known 6x6 matrix and I've written the below code using SVD to get the vector x which works to a certain extent. The answer is approximately correct but not good enough to be useful to me, how can I improve the precision of the calculation? Lowering eps...
`A` is full rank --- so `x` is **0** Since it looks like you need a least-squares solution, i.e. `min ||A*x|| s.t. ||x|| = 1`, do the SVD such that `[U S V] = svd(A)` and the last column of `V` (assuming that the columns are sorted in order of decreasing singular values) is `x`. I.e., ``` U = -0.23024 -0.2...
log2 in python math module
2,993,214
31
2010-06-07T21:13:00Z
2,993,288
39
2010-06-07T21:24:31Z
[ "python", "math" ]
why doesn't it exist? ``` import math [x for x in dir(math) if 'log' in x] >>> ['log', 'log10', 'log1p'] ``` I know I can do log(x,2), but log2 is really common, so I'm kind of baffled. Oh, it looks like it's only defined in C99, not C90, I guess that answers my question. Still seems kind of silly.
I think you've answered your own question. :-) There's no `log2(x)` because you can do `log(x, 2)`. As The Zen of Python ([PEP 20](http://www.python.org/dev/peps/pep-0020/)) says, "There should be one-- and preferably only one --obvious way to do it." That said, `log2` was considered in [Issue3366](http://bugs.python....
Gstreamer of python's gst.LinkError problem
2,993,777
10
2010-06-07T23:03:00Z
3,041,321
20
2010-06-14T22:14:29Z
[ "python", "gstreamer" ]
I am wiring a gstreamer application with Python. And I get a LinkError with following code: ``` import pygst pygst.require('0.10') import gst import pygtk pygtk.require('2.0') import gtk # this is very important, without this, callbacks from gstreamer thread # will messed our program up gtk.gdk.threads_init() def m...
your problem is here: ``` gst.element_link_many(filesrc, decode, convert, sink) ``` the reason is that not all elements have simple, static inputs and outputs. at this point in your program, *your decodebin does not have any source pads* (that is: no outputs). a pad is like a nipple - it's an input / output to an el...
deleting all the file of certain size
2,994,035
3
2010-06-08T00:10:03Z
2,994,050
18
2010-06-08T00:15:26Z
[ "python", "perl", "shell" ]
i have bunch of log files and I have to delete the files of some small sizes, which were erroneous files that got created. ( 63bytes ). I have to copy only those files which have data in it .
Shell (linux); ``` find . -type f -size 63c -delete ``` Will traverse subdirectories (unless you tell it otherwise)
python distutils does not include data_files
2,994,396
19
2010-06-08T02:16:26Z
2,998,311
21
2010-06-08T14:37:00Z
[ "python", "installation", "distutils" ]
I am new to distutils.. I am trying to include few data files along with the package.. here is my code.. ``` from distutils.core import setup setup(name='Scrapper', version='1.0', description='Scrapper', packages=['app', 'db', 'model', 'util'], data_files=[('app', ['app/scrapper.db'])] ...
You probably need to add a `MANIFEST.in` file containing `"include app/scrapper.db"`. It's a bug in distutils that makes this necessary: anything in `data_files` or `package_data` should be included in the generated `MANIFEST` automatically. But in Python 2.6 and earlier, it is not, so you have to include it in `MANIF...
GEdit/Python execution plugin?
2,995,041
5
2010-06-08T05:51:11Z
3,766,142
14
2010-09-22T03:37:00Z
[ "python", "plugins", "gedit" ]
I'm just starting out learning python with GEdit plus various plugins as my IDE. Visual Studio/F# has a feature which permits the highlighting on a piece of text in the code window which then, on a keypress, gets executed in the F# console. Is there a similar facility/plugin which would enable this sort of behaviour ...
Yes, you use "external tools plugin" * <http://live.gnome.org/Gedit/ToolLauncherPlugin> As an example, 1. Edit > Preferences 2. Plugins 3. Tick "External Tools" 4. Close the Preferences Window 5. Tools > Manage External Tools 6. Click the "Add new too" icon in the bottom left 7. Name it "Execute Highlighted Python C...
Using subprocess wait() and poll()
2,995,983
11
2010-06-08T09:03:51Z
2,996,026
9
2010-06-08T09:12:11Z
[ "python", "subprocess" ]
I am trying to write a small app that uses the `subprocess` module. My program calls an external Bash command that takes some time to process. During this time, I would like to show the user a series of messages like this: > Processing. Please wait... > The output is foo() How can I do this using `Popen.wait()` or...
Both [`wait()`](https://docs.python.org/3.4/library/subprocess.html#subprocess.Popen.wait) (with `timeout` specified) and [`poll()`](https://docs.python.org/3.4/library/subprocess.html#subprocess.Popen.poll) return `None` if the process has not yet finished, and something different if the process *has* finished (I thin...
Using subprocess wait() and poll()
2,995,983
11
2010-06-08T09:03:51Z
25,980,490
16
2014-09-22T18:09:19Z
[ "python", "subprocess" ]
I am trying to write a small app that uses the `subprocess` module. My program calls an external Bash command that takes some time to process. During this time, I would like to show the user a series of messages like this: > Processing. Please wait... > The output is foo() How can I do this using `Popen.wait()` or...
@extraneon's answer is a little backwards. Both `wait()` and `poll()` return the process's exit code if the process has finished. The `poll()` method will return `None` if the process is still running and the `wait()` method will block until the process exits: Check out the following page: <https://docs.python.org/3.4...
What is the difference between a module and a script in Python?
2,996,110
9
2010-06-08T09:27:53Z
2,996,170
24
2010-06-08T09:37:39Z
[ "python", "scripting", "module" ]
Think the title summarizes the question :-)
A script is generally a directly executable piece of code, run by itself. A module is generally a library, imported by other pieces of code. Note that there's no internal distinction -- both are executable and importable, although library code often won't do anything (or will just run its unit tests) when executed dir...