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
Twisted and p2p applications
839,384
13
2009-05-08T11:20:58Z
846,492
12
2009-05-11T02:02:34Z
[ "python", "twisted", "protocols", "p2p" ]
Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?
The best solution is to use the source code for BitTorrent. It was built with Twisted until they switched over to a C++ implementation called Utorrent. * Last known Twisted version of BitTorrent + <http://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz> * Older versions + <http://download.bittorrent.com...
Best Practices for Python Exceptions?
839,636
45
2009-05-08T12:44:43Z
839,662
26
2009-05-08T12:54:39Z
[ "python", "exception" ]
What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this? Basically from my understanding from the s...
> I read several times in books that > exceptions should never ever hold a > string, because strings themselves can > throw exceptions. Any real truth to > this? What? Please provide a reference or a link to this. It's totally untrue. Since all objects can throw exceptions, no object could be contained in an excepti...
Best Practices for Python Exceptions?
839,636
45
2009-05-08T12:44:43Z
839,844
68
2009-05-08T13:41:01Z
[ "python", "exception" ]
What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this? Basically from my understanding from the s...
[Robust exception handling (in Python)](http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/) - a "best practices for Python exceptions" blog post I wrote a while ago. You may find it useful. Some key points from the blog: > **Never use exceptions for flow-control** > > Exceptions exist for exceptional ...
Extracting a URL in Python
839,994
6
2009-05-08T14:17:04Z
840,014
15
2009-05-08T14:20:51Z
[ "python", "url", "parsing" ]
In regards to: <http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related> How can I extract just the url so I can put it into a list/array? --- ## Edit Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it int...
Misunderstood question: ``` >>> from urllib.parse import urlparse >>> urlparse('http://www.ggogle.com/test?t') ParseResult(scheme='http', netloc='www.ggogle.com', path='/test', params='', query='t', fragment='') ``` [or py2.\* version](http://docs.python.org/library/urlparse.html?#urlparse.urlparse): ``` >>>...
Extracting a URL in Python
839,994
6
2009-05-08T14:17:04Z
840,110
14
2009-05-08T14:39:32Z
[ "python", "url", "parsing" ]
In regards to: <http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related> How can I extract just the url so I can put it into a list/array? --- ## Edit Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it int...
In response to the OP's edit I hijacked [Find Hyperlinks in Text using Python (twitter related)](http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related) and came up with this: ``` import re myString = "This is my tweet check it out http://tinyurl.com/blah" print re.search("(?P...
Sort lexicographically?
840,637
7
2009-05-08T16:18:50Z
840,727
7
2009-05-08T16:38:46Z
[ "python", "api", "sorting", "photobucket" ]
I am working on integrating with the Photobucket API and I came across this in their [api docs](http://pic.photobucket.com/dev%5Fhelp/WebHelpPublic/Content/Getting%20Started/Consumer%20Authentication.htm): > *"Sort the parameters by name > lexographically [sic] (byte ordering, the > standard sorting, not natural or ca...
I think that here lexicographic is a "alias" for ascii sort? ``` Lexicographic Natural z1.doc z1.doc z10.doc z2.doc z100.doc z3.doc z101.doc z4.doc z102.doc z5.doc z11.doc z6.doc z12.doc ...
How do you alias a python class to have another name without using inheritance?
840,969
25
2009-05-08T17:35:18Z
840,976
7
2009-05-08T17:36:56Z
[ "python" ]
If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance? e.g. I have a class like: ``` class MyReallyBigClassNameWhichIHateToType: def __init__(self): <blah> [...] ...
Refactor the name, no reason it should have a name that long. Otherwise `whateverName = VeryLongClassName` should do the trick.
How do you alias a python class to have another name without using inheritance?
840,969
25
2009-05-08T17:35:18Z
840,977
50
2009-05-08T17:37:11Z
[ "python" ]
If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance? e.g. I have a class like: ``` class MyReallyBigClassNameWhichIHateToType: def __init__(self): <blah> [...] ...
``` C = MyReallyBigClassNameWhichIHateToType ```
How do you alias a python class to have another name without using inheritance?
840,969
25
2009-05-08T17:35:18Z
840,979
10
2009-05-08T17:37:33Z
[ "python" ]
If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance? e.g. I have a class like: ``` class MyReallyBigClassNameWhichIHateToType: def __init__(self): <blah> [...] ...
You can simply do: ``` ShortName = MyReallyBigClassNameWhichIHateToType ``` A class in Python is just an object like any other, and can have more than one names.
How do you alias a python class to have another name without using inheritance?
840,969
25
2009-05-08T17:35:18Z
841,007
23
2009-05-08T17:45:39Z
[ "python" ]
If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance? e.g. I have a class like: ``` class MyReallyBigClassNameWhichIHateToType: def __init__(self): <blah> [...] ...
Also, if you're importing the name from another module... ``` from modulename import ReallyLongNameWhichIHateToType as FriendlyName ```
What's going on with the lambda expression in this python function?
841,555
5
2009-05-08T20:03:43Z
841,588
12
2009-05-08T20:12:59Z
[ "python", "lambda" ]
Why does this attempt at creating a list of curried functions not work? ``` def p(x, num): print x, num def test(): a = [] for i in range(10): a.append(lambda x: p (i, x)) return a >>> myList = test() >>> test[0]('test') 9 test >>> test[5]('test') 9 test >>> test[9]('test') 9 test ``` What's...
In Python, variables created in loops and branches aren't scoped. All of the functions you're creating with `lambda` have a reference to the same `i` variable, which is set to `9` on the last iteration of the loop. The solution is to create a function which returns a function, thus scoping the iterator variable. This ...
python: can I extend the upper bound of the range() method?
841,584
3
2009-05-08T20:10:49Z
841,589
9
2009-05-08T20:13:01Z
[ "python" ]
What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this: ``` for i in range(1,600851475143): ```
`range(1, 600851475143)` wants to generate a very large list in memory, and you'll get an out of memory error. To save memory, use `xrange` instead of `range`. Unfortunately, `xrange` doesn't work with large numbers (it's an implementation restriction) Example (raises OverflowError): ``` for i in xrange(1, 60085147514...
Django equivalent of COUNT with GROUP BY
842,031
17
2009-05-08T22:08:32Z
842,074
13
2009-05-08T22:25:40Z
[ "python", "sql", "django", "django-queryset", "django-aggregation" ]
I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query: ``` SELECT player_type, COUNT(*) FROM players GROUP BY player_type; ``` Is it possible with Django 1.1's Model Query API or should I just use plain SQL?
Django 1.1 does support aggregation methods like count. You can find [the full documentation here](http://docs.djangoproject.com/en/dev/topics/db/aggregation/). To answer your question, you can use something along the lines of: ``` from django.db.models import Count q = Player.objects.annotate(Count('games')) print q...
Django equivalent of COUNT with GROUP BY
842,031
17
2009-05-08T22:08:32Z
842,876
43
2009-05-09T07:40:12Z
[ "python", "sql", "django", "django-queryset", "django-aggregation" ]
I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query: ``` SELECT player_type, COUNT(*) FROM players GROUP BY player_type; ``` Is it possible with Django 1.1's Model Query API or should I just use plain SQL?
If you are using Django 1.1 beta (trunk): ``` Player.objects.values('player_type').order_by().annotate(Count('player_type')) ``` * `values('player_type')` - for inclusion only `player_type` field into `GROUP BY` clause. * `order_by()` - for exclusion possible default ordering that can cause not needed fields inclusio...
Is there a portable way to get the current username in Python?
842,059
361
2009-05-08T22:20:20Z
842,096
494
2009-05-08T22:30:51Z
[ "python", "portability", "username" ]
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like `os.getuid`: ``` >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' ``` I googled around and was surprised not to find a definitive answer (although perhaps I wa...
Look at [getpass](http://docs.python.org/library/getpass.html) module ``` import getpass getpass.getuser() 'kostya' ``` Availability: Unix, Windows --- p.s. Per comment below "*this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relie...
Is there a portable way to get the current username in Python?
842,059
361
2009-05-08T22:20:20Z
842,107
32
2009-05-08T22:35:54Z
[ "python", "portability", "username" ]
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like `os.getuid`: ``` >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' ``` I googled around and was surprised not to find a definitive answer (although perhaps I wa...
You can probably use: ``` os.getenv('USERNAME') ``` But it's not going to be safe because environment variables can be changed.
Is there a portable way to get the current username in Python?
842,059
361
2009-05-08T22:20:20Z
1,594,451
44
2009-10-20T13:00:12Z
[ "python", "portability", "username" ]
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like `os.getuid`: ``` >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' ``` I googled around and was surprised not to find a definitive answer (although perhaps I wa...
You can also use: ``` os.getlogin() ```
Is there a portable way to get the current username in Python?
842,059
361
2009-05-08T22:20:20Z
1,992,942
14
2010-01-02T21:35:30Z
[ "python", "portability", "username" ]
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like `os.getuid`: ``` >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' ``` I googled around and was surprised not to find a definitive answer (although perhaps I wa...
These might work. I don't know how they behave when running as a service. They aren't portable, but that's what "os.name" and "if" statements are for. win32api.GetUserName() win32api.GetUserNameEx(...) See: <http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html>
Is there a portable way to get the current username in Python?
842,059
361
2009-05-08T22:20:20Z
2,899,055
74
2010-05-24T17:53:51Z
[ "python", "portability", "username" ]
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like `os.getuid`: ``` >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' ``` I googled around and was surprised not to find a definitive answer (although perhaps I wa...
You best bet would be to combine `os.getuid()` with `pwd.getpwuid()`: ``` import os import pwd def get_username(): return pwd.getpwuid( os.getuid() )[ 0 ] ``` Refer to the pwd docs for more details: <http://docs.python.org/library/pwd.html>
Is there a portable way to get the current username in Python?
842,059
361
2009-05-08T22:20:20Z
14,783,939
12
2013-02-09T01:23:29Z
[ "python", "portability", "username" ]
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like `os.getuid`: ``` >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' ``` I googled around and was surprised not to find a definitive answer (although perhaps I wa...
If you are needing this to get user's home dir, below could be considered as portable (win32 and linux at least), part of a standard library. ``` >>> os.path.expanduser('~') 'C:\\Documents and Settings\\johnsmith' ``` Also you could parse such string to get only last path component (ie. user name). See: [os.path.exp...
Is there a portable way to get the current username in Python?
842,059
361
2009-05-08T22:20:20Z
19,865,396
7
2013-11-08T17:47:29Z
[ "python", "portability", "username" ]
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like `os.getuid`: ``` >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' ``` I googled around and was surprised not to find a definitive answer (although perhaps I wa...
Combined `pwd` and `getpass` approach, based on other answers: ``` try: import pwd except ImportError: import getpass pwd = None def current_user(): if pwd: return pwd.getpwuid(os.geteuid()).pw_name else: return getpass.getuser() ```
Is there a portable way to get the current username in Python?
842,059
361
2009-05-08T22:20:20Z
20,402,832
10
2013-12-05T14:39:01Z
[ "python", "portability", "username" ]
Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like `os.getuid`: ``` >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' ``` I googled around and was surprised not to find a definitive answer (although perhaps I wa...
To me using `os` module looks the best for portability: Works best on both Linux and Windows. ``` import os # Gives user's home directory userhome = os.path.expanduser('~') print "User's home Dir: " + userhome # Gives username by splitting path based on OS print "username: " + os.path.split(userhome)[-1] ...
Practical GUI toolkit?
842,075
13
2009-05-08T22:25:43Z
842,103
20
2009-05-08T22:34:06Z
[ "java", "python", "ruby", "user-interface", "cross-platform" ]
I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; [FOX](http://en.wikipedia.org/wiki/WxWidgets), [wx](http://en.wikipedia....
I would go with Qt. It works on all the major platforms, and it's being continually improved. You can also get started really fast. There are bindings for Java, Ruby and Python. Plus it's free if you're writing open source programs.
Practical GUI toolkit?
842,075
13
2009-05-08T22:25:43Z
842,109
7
2009-05-08T22:36:20Z
[ "java", "python", "ruby", "user-interface", "cross-platform" ]
I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; [FOX](http://en.wikipedia.org/wiki/WxWidgets), [wx](http://en.wikipedia....
Honestly, I've built things with Tk, wx, and Qt, and I hate them all equally. Qt's visual editor is the least obnoxious of the three I think.
Piping Batch File output to a Python script
842,120
3
2009-05-08T22:41:21Z
842,372
7
2009-05-09T00:24:23Z
[ "python", "windows", "scripting", "batch-file", "io" ]
I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and u...
``` import subprocess output= subprocess.Popen( ("c:\\bin\\batch.bat", "an_argument", "another_argument"), stdout=subprocess.PIPE).stdout for line in output: # do your work here output.close() ``` Note that it's preferable to start your batch file with "`@echo off`".
Which is more accurate, x**.5 or math.sqrt(x)?
842,245
17
2009-05-08T23:33:00Z
842,258
10
2009-05-08T23:37:57Z
[ "python", "floating-point" ]
I recently discovered that `x**.5` and `math.sqrt(x)` do not always produce the same result in Python: ``` Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 >>> 8885558**.5 - math.sqrt(8885558) -4.5474735088646412e-13 ``` Checking all integers below 10\*\*7, the two methods produced...
Both the pow function and the math.sqrt() function can calculate results that are more accurate than what the default float type can store. I think the errors you're seeing is a result of the limitations of floating point math rather than inaccuracies of the functions. Also, since when is a difference of ~10^(-13) a pr...
Which is more accurate, x**.5 or math.sqrt(x)?
842,245
17
2009-05-08T23:33:00Z
842,358
22
2009-05-09T00:17:04Z
[ "python", "floating-point" ]
I recently discovered that `x**.5` and `math.sqrt(x)` do not always produce the same result in Python: ``` Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 >>> 8885558**.5 - math.sqrt(8885558) -4.5474735088646412e-13 ``` Checking all integers below 10\*\*7, the two methods produced...
Neither one is more accurate, they both diverge from the actual answer in equal parts: ``` >>> (8885558**0.5)**2 8885557.9999999981 >>> sqrt(8885558)**2 8885558.0000000019 >>> 2**1023.99999999999 1.7976931348498497e+308 >>> (sqrt(2**1023.99999999999))**2 1.7976931348498495e+308 >>> ((2**1023.99999999999)**0.5)**2 1....
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python?
842,557
29
2009-05-09T02:47:10Z
842,567
22
2009-05-09T02:57:23Z
[ "python" ]
I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the `dump` operation is occurring, `dump` gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be `load`ed again. Is there a way to make `dump`, o...
Put the function in a thread, and wait for the thread to finish. Python threads cannot be interrupted except with a special C api. ``` import time from threading import Thread def noInterrupt(): for i in xrange(4): print i time.sleep(1) a = Thread(target=noInterrupt) a.start() a.join() print "do...
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python?
842,557
29
2009-05-09T02:47:10Z
842,807
17
2009-05-09T06:26:34Z
[ "python" ]
I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the `dump` operation is occurring, `dump` gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be `load`ed again. Is there a way to make `dump`, o...
Use the [signal](http://docs.python.org/library/signal.html) module to disable SIGINT for the duration of the process: ``` s = signal.signal(signal.SIGINT, signal.SIG_IGN) do_important_stuff() signal.signal(signal.SIGINT, s) ```
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python?
842,557
29
2009-05-09T02:47:10Z
21,919,644
30
2014-02-20T21:09:02Z
[ "python" ]
I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the `dump` operation is occurring, `dump` gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be `load`ed again. Is there a way to make `dump`, o...
The following is a context manager that attaches a signal handler for `SIGINT`. If the context manager's signal handler is called, the signal is delayed by only passing the signal to the original handler when the context manager exits. ``` import signal import logging class DelayedKeyboardInterrupt(object): def _...
What are some good ways to set a path in a Multi-OS supported Python script
842,570
5
2009-05-09T03:00:43Z
842,577
8
2009-05-09T03:06:00Z
[ "python" ]
When writing a Python script that can be executed in different operating system environments (Windows/\*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the current directory. Is this an acceptable approach (I'm rather new to Python) or ...
Definitely have a look at `os.path`. It contains many of the "safe" cross-OS path manipulation functions you need. For example, I've always done this in the scenario you're outlining: ``` os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs') ``` Also note that if you want to get the path separator, you can...
Using Sql Server with Django in production
842,831
32
2009-05-09T06:45:30Z
843,517
17
2009-05-09T15:47:54Z
[ "python", "sql-server", "django", "pyodbc" ]
Has anybody got recent experience with deploying a Django application with an SQL Server database back end? Our workplace is heavily invested in SQL Server and will not support Django if there isn't a sufficiently developed back end for it. I'm aware of mssql.django-pyodbc and django-mssql as unofficially supported ba...
As has been stated, django-pyodbc is a good way to go. PyODBC is probably the most mature SQL Server library for Python there is. The only thing you may have problems with is that pyodbc doesn't support stored procedures very well (you can call them, but you have no way to get results from them). You *can* call them u...
What's the most efficient way to find one of several substrings in Python?
842,856
21
2009-05-09T07:20:49Z
842,871
30
2009-05-09T07:34:52Z
[ "python", "regex", "string", "substring" ]
I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings. To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4...
I would assume a regex is better than checking for each substring individually because *conceptually* the regular expression is modeled as a DFA, and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string). So, here is an example: ``` import re def wo...
How do I check if a variable exists?
843,277
402
2009-05-09T13:10:31Z
843,293
735
2009-05-09T13:16:05Z
[ "python", "exception", "variables" ]
I want to check if a variable exists. Now I'm doing something like this: ``` try: myVar except NameError: # Do something. ``` Are there other ways without exceptions?
To check the existence of a local variable: ``` if 'myVar' in locals(): # myVar exists. ``` To check the existence of a global variable: ``` if 'myVar' in globals(): # myVar exists. ``` To check if an object has an attribute: ``` if hasattr(obj, 'attr_name'): # obj.attr_name exists. ```
How do I check if a variable exists?
843,277
402
2009-05-09T13:10:31Z
843,306
50
2009-05-09T13:19:28Z
[ "python", "exception", "variables" ]
I want to check if a variable exists. Now I'm doing something like this: ``` try: myVar except NameError: # Do something. ``` Are there other ways without exceptions?
The use of variables that haven't been defined is actually a bad thing in any language since it indicates that the logic of the program hasn't been thought through properly. Python will assume you know what you're doing, otherwise you'd be using VB :-). The following trick, which is similar to yours, will ensure that...
How do I check if a variable exists?
843,277
402
2009-05-09T13:10:31Z
843,326
9
2009-05-09T13:27:55Z
[ "python", "exception", "variables" ]
I want to check if a variable exists. Now I'm doing something like this: ``` try: myVar except NameError: # Do something. ``` Are there other ways without exceptions?
Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables. For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code so...
Python: get http headers from urllib call?
843,392
36
2009-05-09T14:11:51Z
843,401
37
2009-05-09T14:17:34Z
[ "python", "urllib", "forwarding" ]
does urllib fetch the whole page? when a urlopen call is made? I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call? ``` import urllib2 m...
What about sending a HEAD request instead of a normal GET request. The following snipped (copied from a similar [question](http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python)) does exactly that. ``` >>> import httplib >>> conn = httplib.HTTPConnection("www.google.com") >>> conn.req...
Python: get http headers from urllib call?
843,392
36
2009-05-09T14:11:51Z
843,403
7
2009-05-09T14:18:33Z
[ "python", "urllib", "forwarding" ]
does urllib fetch the whole page? when a urlopen call is made? I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call? ``` import urllib2 m...
urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).
Python: get http headers from urllib call?
843,392
36
2009-05-09T14:11:51Z
1,640,946
36
2009-10-29T00:17:31Z
[ "python", "urllib", "forwarding" ]
does urllib fetch the whole page? when a urlopen call is made? I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call? ``` import urllib2 m...
Use the `response.info()` method to get the headers. From the [urllib2 docs](http://docs.python.org/library/urllib2.html?highlight=urllib2#module-urllib2): > urllib2.urlopen(url[, data][, timeout]) > > ... > > This function returns a file-like object with two additional methods: > > * geturl() — return the URL of t...
Python: get http headers from urllib call?
843,392
36
2009-05-09T14:11:51Z
9,350,032
15
2012-02-19T14:27:46Z
[ "python", "urllib", "forwarding" ]
does urllib fetch the whole page? when a urlopen call is made? I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call? ``` import urllib2 m...
Actually, it appears that urllib2 can do an HTTP HEAD request. The [question](http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python) that @reto linked to, above, shows how to get urllib2 to do a HEAD request. Here's my take on it: ``` import urllib2 # Derive from Request class and ...
Barchart (o plot) 3D in Python
843,449
6
2009-05-09T14:53:16Z
843,640
7
2009-05-09T16:56:07Z
[ "python", "matplotlib", "plot", "3d" ]
I need to plot some data in various forms. Currently I'm using [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) and I'm fairly happy with the plots I'm able to produce. This question is on how to plot the last one. The data is similar to the "distance table", like [this](http://www.southernct.edu/wellness/uploads...
For some time now, matplotlib had no 3D support, but it has been added back [recently](http://thread.gmane.org/gmane.comp.python.matplotlib.devel/6762/focus=6820). You will need to use the svn version, since no release has been made since, and the documentation is a little sparse (see examples/mplot3d/demo.py). I don't...
Writing a __init__ function to be used in django model
843,580
40
2009-05-09T16:23:35Z
843,669
34
2009-05-09T17:10:33Z
[ "python", "django" ]
I'm trying to write an `__init__` function for one of my models so that I can create an object by doing ``` p = User('name','email') ``` When I write the model, I have ``` def __init__(self, name, email, house_id, password): models.Model.__init__(self) self.name = name self.em...
Django expects the signature of a model's constructor to be `(self, *args, **kwargs)`, or some reasonable facsimile. Your changing the signature to something completely incompatible has broken it.
Writing a __init__ function to be used in django model
843,580
40
2009-05-09T16:23:35Z
843,740
65
2009-05-09T17:55:47Z
[ "python", "django" ]
I'm trying to write an `__init__` function for one of my models so that I can create an object by doing ``` p = User('name','email') ``` When I write the model, I have ``` def __init__(self, name, email, house_id, password): models.Model.__init__(self) self.name = name self.em...
Relying on Django's built-in functionality and passing named parameters would be the simplest way to go. ``` p = User(name="Fred", email="[email protected]") ``` But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with the initializer. ``` # In U...
Profiling in Python: Who called the function?
843,671
40
2009-05-09T17:10:52Z
843,690
32
2009-05-09T17:18:58Z
[ "python", "profiling" ]
I'm profiling in Python using `cProfile`. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most? **EDIT:** I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?
That may not answer your question directly, but will definitely help. If use the profiler with option --sort cumulative it will sort the functions by cumulative time. Which is helpful to detect not only heavy functions but the functions that call them. ``` python -m cProfile --sort cumulative myScript.py ``` There is...
Profiling in Python: Who called the function?
843,671
40
2009-05-09T17:10:52Z
843,703
10
2009-05-09T17:25:37Z
[ "python", "profiling" ]
I'm profiling in Python using `cProfile`. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most? **EDIT:** I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?
[inspect.stack()](http://docs.python.org/library/inspect.html#inspect.stack) will give you the current caller stack.
Profiling in Python: Who called the function?
843,671
40
2009-05-09T17:10:52Z
843,725
92
2009-05-09T17:41:25Z
[ "python", "profiling" ]
I'm profiling in Python using `cProfile`. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most? **EDIT:** I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?
I almost always view the output of the cProfile module using [Gprof2dot](http://code.google.com/p/jrfonseca/wiki/Gprof2Dot), basically it converts the output into a graphvis graph (a `.dot` file), for example: [![example gprof2dot output](http://i.stack.imgur.com/1LrS7.png)](http://jrfonseca.googlecode.com/svn/wiki/gp...
list.append or list +=?
843,751
25
2009-05-09T17:59:10Z
843,761
54
2009-05-09T18:05:09Z
[ "python" ]
Which is more pythonic? ``` list.append(1) ``` or ``` list += [1] ```
From the [Zen of Python](http://www.python.org/dev/peps/pep-0020/): > Explicit is better than implicit. So: `list.append(1)`
list.append or list +=?
843,751
25
2009-05-09T17:59:10Z
843,762
57
2009-05-09T18:05:12Z
[ "python" ]
Which is more pythonic? ``` list.append(1) ``` or ``` list += [1] ```
`list.append(1)` is faster, because it doesn't create a temporary list object.
list.append or list +=?
843,751
25
2009-05-09T17:59:10Z
843,936
16
2009-05-09T20:02:44Z
[ "python" ]
Which is more pythonic? ``` list.append(1) ``` or ``` list += [1] ```
These are two different operations, what you are doing with += is the extend operation. Here is what Python documents have to say about this: > list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x]. > > list.extend(L): Extend the list by appending all the items in the given list; equivalen...
How can I check Hamming Weight without converting to binary?
843,828
8
2009-05-09T18:54:53Z
843,846
7
2009-05-09T19:05:58Z
[ "python", "algorithm", "discrete-mathematics" ]
How can I get the **number of "1"s** in the binary representation of a number without actually converting and counting ? e.g. ``` def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 n /= 2 return c >>> n...
I'm not a python programmer, but hopefully it will be enough for you to follow. ``` c = 0 while n: c += 1 n &= n - 1 return c ``` While a little obscure, it's primary advantage is speed and simplicity. The while loop is only iterated once for every bit set to 1 in n.
Regular expression implementation details
844,183
11
2009-05-09T22:12:50Z
844,267
16
2009-05-09T23:03:17Z
[ "python", "regex" ]
A [question that I answered](http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python) got me wondering: How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to chang...
Python's re module was based on [PCRE](http://en.wikipedia.org/wiki/PCRE), but has moved on to their own implementation. Here is the link to the [C code](http://hg.python.org/cpython/file/a82fc1f366b4/Modules/_sre.c). It appears as though the library is based on recursive backtracking when an incorrect path has been ...
Python regex question: stripping multi-line comments but maintaining a line break
844,681
3
2009-05-10T04:20:41Z
844,721
9
2009-05-10T05:01:02Z
[ "python", "regex", "parsing", "comments" ]
I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /*....*/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead. For example, the code: ``` qwe /* 123 456 789 ...
``` comment_re = re.compile( r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?', re.DOTALL | re.MULTILINE ) def comment_replacer(match): start,mid,end = match.group(1,2,3) if mid is None: # single line comment return '' elif start is not None or end is not None: # multi line...
Performing a getattr() style lookup in a django template
844,746
31
2009-05-10T05:15:16Z
1,112,236
48
2009-07-10T22:09:44Z
[ "python", "django", "django-templates" ]
Python's getattr() method is useful when you don't know the name of a certain attribute in advance. This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups?
I also had to [write this code](http://snipt.net/Fotinakis/django-template-tag-for-dynamic-attribute-lookups/) as a custom template tag recently. To handle all look-up scenarios, it first does a standard attribute look-up, then tries to do a dictionary look-up, then tries a **getitem** lookup (for lists to work), then ...
"x Days ago' template filter in Django?
845,009
7
2009-05-10T09:35:55Z
845,014
21
2009-05-10T09:43:02Z
[ "python", "django" ]
I'm looking for a filter that turns a datetime instance into 'x Days' or 'x years y months' format (as on SO). Suggestions? Am I overlooking something very obvious?
Have a look at the [timesince](http://docs.djangoproject.com/en/1.0/ref/templates/builtins/#timesince) template filter. It's builtin. The following returns a humanized diff between now and `comment_date` (e.g. `'8 hours'`): ``` {{ comment_date|timesince }} ``` The following returns a humanized diff between `question...
How to get line count cheaply in Python?
845,058
470
2009-05-10T10:22:05Z
845,069
49
2009-05-10T10:28:29Z
[ "python", "text-files", "line-count" ]
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: ``` def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 ``` is it possible to do any be...
You could execute a subprocess and run `wc -l filename` ``` import subprocess def file_len(fname): p = subprocess.Popen(['wc', '-l', fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, err = p.communicate() if p.returncode != 0: raise IOEr...
How to get line count cheaply in Python?
845,058
470
2009-05-10T10:22:05Z
845,081
157
2009-05-10T10:37:42Z
[ "python", "text-files", "line-count" ]
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: ``` def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 ``` is it possible to do any be...
You can't get any better than that. After all, any solution will have to read the entire file, figure out how many `\n` you have, and return that result. Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you can do is make sure you don...
How to get line count cheaply in Python?
845,058
470
2009-05-10T10:22:05Z
850,962
139
2009-05-12T02:49:04Z
[ "python", "text-files", "line-count" ]
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: ``` def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 ``` is it possible to do any be...
I believe that a memory mapped file will be the fastest solution. I tried four functions: the function posted by the OP (`opcount`); a simple iteration over the lines in the file (`simplecount`); readline with a memory-mapped filed (mmap) (`mapcount`); and the buffer read solution offered by Mykola Kharechko (`bufcount...
How to get line count cheaply in Python?
845,058
470
2009-05-10T10:22:05Z
1,019,572
308
2009-06-19T19:07:06Z
[ "python", "text-files", "line-count" ]
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: ``` def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 ``` is it possible to do any be...
One line, probably pretty fast: ``` num_lines = sum(1 for line in open('myfile.txt')) ```
How to get line count cheaply in Python?
845,058
470
2009-05-10T10:22:05Z
6,826,326
23
2011-07-26T06:51:01Z
[ "python", "text-files", "line-count" ]
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: ``` def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 ``` is it possible to do any be...
Here is a python program to use the multiprocessing library to distribute the line counting across machines/cores. My test improves counting a 20million line file from 26 seconds to 7 seconds using an 8 core windows 64 server. Note: not using memory mapping makes things much slower. ``` import multiprocessing, sys, ti...
How to get line count cheaply in Python?
845,058
470
2009-05-10T10:22:05Z
19,248,109
8
2013-10-08T12:46:12Z
[ "python", "text-files", "line-count" ]
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: ``` def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 ``` is it possible to do any be...
I would use Python's file object method `readlines`, as follows: ``` with open(input_file) as foo: lines = len(foo.readlines()) ``` This opens the file, creates a list of lines in the file, counts the length of the list, saves that to a variable and closes the file again.
How to get line count cheaply in Python?
845,058
470
2009-05-10T10:22:05Z
27,518,377
26
2014-12-17T04:32:25Z
[ "python", "text-files", "line-count" ]
I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: ``` def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 ``` is it possible to do any be...
I had to post this on a similar question until my reputation score jumped a bit (thanks to whoever bumped me!). All of these solutions ignore one way to make this run considerably faster, namely by using the unbuffered (raw) interface, using bytearrays, and doing your own buffering. (This only applies in Python 3. In ...
Emulating pass-by-value behaviour in python
845,110
33
2009-05-10T11:05:50Z
845,194
24
2009-05-10T11:57:47Z
[ "python", "pass-by-value" ]
I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. One possible way is to use deep copy: ``` from copy import deepcopy def f(data): data = deepcopy(data) #do stuff ``` is there more ef...
You can make a decorator and put the cloning behaviour in that. ``` >>> def passbyval(func): def new(*args): cargs = [deepcopy(arg) for arg in args] return func(*cargs) return new >>> @passbyval def myfunc(a): print a >>> myfunc(20) 20 ``` This is not the most robust way, and doesn't handle key-value argument...
Emulating pass-by-value behaviour in python
845,110
33
2009-05-10T11:05:50Z
845,691
22
2009-05-10T17:16:08Z
[ "python", "pass-by-value" ]
I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. One possible way is to use deep copy: ``` from copy import deepcopy def f(data): data = deepcopy(data) #do stuff ``` is there more ef...
There is no pythonic way of doing this. Python provides very few facilities for *enforcing* things such as private or read-only data. The pythonic philosophy is that "we're all consenting adults": in this case this means that "the function shouldn't change the data" is part of the spec but not enforced in the code. -...
Emulating pass-by-value behaviour in python
845,110
33
2009-05-10T11:05:50Z
9,762,918
8
2012-03-18T22:32:10Z
[ "python", "pass-by-value" ]
I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. One possible way is to use deep copy: ``` from copy import deepcopy def f(data): data = deepcopy(data) #do stuff ``` is there more ef...
There are only a couple of builtin typs that work as references, like `list`, for example. So, for me the pythonic way for doing a pass-by-value, for list, in this example, would be: ``` list1 = [0,1,2,3,4] list2 = list1[:] ``` `list1[:]` creates a new instance of the list1, and you can assign it to a new variable. ...
Concise vector adding in Python?
845,112
21
2009-05-10T11:05:59Z
845,120
9
2009-05-10T11:09:52Z
[ "python" ]
I often do vector addition of Python lists. Example: I have two lists like these: ``` a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] ``` I now want to add b to a to get the result `a = [3.0, 5.0, 7.0]`. Usually I end up doing like this: ``` a[0] += b[0] a[1] += b[1] a[2] += b[2] ``` Is there some efficient, standard way...
How about this: ``` a = [x+y for x,y in zip(a,b)] ```
Concise vector adding in Python?
845,112
21
2009-05-10T11:05:59Z
845,139
27
2009-05-10T11:21:09Z
[ "python" ]
I often do vector addition of Python lists. Example: I have two lists like these: ``` a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] ``` I now want to add b to a to get the result `a = [3.0, 5.0, 7.0]`. Usually I end up doing like this: ``` a[0] += b[0] a[1] += b[1] a[2] += b[2] ``` Is there some efficient, standard way...
If you need efficient vector arithmetic, try [Numpy](http://numpy.scipy.org/). ``` >>> import numpy >>> a=numpy.array([0,1,2]) >>> b=numpy.array([3,4,5]) >>> a+b array([3, 5, 7]) >>> ``` Or (thanks, Andrew Jaffe), ``` >>> a += b >>> a array([3, 5, 7]) >>> ```
Concise vector adding in Python?
845,112
21
2009-05-10T11:05:59Z
845,314
27
2009-05-10T13:15:23Z
[ "python" ]
I often do vector addition of Python lists. Example: I have two lists like these: ``` a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] ``` I now want to add b to a to get the result `a = [3.0, 5.0, 7.0]`. Usually I end up doing like this: ``` a[0] += b[0] a[1] += b[1] a[2] += b[2] ``` Is there some efficient, standard way...
While Numeric is excellent, and list-comprehension solutions OK if you actually wanted to create a new list, I'm surprised nobody suggested the "one obvious way to do it" -- a simple `for` loop! Best: ``` for i, bi in enumerate(b): a[i] += bi ``` Also OK, kinda sorta: ``` for i in xrange(len(a)): a[i] += b[i] ```
Concise vector adding in Python?
845,112
21
2009-05-10T11:05:59Z
845,758
12
2009-05-10T17:58:53Z
[ "python" ]
I often do vector addition of Python lists. Example: I have two lists like these: ``` a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] ``` I now want to add b to a to get the result `a = [3.0, 5.0, 7.0]`. Usually I end up doing like this: ``` a[0] += b[0] a[1] += b[1] a[2] += b[2] ``` Is there some efficient, standard way...
If you think Numpy is overkill, this should be really fast, because this code runs in pure C (`map()` and `__add__()` are both directly implemented in C): ``` a = [1.0,2.0,3.0] b = [4.0,5.0,6.0] c = map(float.__add__, a, b) ``` Or alternatively, if you don't know the types in the list: ``` import operator c = map(o...
Concise vector adding in Python?
845,112
21
2009-05-10T11:05:59Z
846,274
20
2009-05-10T22:54:47Z
[ "python" ]
I often do vector addition of Python lists. Example: I have two lists like these: ``` a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] ``` I now want to add b to a to get the result `a = [3.0, 5.0, 7.0]`. Usually I end up doing like this: ``` a[0] += b[0] a[1] += b[1] a[2] += b[2] ``` Is there some efficient, standard way...
I don't think you will find a faster solution than the 3 sums proposed in the question. The advantages of numpy are visible with larger vectors, and also if you need other operators. numpy is specially useful with matrixes, witch are trick to do with python lists. Still, yet another way to do it :D ``` In [1]: a = [1...
Converting a java System.currentTimeMillis() to date in python
845,153
6
2009-05-10T11:33:43Z
845,167
15
2009-05-10T11:40:38Z
[ "java", "python", "date", "formatting", "timestamp" ]
I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that. How should I do that ? The following give **ValueError: timestamp out of range for platform time\_t** on Linux 32bit ``` #!/usr/bin/env python from datet...
Python expects seconds, so divide it by 1000.0 first: ``` >>> print date.fromtimestamp(1241711346274/1000.0) 2009-05-07 ```
How to print the comparison of two multiline strings in unified diff format?
845,276
7
2009-05-10T12:51:12Z
845,284
17
2009-05-10T12:54:51Z
[ "python", "diff", "unified-diff" ]
Do you know any library that will help doing that? I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that: ``` def print_differences(string1, string2): """ Prints the comparison of string1 to string2 as unified diff format. """ ...
Did you have a look at the built-in python module [difflib](http://docs.python.org/library/difflib.html)? Have a look that this [example](http://docs.python.org/library/difflib.html#differ-example)
How to print the comparison of two multiline strings in unified diff format?
845,276
7
2009-05-10T12:51:12Z
845,432
11
2009-05-10T14:25:22Z
[ "python", "diff", "unified-diff" ]
Do you know any library that will help doing that? I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that: ``` def print_differences(string1, string2): """ Prints the comparison of string1 to string2 as unified diff format. """ ...
This is how I solved: ``` def _unidiff_output(expected, actual): """ Helper function. Returns a string containing the unified diff of two multiline strings. """ import difflib expected=expected.splitlines(1) actual=actual.splitlines(1) diff=difflib.unified_diff(expected, actual) retu...
Canonical/Idiomatic "do what I mean" when passed a string that could a filename, URL, or the actual data to work on
845,408
2
2009-05-10T14:11:21Z
845,424
7
2009-05-10T14:18:51Z
[ "python" ]
It's not uncommon to see Python libraries that expose a universal "opener" function, that accept as their primary argument a string that could either represent a local filename (which it will open and operate on), a URL(which it will download and operate on), or data(which it will operate on). Here's [an example from ...
Ultimately, any module implementing this behaviour is going to parse the string. And act according to the result. In feedparser for example they are parsing the url: ``` if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'): # do something with the url else: # This is a file path r...
using Python objects in C#
845,502
4
2009-05-10T15:11:45Z
845,506
7
2009-05-10T15:14:10Z
[ "c#", "python", "ironpython" ]
Is there an easy way to call Python objects from C#, that is without any COM mess?
Yes, by hosting IronPython.
OOP: good class design
845,966
15
2009-05-10T19:38:22Z
845,984
28
2009-05-10T19:47:10Z
[ "python", "language-agnostic", "oop" ]
My question is related to this one: [Python tool that builds a dependency diagram for methods of a class](http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class). After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed t...
We follow the following principles when designing classes: * [The Single Responsibility Principle](http://www.google.co.za/url?sa=t&source=web&ct=res&cd=2&url=http%3A%2F%2Fwww.objectmentor.com%2Fresources%2Farticles%2Fsrp.pdf&ei=1C4HSu3uEODJtgfs8uWeBw&usg=AFQjCNHQQ1Aw-2yCciEbERpJn3VdHBCmQw&sig2=Pf7Z4GNwRnAiaar%5FyCk%5...
Convert a Python int into a big-endian string of bytes
846,038
41
2009-05-10T20:24:01Z
846,045
32
2009-05-10T20:27:59Z
[ "python" ]
I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3. My ints are on the scale of 35 (base-10) d...
You can use the [struct](http://docs.python.org/library/struct.html) module: ``` import struct print struct.pack('>I', your_int) ``` `'>I'` is a format string. `>` means big endian and `I` means unsigned int. Check the documentation for more format chars.
Convert a Python int into a big-endian string of bytes
846,038
41
2009-05-10T20:24:01Z
846,063
7
2009-05-10T20:42:47Z
[ "python" ]
I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3. My ints are on the scale of 35 (base-10) d...
Probably the best way is via the built-in [struct module](http://docs.python.org/library/struct.html): ``` >>> import struct >>> x = 1245427 >>> struct.pack('>BH', x >> 16, x & 0xFFFF) '\x13\x00\xf3' >>> struct.pack('>L', x)[1:] # could do it this way too '\x13\x00\xf3' ``` Alternatively -- and I wouldn't usually re...
Convert a Python int into a big-endian string of bytes
846,038
41
2009-05-10T20:24:01Z
846,067
12
2009-05-10T20:44:32Z
[ "python" ]
I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3. My ints are on the scale of 35 (base-10) d...
This is fast and works for small and (arbitrary) large ints: ``` def Dump(n): s = '%x' % n if len(s) & 1: s = '0' + s return s.decode('hex') print repr(Dump(1245427)) #: '\x13\x00\xf3' ```
Convert a Python int into a big-endian string of bytes
846,038
41
2009-05-10T20:24:01Z
12,859,903
23
2012-10-12T13:15:51Z
[ "python" ]
I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3. My ints are on the scale of 35 (base-10) d...
In Python 3.2+, you can use [int.to\_bytes](http://docs.python.org/py3k/library/stdtypes.html#int.to_bytes): ## If you don't want to specify the size ``` >>> n = 1245427 >>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0' b'\x13\x00\xf3' ``` ## If you don't mind specifying the size ``` >>> (1245427).to_bytes(...
What's the quickest way for a Ruby programmer to pick up Python?
846,139
10
2009-05-10T21:25:18Z
846,151
9
2009-05-10T21:30:45Z
[ "python", "ruby" ]
I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical langua...
A safe bet is to just dive into python (skim through some tutorials that explain the syntax), and then get coding. The best way to learn any new language is to write code, [lots of it](http://projecteuler.net/index.php?section=problems). Your experience in Ruby will make it easy to pick up python's dynamic concepts (wh...
Problem installing pyscopg2 on Mac OS X
846,383
3
2009-05-11T00:41:23Z
846,403
11
2009-05-11T00:55:08Z
[ "python", "database", "django", "osx" ]
I have downloaded the latest build of pyscopg2 and have tried to build and install it using the directions provided. However i always get an error saying that 'w' is undeclared. Does anybody have any experience with this?
This is an error that crops up when the build tools cannot find your Postgresql libraries. It means one of three things: 1. You don't have postgresql installed on your system. If so, download and build postgres, or download a pre-built psycopg2 binary for OS X. 2. You have postgresql installed on your system, but you ...
Is there a mod_python for Apache HTTP Server 2.2 and Python 2.6 or 3.0?
846,420
2
2009-05-11T01:12:37Z
846,430
9
2009-05-11T01:17:51Z
[ "python", "apache2", "mod-python" ]
I poked around the [mod\_python website](http://www.modpython.org/) and I only found the files for Python 2.5 and earlier for Apache HTTP Server 2.2. I Googled around a little, without significant luck. Any suggestions?
Use mod\_wsgi. mod\_python has been stagnant for a while now. Most of the effort for python web apps has been going into mod\_wsgi.
A ListView of checkboxes in PyQt
846,684
9
2009-05-11T04:02:36Z
854,535
9
2009-05-12T19:49:48Z
[ "python", "qt", "pyqt", "qitemdelegate", "qlistview" ]
I want to display a QListView where each item is a checkbox with some label. The checkboxes should be visible at all times. One way I can think of is using a custom delegate and QAbstractListModel. Are there simpler ways? Can you provide the simplest snippet that does this? Thanks in advance
See my reply to your question on the PyQt mailing list: <http://www.riverbankcomputing.com/pipermail/pyqt/2009-May/023002.html> Summary: You need to use the ItemIsUserCheckable flag and CheckStateRole role.
A ListView of checkboxes in PyQt
846,684
9
2009-05-11T04:02:36Z
855,938
21
2009-05-13T03:34:00Z
[ "python", "qt", "pyqt", "qitemdelegate", "qlistview" ]
I want to display a QListView where each item is a checkbox with some label. The checkboxes should be visible at all times. One way I can think of is using a custom delegate and QAbstractListModel. Are there simpler ways? Can you provide the simplest snippet that does this? Thanks in advance
I ended up using the method provided by [David Boddie](http://stackoverflow.com/users/61047/david-boddie) in the PyQt mailing list. Here's a working snippet based on his code: ``` from PyQt4.QtCore import * from PyQt4.QtGui import * import sys from random import randint app = QApplication(sys.argv) model = QStandar...
Read Unicode characters from command-line arguments in Python 2.x on Windows
846,850
24
2009-05-11T05:44:02Z
846,931
24
2009-05-11T06:21:59Z
[ "python", "windows", "command-line", "unicode", "python-2.x" ]
I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode? Example code: `argv.py` ``` import sys first_arg = sys.argv[1] print first_arg print typ...
Here is a solution that is just what I'm looking for, making a call to the Windows `GetCommandLineArgvW` function: [Get sys.argv with Unicode characters under Windows](http://code.activestate.com/recipes/572200/) (from ActiveState) But I've made several changes, to simplify its usage and better handle certain uses....
Read Unicode characters from command-line arguments in Python 2.x on Windows
846,850
24
2009-05-11T05:44:02Z
847,114
10
2009-05-11T07:45:24Z
[ "python", "windows", "command-line", "unicode", "python-2.x" ]
I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode? Example code: `argv.py` ``` import sys first_arg = sys.argv[1] print first_arg print typ...
Dealing with encodings is very confusing. I *believe* if your inputing data via the commandline it will encode the data as whatever your system encoding is and is not unicode. (Even copy/paste should do this) So it should be correct to decode into unicode using the system encoding: ``` import sys first_arg = sys.ar...
Cross-platform way of getting temp directory in Python
847,850
123
2009-05-11T12:21:46Z
847,866
189
2009-05-11T12:25:18Z
[ "python", "cross-platform", "temporary-directory" ]
Is there a cross-platform way of getting the path to the *`temp`* directory in Python 2.6? For example, under Linux that would be `/tmp`, while under XP `C:\Documents and settings\[user]\Application settings\Temp`. Thanks!
That would be the [tempfile](http://docs.python.org/library/tempfile.html) module. It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed. Example: ``` import tempfile print tempfile.gettempdir() # prints the current temp...
Cross-platform way of getting temp directory in Python
847,850
123
2009-05-11T12:21:46Z
847,874
35
2009-05-11T12:27:30Z
[ "python", "cross-platform", "temporary-directory" ]
Is there a cross-platform way of getting the path to the *`temp`* directory in Python 2.6? For example, under Linux that would be `/tmp`, while under XP `C:\Documents and settings\[user]\Application settings\Temp`. Thanks!
This should do what you want: ``` print tempfile.gettempdir() ``` For me on my Windows box, I get: ``` c:\temp ``` and on my Linux box I get: ``` /tmp ```
How do I upload pickled data to django FileField?
847,904
4
2009-05-11T12:36:38Z
848,737
8
2009-05-11T15:48:04Z
[ "python", "django", "file", "upload", "pickle" ]
I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is: ``` #models.py from django.db import models class Data(models.Model): label = models.CharField(max_length=30) file = models.FileFiel...
Based on the answers to the questions I came up with the following solution: ``` from django.core.files.base import ContentFile import pickle content = pickle.dumps(somedata) fid = ContentFile(content) data_entry.file.save(filename, fid) fid.close() ``` All of it is done on the server side and and users are NOT allo...
Writing/parsing a fixed width file using Python
848,537
11
2009-05-11T15:01:36Z
848,661
15
2009-05-11T15:32:37Z
[ "python", "parsing", "edi" ]
I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires. Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response...
You don't need to assign to slices, just build the string using [`% formatting`](http://docs.python.org/library/stdtypes.html#string-formatting-operations). An example with a fixed format for 3 data items: ``` >>> fmt="%4s%10s%10s" >>> fmt % (1,"ONE",2) ' 1 ONE 2' >>> ``` Same thing, field width supp...
Writing/parsing a fixed width file using Python
848,537
11
2009-05-11T15:01:36Z
848,698
7
2009-05-11T15:37:43Z
[ "python", "parsing", "edi" ]
I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires. Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response...
You can use [justify](http://docs.python.org/library/string.html#string.ljust) functions to left-justify, right-justify and center a string in a field of given width. ``` 'hi'.ljust(10) -> 'hi ' ```
Is it possible to speed-up python IO?
849,058
8
2009-05-11T17:06:46Z
849,645
11
2009-05-11T19:24:57Z
[ "python", "linux", "performance", "text-files" ]
Consider this python program: ``` import sys lc = 0 for line in open(sys.argv[1]): lc = lc + 1 print lc, sys.argv[1] ``` Running it on my 6GB text file, it completes in ~ 2minutes. Question: **is it possible to go faster?** Note that the same time is required by: ``` wc -l myfile.txt ``` so, I suspect the a...
**Throw hardware at the problem.** As gs pointed out, your bottleneck is the hard disk transfer rate. So, no you can't use a better algorithm to improve your time, but you can buy a faster hard drive. **Edit:** Another good point by gs; you could also use a [RAID](http://en.wikipedia.org/wiki/Redundant%5Farray%5Fof%5...
How to limit the maximum value of a numeric field in a Django model?
849,142
87
2009-05-11T17:29:57Z
849,177
9
2009-05-11T17:39:52Z
[ "python", "django", "django-models", "numbers" ]
Django has various numeric fields available for use in models, e.g. [DecimalField](http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield) and [PositiveIntegerField](http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield). Although the former can be restricted to the number of decima...
There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. [Form validation docs](http://docs.djangoproject.com/en/dev/ref/forms/validation/). If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the ...
How to limit the maximum value of a numeric field in a Django model?
849,142
87
2009-05-11T17:29:57Z
849,426
95
2009-05-11T18:31:21Z
[ "python", "django", "django-models", "numbers" ]
Django has various numeric fields available for use in models, e.g. [DecimalField](http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield) and [PositiveIntegerField](http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield). Although the former can be restricted to the number of decima...
You could also create a custom model field type - see <http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields> In this case, you could 'inherit' from the built-in IntegerField and override its validation logic. The more I think about this, I realize how useful this would be for many...
How to limit the maximum value of a numeric field in a Django model?
849,142
87
2009-05-11T17:29:57Z
4,047,378
41
2010-10-28T21:38:25Z
[ "python", "django", "django-models", "numbers" ]
Django has various numeric fields available for use in models, e.g. [DecimalField](http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield) and [PositiveIntegerField](http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield). Although the former can be restricted to the number of decima...
I had this very same problem; here was my solution: ``` SCORE_CHOICES = zip( range(1,n), range(1,n) ) score = models.IntegerField(choices=SCORE_CHOICES, blank=True) ```
How to limit the maximum value of a numeric field in a Django model?
849,142
87
2009-05-11T17:29:57Z
12,026,867
144
2012-08-19T13:32:39Z
[ "python", "django", "django-models", "numbers" ]
Django has various numeric fields available for use in models, e.g. [DecimalField](http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield) and [PositiveIntegerField](http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield). Although the former can be restricted to the number of decima...
You can use [Django's built-in validators](https://docs.djangoproject.com/en/dev/ref/validators/#built-in-validators)— ``` from django.db.models import IntegerField, Model from django.core.validators import MaxValueValidator, MinValueValidator class CoolModelBro(Model): limited_integer_field = IntegerField( ...
How to limit the maximum value of a numeric field in a Django model?
849,142
87
2009-05-11T17:29:57Z
12,027,012
47
2012-08-19T13:54:25Z
[ "python", "django", "django-models", "numbers" ]
Django has various numeric fields available for use in models, e.g. [DecimalField](http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield) and [PositiveIntegerField](http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield). Although the former can be restricted to the number of decima...
``` from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator size = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(5)]) ```
How do I enumerate() over a list of tuples in Python?
849,369
25
2009-05-11T18:20:13Z
849,388
60
2009-05-11T18:23:36Z
[ "python", "list", "enumerate" ]
I've got some code like this: ``` letters = [('a', 'A'), ('b', 'B')] i = 0 for (lowercase, uppercase) in letters: print "Letter #%d is %s/%s" % (i, lowercase, uppercase) i += 1 ``` I've been told that there's an enumerate() function that can take care of the "i" variable for me: ``` for i, l in enumerate(['a...
This is a neat way to do it: ``` letters = [('a', 'A'), ('b', 'B')] for i, (lowercase, uppercase) in enumerate(letters): print "Letter #%d is %s/%s" % (i, lowercase, uppercase) ```
django template includes
849,463
3
2009-05-11T18:41:24Z
849,574
16
2009-05-11T19:11:25Z
[ "python", "django", "django-templates" ]
I'm having an issue with django templates at the moment. I have 3 template files basically: * Base * story\_list * story\_detail Story\_list and \_detail extend Base, and that works perfectly fine. However, list and detail share some code that extend the base template for my sidebar. I'm basically repeating a chunk o...
Generally, using `include`s is not the answer with Django templates. Let me answer your question on several fronts. First, let me address the sidebar. * **Are nearly all the common pages going to be using that sidebar?** Put it in `Base`. Don't override those sidebar blocks (i.e. don't write them at all in your `Stor...
Simple threading in Python 2.6 using thread.start_new_thread()
849,674
11
2009-05-11T19:32:17Z
849,759
22
2009-05-11T19:53:08Z
[ "python", "multithreading", "python-2.6" ]
I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current ``` import thread def myfunction(mystring,*args): print mystring if __name__...
The problem is that your main thread has quit before your new thread has time to finish. The solution is to wait at your main thread. ``` import thread, time def myfunction(mystring,*args): print mystring if __name__ == '__main__': try: thread.start_new_thread(myfunction,('MyStringHere',1)) e...