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
Java equivalent of a Python functionality -> set(string)
1,368,181
2
2009-09-02T14:51:34Z
1,368,214
7
2009-09-02T14:54:58Z
[ "java", "python", "set" ]
I want to mimic a Python functionality in Java. In Python if I want unique characters in a string I can do just, ``` text = "i am a string" print set(text) # o/p is set(['a', ' ', 'g', 'i', 'm', 'n', 's', 'r', 't']) ``` How can I do this in Java trivially or directly?
``` String str = "i am a string"; System.out.println(new HashSet<String>(Arrays.asList(str.split("")))); ``` EDIT: For those who object that they aren't exactly equivalent because str.split will include an empty string in the set, we can do it even more verbose: ``` String str = "i am a string"; Set<String> set = new...
How do I unit test Django Views?
1,368,255
8
2009-09-02T15:02:23Z
1,368,389
9
2009-09-02T15:26:45Z
[ "python", "django", "unit-testing", "views" ]
I want to begin integrating unit tests into my Django projects and I've discovered unit testing a view to be tricky because of the way Django implements views with functions. For example, each function is a view/page in Django if the function has a URL. How do I unit test Django views?
I'm not sure how testing a view is tricky. You just use the [test client](https://docs.djangoproject.com/en/dev/topics/testing/tools/#the-test-client). Code coverage is easy. You reason how how a URL request maps to a code path and make the appropriate URL requests. You can, if you want, call the view functions "man...
python file-like buffer object
1,368,261
12
2009-09-02T15:03:03Z
1,368,272
18
2009-09-02T15:04:48Z
[ "python", "io", "buffer" ]
I've written a buffer class that provides a File-like interface with `read`, `write`, `seek`, `tell`, `flush` methods to a simple string in memory. Of course it is incomplete (e.g. I didn't write `readline`). It's purpose is to be filled by a background thread from some external data source, but let a user treat it lik...
You can use the standard Python modules [`StringIO`](http://docs.python.org/2/library/stringio.html) or [`cStringIO`](http://docs.python.org/2/library/stringio.html#module-cStringIO) to obtain an in-memory buffer which implements the [file interface](http://docs.python.org/2/library/stdtypes.html#bltin-file-objects). ...
How does Django determine if an uploaded image is valid?
1,368,724
3
2009-09-02T16:21:21Z
1,368,786
11
2009-09-02T16:30:35Z
[ "python", "django", "python-imaging-library" ]
I'm trying to add images to my models in my Django app. models.py ``` class ImageMain(models.Model): """This is the Main Image of the product""" product = models.ForeignKey(Product) photo = models.ImageField(upload_to='products') ``` In development mode, every time I try to upload the image via Django admin,...
According to Django's source code. Those three lines are responsible for verifying images: ``` from PIL import Image trial_image = Image.open(file) trial_image.verify() ``` The image type could be unsupported by PIL. Check the list of supported formats [here](http://www.pythonware.com/library/pil/handbook/index.htm)
Default encoding of exception messages
1,369,089
6
2009-09-02T17:27:16Z
1,369,335
8
2009-09-02T18:19:54Z
[ "python", "exception", "encoding", "python-2.x" ]
The following code examines the behaviour of the `float()` method when fed a non-ascii symbol: ``` import sys try: float(u'\xbd') except ValueError as e: print sys.getdefaultencoding() # in my system, this is 'ascii' print e[0].decode('latin-1') # u'invalid literal for float(): ' followed by the 1/2 (one half) ...
e[0] isn't encoded with latin-1; it just so happens that the byte \xbd, when decoded as latin-1, is the character U+00BD. The conversion occurs in `Objects/floatobject.c`. First, the unicode string must be converted to a byte string. This is performed using `PyUnicode_EncodeDecimal()`: ``` if (PyUnicode_EncodeDecima...
Django admin, custom error message?
1,369,548
7
2009-09-02T19:04:23Z
1,369,708
18
2009-09-02T19:42:28Z
[ "python", "django", "django-admin" ]
I would like to know how to show an error message in the Django admin. I have a private user section on my site where the user can create requests using "points". A request takes 1 or 2 points from the user's account (depending on the two type of request), so if the account has 0 points the user cant make any requests...
One way to do that is by overriding the ModelForm for the admin page. That allows you to write custom validation methods and return errors of your choosing very cleanly. Like this in admin.py: ``` from django.contrib import admin from models import * from django import forms class MyForm(forms.ModelForm): class M...
Why is my "exploded" Python code actually running faster?
1,369,697
3
2009-09-02T19:40:11Z
1,369,733
7
2009-09-02T19:46:53Z
[ "python", "optimization" ]
I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners. ``` for line in lines: numbers.append(eval(line.strip().split()[0])) ``` So I wrote the same thing with painfully explicit assignments and ran them against...
Frankly speaking, the first version, where everything is in one line, is a pain to read. The second one is maybe a little too verbose (something in the middle would be appreciated) but it is definitely better. I would not care too much about micro optimizations because of Python internals, and focus only on readable...
Why is my "exploded" Python code actually running faster?
1,369,697
3
2009-09-02T19:40:11Z
1,369,774
15
2009-09-02T19:52:16Z
[ "python", "optimization" ]
I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners. ``` for line in lines: numbers.append(eval(line.strip().split()[0])) ``` So I wrote the same thing with painfully explicit assignments and ran them against...
Your code isn't exploded in the same order. The compact version goes: ``` A > B > C > D > E ``` while your exploded version goes ``` B > C > A > D > E ``` The effect is that strip() is being deferred 2 steps down, which may affect performance depending on what the input is.
show *only* docstring in Sphinx documentation
1,370,283
9
2009-09-02T21:39:09Z
1,384,673
14
2009-09-06T01:37:46Z
[ "python", "documentation", "python-sphinx" ]
Sphinx has a feature called `automethod` that extracts the documentation from a method's docstring and embeds that into the documentation. But it not only embeds the docstring, but also the method signature (name + arguments). How do I embed *only* the docstring (excluding the method signature)? ref: <http://sphinx.po...
I think what you're looking for is: ``` from sphinx.ext import autodoc class DocsonlyMethodDocumenter(autodoc.MethodDocumenter): def format_args(self): return None autodoc.add_documenter(DocsonlyMethodDocumenter) ``` per [the current sources](http://bitbucket.org/birkenfeld/sphinx/src/tip/sphinx/ext/autodoc.p...
What is this piece of Python code doing?
1,370,604
8
2009-09-02T23:03:11Z
1,370,624
16
2009-09-02T23:06:50Z
[ "python", "math", "syntax" ]
This following is a snippet of Python code I found that solves a mathematical problem. What exactly is it doing? I wasn't too sure what to Google for. ``` x, y = x + 3 * y, 4 * x + 1 * y ``` Is this a special Python syntax?
``` x, y = x + 3 * y, 4 * x + 1 * y ``` is the equivalent of: ``` x = x + 3 * y y = 4 * x + 1 * y ``` **EXCEPT** that it uses the original values for x and y in both calculations - because the new values for x and y aren't assigned until both calculations are complete. The generic form is: ``` x,y = a,b ``` where...
What is this piece of Python code doing?
1,370,604
8
2009-09-02T23:03:11Z
1,370,631
12
2009-09-02T23:09:14Z
[ "python", "math", "syntax" ]
This following is a snippet of Python code I found that solves a mathematical problem. What exactly is it doing? I wasn't too sure what to Google for. ``` x, y = x + 3 * y, 4 * x + 1 * y ``` Is this a special Python syntax?
It's an assignment to a [tuple](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences), also called *sequence unpacking*. Probably it's clearer when you add parenthesis around the tuples: ``` (x, y) = (x + 3 * y, 4 * x + 1 * y) ``` The value `x + 3 * y` is assigned to `x` and the value `4 * x + 1 *...
group by year, month, day in a sqlalchemy
1,370,997
9
2009-09-03T01:19:10Z
1,371,029
22
2009-09-03T01:34:25Z
[ "python", "sqlalchemy" ]
I want "DBSession.query(Article).group\_by(Article.created.month).all()" But this query can't using How do I do this using SQLAlchemy?
assuming you db engine actually supports functions like `MONTH()`, you can try ``` import sqlalchemy as sa DBSession.query(Article).group_by( sa.func.year(Article.created), sa.func.month(Article.created)).all() ``` else you can group in python like ``` from itertools import groupby def grouper( item ): return ...
group by year, month, day in a sqlalchemy
1,370,997
9
2009-09-03T01:19:10Z
3,795,778
9
2010-09-25T22:05:29Z
[ "python", "sqlalchemy" ]
I want "DBSession.query(Article).group\_by(Article.created.month).all()" But this query can't using How do I do this using SQLAlchemy?
**THC4k answer works** but I just want to add that `query_result` need to be already **sorted** to get `itertools.groupby` working the way you want. ``` query_result = DBSession.query(Article).order_by(Article.created).all() ``` Here is the explanation in the [itertools.groupby docs](http://docs.python.org/library/it...
Django - flush response?
1,371,020
6
2009-09-03T01:29:31Z
1,371,061
8
2009-09-03T01:50:23Z
[ "python", "django" ]
I am sending an AJAX request to a Django view that can potentially take a lot of time. It goes through some well-defined steps, however, so I would like to print status indicators to the user letting it know when it is finished doing a certain thing and has moved on to the next. If I was using PHP it might look like t...
Most webservers (eg. FCGI/SCGI) do their own buffering, HTTP clients do their own, and so on. It's very difficult to actually get data flushed out in this way and for the client to actually receive it, because it's not a typical operation. The closest to what you're trying to do would be to pass an iterator to HttpRes...
Weird python behaviour on machine with ARM CPU
1,371,228
10
2009-09-03T02:59:57Z
1,371,551
8
2009-09-03T05:26:21Z
[ "python", "floating-point", "arm" ]
What could possibly cause this weird python behaviour? ``` Python 2.6.2 (r262:71600, May 31 2009, 03:55:41) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> .1 1251938906.2350719 >>> .1 0.23507189750671387 >>> .1 0.0 >>> .1 -1073741823.0 >>> .1 -1073741823.0 >>> .1 -1073...
Maybe it's compiled for the wrong [VFP](http://en.wikipedia.org/wiki/ARM%5Farchitecture#VFP) version. Or your ARM has no VFP and needs to use software emulation instead, but the python binary tries to use hardware. --- **EDIT** Your DS-101j build on **FW IXP420 BB** cpu, which is **Intel XScale (armv5b)** ([link](h...
REST / JSON / XML-RPC / SOAP
1,371,312
4
2009-09-03T03:35:22Z
1,371,337
7
2009-09-03T03:43:39Z
[ "python", "android", "service" ]
Sorry for being the 100000th person to ask the same question. But I guess my case is slightly distinctive. The application is that we'd like to have an Android phone client on 3g and a light python web service server. The phone would do most of the work and do a lot of uploading, pictures, GPS, etc etc. The server ju...
REST mandates the general semantics and concepts. The transport and encodings are up to you. They were originally formulated on XML, but JSON is totally applicable. XML-RPC / SOAP are different mechanisms, but mostly the same ideas: how to map OO APIs on top of XML and HTTP. IMHO, they're disgusting from a design view...
Importing external module in IronPython
1,371,994
11
2009-09-03T07:50:17Z
1,372,777
7
2009-09-03T11:07:58Z
[ "python", "import", "ironpython" ]
I'm currently working on an application written in C#, which I'm embedding IronPython in. I generally have no problems about it, but there's one thing that I don't know how to deal with. I want to import an external module into the script. How can I do that? Simple `import ext_lib` doesn't work. Should I add a path to...
Chances are that your path is set up incorrectly. From [the IronPython FAQ](http://ironpython.codeplex.com/Wiki/View.aspx?title=FAQ): > ### How do I use CPython standard libraries? > > To tell IronPython where the Python standard library is, you can add the "lib" directory of CPython to IronPython's path. To do this, ...
Importing external module in IronPython
1,371,994
11
2009-09-03T07:50:17Z
1,379,797
18
2009-09-04T14:58:22Z
[ "python", "import", "ironpython" ]
I'm currently working on an application written in C#, which I'm embedding IronPython in. I generally have no problems about it, but there's one thing that I don't know how to deal with. I want to import an external module into the script. How can I do that? Simple `import ext_lib` doesn't work. Should I add a path to...
Before compiling a script with the PythonEngine, I add the script's directory to the engine's search path. This is what I do in the C# code: ``` string dir = Path.GetDirectoryName(scriptPath); ICollection<string> paths = engine.GetSearchPaths(); if (!String.IsNullOrWhitespace(dir)) { paths....
How do I create a variable number of variables in Python?
1,373,164
96
2009-09-03T12:37:48Z
1,373,185
92
2009-09-03T12:41:05Z
[ "python", "variable-variables" ]
How do I accomplish variable variables in Python? Here is an elaborative manual entry, for instance: *[Variable variables](http://us3.php.net/manual/en/language.variables.variable.php)* I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?
Use dictionaries to accomplish this. Dictionaries are stores of keys and values. ``` >>> dct = {'x': 1, 'y': 2, 'z': 3} >>> dct {'y': 2, 'x': 1, 'z': 3} >>> dct["y"] 2 ``` You can use variable key names to achieve the effect of variable variables without the security risk. ``` >>> x = "spam" >>> z = {x: "eggs"} >>> ...
How do I create a variable number of variables in Python?
1,373,164
96
2009-09-03T12:37:48Z
1,373,192
21
2009-09-03T12:42:00Z
[ "python", "variable-variables" ]
How do I accomplish variable variables in Python? Here is an elaborative manual entry, for instance: *[Variable variables](http://us3.php.net/manual/en/language.variables.variable.php)* I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?
Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing ``` $foo = "bar" $$foo = "baz" ``` you write ``` mydict = {} foo = "bar" mydict[foo] = "baz" ``` This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you...
How do I create a variable number of variables in Python?
1,373,164
96
2009-09-03T12:37:48Z
1,373,198
38
2009-09-03T12:43:26Z
[ "python", "variable-variables" ]
How do I accomplish variable variables in Python? Here is an elaborative manual entry, for instance: *[Variable variables](http://us3.php.net/manual/en/language.variables.variable.php)* I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?
Use the built-in [`getattr`](http://docs.python.org/library/functions.html#getattr) function to get an attribute on an object by name. Modify the name as needed. ``` obj.spam = 'eggs' name = 'spam' getattr(obj, name) # returns 'eggs' ```
How do I create a variable number of variables in Python?
1,373,164
96
2009-09-03T12:37:48Z
1,373,201
33
2009-09-03T12:43:49Z
[ "python", "variable-variables" ]
How do I accomplish variable variables in Python? Here is an elaborative manual entry, for instance: *[Variable variables](http://us3.php.net/manual/en/language.variables.variable.php)* I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?
It's not a good idea. If you are accessing a global variable you can use [globals()](http://docs.python.org/library/functions.html#globals). ``` >>> a = 10 >>> globals()['a'] 10 ``` If you want to access a variable in the local scope you can use [locals()](http://docs.python.org/library/functions.html#locals), but yo...
making python 2.6 exception backward compatible
1,373,255
7
2009-09-03T12:55:16Z
1,373,261
9
2009-09-03T12:56:38Z
[ "python", "exception", "syntax", "python-2.x" ]
I have the following python code: ``` try: pr.update() except ConfigurationException as e: returnString=e.line+' '+e.errormsg ``` This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use ...
This is backward compatible: ``` try: pr.update() except ConfigurationException, e: returnString=e.line+' '+e.errormsg ```
making python 2.6 exception backward compatible
1,373,255
7
2009-09-03T12:55:16Z
2,513,890
12
2010-03-25T08:12:15Z
[ "python", "exception", "syntax", "python-2.x" ]
I have the following python code: ``` try: pr.update() except ConfigurationException as e: returnString=e.line+' '+e.errormsg ``` This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use ...
This is both backward AND forward compatible: ``` import sys try: pr.update() except (ConfigurationException,): e = sys.exc_info()[1] returnString = "%s %s" % (e.line, e.errormsg) ``` This gets rid of the ambiguity problem in python 2.5 and earlier, while still not losing any of the advantages of the pyth...
File open: Is this bad Python style?
1,373,660
10
2009-09-03T14:17:26Z
1,373,713
29
2009-09-03T14:24:50Z
[ "python", "file", "file-io", "coding-style" ]
To read contents of a file: ``` data = open(filename, "r").read() ``` The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing. EDIT: This has actually bitten me in a pr...
Just for the record: This is only slightly longer, and closes the file immediately: ``` from __future__ import with_statement with open(filename, "r") as f: data = f.read() ```
How to add a namespace to an attribute in lxml
1,374,443
7
2009-09-03T16:17:51Z
1,374,757
14
2009-09-03T17:13:08Z
[ "python", "xml", "lxml", "scorm" ]
I'm trying to create an xml entry that looks like this using python and lxml: ``` <resource href="Unit 4.html" adlcp:scormtype="sco"> ``` I'm using python and lxml. I'm having trouble with the `adlcp:scormtype` attribute. I'm new to xml so please correct me if I'm wrong. `adlcp` is a namespace and `scormtype` is an a...
This is not a full reply but just a few pointers. adlcp is not the namespace it is a namespace prefix. The namespace is defined in the document by an attribute like `xmlns:adlcp="http://xxx/yy/zzz"` In lxml you always set an element/attribute name including the namespace e.g. `{http://xxx/yy/zzz}scormtype` instead of...
Find out how many times a regex matches in a string in Python
1,374,457
15
2009-09-03T16:20:44Z
1,374,471
22
2009-09-03T16:22:47Z
[ "python", "regex" ]
Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string `"It actually happened when it acted out of turn."` I want to know how many times `"t a"` appears in the string. In that string, `"t a"` appears twice. I want my function to tell me it appeared t...
``` import re len(re.findall(pattern, string_to_search)) ```
Find out how many times a regex matches in a string in Python
1,374,457
15
2009-09-03T16:20:44Z
1,374,516
7
2009-09-03T16:29:57Z
[ "python", "regex" ]
Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string `"It actually happened when it acted out of turn."` I want to know how many times `"t a"` appears in the string. In that string, `"t a"` appears twice. I want my function to tell me it appeared t...
I know this is a question about regex. I just thought I'd mention the [count](http://docs.python.org/library/stdtypes.html#str.count) method for future reference if someone wants a non-regex solution. ``` >>> s = "It actually happened when it acted out of turn." >>> s.count('t a') 2 ``` Which return the number of non...
Find out how many times a regex matches in a string in Python
1,374,457
15
2009-09-03T16:20:44Z
1,374,893
8
2009-09-03T17:43:59Z
[ "python", "regex" ]
Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string `"It actually happened when it acted out of turn."` I want to know how many times `"t a"` appears in the string. In that string, `"t a"` appears twice. I want my function to tell me it appeared t...
The existing solutions based on `findall` are fine for non-overlapping matches (and no doubt optimal except maybe for HUGE number of matches), although alternatives such as `sum(1 for m in re.finditer(thepattern, thestring))` (to avoid ever materializing the list when all you care about is the count) are also quite pos...
How to get the signed integer value of a long in python?
1,375,897
12
2009-09-03T20:54:38Z
1,375,939
12
2009-09-03T21:03:04Z
[ "python", "unsigned", "signed" ]
If lv stores a long value, and the machine is 32 bits, the following code: ``` iv = int(lv & 0xffffffff) ``` results an iv of type long, instead of the machine's int. How can I get the (signed) int value in this case?
You're working in a high-level scripting language; by nature, the native data types of the system you're running on aren't visible. You can't cast to a native signed int with code like this. If you know that you want the value converted to a 32-bit signed integer--regardless of the platform--you can just do the conver...
How to get the signed integer value of a long in python?
1,375,897
12
2009-09-03T20:54:38Z
9,351,268
13
2012-02-19T17:13:34Z
[ "python", "unsigned", "signed" ]
If lv stores a long value, and the machine is 32 bits, the following code: ``` iv = int(lv & 0xffffffff) ``` results an iv of type long, instead of the machine's int. How can I get the (signed) int value in this case?
``` import ctypes number = lv & 0xFFFFFFFF signed_number = ctypes.c_long(number).value ```
How to make a repeating generator in Python
1,376,438
12
2009-09-03T23:12:33Z
1,376,531
14
2009-09-03T23:40:37Z
[ "python" ]
How do you make a repeating generator, like xrange, in Python? For instance, if I do: ``` >>> m = xrange(5) >>> print list(m) >>> print list(m) ``` I get the same result both times — the numbers 0..4. However, if I try the same with yield: ``` >>> def myxrange(n): ... i = 0 ... while i < n: ... yield i ......
Not directly. Part of the flexibility that allows generators to be used for implementing co-routines, resource management, etc, is that they are always one-shot. Once run, a generator cannot be re-run. You would have to create a new generator object. However, you can create your own class which overrides `__iter__()`....
How to extract a string between 2 other strings in python?
1,376,640
16
2009-09-04T00:17:29Z
1,376,658
27
2009-09-04T00:23:53Z
[ "python", "string" ]
Like if I have a string like `str1 = "IWantToMasterPython"` If I want to extract `"Py"` from the above string. I write: ``` extractedString = foo("Master","thon") ``` I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like `<div class = "lyricbox"> ....lyrics goes h...
The solution is to use a regexp: ``` import re r = re.compile('Master(.*?)thon') m = r.search(str1) if m: lyrics = m.group(1) ```
How to extract a string between 2 other strings in python?
1,376,640
16
2009-09-04T00:17:29Z
1,376,661
8
2009-09-04T00:24:59Z
[ "python", "string" ]
Like if I have a string like `str1 = "IWantToMasterPython"` If I want to extract `"Py"` from the above string. I write: ``` extractedString = foo("Master","thon") ``` I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like `<div class = "lyricbox"> ....lyrics goes h...
``` def foo(s, leader, trailer): end_of_leader = s.index(leader) + len(leader) start_of_trailer = s.index(trailer, end_of_leader) return s[end_of_leader:start_of_trailer] ``` this raises ValueError if the leader is not present in string s, or the trailer is not present after that (you have not specified what beh...
How to extract a string between 2 other strings in python?
1,376,640
16
2009-09-04T00:17:29Z
1,380,182
10
2009-09-04T16:09:02Z
[ "python", "string" ]
Like if I have a string like `str1 = "IWantToMasterPython"` If I want to extract `"Py"` from the above string. I write: ``` extractedString = foo("Master","thon") ``` I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like `<div class = "lyricbox"> ....lyrics goes h...
BeautifulSoup is the easiest way to do what you want. It can be installed like: ``` sudo easy_install beautifulsoup ``` The sample code to do what you want is: ``` from BeautifulSoup import BeautifulSoup doc = ['<div class="lyricbox">Hey You</div>'] soup = BeautifulSoup(''.join(doc)) print soup.find('div', {'class'...
What is faster in Python, "while" or "for xrange"
1,377,429
4
2009-09-04T05:48:23Z
1,377,454
13
2009-09-04T05:57:32Z
[ "python", "micro-optimization" ]
We can do numeric iteration like: ``` for i in xrange(10): print i, ``` and in C-style: ``` i = 0 while i < 10: print i, i = i + 1 ``` Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version? PS. I'm from C++ planet and pretty new on Python one.
Who cares? Seriously. If you want to know, use timeit package (you can invoke it from command line with -m). But it doesn't matter at all, because the difference is negligible. And in general, Python is not a language that you choose if you want speed.
What is faster in Python, "while" or "for xrange"
1,377,429
4
2009-09-04T05:48:23Z
1,378,157
13
2009-09-04T09:26:46Z
[ "python", "micro-optimization" ]
We can do numeric iteration like: ``` for i in xrange(10): print i, ``` and in C-style: ``` i = 0 while i < 10: print i, i = i + 1 ``` Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version? PS. I'm from C++ planet and pretty new on Python one.
I am sure the `while` version is slower. Python will have to lookup the add operation for the integer object on each turn of the loop etc, it is not pure C just because it looks like it! And if you want a pythonic version of exactly the above, use: ``` print " ".join(str(i) for i in xrange(10)) ``` --- Edit: My tim...
Render HTML to PDF in Django site
1,377,446
85
2009-09-04T05:54:35Z
1,377,652
174
2009-09-04T07:12:50Z
[ "python", "html", "django", "pdf", "pdf-generation" ]
For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf. Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).
Try the solution from [Reportlab](http://www.reportlab.org/). Download it and install it as usual with python setup.py install You will also need to install the following modules: xhtml2pdf, html5lib, pypdf with easy\_install. Here is an usage example: **First define this function:** ``` import cStringIO as String...
Render HTML to PDF in Django site
1,377,446
85
2009-09-04T05:54:35Z
13,961,258
9
2012-12-19T21:11:38Z
[ "python", "html", "django", "pdf", "pdf-generation" ]
For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf. Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).
I just whipped this up for CBV. Not used in production but generates a PDF for me. Probably needs work for the error reporting side of things but does the trick so far. ``` import StringIO from cgi import escape from xhtml2pdf import pisa from django.http import HttpResponse from django.template.response import Templa...
Render HTML to PDF in Django site
1,377,446
85
2009-09-04T05:54:35Z
27,419,707
8
2014-12-11T09:45:27Z
[ "python", "html", "django", "pdf", "pdf-generation" ]
For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf. Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).
Try [wkhtmltopdf](http://wkhtmltopdf.org/) with either one of the following wrappers [django-wkhtmltopdf](https://github.com/incuna/django-wkhtmltopdf) or [python-pdfkit](https://github.com/JazzCore/python-pdfkit/) This worked great for me,supports javascript and css or anything for that matter which a webkit browser...
Python multiprocessing with twisted's reactor
1,377,494
4
2009-09-04T06:08:57Z
1,378,840
11
2009-09-04T12:06:34Z
[ "python", "twisted", "multiprocessing" ]
Dear everyone I am working on a xmlrpc server which has to perform certain tasks cyclically. I am using twisted as the core of the xmlrpc service but I am running into a little problem: ``` class cemeteryRPC(xmlrpc.XMLRPC): def __init__(self, dic): xmlrpc.XMLRPC.__init__(self) def xmlrpc_foo(self): ...
Do you really need to run Twisted in a separate process? That looks pretty unusual to me. Try to think of Twisted's Reactor as your main loop - and hang everything you need off that - rather than trying to run Twisted as a background task. The more normal way of performing this sort of operation would be to use Twist...
Python dictionary to store socket objects
1,378,079
3
2009-09-04T09:02:32Z
1,378,084
10
2009-09-04T09:05:41Z
[ "python" ]
Can we store socket objects in a Python dictionary. I want to create a socket, store socket object, do some stuff and then read from the socket(search from dictionary to get socketobject).
Yes: ``` >>> import socket >>> s = socket.socket() >>> d = {"key" : s} >>> d {'key': <socket._socketobject object at 0x00CEB5A8>} ```
Python dicts in sqlalchemy
1,378,325
15
2009-09-04T10:03:36Z
1,378,818
42
2009-09-04T12:00:09Z
[ "python", "sql", "sqlite", "sqlalchemy" ]
I would like to load/save a dict to/from my sqlite DB, but am having some problems figuring out a simple way to do it. I don't really need to be able to filter, etc., based on the contents so a simple conversion to/from string is fine. The next-best thing would be foreign keys. Please don't post links to huge examples...
The SQLAlchemy [PickleType](http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.PickleType) is meant exactly for this. ``` class SomeEntity(Base): __tablename__ = 'some_entity' id = Column(Integer, primary_key=True) attributes = Column(PickleType) # Just set the attribute to save i...
Python: how to format traceback objects
1,378,889
15
2009-09-04T12:19:51Z
1,378,909
19
2009-09-04T12:24:44Z
[ "python", "object", "format", "traceback" ]
I have a traceback object that I want to show in the nice format I get when calling `traceback.format_exc()`. Is there a builtin function for this? Or a few lines of code?
format\_exc is really just ``` etype, value, tb = sys.exc_info() return ''.join(format_exception(etype, value, tb, limit)) ``` So if you have the exception type, value, and traceback ready, it should be easy. If you have just the exception, notice that `format_exception` is essentially. ``` list = ['Trac...
Python: how to format traceback objects
1,378,889
15
2009-09-04T12:19:51Z
1,378,910
7
2009-09-04T12:25:01Z
[ "python", "object", "format", "traceback" ]
I have a traceback object that I want to show in the nice format I get when calling `traceback.format_exc()`. Is there a builtin function for this? Or a few lines of code?
Have you tried [traceback.print\_tb](http://docs.python.org/library/traceback.html#traceback.print%5Ftb) or [traceback.format\_tb](http://docs.python.org/library/traceback.html#traceback.format%5Ftb)?
list of methods for python shell?
1,378,926
6
2009-09-04T12:29:08Z
1,378,929
7
2009-09-04T12:29:57Z
[ "python", "shell", "interactive" ]
You'd have already found out by my usage of terminology that I'm a python n00b. straight forward question: How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?
`dir( object )` will give you the list. for instance: ``` a = 2 dir( a ) ``` will list off all the methods you can call for an integer.
list of methods for python shell?
1,378,926
6
2009-09-04T12:29:08Z
1,379,700
14
2009-09-04T14:42:50Z
[ "python", "shell", "interactive" ]
You'd have already found out by my usage of terminology that I'm a python n00b. straight forward question: How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?
Existing answers do a good job of showing you how to get the ATTRIBUTES of an object, but do not precisely answer the question you posed -- how to get the METHODS of an object. Python objects have a unified namespace (differently from Ruby, where methods and attributes use different namespaces). Consider for example: ...
is there a way to start/stop linux processes with python?
1,378,974
6
2009-09-04T12:38:06Z
1,378,989
7
2009-09-04T12:40:44Z
[ "python", "linux" ]
I want to be able to start a process and then be able to kill it afterwards
Have a look at the [`subprocess`](http://docs.python.org/library/subprocess.html) module. You can also use low-level primitives like `fork()` via the `os` module.
is there a way to start/stop linux processes with python?
1,378,974
6
2009-09-04T12:38:06Z
1,385,959
12
2009-09-06T15:43:41Z
[ "python", "linux" ]
I want to be able to start a process and then be able to kill it afterwards
Here's a little python script that starts a process, checks if it is running, waits a while, kills it, waits for it to terminate, then checks again. It uses the 'kill' command. Version 2.6 of python subprocess has a kill function. This was written on 2.5. ``` import subprocess import time proc = subprocess.Popen(["sl...
pytz localize vs datetime replace
1,379,740
25
2009-09-04T14:50:11Z
1,379,874
19
2009-09-04T15:12:52Z
[ "python", "datetime", "timezone", "utc", "pytz" ]
I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime: .localize behaviour: ``` >>> tz <DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD> >>> d datetime.datetime(2009, 9, 2, 14, 45, 42, 91421) >>> tz.localize(d) datetime.datetime(2009, 9, 2...
`localize` just assumes that the naive datetime you pass it is "right" (except for not knowing about the timezone!) and so just sets the timezone, no other adjustments. You can (and it's advisable...) internally work in UTC (rather than with naive datetimes) and use `replace` when you need to perform I/O of datetimes ...
Set Snow Leopard to use python 2.5 rather than 2.6
1,380,281
6
2009-09-04T16:27:01Z
1,380,328
8
2009-09-04T16:38:04Z
[ "python", "osx", "osx-snow-leopard" ]
I just upgraded to Snow Leopard and I'm trying to get it to use the old python 2.5 install. I had with all my modules in it. Does anyone know how to set the default python install to 2.5?
I worked this out - if you have this problem open a terminal and type: ``` defaults write com.apple.versioner.python Version 2.5 ```
Can I add parameters to a python property to reduce code duplication?
1,380,566
4
2009-09-04T17:30:12Z
1,380,598
17
2009-09-04T17:37:19Z
[ "python" ]
I have a the following class: ``` class Vector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def _getx(self): return self._x def _setx(self, value): self._x = float(value) x = property(_getx, _setx) def _gety(self): re...
Sure, make a custom descriptor as per the concepts clearly explained in [this doc](http://users.rcn.com/python/download/Descriptor.htm): ``` class JonProperty(object): def __init__(self, name): self.name = name def __get__(self, obj, objtype): return getattr(obj, self.name) def __set__(se...
How to get list opened windows in PyGTK or GTK in Ubuntu?
1,380,784
4
2009-09-04T18:18:40Z
1,380,988
8
2009-09-04T19:01:40Z
[ "python", "ubuntu", "gtk", "pygtk", "window-management" ]
How to get list opened windows in PyGTK or GTK or other programming language? in Ubuntu? **edit:** i want get list paths opened directories on desktop!
You probably want to use libwnck: <http://library.gnome.org/devel/libwnck/stable/> I believe there are python bindings in python-gnome or some similar package. Once you have the GTK+ mainloop running, you can do the following: ``` import wnck window_list = wnck.screen_get_default().get_windows() ``` Some interesti...
How to get list opened windows in PyGTK or GTK in Ubuntu?
1,380,784
4
2009-09-04T18:18:40Z
16,703,307
7
2013-05-22T23:37:06Z
[ "python", "ubuntu", "gtk", "pygtk", "window-management" ]
How to get list opened windows in PyGTK or GTK or other programming language? in Ubuntu? **edit:** i want get list paths opened directories on desktop!
Welcome to 2013! Here's the code using `Wnck` and its modern GObject Introspection libraries instead of the now deprecated PyGTK method. You may also check [my other answer about wnck](http://stackoverflow.com/a/16703115/624066): ``` from gi.repository import Gtk, Wnck Gtk.init([]) # necessary only if not using a Gt...
Add Variables to Tuple
1,380,860
128
2009-09-04T18:36:18Z
1,380,875
160
2009-09-04T18:39:39Z
[ "python", "tuples" ]
I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. **What I am Doing**: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me w...
Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples: ``` a = (1, 2, 3) b = a + (4, 5, 6) c = b[1:] ``` And, of course, build them from existing values: ``` name = "Joe" age = 40 location = "New York" joe = (...
Add Variables to Tuple
1,380,860
128
2009-09-04T18:36:18Z
8,538,676
111
2011-12-16T18:43:21Z
[ "python", "tuples" ]
I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. **What I am Doing**: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me w...
You can start with a blank tuple with something like t = (). You can add with +, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,). You can add a tuple of multiple elements with or without that trailing comma. ``` >>> t = () >>> t = t + (1,) >>> t (1,) >>> ...
Add Variables to Tuple
1,380,860
128
2009-09-04T18:36:18Z
23,530,113
16
2014-05-07T23:20:59Z
[ "python", "tuples" ]
I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. **What I am Doing**: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me w...
Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end: ``` mylist = [] for x in range(5): mylist.append(x) mytuple = tuple(mylist) print mytuple ``` returns ``` (0, 1, 2, 3, 4) ``` I sometimes use this when I have to pass a tuple as a function argument...
Logging multithreaded processes in python
1,380,985
3
2009-09-04T19:01:13Z
1,381,468
7
2009-09-04T20:46:22Z
[ "python", "multithreading", "logging" ]
I was thinking of using the logging module to log all events to one file. The number of threads should be constant from start to finish, but if one thread fails, I'd like to just log that and continue on. What's a simple way of accomplishing this? Thanks!
Not entirely sure what you mean by "one thread fails", but if by "fail" you mean that an exception propagates all the way up to the top function of the thread, then you can wrap every thread's top function (e.g. in a decorator) to catch any exception, log whatever you wish, and re-raise. The `logging` module should ens...
Easiest way to write a Python program with access to Django database functionality
1,381,346
3
2009-09-04T20:16:20Z
1,381,395
13
2009-09-04T20:30:39Z
[ "python", "django", "django-models", "django-orm" ]
I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct U...
``` from django.core.management import setup_environ from django.core.mail import EmailMultiAlternatives, send_mail from django.contrib.auth.models import User import settings from my.app.models import * setup_environ(settings) ``` This was how I did it for a cron that emailed parties daily updates. The .py lived in...
Easiest way to write a Python program with access to Django database functionality
1,381,346
3
2009-09-04T20:16:20Z
1,381,619
9
2009-09-04T21:27:12Z
[ "python", "django", "django-models", "django-orm" ]
I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct U...
An alternative to all the approaches given here is to write your cron job as a custom `./manage.py` command. This is very easy to do, and gives you the ability to do `./manage.py yourcommand` either on the command line or in your crontab. [The documentation](http://docs.djangoproject.com/en/dev/howto/custom-management...
C# way to mimic Python Dictionary Syntax
1,381,359
11
2009-09-04T20:21:21Z
1,381,380
11
2009-09-04T20:26:12Z
[ "c#", "python", "syntax", "dictionary", "types" ]
Is there a good way in C# to mimic the following python syntax: ``` mydict = {} mydict["bc"] = {} mydict["bc"]["de"] = "123"; # <-- This line mydict["te"] = "5"; # <-- While also allowing this line ``` In other words, I'd like something with [] style access that can return either another dictionary or a str...
You can achieve this by having the class, lets call it PythonDictionary, which is returned from `mydict["bc"]` have the following members. * A indexer property to allow for the ["de"] access * A implicit conversion from string to PythonDictionary That should allow both cases to compile just fine. For example ``` pu...
Purely functional data structures with copy-on-write?
1,381,592
7
2009-09-04T21:19:28Z
1,381,664
8
2009-09-04T21:36:12Z
[ "python", "functional-programming", "immutability", "copy-on-write" ]
I want to have the advantage of functional data structures (multiple versions of data that can share structure) but be able to modify it in an imperative style. What I'm thinking about (and a possible use): a RPG game in which whole game history is stored (for example, to allow for travelling back in time). Using copy...
[Functional ("persistent") data structures](http://en.wikipedia.org/wiki/Purely%5Ffunctional#Examples%5Fof%5Fpurely%5Ffunctional%5Fdata%5Fstructures) are typically recursively built up out of immutable nodes (e.g. singly linked list where common suffixes are shared, search tree or heap where only the parts of the tree ...
"WindowsError: exception: access violation..." - ctypes question
1,382,076
3
2009-09-05T00:35:26Z
1,403,195
11
2009-09-10T03:18:18Z
[ "python", "ctypes", "access-violation", "windowserror" ]
Howdy all - Here is the prototype for a C function that resides in a DLL: ``` extern "C" void__stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*); ``` In another thread, I asked about how to properly create and send the necessary arguments to this function. Here is the thread: <http://...
The error you're getting is not related to Administrative rights. The problem is you're using C and inadvertently performing illegal operations (the kind of operations that if went unchecked would probably crash your system). The error you get indicates that your program is trying to write to memory address 1001, but ...
sqlalchemy easy way to insert or update?
1,382,469
22
2009-09-05T04:33:13Z
1,415,306
30
2009-09-12T14:55:50Z
[ "python", "sqlalchemy" ]
I have a sequence of new objects. They all look like similar to this: Foo(pk\_col1=x, pk\_col2=y, val='bar') Some of those are Foo that exist (i.e. only val differs from the row in the db) and should generate update queries. The others should generate inserts. I can think of a few ways of doing this, the best being:...
I think you are after [new\_obj = session.merge(obj)](http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#merging). This will merge an object in a detached state into the session if the primary keys match and will make a new one otherwise. So `session.save(new_obj)` will work for both insert and upda...
How do I do Debian packaging of a Python package?
1,382,569
39
2009-09-05T05:39:23Z
1,382,593
17
2009-09-05T06:00:43Z
[ "python", "debian" ]
I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions. The Python package for testing purposes will just be a directory with an empty `__init__.py` file and a single Python module, `package_test.py`. The ...
I would take the sources of an existing Debian package, and replace the actual package in it with your package. To find a list of packages that depend on python-support, do ``` apt-cache rdepends python-support ``` Pick a package that is `Architecture: all`, so that it is a pure-Python package. Going through this li...
How do I do Debian packaging of a Python package?
1,382,569
39
2009-09-05T05:39:23Z
2,796,210
19
2010-05-09T00:50:12Z
[ "python", "debian" ]
I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions. The Python package for testing purposes will just be a directory with an empty `__init__.py` file and a single Python module, `package_test.py`. The ...
I think what you want is <http://pypi.python.org/pypi/stdeb>: > stdeb produces Debian source packages > from Python packages via a new > distutils command, sdist\_dsc. > Automatic defaults are provided for > the Debian package, but many aspects > of the resulting package can be > customized (see the customizing > sect...
How do I do Debian packaging of a Python package?
1,382,569
39
2009-09-05T05:39:23Z
14,423,375
13
2013-01-20T09:55:25Z
[ "python", "debian" ]
I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions. The Python package for testing purposes will just be a directory with an empty `__init__.py` file and a single Python module, `package_test.py`. The ...
Most of the answers posted here are outdated, fortunately a great Debian wiki post has been made recently, which explains the current best practices and describes how to build Debian packages for Python modules and applications. * <http://wiki.debian.org/Python/Packaging>
How do I do Debian packaging of a Python package?
1,382,569
39
2009-09-05T05:39:23Z
25,275,227
9
2014-08-12T22:37:15Z
[ "python", "debian" ]
I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions. The Python package for testing purposes will just be a directory with an empty `__init__.py` file and a single Python module, `package_test.py`. The ...
The right way of building a deb package is using `dpkg-buildpackage` but sometimes it is a little bit complicated. Instead you can use `dpkg -b <folder>` and it will create your Debian package. These are the basics for creating a Debian package with `dpkg -b <folder>` with any binary or with any kind of script that ru...
Which PEP's are must reads?
1,382,648
46
2009-09-05T06:43:05Z
1,382,661
24
2009-09-05T06:51:34Z
[ "python", "pep" ]
I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?
Definitely [PEP 8](http://www.python.org/dev/peps/pep-0008/), a Style Guide for Python.
Which PEP's are must reads?
1,382,648
46
2009-09-05T06:43:05Z
1,382,981
8
2009-09-05T10:34:42Z
[ "python", "pep" ]
I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?
It is now retrospective, but still interesting: I think [Things that will Not Change in Python 3000](http://www.python.org/dev/peps/pep-3099/) is a good read, with lots of links to the discussions that preceded the decisions.
Which PEP's are must reads?
1,382,648
46
2009-09-05T06:43:05Z
1,383,045
9
2009-09-05T11:00:43Z
[ "python", "pep" ]
I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?
Also pep [0257](http://www.python.org/dev/peps/pep-0257/) docstring convention
Which PEP's are must reads?
1,382,648
46
2009-09-05T06:43:05Z
1,383,659
13
2009-09-05T15:59:54Z
[ "python", "pep" ]
I'm a fairly strong Python coder, but too much of my style is a little haphazard, and I'm sure there are more Pythonic solutions to many problems than the ones I come up with. Which PEPs are essential for any well versed Pythonista to read?
Although Python is incredibly intuitive, a lot of people do not comprehend his philosophy. > [Pep 20](http://www.python.org/dev/peps/pep-0020/): **The Zen of Python** > > * Beautiful is better than ugly. > * Explicit is better than implicit. > * Simple is better than complex. > * Complex is better than complicated. > ...
Dynamically attaching a method to an existing Python object generated with swig?
1,382,871
7
2009-09-05T09:30:59Z
1,383,646
19
2009-09-05T15:51:30Z
[ "python", "class", "dynamic", "methods" ]
I am working with a Python class, and I don't have write access to its declaration. How can I attach a custom method (such as **`__str__`**) to the objects created from that class without modifying the class declaration? EDIT: Thank you for all your answers. I tried them all but they haven't resolved my problem. Here ...
If you create a wrapper class, this will work with any other class, either built-in or not. This is called "containment and delegation", and it is a common alternative to inheritance: ``` class SuperDuperWrapper(object): def __init__(self, origobj): self.myobj = origobj def __str__(self): retur...
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
78
2009-09-05T09:59:17Z
1,383,009
11
2009-09-05T10:47:29Z
[ "python", "virtualenv", "pip" ]
I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to. For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version. ``` $ virtualenv --no-site-packages foo ...
`--no-site-packages` should, as the name suggests, remove the standard site-packages directory from sys.path. Anything else that lives in the standard Python path will remain there.
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
78
2009-09-05T09:59:17Z
1,402,050
21
2009-09-09T20:57:04Z
[ "python", "virtualenv", "pip" ]
I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to. For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version. ``` $ virtualenv --no-site-packages foo ...
Eventually I found that, for whatever reason, pip -E was not working. However, if I actually activate the virtualenv, and use easy\_install provided by virtualenv to install pip, then use pip directly from within, it seems to work as expected and only show the packages in the virtualenv
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
78
2009-09-05T09:59:17Z
15,178,877
10
2013-03-02T20:06:48Z
[ "python", "virtualenv", "pip" ]
I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to. For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version. ``` $ virtualenv --no-site-packages foo ...
I know this is a very old question but for those arriving here looking for a solution: Don't forget to **activate the virtualenv** (`source bin/activate`) before running `pip freeze`. Otherwise you'll get a list of all global packages.
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
78
2009-09-05T09:59:17Z
15,887,589
60
2013-04-08T19:46:09Z
[ "python", "virtualenv", "pip" ]
I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to. For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version. ``` $ virtualenv --no-site-packages foo ...
I had a problem like this, until I realized that (long before I had discovered virtualenv), I had gone adding directories to the PYTHONPATH in my .bashrc file. As it had been over a year beforehand, I didn't think of that straight away.
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
78
2009-09-05T09:59:17Z
33,366,748
7
2015-10-27T11:25:36Z
[ "python", "virtualenv", "pip" ]
I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to. For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version. ``` $ virtualenv --no-site-packages foo ...
You have to make sure you are running the `pip` binary in the virtual environment you created, not the global one. ``` env/bin/pip freeze ``` --- See a test: We create the virtualenv with the `--no-site-packages` option: ``` $ virtualenv --no-site-packages -p /usr/local/bin/python mytest Running virtualenv with in...
latin-1 to ascii
1,382,998
13
2009-09-05T10:44:40Z
1,383,056
8
2009-09-05T11:06:43Z
[ "python", "unicode" ]
I have a unicode string with accented latin chars e.g. ``` n=unicode('Wikipédia, le projet d’encyclopédie','utf-8') ``` I want to convert it to plain ascii i.e. 'Wikipedia, le projet dencyclopedie', so all acute/accent,cedilla etc should get removed What is the fastest way to do that, as it needed to be done for...
The "correct" way to do this is to register your own error handler for unicode encoding/decoding, and in that error handler provide the replacements from è to e and ö to o, etc. Like so: ``` # -*- coding: UTF-8 -*- import codecs map = {u'é': u'e', u'’': u"'", # ETC } def asciify(error): ...
latin-1 to ascii
1,382,998
13
2009-09-05T10:44:40Z
1,383,721
15
2009-09-05T16:34:29Z
[ "python", "unicode" ]
I have a unicode string with accented latin chars e.g. ``` n=unicode('Wikipédia, le projet d’encyclopédie','utf-8') ``` I want to convert it to plain ascii i.e. 'Wikipedia, le projet dencyclopedie', so all acute/accent,cedilla etc should get removed What is the fastest way to do that, as it needed to be done for...
So here are three approaches, more or less as given or suggested in other answers: ``` # -*- coding: utf-8 -*- import codecs import unicodedata x = u"Wikipédia, le projet d’encyclopédie" xtd = {ord(u'’'): u"'", ord(u'é'): u'e', } def asciify(error): return xtd[ord(error.object[error.start])], error.end ...
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
21
2009-09-05T11:40:31Z
1,383,153
24
2009-09-05T11:51:18Z
[ "python", "django", "django-syncdb" ]
I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is: ``` DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres'...
There seems to be a problem with your `psycopg2` installation – Python does not find it. This is a Python installation problem, not a Django issue. You can try to load it manually using the Python interpreter and see if it works: ``` $ python >>> import psycopg2 ``` If you get an `ImportError` exception, your inst...
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
21
2009-09-05T11:40:31Z
5,148,709
10
2011-02-28T23:14:05Z
[ "python", "django", "django-syncdb" ]
I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is: ``` DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres'...
For the record I got the same error for a different reason: I had put ``` 'ENGINE': 'django.db.backends.postgresql' ``` instead of ``` 'ENGINE': 'django.db.backends.postgresql_psycopg2' ``` in `settings.py`
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
21
2009-09-05T11:40:31Z
10,399,009
14
2012-05-01T14:18:47Z
[ "python", "django", "django-syncdb" ]
I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is: ``` DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres'...
If you have `pip` installed, simply install the missing extension by running: ``` $ pip install psycopg2 ```
Can I use __init__.py to define global variables?
1,383,239
46
2009-09-05T12:33:03Z
1,383,248
25
2009-09-05T12:38:56Z
[ "python", "global-variables", "module", "packages", "init" ]
I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the `__init__.py` file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from the...
You cannot do that. You will have to explicitely import your constants into each individual module's namespace. The best way to achieve this is to define your constants in a "config" module and import it everywhere you require it: ``` # mypackage/config.py MY_CONST = 17 # mypackage/main.py from mypackage.config impor...
Can I use __init__.py to define global variables?
1,383,239
46
2009-09-05T12:33:03Z
1,383,281
75
2009-09-05T12:57:05Z
[ "python", "global-variables", "module", "packages", "init" ]
I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the `__init__.py` file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from the...
You should be able to put them in \_\_init\_\_.py. This is done all the time. mypackage/\_\_init\_\_.py: ``` MY_CONSTANT = 42 ``` mypackage/mymodule.py: ``` from mypackage import MY_CONSTANT print "my constant is", MY_CONSTANT ``` Then, import mymodule: ``` >>> from mypackage import mymodule my constant is 42 ```...
Logging, StreamHandler and standard streams
1,383,254
37
2009-09-05T12:45:17Z
1,383,365
60
2009-09-05T13:46:23Z
[ "python", "logging" ]
I can't figure out how to log info-level messages to stdout, but everything else to stderr. I already read this <http://docs.python.org/library/logging.html>. Any suggestion?
The following script, `log1.py`: ``` import logging, sys class SingleLevelFilter(logging.Filter): def __init__(self, passlevel, reject): self.passlevel = passlevel self.reject = reject def filter(self, record): if self.reject: return (record.levelno != self.passlevel) ...
Logging, StreamHandler and standard streams
1,383,254
37
2009-09-05T12:45:17Z
24,956,305
9
2014-07-25T12:56:45Z
[ "python", "logging" ]
I can't figure out how to log info-level messages to stdout, but everything else to stderr. I already read this <http://docs.python.org/library/logging.html>. Any suggestion?
Generally, I think it makes sense to **redirect messages lower than `WARNING` to *stdout*, instead of only `INFO` messages**. Based on *Vinay Sajip*'s excellent answer, I came up with this: ``` class MaxLevelFilter(Filter): '''Filters (lets through) all messages with level < LEVEL''' def __init__(self, level)...
Python : Revert to base __str__ behavior
1,384,542
6
2009-09-06T00:00:39Z
1,384,559
12
2009-09-06T00:06:42Z
[ "python", "string" ]
How can I revert back to the default function that python uses if there is no `__str__` method? ``` class A : def __str__(self) : return "Something useless" class B(A) : def __str__(self) : return some_magic_base_function(self) ```
You can use `object.__str__()`: ``` class A: def __str__(self): return "Something useless" class B(A): def __str__(self): return object.__str__(self) ``` This gives you the default output for instances of `B`: ``` >>> b = B() >>> str(b) '<__main__.B instance at 0x7fb34c4f09e0>' ```
How to "slow down" a MIDI file (ideally in Python)?
1,384,588
14
2009-09-06T00:35:53Z
1,384,611
9
2009-09-06T00:47:20Z
[ "python", "midi" ]
I have background music for some songs available in both .MID and .KAR formats, but in each case it's being played somewhat faster than I'd like. What's the simplest way to create either .MID or .KAR files with the same content but at a slower tempo -- say, one slowed down by 20% or so, another by 15%, a third by 25%, ...
You could edit the file, as per <http://www.sonicspot.com/guide/midifiles.html> Although there probably is a MIDI reading/writing library already. In fact, it was a matter of seeing the related questions: <http://stackoverflow.com/questions/569321/simple-cross-platform-midi-library-for-python> > Set Tempo > > This me...
How to "slow down" a MIDI file (ideally in Python)?
1,384,588
14
2009-09-06T00:35:53Z
1,449,597
13
2009-09-19T21:34:34Z
[ "python", "midi" ]
I have background music for some songs available in both .MID and .KAR formats, but in each case it's being played somewhat faster than I'd like. What's the simplest way to create either .MID or .KAR files with the same content but at a slower tempo -- say, one slowed down by 20% or so, another by 15%, a third by 25%, ...
As Vinko says, you can edit the midifile, but since it's a binary format, squeezed into the least number of bits possible, it helps to have help. This is a midi-to-text converter (and vice-versa): <http://midicomp.opensrc.org/> I've been using it quite a bit lately. it's pretty trivial to do text processing (e.g. ...
Should I use Mako for Templating?
1,384,634
7
2009-09-06T01:11:38Z
1,384,699
18
2009-09-06T01:54:26Z
[ "python", "template-engine", "mako", "genshi" ]
I've been considering a templating solution, although my choices are between Mako and Genshi. I find templating in Genshi a bit ugly, so I'm shifting more towards Mako. I've gone to wonder: what is so good about the fact that Mako allows embedded Python code? How is it convenient for the average joe? Wouldn't templat...
As the mako [homepage](http://www.makotemplates.org/) points out, Mako's advantages are pretty clear: insanely fast, instantly familiar to anyone who's handy with Python in terms of both syntax and features. Genshi chooses "interpretation" instead of ahead-of-time Python code generation (according to their [FAQ](http:...
Should I use Mako for Templating?
1,384,634
7
2009-09-06T01:11:38Z
1,391,510
15
2009-09-08T01:16:12Z
[ "python", "template-engine", "mako", "genshi" ]
I've been considering a templating solution, although my choices are between Mako and Genshi. I find templating in Genshi a bit ugly, so I'm shifting more towards Mako. I've gone to wonder: what is so good about the fact that Mako allows embedded Python code? How is it convenient for the average joe? Wouldn't templat...
> Wouldn't templating JUST suffice without having embedded Python code? Only if your templating language has enough logical functionality that it is essentially a scripting language in itself. At which point, you might just as well have used Python. More involved sites often need complex presentation logic and non-tr...
Django admin and showing thumbnail images
1,385,094
44
2009-09-06T07:15:35Z
1,385,145
64
2009-09-06T07:43:07Z
[ "python", "django", "django-admin" ]
I'm trying to show thumbnail images in Django admin, but I can only see the path to the images, but not the rendered images. I don't know what I'm doing wrong. Server media URL: ``` from django.conf import settings (r'^public/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), ``` Fu...
This is in the source for [photologue](http://code.google.com/p/django-photologue/) (see `models.py`, slightly adapted to remove irrelevant stuff): ``` def admin_thumbnail(self): return u'<img src="%s" />' % (self.image.url) admin_thumbnail.short_description = 'Thumbnail' admin_thumbnail.allow_tags = True ``` The...
Unpickling classes from Python 3 in Python 2
1,385,096
5
2009-09-06T07:15:54Z
1,385,100
11
2009-09-06T07:18:45Z
[ "python", "python-3.x", "pickle" ]
If a Python 3 class is pickled using protocol 2, it is supposed to work in Python 2, but unfortunately, this fails because the names of some classes have changed. Assume we have code called as follows. Sender ``` pickle.dumps(obj,2) ``` Receiver ``` pickle.loads(atom) ``` To give a specific case, if `obj={}`, the...
This problem is [Python issue 3675](http://bugs.python.org/issue3675). This bug is actually fixed in Python 3.11. If we import: ``` from lib2to3.fixes.fix_imports import MAPPING ``` MAPPING maps Python 2 names to Python 3 names. We want this in reverse. ``` REVERSE_MAPPING={} for key,val in MAPPING.items(): REV...
Calling non-static method from static one in Python
1,385,546
3
2009-09-06T12:20:29Z
1,385,650
7
2009-09-06T13:13:35Z
[ "python", "oop" ]
I can't find if it's possible to call a non-static method from a static one in Python. Thanks EDIT: Ok. And what about static from static? Can I do this: ``` class MyClass(object): @staticmethod def static_method_one(cmd): ... @staticmethod def static_method_two(cmd): static_method_one(...
It's perfectly possible, but not very meaningful. Ponder the following class: ``` class MyClass: # Normal method: def normal_method(self, data): print "Normal method called with instance %s and data %s" % (self, data) @classmethod def class_method(cls, data): print "Class method called...
How to get 280slides.com functionality?
1,385,722
3
2009-09-06T13:51:26Z
1,385,927
8
2009-09-06T15:29:29Z
[ "python", "rich-internet-application" ]
I have seen 280slides.com and it is really impresive. But its developers had to create their own language. Which platform or language would you use to have an as similar as possible functionality? Is it possible to do something similar in python? Could you give any working examples?
Inventing our own language was a miniscule part of the problem. What was important was developing the right framework, which is now available as Cappuccino (cappuccino.org). You ask what platform/language you could use to develop something similar? I assume you already know that the answer to what platform is the web....
Should __init__() call the parent class's __init__()?
1,385,759
61
2009-09-06T14:04:23Z
1,385,767
14
2009-09-06T14:11:23Z
[ "python" ]
I'm used that in Objective-C I've got this construct: ``` - (void)init { if (self = [super init]) { // init class } return self; } ``` Should Python also call the parent class's implementation for `__init__`? ``` class NewClass(SomeOtherClass): def __init__(self): SomeOtherClass.__ini...
**Edit**: (after the code change) There is no way for us to tell you whether you need or not to call your parent's `__init__` (or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your `__init__` is done in parent class, you can just...
Should __init__() call the parent class's __init__()?
1,385,759
61
2009-09-06T14:04:23Z
1,385,778
32
2009-09-06T14:18:07Z
[ "python" ]
I'm used that in Objective-C I've got this construct: ``` - (void)init { if (self = [super init]) { // init class } return self; } ``` Should Python also call the parent class's implementation for `__init__`? ``` class NewClass(SomeOtherClass): def __init__(self): SomeOtherClass.__ini...
In Python, calling the super-class' `__init__` is optional. If you call it, it is then also optional whether to use the `super` identifier, or whether to explicitly name the super class: ``` object.__init__(self) ``` In case of object, calling the super method is not strictly necessary, since the super method is empt...
Should __init__() call the parent class's __init__()?
1,385,759
61
2009-09-06T14:04:23Z
1,385,836
71
2009-09-06T14:51:06Z
[ "python" ]
I'm used that in Objective-C I've got this construct: ``` - (void)init { if (self = [super init]) { // init class } return self; } ``` Should Python also call the parent class's implementation for `__init__`? ``` class NewClass(SomeOtherClass): def __init__(self): SomeOtherClass.__ini...
If you need something from super's `__init__` to be done in addition to what is being done in the current class's `__init__,` you must call it yourself, since that will not happen automatically. But if you don't need anything from super's `__init__,` no need to call it. Example: ``` >>> class C(object): def __init...
Should __init__() call the parent class's __init__()?
1,385,759
61
2009-09-06T14:04:23Z
7,059,529
28
2011-08-14T20:31:39Z
[ "python" ]
I'm used that in Objective-C I've got this construct: ``` - (void)init { if (self = [super init]) { // init class } return self; } ``` Should Python also call the parent class's implementation for `__init__`? ``` class NewClass(SomeOtherClass): def __init__(self): SomeOtherClass.__ini...
In Anon's answer: *"If you need something from super's `__init__` to be done in addition to what is being done in the current class's `__init__` , you must call it yourself, since that will not happen automatically"* It's incredible: he is wording exactly the contrary of the principle of inheritance. . It is not t...