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
Problems using nose in a virtualenv
864,956
34
2009-05-14T18:30:15Z
864,967
37
2009-05-14T18:32:54Z
[ "python", "virtualenv", "nose", "nosetests" ]
I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment. The odd thing is that i can set ``` test_suite = 'nose.collector' ``` in setup.py and run the tests just fine as ``` python setup.py test ``` but when running nosetests straight...
Are you able to run `myenv/bin/python /usr/bin/nosetests`? That should run Nose using the virtual environment's library set.
Problems using nose in a virtualenv
864,956
34
2009-05-14T18:30:15Z
865,737
8
2009-05-14T20:59:22Z
[ "python", "virtualenv", "nose", "nosetests" ]
I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment. The odd thing is that i can set ``` test_suite = 'nose.collector' ``` in setup.py and run the tests just fine as ``` python setup.py test ``` but when running nosetests straight...
Here's what works for me: ``` $ virtualenv --no-site-packages env1 $ cd env1 $ source bin/activate # makes "env1" environment active, # you will notice that the command prompt # now has the environment name in it. (env1)$ easy_install nose ...
Problems using nose in a virtualenv
864,956
34
2009-05-14T18:30:15Z
5,409,951
7
2011-03-23T18:35:21Z
[ "python", "virtualenv", "nose", "nosetests" ]
I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment. The odd thing is that i can set ``` test_suite = 'nose.collector' ``` in setup.py and run the tests just fine as ``` python setup.py test ``` but when running nosetests straight...
I got a similar problem. The following workaround helped: ``` python `which nosetests` ``` (instead of just `nosestests`)
Problems using nose in a virtualenv
864,956
34
2009-05-14T18:30:15Z
5,918,777
46
2011-05-07T02:35:46Z
[ "python", "virtualenv", "nose", "nosetests" ]
I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment. The odd thing is that i can set ``` test_suite = 'nose.collector' ``` in setup.py and run the tests just fine as ``` python setup.py test ``` but when running nosetests straight...
You need to have a copy of nose installed in the virtual environment. In order to force installation of nose into the virtualenv, even though it is already installed in the global site-packages, run `pip install` with the `-I` flag: ``` (env1)$ pip install nose -I ``` From then on you can just run `nosetests` as usua...
How do I correctly clean up a Python object?
865,115
249
2009-05-14T19:04:12Z
865,272
337
2009-05-14T19:39:56Z
[ "python", "destructor" ]
``` class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) ``` `__del__(self)` above fails with an AttributeError exception. I understand [Python doesn't guarantee](http://docs.python.org/reference/datamodel.html#cus...
I'd recommend using Python's `with` statement for managing resources that need to be cleaned up. The problem with using an explicit `close()` statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a `finally` block to prevent a resource leak when an exception occurs. ...
How do I correctly clean up a Python object?
865,115
249
2009-05-14T19:04:12Z
865,354
14
2009-05-14T19:51:55Z
[ "python", "destructor" ]
``` class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) ``` `__del__(self)` above fails with an AttributeError exception. I understand [Python doesn't guarantee](http://docs.python.org/reference/datamodel.html#cus...
I don't think that it's possible for instance members to be removed before `__del__` is called. My guess would be that the reason for your particular AttributeError is somewhere else (maybe you mistakenly remove self.file elsewhere). However, as the others pointed out, you should avoid using `__del__`. The main reason...
How do I correctly clean up a Python object?
865,115
249
2009-05-14T19:04:12Z
13,621,521
8
2012-11-29T08:22:09Z
[ "python", "destructor" ]
``` class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) ``` `__del__(self)` above fails with an AttributeError exception. I understand [Python doesn't guarantee](http://docs.python.org/reference/datamodel.html#cus...
I think the problem could be in `__init__` if there is more code than shown? `__del__` will be called even when `__init__` has not been executed properly or threw an exception. [Source](http://www.algorithm.co.il/blogs/programming/python-gotchas-1-__del__-is-not-the-opposite-of-__init__/)
How do I correctly clean up a Python object?
865,115
249
2009-05-14T19:04:12Z
30,349,291
12
2015-05-20T12:11:21Z
[ "python", "destructor" ]
``` class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) ``` `__del__(self)` above fails with an AttributeError exception. I understand [Python doesn't guarantee](http://docs.python.org/reference/datamodel.html#cus...
As an appendix to [Clint's answer](http://stackoverflow.com/a/865272/321973), you can simplify `PackageResource` using [`contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager): ``` @contextlib.contextmanager def packageResource(): class Package: ... pac...
How do you grep through code that lives in many different directories?
865,382
14
2009-05-14T19:58:09Z
865,400
16
2009-05-14T20:00:33Z
[ "python", "grep", "plone", "zope" ]
I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?
``` find DIRECTORY -name "*.py" | xargs grep PATTERN ``` By the way, since writing this, I have discovered [ack](http://beyondgrep.com/), which is a much better solution.
How do you grep through code that lives in many different directories?
865,382
14
2009-05-14T19:58:09Z
865,481
18
2009-05-14T20:15:21Z
[ "python", "grep", "plone", "zope" ]
I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?
I would strongly recommend [ack](http://betterthangrep.com/), a grep substitute, "aimed at programmers with large trees of heterogeneous source code" (from the website)
how to isinstance(x, module)?
865,503
11
2009-05-14T20:18:19Z
865,523
21
2009-05-14T20:21:08Z
[ "python" ]
I need to test if a variable is a module or not. How to do this in the cleanest way? I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument.
``` >>> import os, types >>> isinstance(os, types.ModuleType) True ``` (It also works for your own Python modules, as well as built-in ones like `os`.)
How can I perform divison on a datetime.timedelta in python?
865,618
19
2009-05-14T20:37:32Z
865,639
7
2009-05-14T20:41:21Z
[ "python", "date", "datetime", "division", "timedelta" ]
I'd like to be able to do the following: ``` num_intervals = (cur_date - previous_date) / interval_length ``` or ``` print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' ``` but the division operation is unsupported on timedeltas. Is the...
Sure, just convert to a number of seconds (minutes, milliseconds, hours, take your pick of units) and do the division. *EDIT* (again): so you can't assign to `timedelta.__div__`. Try this, then: ``` divtdi = datetime.timedelta.__div__ def divtd(td1, td2): if isinstance(td2, (int, long)): return divtdi(td1...
How can I perform divison on a datetime.timedelta in python?
865,618
19
2009-05-14T20:37:32Z
865,655
8
2009-05-14T20:44:46Z
[ "python", "date", "datetime", "division", "timedelta" ]
I'd like to be able to do the following: ``` num_intervals = (cur_date - previous_date) / interval_length ``` or ``` print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' ``` but the division operation is unsupported on timedeltas. Is the...
Division and multiplication by integers seems to work [out of the box](http://docs.python.org/library/datetime.html#timedelta-objects): ``` >>> from datetime import timedelta >>> timedelta(hours=6) datetime.timedelta(0, 21600) >>> timedelta(hours=6) / 2 datetime.timedelta(0, 10800) ```
"else" considered harmful in Python?
865,741
11
2009-05-14T21:00:06Z
865,764
30
2009-05-14T21:04:53Z
[ "python", "if-statement" ]
In an [answer](http://stackoverflow.com/questions/855759/python-try-else/855783#855783) (by [S.Lott)](http://stackoverflow.com/users/10661/s-lott) to a question about Python's `try...else` statement: > Actually, even on an if-statement, the > else: can be abused in truly terrible > ways creating bugs that are very har...
S.Lott has obviously seen some bad code out there. Haven't we all? I do not consider else harmful, though I've seen it used to write bad code. In those cases, all the surrounding code has been bad as well, so why blame poor else?
"else" considered harmful in Python?
865,741
11
2009-05-14T21:00:06Z
865,768
15
2009-05-14T21:06:57Z
[ "python", "if-statement" ]
In an [answer](http://stackoverflow.com/questions/855759/python-try-else/855783#855783) (by [S.Lott)](http://stackoverflow.com/users/10661/s-lott) to a question about Python's `try...else` statement: > Actually, even on an if-statement, the > else: can be abused in truly terrible > ways creating bugs that are very har...
No it is not harmful, it is necessary. There should always be a catch-all statement. All switches should have a default. All pattern matching in an ML language should have a default. The argument that it is impossible to reason what is true after a series of if statements is a fact of life. The computer is the bigges...
"else" considered harmful in Python?
865,741
11
2009-05-14T21:00:06Z
865,779
7
2009-05-14T21:09:25Z
[ "python", "if-statement" ]
In an [answer](http://stackoverflow.com/questions/855759/python-try-else/855783#855783) (by [S.Lott)](http://stackoverflow.com/users/10661/s-lott) to a question about Python's `try...else` statement: > Actually, even on an if-statement, the > else: can be abused in truly terrible > ways creating bugs that are very har...
Saying that else is considered harmful is a bit like saying that variables or classes are harmful. Heck, it's even like saying that goto is harmful. Sure, things can be misused. But at some point, you just have to trust programmers to be adults and be smart enough not to. What it comes down to is this: if you're willi...
"else" considered harmful in Python?
865,741
11
2009-05-14T21:00:06Z
865,781
7
2009-05-14T21:09:31Z
[ "python", "if-statement" ]
In an [answer](http://stackoverflow.com/questions/855759/python-try-else/855783#855783) (by [S.Lott)](http://stackoverflow.com/users/10661/s-lott) to a question about Python's `try...else` statement: > Actually, even on an if-statement, the > else: can be abused in truly terrible > ways creating bugs that are very har...
I wouldn't say it is harmful, but there are times when the else statement can get you into trouble. For instance, if you need to do some processing based on an input value and there are only two valid input values. Only checking for one could introduce a bug. eg: ``` The only valid inputs are 1 and 2: if(input == 1) ...
Is everything an object in python like ruby?
865,911
28
2009-05-14T21:33:02Z
865,963
47
2009-05-14T21:40:38Z
[ "python", "ruby", "object" ]
A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby. Is this true? Is everything an object in python like ruby? How are the two different in this respect or are they really the same? For e...
[DiveIntoPython - Everything Is an Object](http://www.diveintopython.net/getting_to_know_python/everything_is_an_object.html) > Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute `__doc__`, which returns the doc string defined in the function's ...
Is everything an object in python like ruby?
865,911
28
2009-05-14T21:33:02Z
866,039
13
2009-05-14T21:51:48Z
[ "python", "ruby", "object" ]
A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby. Is this true? Is everything an object in python like ruby? How are the two different in this respect or are they really the same? For e...
In answer to your second question, yes: ``` >>> (1).__add__(2) 3 ```
Is everything an object in python like ruby?
865,911
28
2009-05-14T21:33:02Z
866,083
12
2009-05-14T22:02:51Z
[ "python", "ruby", "object" ]
A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby. Is this true? Is everything an object in python like ruby? How are the two different in this respect or are they really the same? For e...
"everything" is a tad of an overbid, for both Python and Ruby -- for example, `if` is not "an object", rather it's a keyword used to start a conditional statement or (in Python) inside list comprehensions and generator expressions. The enthusiasm of finding out that functions, classes, methods, and all sort of such thi...
Is everything an object in python like ruby?
865,911
28
2009-05-14T21:33:02Z
866,085
24
2009-05-14T22:03:28Z
[ "python", "ruby", "object" ]
A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby. Is this true? Is everything an object in python like ruby? How are the two different in this respect or are they really the same? For e...
While everything is an object in Python, it differs from Ruby in its approach to resolving names and interacting with objects. For example, while Ruby provides you with a 'to\_s' method on the Object base class, in order to expose that functionality, Python integrates it into the string type itself - you convert a typ...
Using BeautifulSoup to find a HTML tag that contains certain text
866,000
33
2009-05-14T21:46:12Z
866,050
40
2009-05-14T21:53:21Z
[ "python", "regex", "beautifulsoup", "html-content-extraction" ]
I'm trying to get the elements in an HTML doc that contain the following pattern of text: #\S{11} ``` <h2> this is cool #12345678901 </h2> ``` So, the previous would match by using: ``` soup('h2',text=re.compile(r' #\S{11}')) ``` And the results would be something like: ``` [u'blahblah #223409823523', u'thisisinte...
``` from BeautifulSoup import BeautifulSoup import re html_text = """ <h2>this is cool #12345678901</h2> <h2>this is nothing</h2> <h1>foo #126666678901</h1> <h2>this is interesting #126666678901</h2> <h2>this is blah #124445678901</h2> """ soup = BeautifulSoup(html_text) for elem in soup(text=re.compile(r' #\S{11}'...
Using BeautifulSoup to find a HTML tag that contains certain text
866,000
33
2009-05-14T21:46:12Z
13,349,041
9
2012-11-12T18:05:50Z
[ "python", "regex", "beautifulsoup", "html-content-extraction" ]
I'm trying to get the elements in an HTML doc that contain the following pattern of text: #\S{11} ``` <h2> this is cool #12345678901 </h2> ``` So, the previous would match by using: ``` soup('h2',text=re.compile(r' #\S{11}')) ``` And the results would be something like: ``` [u'blahblah #223409823523', u'thisisinte...
BeautifulSoup search operations deliver [a list of] `BeautifulSoup.NavigableString` objects when `text=` is used as a criteria as opposed to `BeautifulSoup.Tag` in other cases. Check the object's `__dict__` to see the attributes made available to you. Of these attributes, `parent` is favored over `previous` because of ...
python dealing with Nonetype before cast\addition
866,208
4
2009-05-14T22:33:10Z
866,230
13
2009-05-14T22:38:11Z
[ "python", "types" ]
I'm pulling a row from a db and adding up the fields (approx 15) to get a total. But some field values will be Null, which causes an error in the addition of the fields (`TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'`) Right now, with each field, I get the field value and set it to 'x#', then chec...
You can do it easily like this: ``` result = sum(field for field in row if field) ```
How can I build multiple submit buttons django form?
866,272
101
2009-05-14T22:50:25Z
866,311
58
2009-05-14T23:03:30Z
[ "python", "button", "django-forms", "submit" ]
I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter: ``` <form action="" method="post"> {{ form_newsletter }} <input type="submit" name="newsletter_sub" value="Subscribe" /> <input type="submit" name="newsletter_unsub" value="Unsubscribe" /> </form> ``` I have also...
You can use `self.data` in the `clean_email` method to access the POST data before validation. It should contain a key called `newsletter_sub` or `newsletter_unsub` depending on which button was pressed. ``` # in the context of a django.forms form def clean(self): if 'newsletter_sub' in self.data: # do su...
How can I build multiple submit buttons django form?
866,272
101
2009-05-14T22:50:25Z
2,011,023
167
2010-01-06T04:50:40Z
[ "python", "button", "django-forms", "submit" ]
I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter: ``` <form action="" method="post"> {{ form_newsletter }} <input type="submit" name="newsletter_sub" value="Subscribe" /> <input type="submit" name="newsletter_unsub" value="Unsubscribe" /> </form> ``` I have also...
Eg: ``` if 'newsletter_sub' in request.POST: # do subscribe elif 'newsletter_unsub' in request.POST: # do unsubscribe ```
python instance variables as optional arguments
867,115
7
2009-05-15T05:40:57Z
867,124
14
2009-05-15T05:45:31Z
[ "python", "function", "class" ]
In python, is there a way I can use instance variables as optional arguments in a class method? ie: ``` def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... ``` Any help would be appreciated.
Try this: ``` def foo(self, blah=None): if blah is None: # faster than blah == None - thanks to kcwu blah = self.instance_var ```
Python Class Members Initialization
867,219
33
2009-05-15T06:17:50Z
867,226
47
2009-05-15T06:19:29Z
[ "python", "class", "initialization" ]
I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions... The scenario: I have a cla...
What you keep referring to as a bug is the [documented](http://docs.python.org/tutorial/classes.html), standard behavior of Python classes. Declaring a dict outside of `__init__` as you initially did is declaring a class-level variable. It is only created once at first, whenever you create new objects it will reuse th...
How do languages such as Python overcome C's Integral data limits?
867,393
2
2009-05-15T07:26:49Z
867,411
9
2009-05-15T07:33:02Z
[ "python", "c", "types", "integer" ]
While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact: In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified [here](http://en.wikipedia.org/wiki/Integer%5F%28compu...
It's called *Arbitrary Precision Arithmetic*. There's more here: <http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic>
Creating a wrapper for a C library in Python
867,850
5
2009-05-15T10:06:06Z
867,864
10
2009-05-15T10:13:15Z
[ "python", "c" ]
I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code. I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Especially sin...
> Python has no way to store pointers, and thus I can't store the pointer to the stream decoder **ctypes** has pointers, and ctypes can be used to wrap existing C libraries. Just a tip, you will need to wrap/rewrite all relavent C structures into ctypes.Structure. Take look at examples: [code.google.com/p/pyxlib-ctype...
Convert unicode codepoint to UTF8 hex in python
867,866
11
2009-05-15T10:13:24Z
867,880
17
2009-05-15T10:18:55Z
[ "python", "unicode" ]
I want to convert a number of unicode codepoints read from a file to their UTF8 encoding. e.g I want to convert the string `'FD9B'` to the string `'EFB69B'`. I can do this manually using string literals like this: ``` u'\uFD9B'.encode('utf-8') ``` but I cannot work out how to do it programatically.
Use the built-in function `unichr()` to convert the number to character, then encode that: ``` >>> unichr(int('fd9b', 16)).encode('utf-8') '\xef\xb6\x9b' ``` This is the string itself. If you want the string as ASCII hex, you'd need to walk through and convert each character `c` to hex, using `hex(ord(c))` or similar...
What host to use when making a UDP socket in python?
868,173
4
2009-05-15T11:37:25Z
868,191
10
2009-05-15T11:40:10Z
[ "python", "sockets", "udp" ]
I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python: ``` import socket import sys HOST = ??????? PORT = 80 # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST,PORT)) data,addr ...
The host argument is the host IP you want to bind to. Specify the IP of one of your interfaces (Eg, your public IP, or 127.0.0.1 for localhost), or use 0.0.0.0 to bind to all interfaces. If you bind to a specific interface, your service will only be available on that interface - for example, if you want to run somethin...
Problem using py2app with the lxml package
868,510
5
2009-05-15T12:52:37Z
888,551
10
2009-05-20T15:15:54Z
[ "python", "lxml", "py2app" ]
I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' ins...
Found it. py2app has a 'frameworks' option to let you specify frameworks, and also dylibs. My setup.py file now looks like this: ``` from setuptools import setup DATA_FILES = [] OPTIONS = {'argv_emulation': True, 'packages' : ['lxml'], 'frameworks' : ['/usr/local/libxml2-2.7.2/lib/libxml2.2.7.2....
Why is looping over range() in Python faster than using a while loop?
869,229
49
2009-05-15T15:06:41Z
869,295
22
2009-05-15T15:18:02Z
[ "python", "performance", "benchmarking" ]
The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute. Loop 1: ``` int i = 0 while i < 100000000: i += 1 ``` Loop 2: ``` for n in range(0,100000000): pass ``` Why...
`range()` is implemented in C, whereas `i += 1` is interpreted. Using `xrange()` could make it even faster for large numbers. Starting with Python 3.0 `range()` is the same as previously `xrange()`.
Why is looping over range() in Python faster than using a while loop?
869,229
49
2009-05-15T15:06:41Z
869,347
93
2009-05-15T15:27:07Z
[ "python", "performance", "benchmarking" ]
The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute. Loop 1: ``` int i = 0 while i < 100000000: i += 1 ``` Loop 2: ``` for n in range(0,100000000): pass ``` Why...
see the disassembly of python byte code, you may get a more concrete idea use while loop: ``` 1 0 LOAD_CONST 0 (0) 3 STORE_NAME 0 (i) 2 6 SETUP_LOOP 28 (to 37) >> 9 LOAD_NAME 0 (i) # <- 12 LOAD_CO...
How do I disassemble a Python script?
869,586
9
2009-05-15T16:12:02Z
869,600
12
2009-05-15T16:14:49Z
[ "python", "debugging", "reverse-engineering" ]
Earlier today, I [asked a question](http://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop) about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples. I'd like to know more. How can I disassemble my own P...
Look at the [dis](http://docs.python.org/library/dis.html) module: ``` def myfunc(alist): return len(alist) >>> dis.dis(myfunc) 2 0 LOAD_GLOBAL 0 (len) 3 LOAD_FAST 0 (alist) 6 CALL_FUNCTION 1 9 RETURN_VALUE ```
Populating a list/array by index in Python?
869,778
20
2009-05-15T16:57:25Z
869,805
22
2009-05-15T17:01:13Z
[ "python", "list" ]
Is this possible: ``` myList = [] myList[12] = 'a' myList[22] = 'b' myList[32] = 'c' myList[42] = 'd' ``` When I try, I get: ``` # IndexError: list assignment index out of range # ```
For a "sparse list" you could use a `dict` instead: ``` mylist = {} mylist[12] = 'a' ``` etc. If you want an actual list (initialize it with `[]`, *not* `()`, of course!-) you need to fill the un-set slots to \_some\_thing, e.g. `None`, by a little auxiliary function or by subclassing `list`.
Populating a list/array by index in Python?
869,778
20
2009-05-15T16:57:25Z
869,818
37
2009-05-15T17:03:29Z
[ "python", "list" ]
Is this possible: ``` myList = [] myList[12] = 'a' myList[22] = 'b' myList[32] = 'c' myList[42] = 'd' ``` When I try, I get: ``` # IndexError: list assignment index out of range # ```
You'll have to pre-fill it with something (e.g. `0` or `None`) before you can index it: ``` myList = [None] * 100 # Create list of 100 'None's myList[12] = 'a' # etc. ``` Alternatively, use a dict instead of a list, as [Alex Martelli suggested](http://stackoverflow.com/questions/869778/populating-a-list-array-by-in...
Populating a list/array by index in Python?
869,778
20
2009-05-15T16:57:25Z
869,901
13
2009-05-15T17:20:46Z
[ "python", "list" ]
Is this possible: ``` myList = [] myList[12] = 'a' myList[22] = 'b' myList[32] = 'c' myList[42] = 'd' ``` When I try, I get: ``` # IndexError: list assignment index out of range # ```
Here's a quick list wrapper that will auto-expand your list with zeros if you attempt to assign a value to a index past it's length. ``` class defaultlist(list): def __setitem__(self, index, value): size = len(self) if index >= size: self.extend(0 for _ in range(size, index + 1)) list._...
Loop backwards using indices in Python?
869,885
92
2009-05-15T17:17:06Z
869,902
146
2009-05-15T17:20:46Z
[ "python", "loops" ]
I am trying to loop from 100 to 0. How do I do this in Python? `for i in range (100,0)` doesn't work.
Try `range(100,-1,-1)`, the 3rd argument being the increment to use (documented [here](https://docs.python.org/library/functions.html#range)).
Loop backwards using indices in Python?
869,885
92
2009-05-15T17:17:06Z
869,905
13
2009-05-15T17:21:39Z
[ "python", "loops" ]
I am trying to loop from 100 to 0. How do I do this in Python? `for i in range (100,0)` doesn't work.
``` for i in range(100, -1, -1) ``` and some slightly longer (and slower) solution: ``` for i in reversed(range(101)) for i in range(101)[::-1] ```
Loop backwards using indices in Python?
869,885
92
2009-05-15T17:17:06Z
869,914
103
2009-05-15T17:24:09Z
[ "python", "loops" ]
I am trying to loop from 100 to 0. How do I do this in Python? `for i in range (100,0)` doesn't work.
In my opinion, this is the most readable: ``` for i in reversed(xrange(101)): print i, ```
Loop backwards using indices in Python?
869,885
92
2009-05-15T17:17:06Z
1,750,432
8
2009-11-17T17:26:02Z
[ "python", "loops" ]
I am trying to loop from 100 to 0. How do I do this in Python? `for i in range (100,0)` doesn't work.
Generally in Python, you can use negative indices to start from the back: ``` numbers = [10, 20, 30, 40, 50] for i in xrange(len(numbers)): print numbers[-i - 1] ``` Result: ``` 50 40 30 20 10 ```
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned?
870,520
20
2009-05-15T19:48:02Z
870,559
17
2009-05-15T19:53:36Z
[ "python", "filter", "whitelist" ]
Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'. How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then ite...
``` s = 'Agh#$%#%2341- -!zdrkfd' print ''.join(c for c in s if c.islower()) ``` String objects are iterable; there is no need to "explode" the string into a list. You can put whatever condition you want in the list comprehension, and it will filter characters accordingly. You could also implement this using a regex...
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned?
870,520
20
2009-05-15T19:48:02Z
870,748
30
2009-05-15T20:35:58Z
[ "python", "filter", "whitelist" ]
Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'. How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then ite...
If you are looking for efficiency. Using the [translate](http://docs.python.org/library/stdtypes.html#str.translate) function is the fastest you can get. It can be used to quickly replace characters and/or delete them. ``` import string delete_table = string.maketrans( string.ascii_lowercase, ' ' * len(string.as...
Pythonic way to split comma separated numbers into pairs
870,652
17
2009-05-15T20:10:32Z
870,677
44
2009-05-15T20:15:55Z
[ "python", "tuples" ]
I'd like to split a comma separated value into pairs: ``` >>> s = '0,1,2,3,4,5,6,7,8,9' >>> pairs = # something pythonic >>> pairs [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] ``` What would *# something pythonic* look like? How would you detect and handle a string with an odd set of numbers?
Something like: ``` zip(t[::2], t[1::2]) ``` Full example: ``` >>> s = ','.join(str(i) for i in range(10)) >>> s '0,1,2,3,4,5,6,7,8,9' >>> t = [int(i) for i in s.split(',')] >>> t [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> p = zip(t[::2], t[1::2]) >>> p [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] >>> ``` If the number of item...
Pythonic way to split comma separated numbers into pairs
870,652
17
2009-05-15T20:10:32Z
870,682
8
2009-05-15T20:16:32Z
[ "python", "tuples" ]
I'd like to split a comma separated value into pairs: ``` >>> s = '0,1,2,3,4,5,6,7,8,9' >>> pairs = # something pythonic >>> pairs [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] ``` What would *# something pythonic* look like? How would you detect and handle a string with an odd set of numbers?
How about this: ``` >>> x = '0,1,2,3,4,5,6,7,8,9'.split(',') >>> def chunker(seq, size): ... return (tuple(seq[pos:pos + size]) for pos in xrange(0, len(seq), size)) ... >>> list(chunker(x, 2)) [('0', '1'), ('2', '3'), ('4', '5'), ('6', '7'), ('8', '9')] ``` This will also nicely handle uneven amounts: ``` >>> x...
Pythonic way to split comma separated numbers into pairs
870,652
17
2009-05-15T20:10:32Z
870,724
8
2009-05-15T20:29:28Z
[ "python", "tuples" ]
I'd like to split a comma separated value into pairs: ``` >>> s = '0,1,2,3,4,5,6,7,8,9' >>> pairs = # something pythonic >>> pairs [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] ``` What would *# something pythonic* look like? How would you detect and handle a string with an odd set of numbers?
A more general option, that also works on iterators and allows for combining any number of items: ``` def n_wise(seq, n): return zip(*([iter(seq)]*n)) ``` Replace zip with itertools.izip if you want to get a lazy iterator instead of a list.
How to generate a file with DDL in the engine's SQL dialect in SQLAlchemy?
870,925
7
2009-05-15T21:19:13Z
870,958
13
2009-05-15T21:33:37Z
[ "python", "sqlalchemy" ]
Suppose I have an `engine` pointing at MySQL database: ``` engine = create_engine('mysql://arthurdent:answer42@localhost/dtdb', echo=True) ``` I can populate `dtdb` with tables, FKs, etc by: ``` metadata.create_all(engine) ``` Is there an easy way to generate the SQL file that contains all the DDL statements instea...
The quick answer is in the [SQLAlchemy 0.8 FAQ](http://docs.sqlalchemy.org/en/rel_0_8/faq.html#how-can-i-get-the-create-table-drop-table-output-as-a-string). In SQLAlchemy 0.8 you need to do ``` engine = create_engine( 'mssql+pyodbc://./MyDb', strategy='mock', executor= lambda sql, *multiparams, **params: print (sql....
Django: Overriding __init__ for Custom Forms
871,037
14
2009-05-15T22:00:04Z
871,082
25
2009-05-15T22:13:03Z
[ "python", "django" ]
I am making a custom form object in Django which has an overrided \_\_init\_\_ method. The purpose of overriding the method is to dynamically generate drop-down boxes based on the new parameters. For example, ``` class TicketForm(forms.Form): Type = Type.GetTicketTypeField() def __init__(self, data=None, fil...
You can dynamically modify your form by using the `self.fields` dict. Something like this may work for you: ``` class TicketForm(forms.Form): Type = Type.GetTicketTypeField() def __init__(self, ticket, *args, **kwargs): super(TicketForm, self).__init__(*args, **kwargs) self.fields['state'] = State.GetTic...
Python program using os.pipe and os.fork() issue
871,447
10
2009-05-16T01:36:53Z
872,637
10
2009-05-16T15:30:19Z
[ "python", "pipe", "fork" ]
I've recently needed to write a script that performs an **os.fork()** to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with **os.pipe()**. The child closes the `'r'` end of the pipe and the parent closes the `'w'` end of the pipe, as...
Are you using read() without specifying a size, or treating the pipe as an iterator (`for line in f`)? If so, that's probably the source of your problem - read() is defined to read until the end of the file before returning, rather than just read what is available for reading. That will mean it will block until the chi...
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python)
872,290
6
2009-05-16T12:01:37Z
872,297
13
2009-05-16T12:05:17Z
[ "python", "string" ]
I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list). What would be the most efficient way to do this in Python? The trivial solution is to load the file into a list a...
The python [Set](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) is what you should try. > A set object is an unordered collection of distinct hashable objects. Common uses include **membership testing**, removing duplicates from a sequence, and computing mathematical operations such as intersect...
Pythonic Way to Initialize (Complex) Static Data Members
872,973
12
2009-05-16T18:20:29Z
872,989
13
2009-05-16T18:27:32Z
[ "python", "class" ]
I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this: ``` def generate_data(): ... do some analysis and return complex object e.g. list ... class Coo: data_member = generate_data() ... rest of class code...
You're right on all counts. `data_member` will be created once, and will be available to all instances of `coo`. If any instance modifies it, that modification will be visible to all other instances. Here's an example that demonstrates all this, with its output shown at the end: ``` def generate_data(): print "Ge...
Pythonic Way to Initialize (Complex) Static Data Members
872,973
12
2009-05-16T18:20:29Z
873,083
11
2009-05-16T19:15:53Z
[ "python", "class" ]
I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this: ``` def generate_data(): ... do some analysis and return complex object e.g. list ... class Coo: data_member = generate_data() ... rest of class code...
As others have answered you're right -- I'll add one more thing to be aware of: If an instance modifies the object `coo.data_member` itself, for example ``` self.data_member.append('foo') ``` then the modification is seen by the rest of the instances. However if you do ``` self.data_member = new_object ``` then a n...
How do you pass script arguments to pdb (Python)?
873,089
8
2009-05-16T19:17:41Z
873,136
15
2009-05-16T19:39:12Z
[ "python", "debugging", "arguments", "pdb" ]
I've got python script (ala #! /usr/bin/python) and I want to debug it with pdb. How can I pass arguments to the script? I have a python script and would like to debug it with pdb. Is there a way that I can pass arguments to the scripts?
``` python -m pdb myscript.py arg1 arg2 ... ``` This invokes `pdb` as a script to debug another script. You can pass command-line arguments after the script name. See the [pdb doc page](http://docs.python.org/library/pdb.html) for more details.
Python's most efficient way to choose longest string in list?
873,327
89
2009-05-16T21:15:30Z
873,333
253
2009-05-16T21:19:46Z
[ "python", "list", "list-comprehension" ]
I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1 For example: ``` mylist = ['123','123456','1234'] for each in mylist: if condition1: do_something() elif ___________...
From the [Python documentation](http://docs.python.org/whatsnew/2.5.html#other-language-changes) itself, you can use [`max`](http://docs.python.org/library/functions.html#max): ``` >>> mylist = ['123','123456','1234'] >>> print max(mylist, key=len) 123456 ```
GitPython and sending commands to the Git object
873,740
3
2009-05-17T02:04:40Z
873,896
9
2009-05-17T04:27:46Z
[ "python", "git" ]
[GitPython](http://gitorious.org/git-python) is a way of interacting with git from python. I'm trying to access the basic git commands (e.g. `git commit -m "message"`) from this module, which according to [this](http://pysync.googlecode.com/files/GitPython.pdf) should be accessed through the Git module. Here's what I'v...
I havn't tried it to verify yet but it seems git.Git.execute expects a list of commandline arguments (if you give it a string it'll look for an executable exactly matching the string, spaces and everything - which naturally wouldn't be found), so something like this I think would work: ``` import git import os, os.pat...
Print space after each word
873,790
2
2009-05-17T02:37:28Z
873,800
13
2009-05-17T02:47:08Z
[ "java", "python", "ruby", "string" ]
what is an easy/effective way to combine an array of words together with a space in between, but no space before or after? I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though. Preferably code in Java, Python, or Ruby.
Well, in Python it will be straightforward using **join**: ``` values = ["this", "is", "your", "array"] result = " ".join(values) ```
Print space after each word
873,790
2
2009-05-17T02:37:28Z
873,835
7
2009-05-17T03:19:03Z
[ "java", "python", "ruby", "string" ]
what is an easy/effective way to combine an array of words together with a space in between, but no space before or after? I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though. Preferably code in Java, Python, or Ruby.
Yes, this is what `join` was made for. Here is the Ruby version: ``` ["word", "another", "word"].join(" ") ``` `<flamebait>` As you can see, Ruby makes `join` a method on `Array` instead of `String`, and is thus far more sensible. `</flamebait>`
Google App Engine: Production versus Development Settings
873,949
8
2009-05-17T05:16:37Z
874,478
15
2009-05-17T12:11:06Z
[ "python", "google-app-engine" ]
How do you setup a settings file? One is for your local development server and another set of setting values for when you upload to Google App Engine? For example, I would like to set up a settings file where I store the Absolute Root URL.
It's not clear from your question if you're asking about the Java or Python runtime. I'll assume Python for now. Just like any other Python webapp, the settings file can be wherever and whatever you want. I usually use a .py file called 'settings.py' or 'config.py' in the root directory of my app. For example, see [Bl...
Python: load words from file into a set
874,017
17
2009-05-17T06:33:54Z
874,025
33
2009-05-17T06:38:20Z
[ "python", "text-files" ]
I have a simple text file with several thousands of words, each in its own line, e.g. ``` aardvark hello piper ``` I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose): ``` my_set = set(open('filename.txt')) ``` The above code prod...
The strip() method of strings removes whitespace from both ends. ``` set(line.strip() for line in open('filename.txt')) ```
Python: load words from file into a set
874,017
17
2009-05-17T06:33:54Z
874,030
9
2009-05-17T06:41:17Z
[ "python", "text-files" ]
I have a simple text file with several thousands of words, each in its own line, e.g. ``` aardvark hello piper ``` I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose): ``` my_set = set(open('filename.txt')) ``` The above code prod...
Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your file is in GBs ``` words = set(open('filename.txt').read().split()) ```
Read .mat files in Python
874,461
170
2009-05-17T12:02:04Z
874,488
243
2009-05-17T12:16:13Z
[ "python", "matlab", "file-io", "scipy", "mat-file" ]
Does anyone have successful experience reading binary Matlab .mat files in Python? (I've seen that `scipy` has alleged support for reading .mat files, but I'm unsuccessful with it. I installed `scipy` version 0.7.0, and I can't find the `loadmat()` method)
Silly me. Forgot to import io... ``` import scipy.io mat = scipy.io.loadmat('file.mat') ```
Read .mat files in Python
874,461
170
2009-05-17T12:02:04Z
19,340,117
61
2013-10-12T23:06:48Z
[ "python", "matlab", "file-io", "scipy", "mat-file" ]
Does anyone have successful experience reading binary Matlab .mat files in Python? (I've seen that `scipy` has alleged support for reading .mat files, but I'm unsuccessful with it. I installed `scipy` version 0.7.0, and I can't find the `loadmat()` method)
scipy.io.savemat or scipy.io.loadmat does NOT work for matlab arrays --v7.3. But the good part is that matlab --v7.3 files are hdf5 datasets. So they can be read using a number of tools, including numpy. For python, you will need the h5py extension, which requires HDF5 on your system. ``` import numpy as np, h5py f ...
Read .mat files in Python
874,461
170
2009-05-17T12:02:04Z
30,868,935
7
2015-06-16T13:25:39Z
[ "python", "matlab", "file-io", "scipy", "mat-file" ]
Does anyone have successful experience reading binary Matlab .mat files in Python? (I've seen that `scipy` has alleged support for reading .mat files, but I'm unsuccessful with it. I installed `scipy` version 0.7.0, and I can't find the `loadmat()` method)
I've screwed half an hour even after reading the answers. Hope this answer helps First save the mat file as ``` save('test.mat','-v7') ``` After that in Python use the usual loadmat ``` import scipy.io as sio test = sio.loadmat('test.mat') ```
Python - install script to system
874,521
26
2009-05-17T12:36:31Z
874,539
30
2009-05-17T12:46:22Z
[ "python", "install" ]
how can I make setup.py file for my own script? I have to make my script global. (add it to /usr/bin) so I could run it from console just type: scriptName arguments. OS: Linux. **EDIT:** Now my script is installable, but how can i make it global? So that i could run it from console just name typing.
EDIT: This answer deals only with installing executable scripts into `/usr/bin`. I assume you have basic knowledge on how `setup.py` files work. Create your script and place it in your project like this: ``` yourprojectdir/ setup.py scripts/ myscript.sh ``` In your `setup.py` file do this: ``` from ...
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
874,815
41
2009-05-17T15:20:29Z
875,281
8
2009-05-17T19:16:53Z
[ "python", "subprocess", "stdout", "popen" ]
I'd like to use the subprocess module in the following way: 1. create a new process that potentially takes a long time to execute. 2. capture `stdout` (or `stderr`, or potentially both, either together or separately) 3. Process data from the subprocess **as it comes in,** perhaps firing events on every line received (...
Update with code that appears not to work (on windows anyway) ``` class ThreadWorker(threading.Thread): def __init__(self, callable, *args, **kwargs): super(ThreadWorker, self).__init__() self.callable = callable self.args = args self.kwargs = kwargs self.setDaemon(True) ...
Project Euler Problem 245
875,027
7
2009-05-17T17:20:00Z
911,612
9
2009-05-26T16:37:17Z
[ "python", "algorithm", "math" ]
I'm onto [problem 245](http://projecteuler.net/index.php?section=problems&id=245) now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far: We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) ...
Project Euler isn't fond of discussing problems on public forums like StackOverflow. All tasks are made to be done solo, if you encounter problems you may ask help for a specific mathematical or programming concept, but you can't just decide to ask how to solve the problem at hand - takes away the point of project Eule...
Receiving 16-bit integers in Python
875,046
8
2009-05-17T17:31:50Z
875,062
19
2009-05-17T17:36:48Z
[ "python", "integer" ]
I'm reading 16-bit integers from a piece of hardware over the serial port. Using Python, how can I get the LSB and MSB right, and make Python understand that it is a 16 bit signed integer I'm fiddling with, and not just two bytes of data?
Try using the [struct](http://docs.python.org/library/struct.html) module: ``` import struct # read 2 bytes from hardware as a string s = hardware.readbytes(2) # h means signed short # < means "little-endian, standard size (16 bit)" # > means "big-endian, standard size (16 bit)" value = struct.unpack("<h", s) # hardwa...
How to print a list, dict or collection of objects, in Python
875,074
17
2009-05-17T17:41:03Z
875,077
21
2009-05-17T17:42:22Z
[ "python", "list" ]
I have written a class in python that implements `__str__(self)` but when I use print on a list containing instances of this class, I just get the default output `<__main__.DSequence instance at 0x4b8c10>`. Is there another magic function I need to implement to get this to work, or do I have to write a custom print fun...
Yes, you need to use [`__repr__`](http://docs.python.org/reference/datamodel.html#object.%5F%5Frepr%5F%5F). A quick example of its behavior: ``` >>> class Foo: ... def __str__(self): ... return '__str__' ... def __repr__(self): ... return '__repr__' ... >>> bar = Foo() >>> bar __repr__...
Simple data storing in Python
875,228
3
2009-05-17T19:00:20Z
875,347
10
2009-05-17T19:51:09Z
[ "python", "file-io", "csv", "multidimensional-array", "fileparsing" ]
I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed. I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work ...
In addition to `pickle` ([mentioned above](http://stackoverflow.com/questions/875228/simple-data-storing-in-python/875272#875272)), there's [`json`](http://docs.python.org/library/json.html) (built in to 2.6, available via [simplejson](http://pypi.python.org/pypi/simplejson/) before that), and [`marshal`](http://docs.p...
Is there a value in using map() vs for?
875,337
10
2009-05-17T19:45:43Z
875,344
23
2009-05-17T19:49:16Z
[ "python", "for-loop", "map-function" ]
Does map() iterate through the list like "for" would? Is there a value in using map vs for? If so, right now my code looks like this: ``` for item in items: item.my_func() ``` If it makes sense, I would like to make it map(). Is that possible? What is an example like?
You could use [`map`](http://docs.python.org/3.0/library/functions.html#map) instead of the `for` loop you've shown, but since you do not appear to use the result of `item.my_func()`, this is **not recommended**. `map` should be used if you want to apply a function without side-effects to all elements of a list. In all...
editing a wav files using python
875,476
3
2009-05-17T20:54:38Z
875,775
14
2009-05-17T23:50:00Z
[ "python", "audio" ]
and between each word in the wav file I have full silence (I checked with Hex workshop and silence is represented with 0's) how can I cut the non-silence sound ? I'm programming using python thanks
Python has a [wav module](http://docs.python.org/library/wave.html). You can use it to open a wav file for reading and use the `getframes(1)' command to walk through the file frame by frame. ``` import wave w = wave.open('beeps.wav', 'r') for i in range(): frame = w.readframes(1) ``` The frame returned will be a byte...
How does one encode and decode a string with Python for use in a URL?
875,771
4
2009-05-17T23:45:12Z
875,777
9
2009-05-17T23:51:22Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
I have a string like this: ``` String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] ``` I would like to encrypt String A to be used in a clean URL. something like this: ``` String B: [ cYdfkeYss4543423sdfHsaaZ ] ``` Is there a encode API in python, given String A, it returns String B? Is there a decode API...
One way of doing the encode/decode is to use the package base64, for an example: ``` import base64 import sys encoded = base64.b64encode(sys.stdin.read()) print encoded decoded = base64.b64decode(encoded) print decoded ``` Is it what you were looking for? With your particular case you get: input: 12234\_1\_Hello'W...
How does one encode and decode a string with Python for use in a URL?
875,771
4
2009-05-17T23:45:12Z
1,184,226
9
2009-07-26T10:27:29Z
[ "python", "string", "hash", "urlencode", "clean-urls" ]
I have a string like this: ``` String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] ``` I would like to encrypt String A to be used in a clean URL. something like this: ``` String B: [ cYdfkeYss4543423sdfHsaaZ ] ``` Is there a encode API in python, given String A, it returns String B? Is there a decode API...
note that theres a huge difference between encoding and encryption. if you want to send sensitive data, then dont use the encoding mentioned above ;)
Generating color ranges in Python
876,853
9
2009-05-18T09:24:32Z
876,872
27
2009-05-18T09:29:59Z
[ "python", "colors" ]
I want to generate a list of color specifications in the form of (r, g, b) tuples, that span the entire color spectrum with as many entries as I want. So for 5 entries I would want something like: * (0, 0, 1) * (0, 1, 0) * (1, 0, 0) * (1, 0.5, 1) * (0, 0, 0.5) Of course, if there are more entries than combination of ...
Use the HSV/HSB/HSL color space (three names for more or less the same thing). Generate N tuples equally spread in hue space, then just convert them to RGB. Sample code: ``` import colorsys N = 5 HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)] RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples) ```
How can I create an local webserver for my python scripts?
877,033
14
2009-05-18T10:13:26Z
877,053
15
2009-05-18T10:19:46Z
[ "python", "webserver", "simplehttpserver" ]
I'm looking to use a local webserver to run a series of python scripts for the user. For various unavoidable reasons, the python script must run locally, not on a server. As a result, I'll be using HTML+browser as the UI, which I'm comfortable with, for the front end. I've been looking, therefore, for a lightweight we...
Don't waste a lot of time creating Windows service. Don't waste a lot of time on Windows Apache. Just make a Python service that responds to HTTP requests. Look at <http://docs.python.org/library/basehttpserver.html> Python offers an HTTP server that you can extend with your server-side methods. Look at <http://doc...
Find the number of 1s in the same position in two arrays
877,059
7
2009-05-18T10:21:45Z
877,082
19
2009-05-18T10:29:26Z
[ "python", "list" ]
I have two lists: ``` A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] ``` I want to find the number of 1s in the same position in both lists. The answer for these arrays would be 2.
A little shorter and hopefully more pythonic way: ``` >>> A=[0,0,0,1,0,1] >>> B=[0,0,1,1,1,1] x = sum(1 for a,b in zip(A,B) if (a==b==1)) >>> x 2 ```
HTTPSConnection module missing in Python 2.6 on CentOS 5.2
877,072
7
2009-05-18T10:24:57Z
877,292
7
2009-05-18T11:38:46Z
[ "python", "centos" ]
I'm playing around with a Python application on CentOS 5.2. It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection. When I try running my application I get an error regarding HTTPSConnection being missing: "AttributeError: 'module' object has no attribu...
citing from the python documentation (<http://docs.python.org/library/httplib.html>): **Note** HTTPS support is only available if the socket module was compiled with SSL support. You should find out how python on the CentOS you are using was built.
python dict.add_by_value(dict_2)?
877,295
9
2009-05-18T11:40:11Z
878,168
8
2009-05-18T15:00:51Z
[ "python", "code-golf", "dictionary" ]
The problem: ``` >>> a = dict(a=1,b=2 ) >>> b = dict( b=3,c=2) >>> c = ??? c = {'a': 1, 'b': 5, 'c': 2} ``` So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long: ``` c = dict([(i,a.get(i,0) + b.get(i,0)) ...
solving not in terms of "length" but performance, I'd do the following: ``` >>> from collections import defaultdict >>> def d_sum(a, b): d = defaultdict(int, a) for k, v in b.items(): d[k] += v return dict(d) >>> a = {'a': 1, 'b': 2} >>> b = {'c': 2, 'b': 3} >>> d_sum(a, b) {'a': 1,...
python dict.add_by_value(dict_2)?
877,295
9
2009-05-18T11:40:11Z
11,837,857
7
2012-08-07T00:42:22Z
[ "python", "code-golf", "dictionary" ]
The problem: ``` >>> a = dict(a=1,b=2 ) >>> b = dict( b=3,c=2) >>> c = ??? c = {'a': 1, 'b': 5, 'c': 2} ``` So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long: ``` c = dict([(i,a.get(i,0) + b.get(i,0)) ...
Easiest to just use a `Counter` ``` >>> from collections import Counter >>> a = dict(a=1,b=2 ) >>> b = dict( b=3,c=2) >>> Counter(a)+Counter(b) Counter({'b': 5, 'c': 2, 'a': 1}) >>> dict(Counter({'b': 5, 'c': 2, 'a': 1})) {'a': 1, 'c': 2, 'b': 5} ```
try... except... except... : how to avoid repeating code
877,440
3
2009-05-18T12:14:41Z
877,485
8
2009-05-18T12:25:52Z
[ "python", "try-catch", "dry" ]
* I'd like to avoid writting `errorCount += 1` in more than one place. * I'm looking for a better way than ``` success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() ``` * I'm tryi...
This look like a possible application of Python's new `with` statement. It allows to to unwind operations and release resources securely no matter what outcome a block of code had. Read about it in [PEP 343](http://www.python.org/dev/peps/pep-0343/)
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
31
2009-05-18T12:24:11Z
877,564
35
2009-05-18T12:47:07Z
[ "python", "arrays", "math", "numpy" ]
I have a 2d array that looks like this: ``` XX xx ``` What's the most efficient way to add an extra row and column: ``` xxy xxy yyy ``` For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the...
The shortest in terms of lines of code i can think of is for the first question. ``` >>> import numpy as np >>> p = np.array([[1,2],[3,4]]) >>> p = np.append(p, [[5,6]], 0) >>> p = np.append(p, [[7],[8],[9]],1) >>> p array([[1, 2, 7], [3, 4, 8], [5, 6, 9]]) ``` And the for the second question ``` p = np....
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
31
2009-05-18T12:24:11Z
5,650,582
31
2011-04-13T14:04:28Z
[ "python", "arrays", "math", "numpy" ]
I have a 2d array that looks like this: ``` XX xx ``` What's the most efficient way to add an extra row and column: ``` xxy xxy yyy ``` For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the...
**A useful alternative answer to the first question, using the examples from** tomeedee’s **answer, would be to use numpy’s** vstack **and** column\_stack **methods:** Given a matrix p, ``` >>> import numpy as np >>> p = np.array([ [1,2] , [3,4] ]) ``` an augmented matrix can be generated by: ``` >>> p = np.vst...
Why return NotImplemented instead of raising NotImplementedError
878,943
134
2009-05-18T17:43:40Z
878,985
9
2009-05-18T17:54:03Z
[ "python" ]
Python has a singleton called [`NotImplemented`](https://docs.python.org/2/library/constants.html#NotImplemented). Why would someone want to ever return `NotImplemented` instead of raising the [`NotImplementedError`](https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError) exception? Won't it ...
My guess would be performance. In a situation like rich comparisons, where you could be doing lots of operations in a short time, setting up and handling lots of exceptions could take a lot longer than simply returning a `NotImplemented` value.
Why return NotImplemented instead of raising NotImplementedError
878,943
134
2009-05-18T17:43:40Z
879,005
149
2009-05-18T17:58:32Z
[ "python" ]
Python has a singleton called [`NotImplemented`](https://docs.python.org/2/library/constants.html#NotImplemented). Why would someone want to ever return `NotImplemented` instead of raising the [`NotImplementedError`](https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError) exception? Won't it ...
It's because `__lt__()` and related comparison methods are quite commonly used indirectly in list sorts and such. Sometimes the algorithm will choose to try another way or pick a default winner. Raising an exception would break out of the sort unless caught, whereas `NotImplemented` doesn't get raised and can be used i...
Windows cmd encoding change causes Python crash
878,972
38
2009-05-18T17:52:10Z
3,259,271
67
2010-07-15T19:35:10Z
[ "python", "windows", "unicode", "encoding", "cmd" ]
First I change Windows CMD encoding to utf-8 and run Python interpreter: ``` chcp 65001 python ``` Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). ``` >>> import sys >>> print u'ëèæîð'.encode(sys.stdin.encoding) ``` ...
Here's how to alias `cp65001` to UTF-8 without changing `encodings\aliases.py`: ``` import codecs codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) ``` (IMHO, don't pay any attention to the silliness about `cp65001` not being identical to UTF-8 at <http://bugs.python.org/issue6058#ms...
Windows cmd encoding change causes Python crash
878,972
38
2009-05-18T17:52:10Z
12,834,315
24
2012-10-11T07:26:37Z
[ "python", "windows", "unicode", "encoding", "cmd" ]
First I change Windows CMD encoding to utf-8 and run Python interpreter: ``` chcp 65001 python ``` Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). ``` >>> import sys >>> print u'ëèæîð'.encode(sys.stdin.encoding) ``` ...
Set **PYTHONIOENCODING** system variable: ``` > chcp 65001 > set PYTHONIOENCODING=utf-8 > python example.py Encoding is utf-8 ``` Source of example.py is simple: ``` import sys print "Encoding is", sys.stdin.encoding ```
How to install python-dateutil on Windows?
879,156
43
2009-05-18T18:38:53Z
879,879
17
2009-05-18T21:15:02Z
[ "python", "install", "python-dateutil" ]
I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up [python-dateutil](http://pypi.python.org/pypi/python-dateutil) which should ...
Why didn't someone tell me I was being a total noob? All I had to do was copy the `dateutil` directory to someplace in my Python path, and it was good to go.
How to install python-dateutil on Windows?
879,156
43
2009-05-18T18:38:53Z
7,186,957
54
2011-08-25T08:05:27Z
[ "python", "install", "python-dateutil" ]
I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up [python-dateutil](http://pypi.python.org/pypi/python-dateutil) which should ...
If dateutil is missing install it via: ``` pip install python-dateutil ``` Or on Ubuntu: ``` sudo apt-get install python-dateutil ```
How to ignore deprecation warnings in Python
879,173
73
2009-05-18T18:42:44Z
879,208
71
2009-05-18T18:50:07Z
[ "python", "warnings", "deprecated", "ignore" ]
I keep getting this : ``` DeprecationWarning: integer argument expected, got float ``` How do I make this message go away? Is there a way to avoid warnings in Python?
I [Googled](http://www.google.nl/search?q=python+silence+Deprecationwarning) and [found](https://docs.python.org/3/library/warnings.html): ``` #!/usr/bin/env python -W ignore::DeprecationWarning ``` If you're on Windows: pass `-W ignore::DeprecationWarning` as an argument to Python. (But resolving the issue may be ...
How to ignore deprecation warnings in Python
879,173
73
2009-05-18T18:42:44Z
879,249
83
2009-05-18T19:01:48Z
[ "python", "warnings", "deprecated", "ignore" ]
I keep getting this : ``` DeprecationWarning: integer argument expected, got float ``` How do I make this message go away? Is there a way to avoid warnings in Python?
You should just fix your code but just in case, ``` import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) ```
How to ignore deprecation warnings in Python
879,173
73
2009-05-18T18:42:44Z
1,640,777
108
2009-10-28T23:24:01Z
[ "python", "warnings", "deprecated", "ignore" ]
I keep getting this : ``` DeprecationWarning: integer argument expected, got float ``` How do I make this message go away? Is there a way to avoid warnings in Python?
I had these: > /home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86\_64.egg/twisted/persisted/sob.py:12: > DeprecationWarning: the md5 module is > deprecated; use hashlib instead > import os, md5, sys > > /home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86\_64...
How to ignore deprecation warnings in Python
879,173
73
2009-05-18T18:42:44Z
2,381,422
19
2010-03-04T17:35:36Z
[ "python", "warnings", "deprecated", "ignore" ]
I keep getting this : ``` DeprecationWarning: integer argument expected, got float ``` How do I make this message go away? Is there a way to avoid warnings in Python?
I found the cleanest way to do this (especially on windows) is by adding the following to C:\Python26\Lib\site-packages\sitecustomize.py: ``` import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) ``` Note that I had to create this file. Of course, change the path to python if yours is differe...
Serializing a Python Object to XML (Apple .plist)
879,212
3
2009-05-18T18:51:32Z
879,222
7
2009-05-18T18:54:30Z
[ "python", "xml", "plist" ]
I need to read and serialize objects from and to XML, Apple's .plist format in particular. What's the most intelligent way to do it in Python? Are there any ready-made solutions?
Check out [plistlib](http://docs.python.org/dev/library/plistlib.html).
logging with filters
879,732
16
2009-05-18T20:43:48Z
879,765
12
2009-05-18T20:49:26Z
[ "python", "logging" ]
I'm using Logging (import logging) to log messages. Within 1 single module, I am logging messages at the debug level (my\_logger.debug('msg')); Some of these debug messages come from function\_a() and others from function\_b(); I'd like to be able to enable/disable logging based on whether they come from a or from b;...
Do not use global. It's an accident waiting to happen. You can give your loggers any "."-separated names that are meaningful to you. You can control them as a hierarchy. If you have loggers named `a.b.c` and `a.b.d`, you can check the logging level for `a.b` and alter both loggers. You can have any number of loggers...
logging with filters
879,732
16
2009-05-18T20:43:48Z
879,937
25
2009-05-18T21:27:07Z
[ "python", "logging" ]
I'm using Logging (import logging) to log messages. Within 1 single module, I am logging messages at the debug level (my\_logger.debug('msg')); Some of these debug messages come from function\_a() and others from function\_b(); I'd like to be able to enable/disable logging based on whether they come from a or from b;...
Just implement a subclass of `logging.Filter`: <http://docs.python.org/library/logging.html#filter-objects>. It will have one method, `filter(record)`, that examines the log record and returns True to log it or False to discard it. Then you can install the filter on either a `Logger` or a `Handler` by calling its `addF...
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
880,160
4
2009-05-18T22:42:38Z
880,240
7
2009-05-18T23:16:17Z
[ "python", "attributes", "methods", "python-datamodel" ]
I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die...
Instead of: "`print hasattr(d1,each)`", try: "`print each, type(getattr(d1,each))`". You should find the results informative. Also, in place of `dir()` try `help()`, which I think you're really looking for.
How to strip html/javascript from text input in django
880,188
51
2009-05-18T22:53:47Z
880,212
34
2009-05-18T23:04:13Z
[ "python", "django" ]
What is the easiest way to strip all html/javascript from a string?
The [striptags](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#striptags) template filter. ``` {{ value|striptags }} ```
How to strip html/javascript from text input in django
880,188
51
2009-05-18T22:53:47Z
880,238
112
2009-05-18T23:15:37Z
[ "python", "django" ]
What is the easiest way to strip all html/javascript from a string?
If you want to strip tags in the python, you can use: ``` from django.utils.html import strip_tags strip_tags(string_value) ``` EDIT: If you are using strip\_tags, than you should update your django. Because security researchers found a way in order to bypass strip\_tags . Further information : <http://www.mehmetinc...