title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to profile a Django custom management command exclusively
1,687,125
7
2009-11-06T11:54:56Z
1,693,616
9
2009-11-07T16:40:05Z
[ "python", "django", "profiling" ]
I would like to profile a custom management command that is relatively CPU intensive (renders an image using PIL). When I use the following command I get all sorts of Django modules (admin, ORM etc) in my profiling results: ``` python -m cProfile manage.py testrender ``` I have removed all imports that can potentiall...
I solved this problem the following way: ``` from cProfile import Profile from django.core.management.base import BaseCommand class Command(BaseCommand): ... def _handle(self, *args, **options): # Actual code I want to profile pass def handle(self, *args, **options): if options[...
Why does str.lstrip strips an extra character?
1,687,171
9
2009-11-06T12:05:30Z
1,687,179
22
2009-11-06T12:08:10Z
[ "python", "string" ]
``` Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> path = "/Volumes/Users" >>> path.lstrip('/Volume') 's/Users' >>> path.lstrip('/Volumes') 'Users' >>> ``` I am expecting output o...
`lstrip` is character-based, it removes all characters from the left end that are in that string. To verify this, try this: ``` "/Volumes/Users".lstrip("semuloV/") ``` Since / is part of the string, it is removed. I suspect you need to use slicing instead: ``` if s.startsWith("/Volumes"): s = s[8:] ``` but ho...
Why does str.lstrip strips an extra character?
1,687,171
9
2009-11-06T12:05:30Z
1,687,188
13
2009-11-06T12:09:48Z
[ "python", "string" ]
``` Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> path = "/Volumes/Users" >>> path.lstrip('/Volume') 's/Users' >>> path.lstrip('/Volumes') 'Users' >>> ``` I am expecting output o...
The argument passed to `lstrip` is taken as a set of characters! ``` >>> ' spacious '.lstrip() 'spacious ' >>> 'www.example.com'.lstrip('cmowz.') 'example.com' ``` See also the [documentation](http://docs.python.org/library/stdtypes.html) You might want to use str.replace() ``` str.replace(old, new[, count]) ...
Why does str.lstrip strips an extra character?
1,687,171
9
2009-11-06T12:05:30Z
1,687,204
17
2009-11-06T12:13:38Z
[ "python", "string" ]
``` Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> path = "/Volumes/Users" >>> path.lstrip('/Volume') 's/Users' >>> path.lstrip('/Volumes') 'Users' >>> ``` I am expecting output o...
Strip is character-based. If you are trying to do path manipulation you should have a look at [os.path](http://docs.python.org/library/os.path.html) ``` >>> os.path.split("/Volumes/Users") ('/Volumes', 'Users') ```
PyCrypto not fully installed on Windows XP
1,687,283
29
2009-11-06T12:32:11Z
1,687,516
43
2009-11-06T13:12:27Z
[ "python", "windows", "pycrypto" ]
I ran `python setup.py install` in a Windows XP console, and it reported as follows: ``` running install running build running build_py running build_ext warning: GMP library not found; Not building Crypto.PublicKey._fastmath. building 'Crypto.Random.OSRNG.winrandom' extension error: None ``` When I try to run a scri...
On windows, it may just be easier installing PyCrypto via a prebuilt windows installer. The Voidspace site has [PyCrypto 2.1 and 2.3 installers for Python 2.2-2.7](http://www.voidspace.org.uk/python/modules.shtml#pycrypto).
Updating Python on Mac
1,687,357
15
2009-11-06T12:45:57Z
1,687,456
23
2009-11-06T13:00:27Z
[ "python", "osx", "python-3.x" ]
I wanted to update my python 2.6.1 to 3.x on mac but i was wondering if its possible to do it using terminal or i have to download the installer from python website? The reason why i am asking this question is because installer is not updating my terminal python version.
The default Python on OS X shouldn't be messed with as it's used by the OS itself. If your default is 2.6.1 then you must have Snow Leopard. If you just install from the [standard 3.1 disk image](http://www.python.org/ftp/python/3.1.1/python-3.1.1.dmg) then you can invoke it using `python3.1` from the terminal (you do...
What is the default chunker for NLTK toolkit in Python?
1,687,510
9
2009-11-06T13:10:20Z
1,687,712
9
2009-11-06T13:49:23Z
[ "python", "nlp", "nltk", "chunking" ]
I am using their default POS tagging and default tokenization..and it seems sufficient. I'd like their default chunker too. I am reading the NLTK toolkit book, but it does not seem like they have a default chunker?
You can get out of the box named entity chunking with the nltk.ne\_chunk() method. It takes a list of POS tagged tuples: `nltk.ne_chunk([('Barack', 'NNP'), ('Obama', 'NNP'), ('lives', 'NNS'), ('in', 'IN'), ('Washington', 'NNP')])` results in: `Tree('S', [Tree('PERSON', [('Barack', 'NNP')]), Tree('ORGANIZATION', [('O...
What is the default chunker for NLTK toolkit in Python?
1,687,510
9
2009-11-06T13:10:20Z
1,691,962
8
2009-11-07T04:10:04Z
[ "python", "nlp", "nltk", "chunking" ]
I am using their default POS tagging and default tokenization..and it seems sufficient. I'd like their default chunker too. I am reading the NLTK toolkit book, but it does not seem like they have a default chunker?
I couldn't find a default chunker/shallow parser either. Although the book describes how to build and train one with example features. Coming up with additional features to get good performance shouldn't be too difficult. See Chapter 7's section on [Training Classifier-based Chunkers](http://nltk.googlecode.com/svn/tr...
Why does an assignment for double-sliced numpy arrays not work?
1,687,566
8
2009-11-06T13:21:56Z
1,687,787
9
2009-11-06T14:01:06Z
[ "python", "numpy", "variable-assignment", "slice" ]
why do the following lines not work as I expect? ``` import numpy as np a = np.array([0,1,2,1,1]) a[a==1][1:] = 3 print a >>> [0 1 2 1 1] # I would expect [0 1 2 3 3] ``` Is this a 'bug' or is there another recommended way to this? On the other hand, the following works: ``` a[a==1] = 3 print a >>> [0 3 2 3 3] ``` ...
It's related to how fancy indexing works. There is a thorough explanation [here](http://mail.scipy.org/pipermail/numpy-discussion/2008-January/031101.html). It is done this way to allow inplace modification with fancy indexing (ie `a[x>3] *= 2`). A consequence of this is that you can't assign to a double index as you h...
How flatten a list of lists one step
1,688,712
2
2009-11-06T16:31:10Z
1,688,768
10
2009-11-06T16:38:01Z
[ "python" ]
I have a list of lists of tuples ``` A= [ [(1,2,3),(4,5,6)], [(7,8,9),(8,7,6),(5,4,3)],[(2,1,0),(1,3,5)] ] ``` The outer list can have any number of inner lists, the inner lists can have any number of tuples, a tuple always has 3 integers. I want to generate all combination of tuples, one from each list: ``` [(1,2,...
``` itertools.product(*A) ``` For more details check the [python tutorial](http://www.python.org/doc/current/tutorial/controlflow.html#arbitrary-argument-lists)
Datetime - 10 Hours
1,688,719
3
2009-11-06T16:32:00Z
1,688,738
14
2009-11-06T16:34:05Z
[ "python", "datetime" ]
Consider: ``` now = datetime.datetime.now() now datetime.datetime(2009, 11, 6, 16, 6, 42, 812098) ``` How would I create a new datetime object (`past`) and minus `n` values from the hours?
Use `timedelta` in the `datetime` module: ``` import datetime now = datetime.datetime.now() past = now - datetime.timedelta(hours=10) ```
Datetime - 10 Hours
1,688,719
3
2009-11-06T16:32:00Z
1,688,779
8
2009-11-06T16:39:10Z
[ "python", "datetime" ]
Consider: ``` now = datetime.datetime.now() now datetime.datetime(2009, 11, 6, 16, 6, 42, 812098) ``` How would I create a new datetime object (`past`) and minus `n` values from the hours?
Use a [timedelta](http://docs.python.org/library/datetime.html?highlight=timedelta#datetime.timedelta) object. ``` >>> now = datetime.datetime.now() >>> now datetime.datetime(2009, 11, 6, 16, 35, 50, 593000) >>> ten_hours = datetime.timedelta(hours=10) >>> now + ten_hours datetime.datetime(2009, 11, 7, 2, 35, 50, 5930...
PHPs call_user_func_array in Python
1,688,931
5
2009-11-06T17:01:15Z
1,688,948
9
2009-11-06T17:03:48Z
[ "php", "python" ]
Is there an equivalent in Python for PHP's [call\_user\_func\_array](http://www.php.net/manual/en/function.call-user-func-array.php)?
Call the function with the array preceded by \*: ``` function(*array) ```
python or bash - adding " at beginning of line and ", at end of line
1,688,952
2
2009-11-06T17:04:24Z
1,689,011
8
2009-11-06T17:15:35Z
[ "python", "linux", "bash" ]
I have text file with something like ``` first line line nr 2 line three ``` etc And i want to generate ``` "first line", "line nr 2", "line three", ``` I wonder how to do this in python or maybe in bash if it's easier/quicker. I know there is different code for opening file and different for reading only one line...
``` sed 's/.*/"&",/' ```
Run Python script without Windows console appearing
1,689,015
36
2009-11-06T17:16:28Z
1,689,024
60
2009-11-06T17:17:10Z
[ "python", "windows", "shell" ]
Is there any way to run a Python script in Windows XP without a command shell momentarily appearing? I often need to automate WordPerfect (for work) with Python, and even if my script has no output, if I execute it from without WP an empty shell still pops up for a second before disappearing. Is there any way to preven...
pythonw.exe will run the script without a command prompt. The problem is that the Python interpreter, Python.exe, is linked against the console subsystem to produce console output (since that's 90% of cases) -- pythonw.exe is instead linked against the GUI subsystem, and Windows will not create a console output window ...
Run Python script without Windows console appearing
1,689,015
36
2009-11-06T17:16:28Z
1,689,269
14
2009-11-06T18:00:29Z
[ "python", "windows", "shell" ]
Is there any way to run a Python script in Windows XP without a command shell momentarily appearing? I often need to automate WordPerfect (for work) with Python, and even if my script has no output, if I execute it from without WP an empty shell still pops up for a second before disappearing. Is there any way to preven...
If you name your files with the ".pyw" extension, then windows will execute them with the pythonw.exe interpreter. This will not open the dos console for running your script.
Is there a more succinct / pythonic way to do this? (counting longest seq of heads, tails in coin flips)
1,689,032
11
2009-11-06T17:18:33Z
1,689,162
7
2009-11-06T17:39:51Z
[ "python" ]
Count the longest sequence of heads and tails in 200 coin flips. I did this - is there a niftier way to do it in python? (without being too obfuscated) ``` import random def toss(n): count = [0,0] longest = [0,0] for i in xrange(n): coinface = random.randrange(2) count[coinface] += 1 ...
You can use `itertools`, which is a much more Pythonic way to do this: ``` def toss(n): rolls = [random.randrange(2) for i in xrange(n)] maximums = [0, 0] for which, grp in itertools.groupby(rolls): maximums[which] = max(len(list(grp)), maximums[which]) print "Longest sequence of heads %d, tai...
Is there a more succinct / pythonic way to do this? (counting longest seq of heads, tails in coin flips)
1,689,032
11
2009-11-06T17:18:33Z
1,689,174
11
2009-11-06T17:42:00Z
[ "python" ]
Count the longest sequence of heads and tails in 200 coin flips. I did this - is there a niftier way to do it in python? (without being too obfuscated) ``` import random def toss(n): count = [0,0] longest = [0,0] for i in xrange(n): coinface = random.randrange(2) count[coinface] += 1 ...
``` def coins(num): lst = [random.randrange(2) for i in range(num)] lst = [(i, len(list(j))) for i, j in itertools.groupby(lst)] tails = max(j for i, j in lst if i) heads = max(j for i, j in lst if not i) return {1: tails, 0: heads} ```
Is there a more succinct / pythonic way to do this? (counting longest seq of heads, tails in coin flips)
1,689,032
11
2009-11-06T17:18:33Z
1,689,209
11
2009-11-06T17:47:11Z
[ "python" ]
Count the longest sequence of heads and tails in 200 coin flips. I did this - is there a niftier way to do it in python? (without being too obfuscated) ``` import random def toss(n): count = [0,0] longest = [0,0] for i in xrange(n): coinface = random.randrange(2) count[coinface] += 1 ...
``` import collections, itertools, random def makesequence(choices=2, length=200): return [random.randrange(choices) for _ in itertools.repeat(None, length)] def runlengths(sequence): runlength_by_item = collections.defaultdict(set) for key, group in itertools.groupby(sequence): runlength_by_item[key].add(s...
Python: ulimit and nice for subprocess.call / subprocess.Popen?
1,689,505
30
2009-11-06T18:44:01Z
1,689,787
10
2009-11-06T19:28:06Z
[ "python", "resources", "nice", "ulimit" ]
I need to limit the amount of time and cpu taken by external command line apps I spawn from a python process using subprocess.call , mainly because sometimes the spawned process gets stuck and pins the cpu at 99%. nice and ulimit seem like reasonable ways to do this, but I'm not sure how they'd interact with subproces...
You can set limits for subprocesses with the `ulimit` and `nice` shell commands like this: ``` import subprocess subprocess.Popen('ulimit -t 60; nice -n 15 cpuhog', shell=True) ``` This runs `cpuhog` with a limit of 60 seconds of CPU time and a niceness adjustment of 15. Note that there is no simple way to set a 20% ...
Python: ulimit and nice for subprocess.call / subprocess.Popen?
1,689,505
30
2009-11-06T18:44:01Z
1,689,991
71
2009-11-06T19:59:22Z
[ "python", "resources", "nice", "ulimit" ]
I need to limit the amount of time and cpu taken by external command line apps I spawn from a python process using subprocess.call , mainly because sometimes the spawned process gets stuck and pins the cpu at 99%. nice and ulimit seem like reasonable ways to do this, but I'm not sure how they'd interact with subproces...
Use the preexec\_fn parameter to subprocess.Popen, and the resource module. Example: *parent.py:* ``` #!/usr/bin/env python import os import sys import resource import subprocess def setlimits(): # Set maximum CPU time to 1 second in child process, after fork() but before exec() print "Setting resource limi...
Tool like 2to3, except for merges
1,689,548
4
2009-11-06T18:52:30Z
1,689,736
7
2009-11-06T19:20:29Z
[ "python", "merge", "python-3.x", "py2to3" ]
I maintain a fork of my project for Python 3.1. When I initially made the port from 2.6, I used 2to3, but now I constantly have to merge new code from the 2.6 fork into the 3.1 fork. How can I perform the 2to3 operation on these merges automatically? (I use git, if it matters.)
Hmmm, you are in a tough position. Perhaps you could run 2to3 on the 2.6 fork, then merge the results of that into your 3.1 branch? Alternatively, perhaps this pain will make you reconsider your strategy of maintaining two distinct branches for the two Python versions? I've had good luck using a single codebase for bo...
Getting an instance name inside class __init__()
1,690,400
11
2009-11-06T20:58:57Z
1,690,433
16
2009-11-06T21:04:13Z
[ "python", "class", "variables", "object", "instance" ]
While building a new class object in python, I want to be able to create a default value based on the instance name of the class without passing in an extra argument. How can I accomplish this? Here's the basic pseudo-code I'm trying for: ``` class SomeObject(): defined_name = u"" def __init__(self, def_name=...
Instances don't have names. By the time the global name `ThisObject` gets **bound** to the instance created by evaluating the `SomeObject` constructor, the constructor has finished running. If you want an object to have a name, just pass the name along in the constructor. ``` def __init__(self, name): self.name =...
Getting an instance name inside class __init__()
1,690,400
11
2009-11-06T20:58:57Z
1,690,751
13
2009-11-06T21:54:19Z
[ "python", "class", "variables", "object", "instance" ]
While building a new class object in python, I want to be able to create a default value based on the instance name of the class without passing in an extra argument. How can I accomplish this? Here's the basic pseudo-code I'm trying for: ``` class SomeObject(): defined_name = u"" def __init__(self, def_name=...
Well, there is almost a way to do it: ``` #!/usr/bin/env python import traceback class SomeObject(): def __init__(self, def_name=None): if def_name == None: (filename,line_number,function_name,text)=traceback.extract_stack()[-2] def_name = text[:text.find('=')].strip() self....
How to post a file via HTTP with cookies using python poster lib
1,690,446
2
2009-11-06T21:05:59Z
2,356,659
7
2010-03-01T15:02:18Z
[ "python", "http", "cookies", "file-upload" ]
Using Chris Atlee's python [poster library](http://atlee.ca/software/poster/) is there any way to include cookie handling? I have python http login code, which works with cookies: ``` cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) request = urllib2.Request(lo...
I sent an email to Chris AtLee asking whether we could get a basic authentication example. He was very cool about answering my questions and even ran some example code I sent him. To include cookie handling, you do something like this: ``` opener = poster.streaminghttp.register_openers() opener.add_handler(urllib2.HT...
Is there any benefit to returning a hash constructed with dict rather than just using the curly braces syntax?
1,690,517
4
2009-11-06T21:17:45Z
1,690,569
15
2009-11-06T21:25:03Z
[ "python", "hash", "dictionary" ]
In some Python code I've read I keep noticing this code: ``` return dict(somekey=somevalue) ``` Does that have any benefit over: ``` return {somekey:somevalue} ``` I tend to say no, since both objects will belong to the same `dict` type, but I may be wrong.
``` >>> def foo(): return dict(a=1) ... >>> def bar(): return {'a':1} ... >>> import dis >>> dis.dis(foo) 1 0 LOAD_GLOBAL 0 (dict) 3 LOAD_CONST 1 ('a') 6 LOAD_CONST 2 (1) 9 CALL_FUNCTION 256 12 RETURN_VA...
Activate virtualenv via os.system()
1,691,076
4
2009-11-06T22:55:18Z
1,691,123
11
2009-11-06T23:02:18Z
[ "python", "django", "virtualenv", "fabric", "pip" ]
I'm writing a Python-based shell script to boilerplate a Django app with virtualenv, pip, and fabric. Should be straightforward enough, but it appears that I'm not able to activate and run commands in the virtualenv through the shell script. ``` os.system('virtualenv %s --no-site-packages' % project_name) os.system('s...
Each call to os.system runs the command in a new subshell, which has the same properties as the original python process. Try putting the commands into one string separated by semicolons.
Is TCP Guaranteed to arrive in order?
1,691,179
24
2009-11-06T23:16:50Z
1,691,189
38
2009-11-06T23:19:18Z
[ "python", "tcp", "twisted", "protocols" ]
If I send two TCP messages, do I need to handle the case where the latter arrives before the former? Or is it guaranteed to arrive in the order I send it? I assume that this is not a Twisted-specific example, because it should conform to the TCP standard, but if anyone familiar with Twisted could provide a Twisted-spec...
As long as the two messages were sent *on the same TCP connection*, order will be maintained. If multiple connections are opened between the same pair of processes, you may be in trouble. Regarding Twisted, or any other asynchronous event system: I expect you'll get the `dataReceived` messages in the order that bytes ...
Is TCP Guaranteed to arrive in order?
1,691,179
24
2009-11-06T23:16:50Z
1,691,194
7
2009-11-06T23:20:34Z
[ "python", "tcp", "twisted", "protocols" ]
If I send two TCP messages, do I need to handle the case where the latter arrives before the former? Or is it guaranteed to arrive in the order I send it? I assume that this is not a Twisted-specific example, because it should conform to the TCP standard, but if anyone familiar with Twisted could provide a Twisted-spec...
TCP is a stream, UDP is a message. You're mixing up terms. For TCP it is true that the stream will arrive in the same order as it was send. There are no distict messages in TCP, bytes appear as they arrive, interpreting them as messages is up to you.
Is TCP Guaranteed to arrive in order?
1,691,179
24
2009-11-06T23:16:50Z
1,691,197
16
2009-11-06T23:21:52Z
[ "python", "tcp", "twisted", "protocols" ]
If I send two TCP messages, do I need to handle the case where the latter arrives before the former? Or is it guaranteed to arrive in the order I send it? I assume that this is not a Twisted-specific example, because it should conform to the TCP standard, but if anyone familiar with Twisted could provide a Twisted-spec...
TCP is connection-oriented and offers its Clients **in-order** delivery. Of course this applies to the connection level: individual connections are independent. You should note that normally we refer to "TCP streams" and "UDP messages". Whatever Client library you use (e.g. Twisted), the underlying TCP connection is ...
Is TCP Guaranteed to arrive in order?
1,691,179
24
2009-11-06T23:16:50Z
1,691,220
11
2009-11-06T23:26:56Z
[ "python", "tcp", "twisted", "protocols" ]
If I send two TCP messages, do I need to handle the case where the latter arrives before the former? Or is it guaranteed to arrive in the order I send it? I assume that this is not a Twisted-specific example, because it should conform to the TCP standard, but if anyone familiar with Twisted could provide a Twisted-spec...
TCP "guarantees" that a receiver will receive the reconstituted stream of bytes as it was originally sent by the sender. However, between the TCP send/receive endpoints (i.e., the physical network), the data can be received out of order, it can be fragmented, it can be corrupted, and it can even be lost. TCP accounts f...
What is a scripting engine?
1,691,201
9
2009-11-06T23:22:45Z
1,691,250
11
2009-11-06T23:35:40Z
[ "java", "python", "ruby", "scripting" ]
I've seen [here](http://stackoverflow.com/questions/101055/when-is-a-language-considered-a-scripting-language) that what sets a programming language apart from a scripting language is the scripting engine. But I don't understand how it works, so I don't know the difference. For example, I see code in Java calling meth...
There is no hard and fast line between a "scripting language" and a "programming language". Properties of "scripting languages" tend to include: * garbage-collected memory manager, with no need to explicitly allocate and free objects * ability to simply execute commands, without a bunch of boilerplate code. Java is u...
Does Google allow other people to use their "Did you mean" API?
1,691,275
6
2009-11-06T23:43:19Z
1,691,335
8
2009-11-07T00:00:17Z
[ "python", "api", "spell-checking", "google-api" ]
I have been searching all over the Internet, but did not find that exact API. I'd like to use their Did You mean feature for my own website.
Pygoogle has an api call for that <http://pygoogle.sourceforge.net/dist/doc/public/google-module.html#doSpellingSuggestion> ``` >>> import google >>> google.LICENSE_KEY = '...' >>> google.doSpellingSuggestion('pithon') 'python' ```
Performance difference in alternative switches in Python
1,692,107
3
2009-11-07T05:29:10Z
1,692,135
8
2009-11-07T05:50:45Z
[ "python", "performance", "switch-statement" ]
I have read a few articles around alternatives to the switch statement in Python. Mainly using dicts instead of lots of if's and elif's. However none really answer the question: is there one with better performance or efficiency? I have read a few arguments that if's and elifs would have to check each statement and bec...
`dict`'s perfomance is typically going to be unbeatable, because a lookup into a `dict` is going to be O(1) except in rare and practically never-observed cases (where they key involves user-coded types with lousy hashing;-). You don't have to "create new modules" as you say, just arbitrary callables, and that creation,...
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
41
2009-11-07T08:07:05Z
1,692,428
80
2009-11-07T08:28:18Z
[ "python", "loops", "list", "tuples" ]
I would like do something like that. ``` list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.com/', ...
That is a very strange way to organize things. If you stored in a dictionary, this is easy: ``` # This example should work in any version of Python. # urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 } urls_d = {} for url in list_of_urls: if not url in urls_d: urls_d[...
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
41
2009-11-07T08:07:05Z
1,692,429
11
2009-11-07T08:28:28Z
[ "python", "loops", "list", "tuples" ]
I would like do something like that. ``` list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.com/', ...
Use [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict): ``` from collections import defaultdict urls = defaultdict(int) for url in list_of_urls: urls[url] += 1 ```
Python : List of dict, if exists increment a dict value, if not append a new dict
1,692,388
41
2009-11-07T08:07:05Z
1,692,435
43
2009-11-07T08:31:00Z
[ "python", "loops", "list", "tuples" ]
I would like do something like that. ``` list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.com/', ...
Using the default works, but so does: ``` urls[url] = urls.get(url, 0) + 1 ``` using `.get`, you can get a default return if it doesn't exist. By default it's None, but in the case I sent you, it would be 0.
Open web page with custom cookies in Python
1,692,396
5
2009-11-07T08:11:30Z
1,692,484
7
2009-11-07T08:57:45Z
[ "python", "cookies", "urllib2" ]
For example, I have cookies ``` my_cookies = {'name': 'Albert', 'uid': '654897897564'} ``` and I want to open page <http://website.com> ``` opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)')) opener.open('http://website.com').read() ``` H...
You just need a few more steps: ``` import urllib2 import cookielib cp = urllib2.HTTPCookieProcessor() cj = cp.cookiejar # see cookielib.Cookie documentation for options description cj.set_cookie(cookielib.Cookie(0, 'a_cookie', 'a_value', '80', False, 'domain', True, False, '/path', ...
What cool hacks can be done using sys.settrace?
1,692,866
18
2009-11-07T12:25:47Z
1,693,056
8
2009-11-07T13:39:33Z
[ "python" ]
I love being able to modify the arguments the get sent to a function, using `settrace`, like : ``` import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "__main__": sys.settra...
Of course, code coverage is accomplished with the trace function. One cool thing we haven't had before is branch coverage measurement, and that's coming along nicely, about to be released in an alpha version of [coverage.py](http://bitbucket.org/ned/coveragepy). So for example, consider this function: ``` def foo(x):...
What cool hacks can be done using sys.settrace?
1,692,866
18
2009-11-07T12:25:47Z
1,693,108
22
2009-11-07T14:00:59Z
[ "python" ]
I love being able to modify the arguments the get sent to a function, using `settrace`, like : ``` import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "__main__": sys.settra...
I would strongly recommend against abusing settrace. I'm assuming you understand this stuff, but others coming along later may not. There are a few reasons: 1. Settrace is a very blunt tool. The OP's example is a simple one, but there's practically no way to extend it for use in a real system. 2. It's mysterious. Anyo...
What cool hacks can be done using sys.settrace?
1,692,866
18
2009-11-07T12:25:47Z
17,568,951
13
2013-07-10T11:01:11Z
[ "python" ]
I love being able to modify the arguments the get sent to a function, using `settrace`, like : ``` import sys def trace_func(frame,event,arg): value = frame.f_locals["a"] if value % 2 == 0: value += 1 frame.f_locals["a"] = value def f(a): print a if __name__ == "__main__": sys.settra...
I made a module called [`pycallgraph`](http://pycallgraph.slowchop.com/) which generates call graphs using `sys.settrace()`. ![](http://i.stack.imgur.com/aiNEA.png)
What is the use of Python's basic optimizations mode? (python -O)
1,693,088
36
2009-11-07T13:51:35Z
1,693,127
24
2009-11-07T14:07:25Z
[ "python", "optimization", "assert", "bytecode" ]
Python has a flag `-O` that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page: > -O Turn on basic optimizations. This changes the filename extension > for compiled (bytecode) files from .pyc t...
On stripping assert statements: this is a standard option in the C world, where many people believe part of the definition of ASSERT is that it doesn't run in production code. Whether stripping them out or not makes a difference depends less on how many asserts there are than on how much work those asserts do: ``` def...
What is the use of Python's basic optimizations mode? (python -O)
1,693,088
36
2009-11-07T13:51:35Z
1,698,167
30
2009-11-08T22:35:40Z
[ "python", "optimization", "assert", "bytecode" ]
Python has a flag `-O` that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page: > -O Turn on basic optimizations. This changes the filename extension > for compiled (bytecode) files from .pyc t...
Another use for the `-O` flag is that the value of the `__debug__` builtin variable is set to `False`. So, basically, your code can have a lot of "debugging" paths like: ``` if __debug__: # output all your favourite debugging information # and then more ``` which, when running under `-O`, won't even be inc...
How does ironpython speed compare to other .net languages?
1,693,205
11
2009-11-07T14:27:18Z
1,693,388
9
2009-11-07T15:21:50Z
[ ".net", "python", "performance", "ironpython" ]
I would like to give sources for what I'm saying but I just dont have them, it's something I heard. Once a programming professor told me that some software benchmarking done to .net vs Python in some particular items it gave a relation of 5:8 in favor of .NET . That was his argument in favor of Python not being so muc...
Here are two interesting links with comparisons between IronPython, CPython, and C# (among others): * CPython vs C# (Mono) [benchmarks](http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=python&lang2=csharp&box=1), based on several programs detailed on the site. * CPython vs IronPython [benchmarks](http...
Difference between ^ Operator in JS and Python
1,694,507
2
2009-11-07T21:34:45Z
1,694,524
7
2009-11-07T21:41:17Z
[ "javascript", "python", "bit-manipulation", "xor" ]
I need to port some JS code which involves `Math.random()*2147483648)^(new Date).getTime()`. While it looks like for smaller numbers, the python function and the JS function are equivalent in function, but with large numbers like this, the values end up entirely different. Python: ``` >>> 2147483647 ^ 1257628307380 1...
Python has unlimited-precision integers, while Javascript is using a 32-bit integer. You can manually apply a 32-bit limit to get the result you want: ``` def xor32bit(a, b): m = (a ^ b) % (2**32) if m > (2**16): m -= 2**32 return m ```
Secure Python intepreter?
1,695,014
6
2009-11-08T01:20:04Z
1,695,034
7
2009-11-08T01:28:05Z
[ "python", "security", "virtual-machine", "interpreter" ]
Is there a secure Python intepreter? Imagine a Python VM you can run on your machine, that restricts the operations. No files can be opened, no system calls, etc. It just transforms stdin to stdout, maybe with text processing + math etc. Does such a secure Python VM exist?
I know of no such "secure interpreter" that is openly distributed (obviously Google has one that it uses in App Engine, though with somewhat different restrictions from those you desire, e.g., certain files *can* be opened, in a read-only way). There are some claims for it, though, e.g. [here](http://wiki.python.org/mo...
How to percent-encode URL parameters in Python?
1,695,183
153
2009-11-08T02:43:45Z
1,695,199
219
2009-11-08T02:52:22Z
[ "python", "url", "encoding", "urllib", "urlencode" ]
If I do ``` url = "http://example.com?p=" + urllib.quote(query) ``` 1. It doesn't encode `/` to `%2F` (breaks OAuth normalization) 2. It doesn't handle Unicode (it throws an exception) Is there a better library?
From the [docs](http://docs.python.org/library/urllib.html#urllib.quote): ``` urllib.quote(string[, safe]) ``` > Replace special characters in string > using the %xx escape. Letters, digits, > and the characters '\_.-' are never > quoted. By default, this function is > intended for quoting the path section > of the U...
How to percent-encode URL parameters in Python?
1,695,183
153
2009-11-08T02:43:45Z
13,625,238
60
2012-11-29T11:52:51Z
[ "python", "url", "encoding", "urllib", "urlencode" ]
If I do ``` url = "http://example.com?p=" + urllib.quote(query) ``` 1. It doesn't encode `/` to `%2F` (breaks OAuth normalization) 2. It doesn't handle Unicode (it throws an exception) Is there a better library?
In Python 3, [`urllib.quote`](http://docs.python.org/2/library/urllib.html#urllib.quote) has been moved to [`urllib.parse.quote`](http://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote) and it does handle unicode by default. ``` >>> from urllib.parse import quote >>> quote('/test') '/test' >>> quote('/t...
How to percent-encode URL parameters in Python?
1,695,183
153
2009-11-08T02:43:45Z
31,401,601
15
2015-07-14T08:30:58Z
[ "python", "url", "encoding", "urllib", "urlencode" ]
If I do ``` url = "http://example.com?p=" + urllib.quote(query) ``` 1. It doesn't encode `/` to `%2F` (breaks OAuth normalization) 2. It doesn't handle Unicode (it throws an exception) Is there a better library?
My answer is similar to Paolo's answer. I think module `requests` is much better. It's based on `urllib3`. You can try this: ``` >>> from requests.utils import quote >>> quote('/test') '/test' >>> quote('/test', safe='') '%2Ftest' ```
"".join(reversed(val)) vs val[::-1]...which is pythonic?
1,695,385
14
2009-11-08T04:42:34Z
1,695,416
45
2009-11-08T04:59:12Z
[ "python" ]
So according to the *Zen of Python* ... *Explicit is better than implicit*...*Sparse is better than dense*...*Readability counts*...but then again *Flat is better than nested*...so then which is *pythonic*? ``` val = "which is pythonic?" print("".join(reversed(val))) ``` or ``` print(val[::-1]) ``` I'm just a Java ...
My wife Anna has nicknamed `x[::-1]` "the Martian Smiley" -- I mostly bow to her (and her long experience in training &c, and studies in human psychology &c), when it comes to judging what's easy and natural for most people, and she absolutely *loves* the martial smiley. "Just walk it backwards" -- how much more direct...
Searching values of a list in another List using Python
1,695,452
3
2009-11-08T05:20:21Z
1,695,470
7
2009-11-08T05:27:51Z
[ "python", "list" ]
I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this: ``` for nums in l1: if nums in l2: return True else: return False ``` This would be true but I'm trying to return True only if list1 is in li...
``` try: last_found = -1 for num in L1: last_found = L2.index(num, last_found + 1) return True except ValueError: return False ``` The `index` method of list L2 returns the position at which the first argument (`num`) is found in the list; called, like here, with a second arg, it starts looking in the lis...
Does WordNet have "levels"? (NLP)
1,695,971
4
2009-11-08T10:29:19Z
1,695,983
11
2009-11-08T10:34:12Z
[ "python", "text", "nlp", "words", "wordnet" ]
For example... Chicken is an **animal**. Burrito is a **food**. WordNet allows you to do "is-a"...the hiearchy feature. However, how do I know when to stop travelling up the tree? I want a LEVEL. That is consistent. For example, if presented with a bunch of words, I want wordNet to categorize all of them, but a...
WordNet is a lexicon rather than an ontology, so 'levels' don't really apply. There is [SUMO](http://www.ontologyportal.org/), which is an upper ontology which relates to WordNet if you want a directed lattice instead of a network. For some domains, SUMO's mid-level ontology is probably where you want to look, but I'...
How to create 3 dimensions matrix in numpy , like matlab a(:,:,:)
1,696,135
17
2009-11-08T11:47:19Z
1,696,206
51
2009-11-08T12:12:25Z
[ "python", "matlab", "numpy" ]
How to create 3 dimensions matrix in numpy , like matlab a(:,:,:) . I try to convert matlab code that create 3d matrix to python by use numpy.array and i don't know how to create 3d matrix/array in numpy
``` a=np.empty((2,3,5)) ``` creates a 2x3x5 array. (There is also np.zeros if you want the values initialized.) You can also reshape existing arrays: ``` a=np.arange(30).reshape(2,3,5) ``` np.arange(30) creates a 1-d array with values from 0..29. The reshape() method returns an array containing the same data with a...
What is the return value of subprocess.call()?
1,696,998
12
2009-11-08T16:10:18Z
1,697,037
7
2009-11-08T16:22:55Z
[ "python", "linux" ]
I am not sure what the return value of `subprocess.call()` means. * Can I safely assume a zero value will always mean that the command executed successfully? * Is the return value equivalent to the exit staus of a shell command? For example, will the following piece of code work for virtually any command on Linux? `...
Yes, `Subprocess.call` returns "actual process return code". You can check official documentation of [Subprocess.call](http://docs.python.org/library/subprocess.html#subprocess.call) and [Subprocess.Popen.returncode](http://docs.python.org/library/subprocess.html#subprocess.Popen.returncode)
Differences between static and instance variables in python. Do they even exist?
1,697,273
8
2009-11-08T17:36:11Z
1,697,283
9
2009-11-08T17:40:16Z
[ "python" ]
A random class definition: ``` class ABC: x = 6 ``` Setting some values, first for the abc instance, later for the static variable: ``` abc = ABC() abc.x = 2 ABC.x = 5 ``` and then print the results: ``` print abc.x print ABC.x ``` which prints ``` 2 5 ``` Now, I don't really get what is going on, because i...
``` class SomeClass: x=6 # class variable def __init__(self): self.y = 666 # instance variable ``` There is virtue in declaring a class scoped variable: it serves as default for one. Think of class scoped variable as you would think of "static" variables in some other languages.
Differences between static and instance variables in python. Do they even exist?
1,697,273
8
2009-11-08T17:36:11Z
1,716,730
14
2009-11-11T17:21:43Z
[ "python" ]
A random class definition: ``` class ABC: x = 6 ``` Setting some values, first for the abc instance, later for the static variable: ``` abc = ABC() abc.x = 2 ABC.x = 5 ``` and then print the results: ``` print abc.x print ABC.x ``` which prints ``` 2 5 ``` Now, I don't really get what is going on, because i...
Warning: the following is an oversimplification; I'm ignoring `__new__()` and a bunch of other special class methods, and handwaving a lot of details. But this explanation will get you pretty far in Python. When you create an instance of a class in Python, like calling **ABC()** in your example: ``` abc = ABC() ``` ...
Python: @staticmethod with @property
1,697,501
22
2009-11-08T18:52:31Z
1,697,546
8
2009-11-08T19:04:34Z
[ "python", "singleton", "properties" ]
I want ``` Stats.singleton.twitter_count += 1 ``` and I thought I could do ``` class Stats: singleton_object = None @property @staticmethod def singleton(): if Stats.singleton_object: return Stats.singleton_object Stats.singleton_object = Stats() return Stats.sing...
Static methods don't make sense in Python. That's because they do nothing that class methods can't, and are class methods much easier to extend in the future (when multiple class methods use each other etc). What you need is simply a class method property. I have a class method property from my code here. It is only ...
Python: @staticmethod with @property
1,697,501
22
2009-11-08T18:52:31Z
1,697,656
13
2009-11-08T19:40:34Z
[ "python", "singleton", "properties" ]
I want ``` Stats.singleton.twitter_count += 1 ``` and I thought I could do ``` class Stats: singleton_object = None @property @staticmethod def singleton(): if Stats.singleton_object: return Stats.singleton_object Stats.singleton_object = Stats() return Stats.sing...
Singletons are pointless in python. ``` class A: class_var = object() # two objects a, b = A(), A() # same var everywhere assert a.class_var is b.class_var is A.class_var ``` Python's `int`s are differnt from simple `object`s, so it's not always that simple . But for your purposes, this seems to be enough: ``` c...
Python: @staticmethod with @property
1,697,501
22
2009-11-08T18:52:31Z
7,864,317
32
2011-10-23T04:20:14Z
[ "python", "singleton", "properties" ]
I want ``` Stats.singleton.twitter_count += 1 ``` and I thought I could do ``` class Stats: singleton_object = None @property @staticmethod def singleton(): if Stats.singleton_object: return Stats.singleton_object Stats.singleton_object = Stats() return Stats.sing...
User kaizer.se was onto something as far as the original question goes. I took it a step further in terms of simplicity, so that it now requires only a single decorator: ``` class classproperty(property): def __get__(self, cls, owner): return classmethod(self.fget).__get__(None, owner)() ``` Usage: ``` c...
Clean input strings without using the django Form classes
1,697,508
10
2009-11-08T18:53:11Z
1,697,569
15
2009-11-08T19:10:52Z
[ "python", "django" ]
Is there a recommended way of using Django to clean an input string without going through the Django form system? That is, I'm writing code that delivers form input via AJAX so I'm skipping the whole Form model django offers. But I do want to clean the input prior to submission to the database.
Django Form models aren't just about rendering forms, they're more about processing and sanitizing form (GET/POST) input, which *is* what you want to do. When the POST or GET data from your AJAX request reaches your server it's essentially indistinguishable from form data. I would advocate creating a Form model that is...
Python threading appears to run threads sequentially
1,697,571
9
2009-11-08T19:11:07Z
1,697,586
10
2009-11-08T19:15:33Z
[ "python", "multithreading" ]
I am trying to use threads in a Python project I am working on, but threads don't appear to be behaving as they are supposed to in my code. It seems that all threads run sequentially (i.e. thread2 starts after thread 1 ends, they don't both start at the same time). I wrote a simple script to test this, and that too run...
In the time it takes the second thread to start the first thread loops and prints already. Here it looks like this, you can see the 2nd thread starting after the first emitted a few hellos. ``` Hello Hello Hello Hello Hello Helloworld Helloworld Helloworld Helloworld Helloworld world world world world world ``` ...
Python threading appears to run threads sequentially
1,697,571
9
2009-11-08T19:11:07Z
1,697,670
10
2009-11-08T19:45:31Z
[ "python", "multithreading" ]
I am trying to use threads in a Python project I am working on, but threads don't appear to be behaving as they are supposed to in my code. It seems that all threads run sequentially (i.e. thread2 starts after thread 1 ends, they don't both start at the same time). I wrote a simple script to test this, and that too run...
Currently in python, threads get changed after executing some specified amount of bytecode instructions. They don't run at the same time. You will only have threads executing in parallel when one of them calls some I/O-intensive or not python-affecting module that can release GIL (global interpreter lock). I'm pretty ...
Checking if a domain name is registered
1,697,663
12
2009-11-08T19:43:27Z
1,697,681
15
2009-11-08T19:48:16Z
[ "php", "python", "dns", "names" ]
How would I go about checking if a domain name is registered? I was thinking about checking if it has a corresponding IP but it doesn't seem to work as well as I had hoped. Is there a solution in either PHP or Python that can check?
"Registered" doesn't mean "assigned an IP address". To know whether a domain name is registered, you'll need to do a whois query. For Python, there's [pywhois](http://code.google.com/p/pywhois/), but from its web site it seems somewhat immature. Also see [this SO question](http://stackoverflow.com/questions/50394/what...
How to pass initial parameter to django's ModelForm instance?
1,697,702
16
2009-11-08T19:54:40Z
1,697,770
28
2009-11-08T20:11:39Z
[ "python", "django", "django-models", "django-forms" ]
The particular case I have is like this: I have a Transaction model, with fields: `from`, `to` (both are `ForeignKey`s to `auth.User` model) and `amount`. In my form, I'd like to present the user 2 fields to fill in: `amount` and `from` (`to` will be automaticly set to current user in a view function). Default widget...
Use the following method (hopefully it's clear enough): ``` class BackupForm(ModelForm): """Form for adding and editing backups.""" def __init__(self, *args, **kwargs): systemid = kwargs.pop('systemid') super(BackupForm, self).__init__(*args, **kwargs) self.fields['units'] = forms.Mode...
How do you convert a Python time.struct_time object into a datetime object?
1,697,815
220
2009-11-08T20:23:23Z
1,697,838
99
2009-11-08T20:30:37Z
[ "python", "datetime" ]
How do you convert a Python `time.struct_time` object into a `datetime.datetime` object? I have a library that provides the first one and a second library that wants the second one...
Like this: ``` >>> structTime = time.localtime() >>> datetime.datetime(*structTime[:6]) datetime.datetime(2009, 11, 8, 20, 32, 35) ```
How do you convert a Python time.struct_time object into a datetime object?
1,697,815
220
2009-11-08T20:23:23Z
1,697,907
299
2009-11-08T20:57:16Z
[ "python", "datetime" ]
How do you convert a Python `time.struct_time` object into a `datetime.datetime` object? I have a library that provides the first one and a second library that wants the second one...
Use [time.mktime()](http://docs.python.org/library/time.html#time.mktime) to convert the time tuple (in localtime) into seconds since the Epoch, then use [datetime.fromtimestamp()](http://docs.python.org/library/datetime.html#datetime.datetime.fromtimestamp) to get the datetime object. ``` from time import mktime from...
How do you convert a Python time.struct_time object into a datetime object?
1,697,815
220
2009-11-08T20:23:23Z
18,726,020
24
2013-09-10T18:08:54Z
[ "python", "datetime" ]
How do you convert a Python `time.struct_time` object into a `datetime.datetime` object? I have a library that provides the first one and a second library that wants the second one...
This is not a direct answer to your question (which was answered pretty well already). However, having had times bite me on the fundament several times, I cannot stress enough that it would behoove you to look closely at what your time.struct\_time object is providing, vs. what other time fields may have. Assuming you...
Convert little endian string to integer
1,698,036
9
2009-11-08T21:49:20Z
1,698,048
16
2009-11-08T21:51:28Z
[ "python", "numpy", "wav" ]
I have read samples out of a wave file using the wave module, but it gives the samples as a string, it's out of wave so it's little endian (for example, `\x00`). What is the easiest way to convert this into a python integer, or a numpy.int16 type? (It will eventually become a numpy.int16, so going directly there is fi...
The `struct` module converts packed data to Python values, and vice-versa. ``` >>> import struct >>> struct.unpack("<h", "\x00\x05") (1280,) >>> struct.unpack("<h", "\x00\x06") (1536,) >>> struct.unpack("<h", "\x01\x06") (1537,) ``` "h" means a short int, or 16-bit int. "<" means use little-endian.
Convert little endian string to integer
1,698,036
9
2009-11-08T21:49:20Z
1,698,160
10
2009-11-08T22:34:44Z
[ "python", "numpy", "wav" ]
I have read samples out of a wave file using the wave module, but it gives the samples as a string, it's out of wave so it's little endian (for example, `\x00`). What is the easiest way to convert this into a python integer, or a numpy.int16 type? (It will eventually become a numpy.int16, so going directly there is fi...
[`struct`](http://docs.python.org/library/struct.html) is fine if you have to convert one or a small number of 2-byte strings to integers, but [`array`](http://docs.python.org/library/array.html?highlight=array#module-array) and `numpy` itself are better options. Specifically, [numpy.fromstring](http://docs.scipy.org/d...
What tools can be used to produce beautiful documentation for a Python project?
1,698,376
5
2009-11-08T23:45:27Z
1,698,387
25
2009-11-08T23:47:37Z
[ "python", "documentation", "latex" ]
I'm working on an open-source project called [python-graph](http://code.google.com/p/python-graph/). We've come to the point where our APIs are stabilising and we've realised that we need some user docs. We already have automatically generated [Epydoc API reference documents](http://www.linux.ime.usp.br/~matiello/pytho...
I have been very impressed by results from [**Sphinx**](http://sphinx.pocoo.org) which seems to be getting more popular. *Edit:* To make this more explicit, allow me to quote the key bullet points from the [**Sphinx home page**](http://sphinx.pocoo.org): > * Output formats: HTML (including Windows HTML Help) and LaTe...
Redirect Embedded Python IO to a console created with AllocConsole
1,698,439
9
2009-11-09T00:07:44Z
1,698,521
9
2009-11-09T00:42:11Z
[ "python", "console", "io-redirection" ]
I am having some trouble getting Python IO redirected to a console that I've allocated for my Win32 app. Is there a Python-specific stream that I need to redirect? Here's more-or-less what I'm doing now (error checking removed, etc.): ``` int __stdcall WinMain(/*Usual stuff here*/) { // Create the console All...
Set `sys.stdout` on the Python side (presumably to an `open('CONOUT$', 'wt')`) to make Python's `print` work, and similarly for `sys.stderr` and `sys.stdin`. (There are faster ways to make this happen from a C extension, but the simplest way is to just execute the Python statements, with a `import sys` in front;-). Wh...
What is meant by 2D array support?
1,698,553
8
2009-11-09T00:49:49Z
1,698,567
10
2009-11-09T00:53:35Z
[ "python", "c", "arrays", "multidimensional-array" ]
I read that Python does not actually support 2D arrays but rather an array of an array. I understand the array of an array thing but what does it mean by supporting 2D arrays? In C a 2D array is simply converted to a 1D array by doing some fancy math ([Seen here](http://stackoverflow.com/questions/1242705/performance-...
There are languages that implement 2D (or 3D, etc) arrays. Fortran is one of them. It means you can write an array index expression like `array[x,y]` and the language will take care of the math to find the correct element. Also, [Numpy](http://numpy.scipy.org/) is a numerical extension to Python that provides n-dimens...
How can I traverse a file system with a generator?
1,698,596
12
2009-11-09T01:00:46Z
1,698,611
39
2009-11-09T01:07:34Z
[ "python", "recursion", "iterator", "generator", "yield" ]
I'm trying to create a utility class for traversing all the files in a directory, including those within subdirectories and sub-subdirectories. I tried to use a generator because generators are cool; however, I hit a snag. ``` def grab_files(directory): for name in os.listdir(directory): full_path = os.pat...
Why reinvent the wheel when you can use [os.walk](http://docs.python.org/library/os.html#os.walk) ``` import os for root, dirs, files in os.walk(path): for name in files: print os.path.join(root, name) ``` os.walk is a generator that yields the file names in a directory tree by walking the tree either top...
How can I traverse a file system with a generator?
1,698,596
12
2009-11-09T01:00:46Z
1,698,711
7
2009-11-09T01:43:35Z
[ "python", "recursion", "iterator", "generator", "yield" ]
I'm trying to create a utility class for traversing all the files in a directory, including those within subdirectories and sub-subdirectories. I tried to use a generator because generators are cool; however, I hit a snag. ``` def grab_files(directory): for name in os.listdir(directory): full_path = os.pat...
I agree with the os.walk solution For pure pedantic purpose, try iterate over the generator object, instead of returning it directly: ``` def grab_files(directory): for name in os.listdir(directory): full_path = os.path.join(directory, name) if os.path.isdir(full_path): for entry in gr...
"Slice lists" and "the ellipsis" in Python; slicing lists and lists of lists with lists of slices
1,698,753
2
2009-11-09T02:01:45Z
1,698,779
10
2009-11-09T02:13:13Z
[ "python", "list", "slice", "itertools" ]
Original question: Can someone tell me how to use "slice lists" and the "ellipsis"? When are they useful? Thanks. Here's what the language definition says about "slice\_list" and "ellipsis"; Alex Martelli's answer points out their origin, which is not what I had envisioned. [<http://docs.python.org/reference/expressi...
Slice lists and ellipsis were originally introduced in Python to supply nice syntax sugar for the precedessor of numpy (good old Numeric). If you're using numpy (no reason to go back to any of its predecessors!-) you should of course use them; if for whatever strange reason you're doing your own implementation of super...
Local import statements in Python
1,699,108
30
2009-11-09T04:34:04Z
1,699,112
11
2009-11-09T04:35:55Z
[ "python", "python-import" ]
I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea? ``` def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i in xrange(10):...
Please see [PEP 8](http://www.python.org/dev/peps/pep-0008/): > Imports are always put at the top of > the file, just after any module > comments and docstrings, and before module globals and constants. Please note that this is purely a stylistic choice as Python will treat all `import` statements the same regardless...
Local import statements in Python
1,699,108
30
2009-11-09T04:34:04Z
1,699,127
9
2009-11-09T04:41:17Z
[ "python", "python-import" ]
I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea? ``` def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i in xrange(10):...
Style aside, it is true that an imported module will only be imported once (unless `reload` is called on said module). However, each call to `import Foo` will have implicitly check to see if that module is already loaded (by checking [`sys.modules`](http://docs.python.org/library/sys.html#sys.modules)). Consider also ...
Local import statements in Python
1,699,108
30
2009-11-09T04:34:04Z
1,704,204
8
2009-11-09T22:03:22Z
[ "python", "python-import" ]
I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea? ``` def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i in xrange(10):...
I've done this, and then wished I hadn't. Ordinarily, if I'm writing a function, and that function needs to use `StringIO`, I can look at the top of the module, see if it's being imported, and then add it if it's not. Suppose I don't do this; suppose I add it locally within my function. And then suppose at someone poi...
Local import statements in Python
1,699,108
30
2009-11-09T04:34:04Z
1,716,375
50
2009-11-11T16:31:37Z
[ "python", "python-import" ]
I think putting the import statement as close to the fragment that uses it helps readability by making its dependencies more clear. Will Python cache this? Should I care? Is this a bad idea? ``` def Process(): import StringIO file_handle=StringIO.StringIO('hello world') #do more stuff for i in xrange(10):...
The other answers evince a mild confusion as to how `import` really works. This statement: ``` import foo ``` is roughly equivalent to this statement: ``` foo = __import__('foo', globals(), locals(), [], -1) ``` That is, it creates a variable in the current scope with the same name as the requested module, and ass...
Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)
1,700,113
6
2009-11-09T10:04:46Z
1,700,122
14
2009-11-09T10:07:11Z
[ "python", "list-comprehension" ]
I want to do something like: ``` all = [ x for x in t[1] for t in tests ] ``` tests looks like: ``` [ ("foo",[a,b,c]), ("bar",[d,e,f]) ] ``` So I want to have the result ``` all = [a,b,c,d,e,f] ``` My code does not work, Python says: ``` UnboundLocalError: local variable 't' referenced before assignment ``` Is ...
It should work the other way around: ``` all = [x for t in tests for x in t[1]] ```
Is there an analogue to Java IllegalStateException in Python?
1,701,199
32
2009-11-09T14:12:55Z
1,701,317
8
2009-11-09T14:31:27Z
[ "java", "python", "exception" ]
IllegalStateException is often used in Java when a method is invoked on an object in inappropriate state. What would you use instead in Python?
[ValueError](http://docs.python.org/library/exceptions.html?highlight=valueerror#exceptions.ValueError) sounds appropriate to me: > Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such a...
Is there an analogue to Java IllegalStateException in Python?
1,701,199
32
2009-11-09T14:12:55Z
1,701,327
23
2009-11-09T14:32:15Z
[ "java", "python", "exception" ]
IllegalStateException is often used in Java when a method is invoked on an object in inappropriate state. What would you use instead in Python?
In Python, that would be `ValueError`, or a subclass of it. For example, trying to `.read()` a closed file raises "ValueError: I/O operation on closed file".
Python: return the index of the first element of a list which makes a passed function true
1,701,211
22
2009-11-09T14:14:32Z
1,701,404
40
2009-11-09T14:39:57Z
[ "python", "list", "function", "indexing" ]
the `list.index(x)` function returns the index in the list of the first item whose value is `x`. is there a function, `list_func_index()`, similar to the `index()` function that has a function, `f()`, as a parameter. the function, `f()` is run on every element, `e`, of the list until `f(e)` returns `True`. then `list_...
You could do that in a one-liner using generators: ``` (i for i,v in enumerate(l) if is_odd(v)).next() ``` The nice thing about generators is that they only compute up to the requested amount. So requesting the first two indices is (almost) just as easy: ``` y = (i for i,v in enumerate(l) if is_odd(v)) x1 = y.next()...
Python: return the index of the first element of a list which makes a passed function true
1,701,211
22
2009-11-09T14:14:32Z
1,701,922
7
2009-11-09T15:51:44Z
[ "python", "list", "function", "indexing" ]
the `list.index(x)` function returns the index in the list of the first item whose value is `x`. is there a function, `list_func_index()`, similar to the `index()` function that has a function, `f()`, as a parameter. the function, `f()` is run on every element, `e`, of the list until `f(e)` returns `True`. then `list_...
@Paul's accepted answer is best, but here's a little lateral-thinking variant, mostly for amusement and instruction purposes...: ``` >>> class X(object): ... def __init__(self, pred): self.pred = pred ... def __eq__(self, other): return self.pred(other) ... >>> l = [8,10,4,5,7] >>> def is_odd(x): return x % 2 != ...
How can I make the PyDev editor selectively ignore errors?
1,702,043
27
2009-11-09T16:14:56Z
1,703,140
45
2009-11-09T19:18:33Z
[ "python", "pydev", "jython", "python-import" ]
I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this: ``` import com.work.project.component.client.Interface.ISubInterface as ISubInterface ``` The problem is that PyDev will always flag this as an error and say "Unresolved import: ISubInterface"....
You can add a comment ``` #@UnresolvedImport #@UnusedVariable ``` So your import becomes: ``` import com.work.project.component.client.Interface.ISubInterface as ISubInterface #@UnresolvedImport ``` That should remove the error/warning. There are other comments you can add as well.
How can I make the PyDev editor selectively ignore errors?
1,702,043
27
2009-11-09T16:14:56Z
1,704,887
26
2009-11-10T00:25:09Z
[ "python", "pydev", "jython", "python-import" ]
I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this: ``` import com.work.project.component.client.Interface.ISubInterface as ISubInterface ``` The problem is that PyDev will always flag this as an error and say "Unresolved import: ISubInterface"....
Add the hash character # at the end of the line then with the cursor on the flagged error, press Ctrl-1. One of the options in the menu will be something like `@UndefinedVariable`. Adding this comment will cause PyDev to ignore the error.
Speeding Up the First Page Load in django
1,702,562
22
2009-11-09T17:38:17Z
1,704,310
30
2009-11-09T22:18:59Z
[ "python", "django", "performance", "mod-wsgi", "pageload" ]
When I update the code on my website I (naturally) restart my apache instance so that the changes will take effect. Unfortunately the first page served by each apache instance is quite slow while it loads everything into RAM for the first time (5-7 sec for this particular site). Subsequent requests only take 0.5 - 1....
The default for Apache/mod\_wsgi is to only load application code on first request to a process which requires that applications. So, first step is to configure mod\_wsgi to preload your code when the process starts and not only the first request. This can be done in mod\_wsgi 2.X using the WSGIImportScript directive. ...
How to Execute a Python File in Notepad ++?
1,702,586
60
2009-11-09T17:41:54Z
1,702,605
76
2009-11-09T17:44:25Z
[ "python", "notepad++" ]
I prefer using Notepad ++ for developing, How do I execute the files in Python through Notepad++?
*I would go for option three.* * **First option:** (Not safe) > The code opens “HKEY\_CURRENT\_USER\Software\Python\PythonCore”, if the key exists it will get the path from the first child key of this key. Check if this key exists, and if does not, you could try creating it. * **Second option:** Use a bat...
How to Execute a Python File in Notepad ++?
1,702,586
60
2009-11-09T17:41:54Z
21,991,705
20
2014-02-24T15:18:39Z
[ "python", "notepad++" ]
I prefer using Notepad ++ for developing, How do I execute the files in Python through Notepad++?
@[Ramiz Uddin's answer](http://stackoverflow.com/questions/1702586/how-to-execute-a-python-file-in-notepad#comment1908592_1702605) definitely deserves more visibility : * Open Notepad++. * On the menu go to: Run -> Run.. (F5). * Type in: `cmd /K python "$(FULL_CURRENT_PATH)`
How to Execute a Python File in Notepad ++?
1,702,586
60
2009-11-09T17:41:54Z
27,038,786
8
2014-11-20T11:44:19Z
[ "python", "notepad++" ]
I prefer using Notepad ++ for developing, How do I execute the files in Python through Notepad++?
Here is what's worked for me: Open notepad++ and press F5. > Type: ***C:\Python27\python.exe -i "$(FULL\_CURRENT\_PATH)"*** for Python 2.7. > > and then ***Save As...***, and pick your own key combo to start it each time you want to run something
What is suggested seed value to use with random.seed()?
1,703,012
4
2009-11-09T18:56:16Z
1,703,021
12
2009-11-09T18:58:11Z
[ "python", "random" ]
Simple enough question: I'm using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this default to the current time, but this is not ideal. It seems like a string literal constant (similar to a password) would al...
According to the documentation for [`random.seed`](http://docs.python.org/library/random.html): > If x is omitted or **None**, current system time is used; current system time is also used to initialize the generator when the module is first imported. If randomness sources are provided by the operating system, they ar...
Parsing date/time string with timezone abbreviated name in Python?
1,703,546
21
2009-11-09T20:26:32Z
1,703,591
10
2009-11-09T20:32:51Z
[ "python", "date", "timezone" ]
I'm trying to parse timestamp strings like `"Sat, 11/01/09 8:00PM EST"` in Python, but I'm having trouble finding a solution that will handle the abbreviated timezone. I'm using [`dateutil`](http://labix.org/python-dateutil)'s `parse()` function, but it doesn't parse the timezone. Is there an easy way to do this?
That probably won't work because those abbreviations aren't unique. See [this page](http://www.timeanddate.com/library/abbreviations/timezones/) for details. You might wind up just having to manually handle it yourself if you're working with a known set of inputs.
Parsing date/time string with timezone abbreviated name in Python?
1,703,546
21
2009-11-09T20:26:32Z
4,766,400
45
2011-01-22T05:46:00Z
[ "python", "date", "timezone" ]
I'm trying to parse timestamp strings like `"Sat, 11/01/09 8:00PM EST"` in Python, but I'm having trouble finding a solution that will handle the abbreviated timezone. I'm using [`dateutil`](http://labix.org/python-dateutil)'s `parse()` function, but it doesn't parse the timezone. Is there an easy way to do this?
`dateutil`'s `parser.parse()` accepts as keyword argument `tzinfos` a dictionary of the kind `{'EST': -5*3600}` (that is, matching the zone name to GMT offset in seconds). So assuming we have that, we can do: ``` >>> import dateutil.parser as dp >>> s = 'Sat, 11/01/09 8:00PM' >>> for tz_code in ('PST','PDT','MST','MDT...
Parsing date/time string with timezone abbreviated name in Python?
1,703,546
21
2009-11-09T20:26:32Z
4,773,905
9
2011-01-23T12:55:09Z
[ "python", "date", "timezone" ]
I'm trying to parse timestamp strings like `"Sat, 11/01/09 8:00PM EST"` in Python, but I'm having trouble finding a solution that will handle the abbreviated timezone. I'm using [`dateutil`](http://labix.org/python-dateutil)'s `parse()` function, but it doesn't parse the timezone. Is there an easy way to do this?
You might try pytz module: <http://pytz.sourceforge.net/> > pytz brings the Olson tz database into > Python. This library allows accurate > and cross platform timezone > calculations using Python 2.3 or > higher. It also solves the issue of > ambiguous times at the end of daylight > savings, which you can read more ab...
How to implement a pythonic equivalent of tail -F?
1,703,640
14
2009-11-09T20:40:36Z
1,703,705
10
2009-11-09T20:49:34Z
[ "python", "file", "tail" ]
What is the pythonic way of watching the tail end of a growing file for the occurrence of certain keywords? In shell I might say: ``` tail -f "$file" | grep "$string" | while read hit; do #stuff done ```
Well, the simplest way would be to constantly read from the file, check what's new and test for hits. ``` import time def watch(fn, words): fp = open(fn, 'r') while True: new = fp.readline() # Once all lines are read this just returns '' # until the file changes and a new line appears ...
python: xml.etree.ElementTree, removing "namespaces"
1,703,882
25
2009-11-09T21:17:47Z
1,704,169
9
2009-11-09T21:58:41Z
[ "python", "xml" ]
I like the way ElementTree parses xml, in particular the Xpath feature. I've an output in xml from an application with nested tags. I'd like to access this tags by name without specifying the namespace, is it possible? For example: ``` root.findall("/molpro/job") ``` instead of: ``` root.findall("{http://www.molpro...
At least with lxml2, it's possible to reduce this overhead somewhat: ``` root.findall("/n:molpro/n:job", namespaces=dict(n="http://www.molpro.net/schema/molpro2006")) ```
Commenting JavaScript functions á la Python Docstrings
1,703,888
14
2009-11-09T21:18:49Z
1,703,923
12
2009-11-09T21:23:35Z
[ "javascript", "python", "comments", "docstring" ]
It is valid JavaScript to write something like this: ``` function example(x) { "Here is a short doc what I do."; // code of the function } ``` The string actually does nothing. Is there any reason, why one shouldn't comment his/her functions in JavaScript in this way? Two points I could think of during wirit...
There's really no point in doing this in Javascript. In Python, the string is made available as the `__doc__` member of the function, class, or module. So these docstrings are available for introspection, etc. If you create strings like this in Javascript, you get no benefit over using a comment, plus you get some dis...
Python (and Django) best import practices
1,704,058
18
2009-11-09T21:42:35Z
1,704,156
12
2009-11-09T21:56:50Z
[ "python", "django", "python-import" ]
Out of the various ways to import code, are there some ways that are preferable to use, compared to others? This link <http://effbot.org/zone/import-confusion.htm> in short states that ``` from foo.bar import MyClass ``` is not the preferred way to import MyClass under normal circumstances or unless you know what you...
First, and primary, rule of imports: never ever use `from foo import *`. The article is discussing the issue of cyclical imports, which still exists today in poorly-structured code. I dislike cyclical imports; their presence is a strong sign that some module is doing too much, and needs to be split up. If for whatever...
Is there a simple process-based parallel map for python?
1,704,401
42
2009-11-09T22:33:42Z
1,704,501
72
2009-11-09T22:49:55Z
[ "python", "parallel-processing", "smp" ]
I'm looking for a simple process-based parallel map for python, that is, a function ``` parmap(function,[data]) ``` that would run function on each element of [data] on a different process (well, on a different core, but AFAIK, the only way to run stuff on different cores in python is to start multiple interpreters),...
I seems like what you need is the [map method in multiprocessing.Pool()](http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map): > **map(func, iterable[, chunksize])** > > ``` > A parallel equivalent of the map() built-in function (it supports only > one iterable argument th...
Get uncompressed size of a .gz file in python
1,704,458
7
2009-11-09T22:43:45Z
1,704,576
8
2009-11-09T23:07:49Z
[ "python", "gzip" ]
Using gzip, tell() returns the offset in the uncompressed file. In order to show a progress bar, I want to know the original (uncompressed) size of the file. Is there an easy way to find out?
The [gzip format](http://www.gzip.org/zlib/rfc-gzip.html#header-trailer) specifies a field called `ISIZE` that: > This contains the size of the original (uncompressed) input data modulo 2^32. In [gzip.py](http://pydoc.org/get.cgi/usr/local/lib/python2.5/gzip.py), which I assume is what you're using for gzip support, ...