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
Python list subtraction operation
3,428,536
85
2010-08-06T23:43:12Z
20,259,489
10
2013-11-28T06:49:43Z
[ "python", "list" ]
I want to do something similar to this: ``` >>> x = [1,2,3,4,5,6,7,8,9,0] >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] >>> y = [1,3,5,7,9] >>> y [1, 3, 5, 7, 9] >>> y - x # (should return [2,4,6,8,0]) ``` But this is not supported by python lists What is the best way of doing it?
if duplicate and ordering items are problem : `[i for i in a if not i in b or b.remove(i)]` ``` a = [1,2,3,3,3,3,4] b = [1,3] result: [2, 3, 3, 3, 4] ```
Python list subtraction operation
3,428,536
85
2010-08-06T23:43:12Z
27,538,360
7
2014-12-18T02:33:35Z
[ "python", "list" ]
I want to do something similar to this: ``` >>> x = [1,2,3,4,5,6,7,8,9,0] >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] >>> y = [1,3,5,7,9] >>> y [1, 3, 5, 7, 9] >>> y - x # (should return [2,4,6,8,0]) ``` But this is not supported by python lists What is the best way of doing it?
For many use cases, the answer you want is: ``` ys = set(y) [item for item in x if item not in ys] ``` This is a hybrid between [aaronasterling's answer](http://stackoverflow.com/a/3428637/908494) and [quantumSoup's answer](http://stackoverflow.com/a/3428547/908494). aaronasterling's version does `len(y)` item compa...
Finding the largest delta between two integers in a list in python
3,428,769
10
2010-08-07T01:20:20Z
3,428,785
18
2010-08-07T01:24:46Z
[ "python" ]
I have a list of integers, i.e.: ``` values = [55, 55, 56, 57, 57, 57, 57, 62, 63, 64, 79, 80] ``` I am trying to find the largest difference between two consecutive numbers. In this case it would be 15 from 64->79. The numbers can be negative or positive, increasing or decreasing or both. The important thing is I ne...
``` max(abs(x - y) for (x, y) in zip(values[1:], values[:-1])) ```
Getting started with Pylons
3,428,795
7
2010-08-07T01:29:45Z
3,428,974
10
2010-08-07T02:57:09Z
[ "python", "authentication", "pylons" ]
I am just starting to use a web framework. I have decided I really like python and started looking at web frameworks. I don't really like django for a few reasons, but from what I have tried so far I found I really like pylons. The problem I have is that I can't find that many articles/tutorials about pylons, especial...
The book suggested by meder (<http://pylonsbook.com/en/1.1/>) is a very good start. I upvoted his anwser because that's where I learned Pylons. However, the book is written for Pylons 0.9.7 (the latest version before 0.10 and 1.0). Pylons is the agglomeration of several high quality libraries. Learning Pylons is all ...
How to remove curly quotes?
3,428,876
2
2010-08-07T02:02:26Z
3,428,885
7
2010-08-07T02:05:34Z
[ "python" ]
In my utf-8 encoded file, there are curly quotes (“”). How do I replace them all with normal quotes (")? ``` cell_info.replace('“','"') cell_info.replace('”','"') ``` did not work. No error message. Thank you. :)
`str.replace()` doesn't replace the original string, it just returns a new one. Do: ``` cell_info = cell_info.replace('“','"').replace('”','"') ```
Python requires a GIL. But Jython & IronPython don't. Why?
3,429,159
5
2010-08-07T04:47:18Z
3,429,193
9
2010-08-07T05:06:37Z
[ "python", "multithreading", "ironpython", "jython", "gil" ]
Why is it that you can run Jython and IronPython without the need for a GIL but Python (CPython) requires a GIL?
Parts of the Interpreter aren't threadsafe, though mostly because making them all threadsafe by massive lock usage would slow single-threaded extremely [(source)](http://effbot.org/pyfaq/can-t-we-get-rid-of-the-global-interpreter-lock.htm). This seems to be related to the CPython garbage collector using reference count...
Determining running programs in Python
3,429,250
13
2010-08-07T05:34:06Z
3,429,265
11
2010-08-07T05:41:32Z
[ "python", "windows", "process" ]
How would I use Python to determine what programs are currently running. I am on Windows.
``` import os os.system('WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid') f = open("C:\ProcessList.txt") plist = f.readlines() f.close() ``` Now plist contains a formatted whitespace-separated list of processes: * The first column is the name of the executable that is running * The second c...
Determining running programs in Python
3,429,250
13
2010-08-07T05:34:06Z
6,844,933
22
2011-07-27T13:15:48Z
[ "python", "windows", "process" ]
How would I use Python to determine what programs are currently running. I am on Windows.
Thanks to @hb2pencil for the WMIC command! Here's how you can pipe the output without a file: ``` import subprocess cmd = 'WMIC PROCESS get Caption,Commandline,Processid' proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for line in proc.stdout: print line ```
Pythonic way to convert a list of integers into a string of comma-separated ranges
3,429,510
12
2010-08-07T07:08:28Z
3,430,231
18
2010-08-07T11:26:13Z
[ "list", "python" ]
I have a list of integers which I need to parse into a string of ranges. For example: ``` [0, 1, 2, 3] -> "0-3" [0, 1, 2, 4, 8] -> "0-2,4,8" ``` And so on. I'm still learning more pythonic ways of handling lists, and this one is a bit difficult for me. My latest thought was to create a list of lists which keeps t...
``` >>> from itertools import count, groupby >>> L=[1, 2, 3, 4, 6, 7, 8, 9, 12, 13, 19, 20, 22, 23, 40, 44] >>> G=(list(x) for _,x in groupby(L, lambda x,c=count(): next(c)-x)) >>> print ",".join("-".join(map(str,(g[0],g[-1])[:len(g)])) for g in G) 1-4,6-9,12-13,19-20,22-23,40,44 ``` The idea here is to pair each elem...
Automatic creation date for django model form objects?
3,429,878
64
2010-08-07T09:21:28Z
3,429,915
128
2010-08-07T09:33:49Z
[ "python", "django" ]
What's the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated? In my model I have: ``` created_at = models.DateTimeField(False, True, editable=False) updated_at = models.DateTimeField(True, True, editable=False) ``` and in my view: ``` if ...
You can use the [`auto_now`](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateField.auto_now) and [`auto_now_add`](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateField.auto_now_add) options for `updated_at` and `created_at` respectively. ``` class MyModel(model...
Most memory-efficient way of holding base64 data in Python?
3,430,016
3
2010-08-07T10:08:16Z
3,430,100
7
2010-08-07T10:34:09Z
[ "python", "algorithm", "data-structures", "md5", "base64" ]
Suppose you have a MD5 hash encoded in base64. Then each character needs only 6 bits to store each character in the resultant 22-byte string (excluding the ending '=='). Thus, each base64 md5 hash can shrink down to 6\*22 = 132 bits, which requires 25% less memory space compared to the original 8\*22=176 bits string. ...
The most efficient way to store base64 encoded data is to decode it and store it as binary. base64 is a transport encoding - there's no sense in storing data in it, especially in memory, unless you have a compelling reason otherwise. Also, nitpick: The output of a hash function is not a hex string - that's just a comm...
Group together arbitrary date objects that are within a time range of each other
3,430,369
4
2010-08-07T12:16:55Z
3,430,444
11
2010-08-07T12:35:15Z
[ "python", "date", "sorting", "group-by", "intervals" ]
I want to split the calendar into two-week intervals starting at `2008-May-5`, or any arbitrary starting point. So I start with several date objects: ``` import datetime as DT raw = ("2010-08-01", "2010-06-25", "2010-07-01", "2010-07-08") transactions = [(DT.datetime.strptime(datestring, "%Y-%m...
``` import datetime as DT import itertools start_date=DT.date(2008,5,5) def mkdate(datestring): return DT.datetime.strptime(datestring, "%Y-%m-%d").date() def fortnight(date): return (date-start_date).days //14 raw = ("2010-08-01", "2010-06-25", "2010-07-01", "2010-07-08") transactions=...
How to get full path of current file's directory in Python?
3,430,372
277
2010-08-07T12:17:52Z
3,430,395
591
2010-08-07T12:24:25Z
[ "python", "filesystems" ]
I want to get the current file's directory path. I tried: ``` >>> os.path.abspath(__file__) 'C:\\python27\\test.py' ``` But how can I retrieve the directory's path? For example: ``` 'C:\\python27\\' ```
If you mean the directory of the script being run: ``` import os os.path.dirname(os.path.abspath(__file__)) ``` If you mean the current working directory: ``` import os os.getcwd() ``` Note that before and after `file` is two underscores, not just one.
How to get unpickling to work with iPython?
3,431,419
7
2010-08-07T17:44:27Z
3,431,475
10
2010-08-07T18:03:26Z
[ "python", "ipython", "pickle" ]
I'm trying to load pickled objects in iPython. The error I'm getting is: > AttributeError: 'FakeModule' object has no attribute 'World' Anybody know how to get it to work, or at least a workaround for loading objects in iPython in order to interactively browse them? Thanks edited to add: I have a script called wo...
Looks like you've modified `FakeModule` between the time you pickled your data, and the time you're trying to unpickle it: specifically, you have removed from that module some top-level object named `World` (perhaps a class, perhaps a function). Pickling serializes classes and function "by name", so they need to be na...
What code can I use to check if Python is running in IDLE?
3,431,498
9
2010-08-07T18:13:35Z
7,459,924
7
2011-09-18T06:40:19Z
[ "python", "python-idle" ]
Just as the title says. I want to write a script that behaves differently depending on whether it's running inside a console window or in IDLE. Is there an object that exists only when running in IDLE that I can check for? An environment variable? I'm using Python 2.6.5 and 2.7 on Windows. ### Edit: *The answers giv...
I would prefer to do: ``` import sys print('Running IDLE' if 'idlelib.run' in sys.modules else 'Out of IDLE') ```
Creating functions in a loop
3,431,676
24
2010-08-07T19:04:33Z
3,431,699
55
2010-08-07T19:09:39Z
[ "python", "function" ]
I'm trying to create functions inside of a loop and storing them in a dictionary. The problem is that all entries in the dictionary seem end up mapping to the last created function. The code goes like this: ``` d = {} def test(**kwargs): for k in kwargs: def f(): print k, kwargs[k] d[k]...
You're running into a problem with *late binding* -- each function looks up `k` as late as possible (thus, when called outside `test`, this happens after the end of the loop). Easily fixed by forcing early binding: change `def f():` to `def f(k=k):` -- default values (the right-hand `k` in `k=k` is a default value for ...
Generating an MD5 checksum of a file
3,431,825
142
2010-08-07T19:50:52Z
3,431,835
205
2010-08-07T19:53:25Z
[ "python", "md5", "checksum", "hashlib" ]
Is there any simple way of generating (and checking) MD5 checksums of a list of files in Python? (I have a small program I'm working on, and I'd like to confirm the checksums of the files).
There is a way that's pretty memory **inefficient**. single file: ``` print hashlib.md5(open(full_path, 'rb').read()).hexdigest() ``` list of files: ``` import hashlib [(fname, hashlib.md5(open(fname, 'rb').read()).digest()) for fname in fnamelst] ``` But, MD5 is known broken and (IMHO) should come with scary depr...
Generating an MD5 checksum of a file
3,431,825
142
2010-08-07T19:50:52Z
3,431,838
136
2010-08-07T19:53:52Z
[ "python", "md5", "checksum", "hashlib" ]
Is there any simple way of generating (and checking) MD5 checksums of a list of files in Python? (I have a small program I'm working on, and I'd like to confirm the checksums of the files).
You can use [hashlib.md5()](http://docs.python.org/library/hashlib.html) Note that sometimes you won't be able to fit the whole file in memory. In that case, you'll have to read chunks of 4096 bytes sequentially and feed them to the Md5 function: ``` def md5(fname): hash_md5 = hashlib.md5() with open(fname, "...
Generating an MD5 checksum of a file
3,431,825
142
2010-08-07T19:50:52Z
21,565,932
18
2014-02-04T23:45:06Z
[ "python", "md5", "checksum", "hashlib" ]
Is there any simple way of generating (and checking) MD5 checksums of a list of files in Python? (I have a small program I'm working on, and I'd like to confirm the checksums of the files).
I'd rather comment on the answer from @Omnifarious, since I'm clearly not adding anything fundamentally new, but I suppose I'm not quite up to commenting status just yet. Anyway, to answer @Nemo's question from Omnifarious's answer: I happened to be thinking about checksums a bit (came here looking for suggestions on ...
Python socket connection timeout
3,432,102
23
2010-08-07T21:28:03Z
3,432,222
42
2010-08-07T22:05:37Z
[ "python", "sockets" ]
I have a socket that I want to timeout when connecting so that I can cancel the whole operation if it can't connect yet it also want to use the makefile for the socket which requires no timeout. Is there an easy way to do this or is this going to be a difficult thing to do? Does python allow a reset of the timeout af...
You just need to use the socket [`settimeout()`](https://docs.python.org/2/library/socket.html#socket.socket.settimeout) method before attempting the `connect()`, please note that after connecting you must `settimeout(None)` to set the socket into blocking mode, such is required for the makefile . Here is the code I am...
How to get the size of a python object in bytes on Google AppEngine?
3,432,402
4
2010-08-07T23:10:31Z
3,432,874
8
2010-08-08T02:45:43Z
[ "python", "google-app-engine", "memcached", "pickle" ]
I need to compute the sizes of some python objects, so I can break them up and store them in memcache without hitting size limits. '**sizeof**()' doesn't seem to be present on python objects in the GAE environment and sys.getsizeof() is also unavailable. GAE itself is clearly checking sizes behind the scenes to enfor...
`memcache` internally and invariably uses `pickle` and stores the resulting string, so you can check with `len(pickle.dumps(yourobject, -1))`. Note that sys.getsizeof (which requires 2.6 or better, which is why it's missing on GAE) would not really help you at all: ``` >>> import sys >>> sys.getsizeof(23) 12 >>> impor...
List comprehension for running total
3,432,830
15
2010-08-08T02:19:27Z
3,432,846
8
2010-08-08T02:28:09Z
[ "python", "list-comprehension", "running-total" ]
I want to get a running total from a list of numbers. For demo purposes, I start with a sequential list of numbers using `range` ``` a = range(20) runningTotal = [] for n in range(len(a)): new = runningTotal[n-1] + a[n] if n > 0 else a[n] runningTotal.append(new) # This one is a syntax error # runningTotal ...
I'm not sure about 'elegant', but I think the following is much simpler and more intuitive (at the cost of an extra variable): ``` a = range(20) runningTotal = [] total = 0 for n in a: total += n runningTotal.append(total) ``` The functional way to do the same thing is: ``` a = range(20) runningTotal = reduce(...
List comprehension for running total
3,432,830
15
2010-08-08T02:19:27Z
3,432,848
21
2010-08-08T02:28:57Z
[ "python", "list-comprehension", "running-total" ]
I want to get a running total from a list of numbers. For demo purposes, I start with a sequential list of numbers using `range` ``` a = range(20) runningTotal = [] for n in range(len(a)): new = runningTotal[n-1] + a[n] if n > 0 else a[n] runningTotal.append(new) # This one is a syntax error # runningTotal ...
A list comprehension has no good (clean, portable) way to refer to the very list it's building. One good and elegant approach might be to do the job in a generator: ``` def running_sum(a): tot = 0 for item in a: tot += item yield tot ``` to get this as a list instead, of course, use `list(running_sum(a))`...
List comprehension for running total
3,432,830
15
2010-08-08T02:19:27Z
3,432,856
17
2010-08-08T02:35:07Z
[ "python", "list-comprehension", "running-total" ]
I want to get a running total from a list of numbers. For demo purposes, I start with a sequential list of numbers using `range` ``` a = range(20) runningTotal = [] for n in range(len(a)): new = runningTotal[n-1] + a[n] if n > 0 else a[n] runningTotal.append(new) # This one is a syntax error # runningTotal ...
If you can use [numpy](http://numpy.scipy.org/), it has a built-in function named `cumsum` that does this. ``` import numpy tot = numpy.cumsum(a) # returns a numpy.ndarray tot = list(tot) # if you prefer a list ```
List comprehension for running total
3,432,830
15
2010-08-08T02:19:27Z
3,432,885
10
2010-08-08T02:50:18Z
[ "python", "list-comprehension", "running-total" ]
I want to get a running total from a list of numbers. For demo purposes, I start with a sequential list of numbers using `range` ``` a = range(20) runningTotal = [] for n in range(len(a)): new = runningTotal[n-1] + a[n] if n > 0 else a[n] runningTotal.append(new) # This one is a syntax error # runningTotal ...
*This can be implemented in 2 lines in Python.* Using a default parameter eliminates the need to maintain an aux variable outside, and then we just do a `map` to the list. ``` def accumulate(x, l=[0]): l[0] += x; return l[0]; map(accumulate, range(20)) ```
Django - how to extend 3rd party models without modifying
3,433,131
9
2010-08-08T04:58:59Z
3,433,146
8
2010-08-08T05:07:06Z
[ "python", "django", "django-models", "model" ]
I want to add a column to a database table but I don't want to modify the 3rd party module in case I need/decide to upgrade the module in the future. Is there a way I can add this field within my code so that with new builds I don't have to add the field manually?
You can use ModelName.add\_to\_class (or .contribute\_to\_class), but if you have already run syncdb, then there is no way to automatically have it add the columns you need. For maintainable code, you will probably want to extend by sub-classing the desired model in your own app, and use something like south to handle...
How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting
3,433,486
44
2010-08-08T07:36:16Z
3,433,503
49
2010-08-08T07:41:32Z
[ "python", "numpy", "scipy", "curve-fitting", "linear-regression" ]
I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic). I use Python and Numpy and for polynomial fitting there is a function `polyfit()`. But I found no such functions for exponential and logarithmic fitting. Are there any? Or how to solv...
For fitting y = A + B log x, just fit y against log x. For fitting y = AeBx, take the logarithm of both side gives log y = log A + Bx. So just fit log y against x.
How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting
3,433,486
44
2010-08-08T07:36:16Z
11,209,147
48
2012-06-26T14:05:24Z
[ "python", "numpy", "scipy", "curve-fitting", "linear-regression" ]
I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic). I use Python and Numpy and for polynomial fitting there is a function `polyfit()`. But I found no such functions for exponential and logarithmic fitting. Are there any? Or how to solv...
You can also fit a set of a data to whatever function you like using curve\_fit from scipy.optimize. For example if you want to fit an exponential function (from the documentation at <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html>): ``` import numpy as np import matplotlib.pyplot as...
How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting
3,433,486
44
2010-08-08T07:36:16Z
15,369,787
24
2013-03-12T18:57:17Z
[ "python", "numpy", "scipy", "curve-fitting", "linear-regression" ]
I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic). I use Python and Numpy and for polynomial fitting there is a function `polyfit()`. But I found no such functions for exponential and logarithmic fitting. Are there any? Or how to solv...
I was having some trouble with this so let me be very explicit so noobs like me can understand. Lets say that we have a data file or something like that ``` # -*- coding: utf-8 -*- import matplotlib.pyplot as plt from scipy.optimize import curve_fit import numpy as np import sympy as sym """ Generate some data, let...
Python Time Delays
3,433,559
16
2010-08-08T08:09:32Z
3,433,565
33
2010-08-08T08:11:38Z
[ "python", "time" ]
I want to know how to call a function after a certain time. I have tried time.sleep() but this halts the whole script. I want the script to carry on, but after ???secs call a function and run the other script at the same time
Have a look at [`threading.Timer`](http://docs.python.org/library/threading.html#timer-objects). It runs your function in a new thread. ``` from threading import Timer def hello(): print "hello, world" t = Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed ```
Expanding tuples in python
3,433,913
2
2010-08-08T10:10:19Z
3,433,944
7
2010-08-08T10:23:27Z
[ "python", "tuples" ]
In the following code: ``` a = 'a' tup = ('tu', 'p') b = 'b' print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup[0], tup[1], b) ``` How can I "expand" (can't figure out a better verb) `tup` so that I don't have to explicitly list all its elements? **NOTE** That I don't want to print `tup` per-se, but its individual elem...
It is possible to [flatten a tuple](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python), but I think in your case, constructing a new tuple by concatenation is easier. ``` 'a: %s, t[0]: %s, t[1]: %s, b:%s'%((a,) + tup + (b,)) # ^^^^^^^^^^^^^^^^^ ```
How to Pass variables to python script?
3,434,048
3
2010-08-08T11:00:07Z
3,434,080
8
2010-08-08T11:07:54Z
[ "python" ]
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, ...
If you are using Python <2.7 I would suggest [optparse](http://docs.python.org/library/optparse.html). optparse is deprecated though, and in 2.7 you should use [argparse](http://docs.python.org/library/argparse.html#module-argparse) It makes passing named parameters a breeze.
Detect English verb tenses using NLTK
3,434,144
9
2010-08-08T11:31:14Z
3,437,522
8
2010-08-09T05:26:21Z
[ "python", "nlp", "nltk" ]
I am looking for a way given an English text count verb phrases in it in past, present and future tenses. For now I am using [NLTK](http://www.nltk.org), do a POS (Part-Of-Speech) tagging, and then count say 'VBD' to get past tenses. This is not accurate enough though, so I guess I need to go further and use chunking, ...
Thee exact answer depends on which chunker you intend to use, but list comprehensions will take you a long way. This gets you the number of verb phrases using a non-existent chunker. ``` len([phrase for phrase in nltk.Chunker(sentence) if phrase[1] == 'VP']) ``` You can take a more fine-grained approach to detect num...
Accessing a class's variable in Python
3,434,581
23
2010-08-08T14:02:08Z
3,434,596
46
2010-08-08T14:05:50Z
[ "python", "class", "methods", "return" ]
``` class Example(object): def the_example(self): itsProblem = "problem" theExample = Example() print(theExample.itsProblem) ``` How do I access a class's variable? I've tried adding this definition: ``` def return_itsProblem(self): return itsProblem ``` Yet, that fails also.
**The anwser, in a few words** In your example, `itsProblem` is a local variable. Your must use `self` to set and get instance variables. You can set it in the `__init__` method. Then your code would be: ``` class Example(object): def __init__(self): self.itsProblem = "problem" theExample = Example() p...
Multi-split in Python
3,435,900
2
2010-08-08T20:12:19Z
3,435,914
13
2010-08-08T20:16:26Z
[ "python", "string", "split" ]
How would I split a string by two opposing values? For example `(` and `)` are the "deliminators" and I have the following string: ``` Wouldn't it be (most) beneficial to have (at least) some idea? ``` I need the following output (as an array) ``` ["Wouldn't it be ", "most", " beneficial to have ", "at least", " som...
[re.split](http://docs.python.org/library/re.html)() ``` s = "Wouldn't it be (most) beneficial to have (at least) some idea?" l = re.split('[()]', s); ```
Does Python have a string contains substring method?
3,437,059
1,519
2010-08-09T02:52:50Z
3,437,068
238
2010-08-09T02:55:04Z
[ "python", "string", "substring", "contains" ]
I'm looking for a `string.contains` or `string.indexof` method in Python. I want to do: ``` if not somestring.contains("blah"): continue ```
If it's just a substring search you can use `string.find("substring")` You do have to be a little careful with `find`, `index`, and `in` though, as they are substring searches. In other words, this: ``` s = "This be a string" if s.find("is") == -1: print "No 'is' here!" else: print "Found 'is' in the string."...
Does Python have a string contains substring method?
3,437,059
1,519
2010-08-09T02:52:50Z
3,437,070
2,285
2010-08-09T02:56:21Z
[ "python", "string", "substring", "contains" ]
I'm looking for a `string.contains` or `string.indexof` method in Python. I want to do: ``` if not somestring.contains("blah"): continue ```
You can use the [`in` operator](https://docs.python.org/reference/expressions.html#membership-test-details): ``` if "blah" not in somestring: continue ```
Does Python have a string contains substring method?
3,437,059
1,519
2010-08-09T02:52:50Z
3,437,130
65
2010-08-09T03:19:09Z
[ "python", "string", "substring", "contains" ]
I'm looking for a `string.contains` or `string.indexof` method in Python. I want to do: ``` if not somestring.contains("blah"): continue ```
`if needle in haystack:` is the normal use, as @Michael says -- it relies on the [`in`](https://docs.python.org/reference/expressions.html#membership-test-details) operator, more readable and faster than a method call. If you truly need a method instead of an operator (e.g. to do some weird `key=` for a very peculiar ...
Does Python have a string contains substring method?
3,437,059
1,519
2010-08-09T02:52:50Z
6,859,010
8
2011-07-28T12:32:04Z
[ "python", "string", "substring", "contains" ]
I'm looking for a `string.contains` or `string.indexof` method in Python. I want to do: ``` if not somestring.contains("blah"): continue ```
Another way to find whether string contains few characters or not with the Boolean return value (i.e. `True` or `False) ``` str1 = "This be a string" find_this = "tr" if find_this in str1: print find_this, " is been found in ", str1 else: print find_this, " is not found in ", str1 ```
Does Python have a string contains substring method?
3,437,059
1,519
2010-08-09T02:52:50Z
19,101,749
32
2013-09-30T18:59:46Z
[ "python", "string", "substring", "contains" ]
I'm looking for a `string.contains` or `string.indexof` method in Python. I want to do: ``` if not somestring.contains("blah"): continue ```
Not there is no `string.contains(str)` method but there is `in` operator: ``` if substring in someString: print "It's there!!!" ``` Here is more complex working example: ``` # print all files with dot in home directory import commands (st, output) = commands.getstatusoutput('ls -a ~') print [f for f in output.sp...
Does Python have a string contains substring method?
3,437,059
1,519
2010-08-09T02:52:50Z
27,138,045
18
2014-11-25T22:33:48Z
[ "python", "string", "substring", "contains" ]
I'm looking for a `string.contains` or `string.indexof` method in Python. I want to do: ``` if not somestring.contains("blah"): continue ```
> # Does Python have a string contains substring method? Yes, but Python has a comparison operator that you should use instead, because the language intends its usage, and other programmers will expect you to use it. That keyword is `in`, which is used as a comparison operator: ``` 'foo' in '**foo**' # returns Tr...
Does Python have a string contains substring method?
3,437,059
1,519
2010-08-09T02:52:50Z
30,465,415
27
2015-05-26T17:46:13Z
[ "python", "string", "substring", "contains" ]
I'm looking for a `string.contains` or `string.indexof` method in Python. I want to do: ``` if not somestring.contains("blah"): continue ```
Basically, you want to find a substring in a string in python. There are 2 ways to search for a substring in a string in python. **Method 1: `in` operator** You can use the python's `in` operator to check for a substring. Its quite simple and intuitive. It will return `True` if the substring was found in the string ...
Does Python have a string contains substring method?
3,437,059
1,519
2010-08-09T02:52:50Z
31,476,788
9
2015-07-17T13:19:36Z
[ "python", "string", "substring", "contains" ]
I'm looking for a `string.contains` or `string.indexof` method in Python. I want to do: ``` if not somestring.contains("blah"): continue ```
So apparently there is nothing similar for vector-wise comparison. An obvious Python way to do so would be: ``` names = ['bob', 'john', 'mike'] any(st in 'bob and john' for st in names) >> True any(st in 'mary and jane' for st in names) >> False ```
Finding the correlation matrix
3,437,513
11
2010-08-09T05:23:01Z
3,442,703
9
2010-08-09T17:51:33Z
[ "python", "algorithm", "scipy" ]
I have a matrix which is fairly large (around 50K rows), and I want to print the correlation coefficient between each row in the matrix. I have written Python code like this: ``` for i in xrange(rows): # rows are the number of rows in the matrix. for j in xrange(i, rows): r = scipy.stats.pearsonr(data[i,:...
**New Solution** After looking at Joe Kington's answer, I decided to look into the `corrcoef()` code and was inspired by it to do the following implementation. ``` ms = data.mean(axis=1)[(slice(None,None,None),None)] datam = data - ms datass = np.sqrt(scipy.stats.ss(datam,axis=1)) for i in xrange(rows): temp = np...
Python nested dictionary lookup with default values
3,437,708
5
2010-08-09T06:14:58Z
3,437,737
12
2010-08-09T06:19:10Z
[ "python", "dictionary", "default-value", "lookup" ]
``` >>> d2 {'egg': 3, 'ham': {'grill': 4, 'fry': 6, 'bake': 5}, 'spam': 2} >>> d2.get('spamx',99) 99 >>> d2.get('ham')['fry'] 6 ``` I want to get value of fry inside of ham, if not, get value, 99 or 88 as the 2nd example. But how?
``` d2.get('ham', {}).get('fry', 88) ``` I would probably break it down into several statements in real life. ``` ham = d2.get('ham', {}) fry = ham.get('fry', 88) ```
Django model inheritance and type check
3,438,003
5
2010-08-09T07:16:09Z
3,438,048
10
2010-08-09T07:22:04Z
[ "python", "django" ]
``` class Machine(models.Model): name= models.CharField( max_length=120) class Meta: abstract = True class Car(Machine): speed = models.IntegerField() class Computer(Machine) ram = models.IntegerField() ``` My question is, how can I understand what type is the Machine model. For instamce I kn...
I am not sure if I understand your question correctly. ***If*** you are trying to find out the type of a given instance you can use the built-in `type` function. ``` an_object = Car(name = "foo", speed = 80) an_object.save() type(an_object) # <class 'project.app.models.Car'> ``` Or if you wish to check if `an_object`...
How to create the union of many sets using a generator expression?
3,438,140
18
2010-08-09T07:38:39Z
3,438,218
37
2010-08-09T07:50:51Z
[ "python", "set", "generator" ]
Suppose I have a list of sets and I want to get the union over all sets in that list. Is there any way to do this using a generator expression? In other words, how can I create the union over all sets in that list *directly* as a `frozenset`?
Just use [the `.union()` method](http://docs.python.org/library/stdtypes.html#set.union). ``` >>> l = [set([1,2,3]), set([4,5,6]), set([1,4,9])] >>> frozenset().union(*l) frozenset([1, 2, 3, 4, 5, 6, 9]) ``` This works for any iterable of iterables.
Creating a TreeMap visualization
3,438,252
4
2010-08-09T07:58:38Z
3,438,280
10
2010-08-09T08:05:41Z
[ "java", "python", "visualization" ]
I want the algorithm for creating a Treemap visualization. Something like this: [An Easy Way to Make a Treemap](http://flowingdata.com/2010/02/11/an-easy-way-to-make-a-treemap/) Problem is that I do not want to use R ... and I want the source-code. Preferably in Python or Java. Thing is that I have to customize it ....
The [TreeMap Java Library](http://sourceforge.net/projects/treemap/) on SourceForge.net is an open source implementation of the algorithm described in [Ben Schneiderman's paper](http://www.cs.umd.edu/local-cgi-bin/hcil/rr.pl?number=91-06). There is also a reference implementation linked to from Schneiderman's [Treemap...
IPython workflow (edit, run)
3,438,531
47
2010-08-09T08:50:29Z
3,531,548
46
2010-08-20T13:59:10Z
[ "python", "user-interface", "ipython", "python-idle" ]
Is there a GUI for IPython that allows me to open/run/edit Python files? My way of working in IDLE is to have two windows open: the shell and a .py file. I edit the .py file, run it, and interact with the results in the shell. Is it possible to use IPython like this? Or is there an alternative way of working?
When I'm working with python, I usually have two terminal windows open - one with IPython, and the other with a fairly customized Vim. Two good resources: * <http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/> * <http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/> --- Though it sounds ...
IPython workflow (edit, run)
3,438,531
47
2010-08-09T08:50:29Z
3,939,065
17
2010-10-15T02:29:50Z
[ "python", "user-interface", "ipython", "python-idle" ]
Is there a GUI for IPython that allows me to open/run/edit Python files? My way of working in IDLE is to have two windows open: the shell and a .py file. I edit the .py file, run it, and interact with the results in the shell. Is it possible to use IPython like this? Or is there an alternative way of working?
[Spyder](http://code.google.com/p/spyderlib/), previously known as SPyderlib / Spyder2 Pretty lightweight, fast and support almost all [features](https://code.google.com/p/spyderlib/wiki/Features) you will ever need to work with a python project. It can edit and run .py files in an embedded IPython instance and then i...
when i easy_install greenlet i got "error: Setup script exited with error: command 'gcc' failed with exit status 1 "
3,438,624
2
2010-08-09T09:06:56Z
3,439,163
8
2010-08-09T10:34:25Z
[ "python", "linux", "ubuntu", "easy-install" ]
when i easy\_install greenlet(also eventlet) as the documents says in ubuntu 10.04 i got the error above. is there anyone know why? Expect your help! And I have install build-essential As I canot take the format right here, so I paste the message printed out there <http://sugelawa.appspot.com/?p=35001> Thank u very ...
(*Warning: Ubuntu specific answer. Somewhat applicable to Debian, to but I don't have the details in my head right now*) To use `easy_install` to install modules that contain C extensions (like `greenlet`), you need a complete development stack installed on your system. For a basic install, the means `build-essential` ...
Common use-cases for pickle in Python
3,438,675
78
2010-08-09T09:15:46Z
3,438,697
9
2010-08-09T09:20:17Z
[ "python", "serialization", "pickle", "use-case" ]
I've looked at the [pickle](http://en.wikipedia.org/wiki/Pickle_%28Python%29) documentation, but I don't understand where pickle is useful. What are some common use-cases for pickle?
Minimal roundtrip example.. ``` >>> import pickle >>> a = Anon() >>> a.foo = 'bar' >>> pickled = pickle.dumps(a) >>> unpickled = pickle.loads(pickled) >>> unpickled.foo 'bar' ``` **Edit:** but as for the question of real-world examples of pickling, perhaps *the* most advanced use of pickling (you'd have to dig quite ...
Common use-cases for pickle in Python
3,438,675
78
2010-08-09T09:15:46Z
3,439,921
38
2010-08-09T12:21:53Z
[ "python", "serialization", "pickle", "use-case" ]
I've looked at the [pickle](http://en.wikipedia.org/wiki/Pickle_%28Python%29) documentation, but I don't understand where pickle is useful. What are some common use-cases for pickle?
Some uses that I have come across: 1) saving a program's state data to disk so that it can carry on where it left off when restarted (persistence) 2) sending python data over a TCP connection in a multi-core or distributed system (marshalling) 3) storing python objects in a database 4) converting an arbitrary pytho...
Some built-in to pad a list in python
3,438,756
29
2010-08-09T09:30:23Z
3,438,818
46
2010-08-09T09:43:12Z
[ "python", "list", "list-manipulation" ]
I have a list of size < *N* and I want to pad it up to the size N with a value. Certainly, I can use something like the following, but I feel that there should be something I missed: ``` >>> N = 5 >>> a = [1] >>> map(lambda x, y: y if x is None else x, a, ['']*N) [1, '', '', '', ''] ```
``` a += [''] * (N - len(a)) ``` or if you don't want to change `a` in place ``` new_a = a + [''] * (N - len(a)) ``` you can always create a subclass of list and call the method whatever you please ``` class MyList(list): def ljust(self, n, fillvalue=''): return self + [fillvalue] * (n - len(self)) a =...
Some built-in to pad a list in python
3,438,756
29
2010-08-09T09:30:23Z
3,438,986
11
2010-08-09T10:09:24Z
[ "python", "list", "list-manipulation" ]
I have a list of size < *N* and I want to pad it up to the size N with a value. Certainly, I can use something like the following, but I feel that there should be something I missed: ``` >>> N = 5 >>> a = [1] >>> map(lambda x, y: y if x is None else x, a, ['']*N) [1, '', '', '', ''] ```
There is no built-in function for this. But you could compose the built-ins for your task (or anything :p). (Modified from itertool's `padnone` and `take` recipes) ``` from itertools import chain, repeat, islice def pad_infinite(iterable, padding=None): return chain(iterable, repeat(padding)) def pad(iterable, s...
Setting spines in matplotlibrc
3,439,344
4
2010-08-09T11:00:15Z
3,509,553
15
2010-08-18T06:42:26Z
[ "python", "matplotlib" ]
For a strange reason I cannot find the way to specify spines configuration in Python's matplotlibrc file. Any idea on how to cause matplotlib not to draw upper and right spines by default? ![spines](http://matplotlib.sourceforge.net/_images/whats_new_99_spines.png) More about info about spines in matplotlib is [here](...
In order to hide the right and top spines of a subplot, you need to both set the colour of the relevant spines to `'none'`, as well as set the tick position to `'left'` for the xtick, and `'bottom'` for the ytick (in order to hide the tick marks as well as the spines). Unfortunately, none of these are currently access...
Setting spines in matplotlibrc
3,439,344
4
2010-08-09T11:00:15Z
36,135,945
7
2016-03-21T16:00:20Z
[ "python", "matplotlib" ]
For a strange reason I cannot find the way to specify spines configuration in Python's matplotlibrc file. Any idea on how to cause matplotlib not to draw upper and right spines by default? ![spines](http://matplotlib.sourceforge.net/_images/whats_new_99_spines.png) More about info about spines in matplotlib is [here](...
To make matplotlib not to draw upper and right spines, one can set the following in matplotlibrc file ``` axes.spines.right : False axes.spines.top : False ```
matplotlib: add circle to plot
3,439,639
20
2010-08-09T11:44:38Z
3,439,953
34
2010-08-09T12:27:13Z
[ "python", "matplotlib" ]
How do I add a small filled circle or point to a countour plot in matplotlib?
Here is an example, using [pylab.Circle](http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.patches.Circle): ``` import numpy as np import matplotlib.pyplot as plt e = np.e X, Y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100)) F = X ** Y G = Y ** X fig = plt.figure() ax = fig.add_subplot(1...
How to strip source from distutils binary distributions?
3,440,016
7
2010-08-09T12:35:38Z
3,444,346
9
2010-08-09T21:25:54Z
[ "python", "bytecode", "distutils" ]
I want to create a bytecode-only distribution from distutils (no really, I do; I know what I'm doing). Using setuptools and the bdist\_egg command, you can simply provide the --exclude-source parameter. Unfortunately the standard commands don't have such an option. * Is there an easy way to strip the source files just...
The distutils "build\_py" command is the one that matters, as it's (indirectly) reused by all the commands that create distributions. If you override the byte\_compile(files) method, something like: ``` try: from setuptools.command.build_py import build_py except ImportError: from distutils.command.build_py im...
How to use itertools.groupby when the key value is in the elements of the iterable?
3,440,549
6
2010-08-09T13:38:07Z
3,440,570
9
2010-08-09T13:42:26Z
[ "python", "group-by", "itertools" ]
To illustrate, I start with a list of 2-tuples: ``` import itertools import operator raw = [(1, "one"), (2, "two"), (1, "one"), (3, "three"), (2, "two")] for key, grp in itertools.groupby(raw, key=lambda item: item[0]): print key, list(grp).pop()[1] ``` yields: ``` 1 one 2 two 1 one...
`groupby` clusters *consecutive* elements of the iterable which have the same key. To produce the output you desire, you must first sort `raw`. ``` for key, grp in itertools.groupby(sorted(raw), key=operator.itemgetter(0)): print key, map(operator.itemgetter(1), grp) # 1 ['one', 'one'] # 2 ['two', 'two'] # 3 ['th...
How to check type of variable? Python
3,440,969
5
2010-08-09T14:25:22Z
3,441,004
13
2010-08-09T14:28:24Z
[ "python", "variables" ]
I need to do one thing if `args` is integer and ather thing if `args` is string. How can i chack type? Example: ``` def handle(self, *args, **options): if not args: do_something() elif args is integer: do_some_ather_thing: elif args is string: do_totally_diff...
First of, `*args` is always a list. You want to check if its content are strings? ``` import types def handle(self, *args, **options): if not args: do_something() # check if everything in args is a Int elif all( isinstance(s, types.IntType) for s in args): do_some_ather_thing() # as befor...
Python: most pythonic way to check if an object is a number
3,441,358
60
2010-08-09T15:04:26Z
3,441,388
15
2010-08-09T15:08:26Z
[ "python", "types", "numbers" ]
Given an arbitrary python object, what's the best way to determine whether it is a number? Here `is` is defined as `acts like a number in certain circumstances`. For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole ve...
This is a good example where exceptions really shine. Just do what you would do with the numeric types and catch the `TypeError` from everything else. But obviously, this only checks if a operation *works*, not whether it *makes sense*! The only real solution for that is to never mix types and always know exactly what...
Python: most pythonic way to check if an object is a number
3,441,358
60
2010-08-09T15:04:26Z
3,441,533
24
2010-08-09T15:22:54Z
[ "python", "types", "numbers" ]
Given an arbitrary python object, what's the best way to determine whether it is a number? Here `is` is defined as `acts like a number in certain circumstances`. For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole ve...
You want to check if some object > acts like a number in certain > circumstances If you're using Python 2.5 or older, the only real way is to check some of those "certain circumstances" and see. In 2.6 or better, you can use `isinstance` with [numbers.Number](http://docs.python.org/library/numbers.html#numbers.Numbe...
Python: most pythonic way to check if an object is a number
3,441,358
60
2010-08-09T15:04:26Z
3,441,601
73
2010-08-09T15:31:12Z
[ "python", "types", "numbers" ]
Given an arbitrary python object, what's the best way to determine whether it is a number? Here `is` is defined as `acts like a number in certain circumstances`. For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole ve...
Use `Number` from the `numbers` module to test `isinstance(n, Number)` (available since 2.6). ``` >>> from numbers import Number ... from decimal import Decimal ... from fractions import Fraction ... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']: ... print '%15s %s' % (n.__repr__(), isinstanc...
The "next" parameter, redirect, django.contrib.auth.login
3,441,436
19
2010-08-09T15:12:29Z
3,442,258
17
2010-08-09T16:50:57Z
[ "python", "django", "django-forms" ]
I'm trying to redirect users to custom url "/gallery/(username)/" after successfully logging in. It currently redirects to the default "/account/profile/" While I know what I can override the redirect url in my settings.py, my url is dynamic thus it will not work. Documentation states that I need to use the "next" par...
I confess I usually use 2 redirects in order to get something like this to work. First, Make your own `registration/login.html` page. You can copy-and-paste the html example in this section of the [authentication docs](http://docs.djangoproject.com/en/1.2/topics/auth/#django.contrib.auth.views.login) to make the proce...
The "next" parameter, redirect, django.contrib.auth.login
3,441,436
19
2010-08-09T15:12:29Z
5,787,355
32
2011-04-26T07:39:00Z
[ "python", "django", "django-forms" ]
I'm trying to redirect users to custom url "/gallery/(username)/" after successfully logging in. It currently redirects to the default "/account/profile/" While I know what I can override the redirect url in my settings.py, my url is dynamic thus it will not work. Documentation states that I need to use the "next" par...
Django's login view `django.contrib.auth.views.login` accepts a dictionary named `extra_context`. The values in the dictionary are directly passed to the template. So you can use that to set the `next` parameter. Once that is done, you can set a hidden field with name `next` and value `{{ next }}` so that it gets rende...
Calling a Python module from Perl
3,441,766
7
2010-08-09T15:50:36Z
3,441,799
18
2010-08-09T15:53:41Z
[ "python", "perl", "interop" ]
I created a module in Python which provides about a dozen functionalities. While it will be mostly used from within Python, there is a good fraction of legacy users which will be calling it from Perl. What is the best way to make a plug in to this module? My thoughts are: 1. Provide the functionalities as command lin...
One other choice is to inline Python directly in your Perl script, using [`Inline::Python`](http://metacpan.org/pod/Inline%3a%3aPython). This may be simpler than other solutions, and only requires one additional module.
Calling a Python module from Perl
3,441,766
7
2010-08-09T15:50:36Z
3,446,205
9
2010-08-10T05:10:04Z
[ "python", "perl", "interop" ]
I created a module in Python which provides about a dozen functionalities. While it will be mostly used from within Python, there is a good fraction of legacy users which will be calling it from Perl. What is the best way to make a plug in to this module? My thoughts are: 1. Provide the functionalities as command lin...
In the short run the easiest solution is to use Inline::Python. Closely followed by calling a command-line script. In the long run, using a server to provide RPC functionality or simply calling a command-line script will give you the most future proof solution. Why? Becuase that way you aren't tied to Perl or Python...
Sqlite. How to get value of Auto Increment Primary Key after Insert, other than last_insert_rowid()?
3,442,033
18
2010-08-09T16:18:24Z
3,442,077
25
2010-08-09T16:26:42Z
[ "python", "sqlite", "flask" ]
I am using Sqlite3 with Flask microframework, but this question concerns only the Sqlite side of things.. Here is a snippet of the code: ``` g.db.execute('INSERT INTO downloads (name, owner, mimetype) VALUES (?, ?, ?)', [name, owner, mimetype]) file_entry = query_db('SELECT last_insert_rowid()') g.db.commit() ``` Th...
The way you're doing it is valid. There won't be a problem if the above snipped is executed concurrently by two scripts. `last_insert_rowid()` returns the rowid of the latest INSERT statement for the connection that calls it. You can also get the rowid by doing `g.db.lastrowid`.
How do I step through/debug a python web application?
3,442,920
5
2010-08-09T18:21:18Z
3,443,018
8
2010-08-09T18:32:21Z
[ "python", "debugging", "step-into" ]
I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request. is this just not possible? if no, why not?
If you put ``` import pdb pdb.set_trace() ``` in your code, the web app will drop to a pdb debugger session upon executing `set_trace`. Also useful, is ``` import code code.interact(local=locals()) ``` which drops you to the python interpreter. Pressing Ctrl-d resumes execution. Still more useful, is ``` import ...
Why does python use two underscores for certain things?
3,443,043
46
2010-08-09T18:34:45Z
3,443,090
15
2010-08-09T18:40:46Z
[ "python", "double-underscore" ]
I'm fairly new to actual programming languages, and Python is my first one. I know my way around Linux a bit, enough to get a summer job with it (I'm still in high school), and on the job, I have a lot of free time which I'm using to learn Python. One thing's been getting me though. What exactly is different in Python...
When you start a method with two underscores (and no trailing underscores), Python's [name mangling](http://docs.python.org/reference/expressions.html#atom-identifiers) rules are applied. This is a way to loosely simulate the `private` keyword from other OO languages such as C++ and Java. (Even so, the method is still ...
Why does python use two underscores for certain things?
3,443,043
46
2010-08-09T18:34:45Z
3,443,428
24
2010-08-09T19:20:09Z
[ "python", "double-underscore" ]
I'm fairly new to actual programming languages, and Python is my first one. I know my way around Linux a bit, enough to get a summer job with it (I'm still in high school), and on the job, I have a lot of free time which I'm using to learn Python. One thing's been getting me though. What exactly is different in Python...
Here is the creator of Python [explaining it](http://python-history.blogspot.com/2009/02/adding-support-for-user-defined-classes.html): > ... rather than devising a new syntax for > special kinds of class methods (such > as initializers and destructors), I > decided that these features could be > handled by simply req...
How can I tell where my python script is hanging?
3,443,607
18
2010-08-09T19:46:47Z
3,443,779
46
2010-08-09T20:11:14Z
[ "python", "debugging" ]
So I'm debugging my python program and have encountered a bug that makes the program hang, as if in an infinite loop. Now, I had a problem with an infinite loop before, but when it hung up I could kill the program and python spat out a helpful exception that told me where the program terminated when I sent it the kill ...
Let's assume that you are running your program as: ``` python YOURSCRIPT.py ``` Try running your program as: ``` python -m trace --trace YOURSCRIPT.py ``` And have some patience while lots of stuff is printed on the screen. If you have an infinite loop, it will go on for-ever (halting problem). If it gets stuck som...
How can I tell where my python script is hanging?
3,443,607
18
2010-08-09T19:46:47Z
3,443,835
23
2010-08-09T20:19:30Z
[ "python", "debugging" ]
So I'm debugging my python program and have encountered a bug that makes the program hang, as if in an infinite loop. Now, I had a problem with an infinite loop before, but when it hung up I could kill the program and python spat out a helpful exception that told me where the program terminated when I sent it the kill ...
Wow! 5 answers already and nobody has suggested the most obvious and simple: 1. Try to find a reproducible test case that causes the hanging behavior. 2. Add logging to your code. This can be as basic as `print "**010"`, `print "**020"`, etc. peppered through major areas. 3. Run code. See where it hangs. Can't underst...
How can I tell where my python script is hanging?
3,443,607
18
2010-08-09T19:46:47Z
3,444,094
7
2010-08-09T20:53:28Z
[ "python", "debugging" ]
So I'm debugging my python program and have encountered a bug that makes the program hang, as if in an infinite loop. Now, I had a problem with an infinite loop before, but when it hung up I could kill the program and python spat out a helpful exception that told me where the program terminated when I sent it the kill ...
If your program is too big and complex to be viable for single stepping with pdb or printing every line with the trace module then you could try a trick from my days of 8-bit games programming. From Python 2.5 onwards pdb has the ability to associate code with a breakpoint by using the `commands` command. You can use t...
Python and ElementTree: return "inner XML" excluding parent element
3,443,831
9
2010-08-09T20:18:41Z
3,446,055
7
2010-08-10T04:34:30Z
[ "python", "xml", "elementtree" ]
In Python 2.6 using ElementTree, what's a good way to fetch the XML (as a string) inside a particular element, like what you can do in HTML and javascript with [`innerHTML`](https://developer.mozilla.org/en/dom%3aelement.innerhtml)? Here's a simplified sample of the XML node I am starting with: ``` <label attr="foo" ...
How about: ``` from xml.etree import ElementTree as ET xml = '<root>start here<child1>some text<sub1/>here</child1>and<child2>here as well<sub2/><sub3/></child2>end here</root>' root = ET.fromstring(xml) def content(tag): return tag.text + ''.join(ET.tostring(e) for e in tag) print content(root) print content(r...
ConfigObj/ConfigParser vs. using YAML for Python settings file
3,444,436
15
2010-08-09T21:41:46Z
3,463,851
7
2010-08-12T00:19:56Z
[ "python", "settings", "configuration-files", "yaml", "configparser" ]
Which is better for creating a settings file for Python programs, the built-in module (ConfigParser) or the independent project (ConfigObj), or using the YAML data serialization format? I have heard that ConfigObj is easier to use than ConfigParser, even though it is not a built-in library. I have also read that PyYAML...
Using ConfigObj is at least very straightforward and ini files in *general* are much simpler (and more widely used) than YAML. For more complex cases, including validation, default values and types, ConfigObj provides a way to do this through configspec validation. Simple code to read an ini file with ConfigObj: ``` ...
Merge PDF files
3,444,645
30
2010-08-09T22:23:10Z
3,444,735
45
2010-08-09T22:40:53Z
[ "python", "pdf", "file-io" ]
I did a search and nothing really seemed to be directly related to this question. Is it possible, using Python, to merge seperate PDF files? Assuming so, I need to extend this a little further. I am hoping to loop through folders in a directory and repeat this procedure. And I may be pushing my luck, but is it possib...
Use [Pypdf](http://pypi.python.org/pypi/pyPdf): > A Pure-Python library built as a PDF toolkit. It is capable of: > \* splitting documents page by page, > \* merging documents page by page, (and much more) An example of two pdf-files being merged into a single file with pyPdf: ``` # Loading the pyPdf Library fr...
Merge PDF files
3,444,645
30
2010-08-09T22:23:10Z
37,945,454
9
2016-06-21T13:12:13Z
[ "python", "pdf", "file-io" ]
I did a search and nothing really seemed to be directly related to this question. Is it possible, using Python, to merge seperate PDF files? Assuming so, I need to extend this a little further. I am hoping to loop through folders in a directory and repeat this procedure. And I may be pushing my luck, but is it possib...
I did it like this using [PyPdf2](https://github.com/mstamy2/PyPDF2) ``` from PyPDF2 import PdfFileMerger pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf'] merger = PdfFileMerger() for pdf in pdfs: merger.append(open(pdf, 'rb')) with open('result.pdf', 'wb') as fout: merger.write(fout) ``` The `...
python unittest methods
3,444,827
6
2010-08-09T22:59:36Z
3,445,054
8
2010-08-09T23:56:15Z
[ "python", "unit-testing" ]
Can I call a test method from within the test class in python? For example: ``` class Test(unittest.TestCase): def setUp(self): #do stuff def test1(self): self.test2() def test2(self): #do stuff ``` update: I forgot the other half of my question. Will setup or teardown be called ...
This is pretty much a **Do Not Do That**. If you want tests run in a specific order define a `runTest` method and do not name your methods `test...`. ``` class Test_Some_Condition( unittest.TestCase ): def setUp( self ): ... def runTest( self ): step1() step2() step3() def tearDown( self ): ... ```...
How should I embed Python in a C++ Builder / Delphi 2010 application?
3,446,799
7
2010-08-10T07:13:45Z
3,447,677
8
2010-08-10T09:42:17Z
[ "python", "delphi", "embed", "c++builder", "c++builder-2010" ]
I'm interested in experimenting with embedding Python in my application, to let the user run Python scripts within the application environment, accessing internal (C++-implemented) objects, etc. I'm quite new to this so don't know exactly what I'm doing. I have read [Embedding Python in Another Application](http://doc...
You should not be afraid of the P4D project at google groups. It seems inactive because, in part, it is very stable and full-featured already. Those components are used in the much more active [PyScripter](http://code.google.com/p/pyscripter/) application which is one of the best python development editors currently av...
Processing data by reference or by value in python
3,447,435
8
2010-08-10T09:07:49Z
3,447,509
15
2010-08-10T09:18:23Z
[ "python", "syntax", "numpy", "syntactic-sugar" ]
Consider the following session. How are the differences explained? I thought that `a += b` is a syntactical sugar of (and thus equivalent to) `a = a + b`. Obviously I'm wrong. ``` >>> import numpy as np >>> a = np.arange(24.).reshape(4,6) >>> print a [[ 0. 1. 2. 3. 4. 5.] [ 6. 7. 8. 9. 10. 11.] ...
Using the `+` operator results in a call to the special method [`__add__`](http://docs.python.org/reference/datamodel.html#object.__add__) which should create a new object and should not modify the original. On the other hand, using the `+=` operator results in a call to [`__iadd__`](http://docs.python.org/reference/d...
Processing data by reference or by value in python
3,447,435
8
2010-08-10T09:07:49Z
3,448,147
7
2010-08-10T10:50:11Z
[ "python", "syntax", "numpy", "syntactic-sugar" ]
Consider the following session. How are the differences explained? I thought that `a += b` is a syntactical sugar of (and thus equivalent to) `a = a + b`. Obviously I'm wrong. ``` >>> import numpy as np >>> a = np.arange(24.).reshape(4,6) >>> print a [[ 0. 1. 2. 3. 4. 5.] [ 6. 7. 8. 9. 10. 11.] ...
You're not wrong, sometimes `a += b` really is syntactic sugar for `a = a + b`, but then sometimes it's not, which is one of the more confusing features of Python - see [this similar question](http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python/2347423#2347423) for more discussion. The `+` op...
Sharing data between processes in Python
3,447,846
6
2010-08-10T10:07:31Z
3,447,907
8
2010-08-10T10:16:46Z
[ "python", "multiprocessing", "lazy-evaluation", "sharing" ]
I have a complex data structure (user-defined type) on which a large number of independent calculations are performed. The data structure is basically immutable. I say basically, because though the interface looks immutable, internally some lazy-evaluation is going on. Some of the lazily calculated attributes are store...
> How do I best share the data-structure between processes? Pipelines. ``` origin.py | process1.py | process2.py | process3.py ``` Break your program up so that each calculation is a separate process of the following form. ``` def transform1( piece ): Some transformation or calculation. ``` For testing, you ca...
Flask / Python. Get mimetype from uploaded file
3,447,883
7
2010-08-10T10:14:01Z
3,448,071
16
2010-08-10T10:41:02Z
[ "python", "webforms", "flask" ]
I am using Flask micro-framework 0.6 and Python 2.6 I need to get the mimetype from an uploaded file so I can store it. Here is the relevent Python/Flask code: ``` @app.route('/upload_file', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] mime...
From the docs: <http://werkzeug.pocoo.org/documentation/dev/datastructures.html#werkzeug.FileStorage> ``` @app.route('/upload_file', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files.get('file') if file: mimetype = file.content_type ...
Function returning a tuple or None: how to call that function nicely?
3,448,701
11
2010-08-10T12:06:11Z
3,448,730
8
2010-08-10T12:09:51Z
[ "python", "return", "tuples" ]
Suppose the following: ``` def MyFunc(a): if a < 0: return None return (a+1, a+2, a+3) v1, v2, v3 = MyFunc() # Bad ofcourse, if the result was None ``` What is the best way to define a function that returns a tuple and yet can be nicely called. Currently, I could do this: ``` r = MyFunc() if r: v1, v2, v3...
This should work nicely: ``` v1, v2, v3 = MyFunc() or (None, None, None) ``` When `MyFunc()` returns a tuple, it will be unpacked, otherwise it will be substituted for a 3-tuple of `None`.
Function returning a tuple or None: how to call that function nicely?
3,448,701
11
2010-08-10T12:06:11Z
3,448,733
13
2010-08-10T12:10:07Z
[ "python", "return", "tuples" ]
Suppose the following: ``` def MyFunc(a): if a < 0: return None return (a+1, a+2, a+3) v1, v2, v3 = MyFunc() # Bad ofcourse, if the result was None ``` What is the best way to define a function that returns a tuple and yet can be nicely called. Currently, I could do this: ``` r = MyFunc() if r: v1, v2, v3...
How about raise an `ArgumentError`? Then you could `try` calling it, and deal with the exception if the argument is wrong. So, something like: ``` try: v1, v2, v3 = MyFunc() except ArgumentError: #deal with it ``` Also, see [katrielalex's answer](http://stackoverflow.com/questions/3448701/function-returning-...
Function returning a tuple or None: how to call that function nicely?
3,448,701
11
2010-08-10T12:06:11Z
3,448,747
8
2010-08-10T12:11:46Z
[ "python", "return", "tuples" ]
Suppose the following: ``` def MyFunc(a): if a < 0: return None return (a+1, a+2, a+3) v1, v2, v3 = MyFunc() # Bad ofcourse, if the result was None ``` What is the best way to define a function that returns a tuple and yet can be nicely called. Currently, I could do this: ``` r = MyFunc() if r: v1, v2, v3...
`recursive` has a truly elegant and Pythonic solution. BUT: why do you want to return `None`? Python has a way of handling errors, and that is by raising an exception: ``` class AIsTooSmallError( ArgumentError ): pass ``` and then ``` raise AIsTooSmallError( "a must be positive." ) ``` The reason this is better is ...
Is monkeypatching stdlib methods a good practice in Python?
3,450,332
2
2010-08-10T14:58:44Z
3,450,390
7
2010-08-10T15:05:41Z
[ "python", "wrapping", "monkeypatching" ]
Over time I found the need to override several `stdlib` methods from Python in order to overcome limitation or to add some missing functionality. In all cases I added a wrapper function and replaced the original method from the module with my wrapper (the wrapper was calling the original method). Why I did this? Just...
None of these things seem to **require** monkeypatching. All of them seem to have better, more robust and reliable solutions. Adding a logging handler is easy. No monkeypatch. Fixing open is done this way. ``` from io import open ``` That was easy. No patch. Logging to `os.system()`? I'd think that a simple "wrapp...
How to get something random in datastore (AppEngine)?
3,450,926
15
2010-08-10T15:59:23Z
3,451,052
17
2010-08-10T16:12:10Z
[ "python", "google-app-engine" ]
Currently i'm using something like this: ``` images = Image.all() count = images.count() random_numb = random.randrange(1, count) image = Image.get_by_id(random_numb) ``` But it turns out that the ids in the datastore on AppEngine don't start from 1. I have two images in datastore and their ids are 60...
The datastore is distributed, so IDs are non-sequential: two datastore nodes need to be able to generate an ID at the same time without causing a conflict. To get a random entity, you can attach a random float between 0 and 1 to each entity on create. Then to query, do something like this: ``` rand_num = random.rando...
How to get something random in datastore (AppEngine)?
3,450,926
15
2010-08-10T15:59:23Z
6,098,002
10
2011-05-23T13:38:36Z
[ "python", "google-app-engine" ]
Currently i'm using something like this: ``` images = Image.all() count = images.count() random_numb = random.randrange(1, count) image = Image.get_by_id(random_numb) ``` But it turns out that the ids in the datastore on AppEngine don't start from 1. I have two images in datastore and their ids are 60...
Another solution (if you don't want to add an additional property). Keep a set of keys in memory. ``` import random # Get all the keys, not the Entities q = ItemUser.all(keys_only=True).filter('is_active =', True) item_keys = q.fetch(2000) # Get a random set of those keys, in this case 20 random_keys = random.samp...
Unzipping files in python
3,451,111
27
2010-08-10T16:19:32Z
3,451,150
55
2010-08-10T16:23:27Z
[ "python", "zip", "unzip", "zipfile" ]
I read through the zipfile modules docs, but couldn't understand how to *unzip* a file, only how to zip a file. How do I unzip all the contents of a zip file into the same directory?
``` import zipfile zip_ref = zipfile.ZipFile(path_to_zip_file, 'r') zip_ref.extractall(directory_to_extract_to) zip_ref.close() ``` That's pretty much it!
Unzipping files in python
3,451,111
27
2010-08-10T16:19:32Z
36,662,770
13
2016-04-16T10:11:09Z
[ "python", "zip", "unzip", "zipfile" ]
I read through the zipfile modules docs, but couldn't understand how to *unzip* a file, only how to zip a file. How do I unzip all the contents of a zip file into the same directory?
If you are using Python 3.2 or later: ``` with zipfile.ZipFile("file.zip","r") as zip_ref: zip_ref.extractall("targetdir") ``` You dont need to use the close or try/catch with this as it uses the [context manager](http://eigenhombre.com/2013/04/20/introduction-to-context-managers/) construction
Python list / sublist selection -1 weirdness
3,451,157
7
2010-08-10T16:23:59Z
3,451,199
34
2010-08-10T16:28:25Z
[ "python", "list", "sublist" ]
So I've been playing around with python and noticed something that seems a bit odd. The semantics of `-1` in selecting from a list don't seem to be consistent. So I have a list of numbers ``` ls = range(1000) ``` The last element of the list if of course `ls[-1]` but if I take a sublist of that so that I get everyth...
In `list[first:last]`, `last` is not included. The 10th element is `ls[9]`, in `ls[0:10]` there isn't `ls[10]`.
how to dynamically create an instance of a class in python?
3,451,779
12
2010-08-10T17:37:54Z
3,451,832
10
2010-08-10T17:44:22Z
[ "python" ]
I have list of class names and want to create their instances dynamically. for example: ``` names=[ 'foo.baa.a', 'foo.daa.c', 'foo.AA', .... ] def save(cName, argument): aa = create_instance(cName) # how to do it? aa.save(argument) save(random_from(names), arg) ``` How to dynamically create that instances in Pyt...
This is often referred to as reflection or sometimes introspection. Check out a similar questions that have an answer for what you are trying to do: [Does Python Have An Equivalent to Java Class forname](http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname) [Can You Use a Str...
how to dynamically create an instance of a class in python?
3,451,779
12
2010-08-10T17:37:54Z
22,959,003
8
2014-04-09T09:57:11Z
[ "python" ]
I have list of class names and want to create their instances dynamically. for example: ``` names=[ 'foo.baa.a', 'foo.daa.c', 'foo.AA', .... ] def save(cName, argument): aa = create_instance(cName) # how to do it? aa.save(argument) save(random_from(names), arg) ``` How to dynamically create that instances in Pyt...
Assuming you have already imported the relevant classes using something like ``` from [app].models import * ``` all you will need to do is ``` klass = globals()["class_name"] instance = klass() ```
Python ftplib timing out
3,451,817
7
2010-08-10T17:43:09Z
3,452,152
7
2010-08-10T18:27:03Z
[ "python", "ftplib" ]
I'm trying to use ftplib to get a file listing and download any new files since my last check. The code I'm trying to run so far is: ``` #!/usr/bin/env python from ftplib import FTP import sys host = 'ftp.***.com' user = '***' passwd = '***' try: ftp = FTP(host) ftp.login(user, passwd) except: print 'Err...
Most likely a conflict between Active and Passive mode. Make sure that one of the following is true: 1. The server supports PASV mode and your client is setting PASV mode 2. If the server does not support passive mode, then your firewall must support active mode FTP transfers. EDIT: I looked at the docs, and found th...
Python ftplib timing out
3,451,817
7
2010-08-10T17:43:09Z
9,817,963
8
2012-03-22T07:19:39Z
[ "python", "ftplib" ]
I'm trying to use ftplib to get a file listing and download any new files since my last check. The code I'm trying to run so far is: ``` #!/usr/bin/env python from ftplib import FTP import sys host = 'ftp.***.com' user = '***' passwd = '***' try: ftp = FTP(host) ftp.login(user, passwd) except: print 'Err...
If Passive Mode is failing for some reason try: ``` ftp.set_pasv(False) ``` to use Active Mode.
twisted: Failure vs. Error
3,452,022
3
2010-08-10T18:09:40Z
3,452,525
7
2010-08-10T19:09:51Z
[ "python", "exception", "exception-handling", "twisted" ]
When should I use a `twisted.python.failure.Failure`, and when should I use something like `twisted.internet.error.ConnectionDone`? Or should I do `twisted.python.failure.Failure(twisted.internet.error.ConnectionDone)`, and if so, in what casese should I do that?
A `Failure` represents an exception and a traceback (often different from the current stack trace). You should use `Failure` when you are constructing an asynchronous exception. So, when you're going to fire a `Deferred` with an error, or when you're going to call a method like `IProtocol.connectionLost` or `ClientFact...
What's the difference of ContentType and MimeType
3,452,381
62
2010-08-10T18:54:58Z
3,452,833
36
2010-08-10T19:50:08Z
[ "python", "django", "content-type", "mime-types" ]
As far as I know, they are absolute equal. However, browsing some django docs, I've found this piece of code: `HttpResponse.__init__(content='', mimetype=None, status=200, content_type='text/html')` which surprise me the two getting along each other. The official docs was able to solve the issue in a pratical manner:...
> Why we use 2 different naming for > (almost the same) thing? Is > "Content-Type" just a name used in > browser requests, and with very little > use outside it? > > What's the main difference between the > each one, and when is right to call > something mimetype as opposed to > content-type ? Am i being pitty and > gr...