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
Product code looks like abcd2343, what to split by letters and numbers
3,340,081
7
2010-07-27T01:07:16Z
3,340,115
14
2010-07-27T01:18:14Z
[ "python", "split" ]
I have a list of product codes in a text file, on each like is the product code that looks like: abcd2343 abw34324 abc3243-23A So it is letters followed by numbers and other characters. I want to split on the first occurrence of a number.
``` In [32]: import re In [33]: s='abcd2343 abw34324 abc3243-23A' In [34]: re.split('(\d+)',s) Out[34]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A'] ``` Or, if you want to split on the first occurrence of a digit: ``` In [43]: re.findall('\d*\D+',s) Out[43]: ['abcd', '2343 abw', '34324 abc', '3...
post to page to login using beautiful soup
3,340,190
6
2010-07-27T01:36:26Z
3,340,203
8
2010-07-27T01:39:42Z
[ "python", "beautifulsoup" ]
I'm using python and beautifulsoup (new to both!), and I want to login to a suppliers website. So their form looks like (simplified): ``` <form name=loginform action=/index.html method="post"> <input name=user> <input name=pass"> </form> ``` Is there a way to keep track for cookies?
Do some more reading. Read about `urllib2` That's what you use to do a POST to login. If you know the `<input>` names, you don't need Beautiful Soup. <http://docs.python.org/library/urllib2.html> Beautiful Soup is what you use to parse a page of results. After you login. After you post the real request.
post to page to login using beautiful soup
3,340,190
6
2010-07-27T01:36:26Z
3,340,234
8
2010-07-27T01:47:36Z
[ "python", "beautifulsoup" ]
I'm using python and beautifulsoup (new to both!), and I want to login to a suppliers website. So their form looks like (simplified): ``` <form name=loginform action=/index.html method="post"> <input name=user> <input name=pass"> </form> ``` Is there a way to keep track for cookies?
Use [mechanize](http://wwwsearch.sourceforge.net/mechanize/) -- that's just the best (3rd party) Python library for interacting with web forms, keeping track of cookies &c.
WTForms... html, autofocus?
3,340,528
7
2010-07-27T03:25:01Z
9,523,294
20
2012-03-01T20:12:15Z
[ "python", "wtforms" ]
Is it possible to have some of the new attribute only attributes used in HTML5, inside of WTForms? Eg, say you want to create a TextField with placeholder="foo", required, and autofocus attributes. How would this be done in WTForms? In html it would look like this: `<input maxlength="256" name="q" value="" placeholde...
In WTForms 1.0, released yesterday, HTML5 compact syntax is now the default. Now you can do (in jinja): ``` {{ form.field(autofocus=true, required=true, placeholder="foo") }} ``` Note that in Jinja, the literal is `true` instead of `True` but if you were to try this in the python console you will need to use the pyth...
Why is tuple faster than list?
3,340,539
35
2010-07-27T03:26:57Z
3,340,588
13
2010-07-27T03:39:18Z
[ "python", "performance", "list", "tuples" ]
I've just read in ["Dive into Python"](http://www.diveintopython3.net/native-datatypes.html#tuples) that "tuples are faster than lists". Tuple is immutable, and list is mutable, but I don't quite understand why tuple is faster. Anyone did a performance test on this?
With the power of the `timeit` module, you can often resolve performance related questions yourself: ``` $ python2.6 -mtimeit -s 'a = tuple(range(10000))' 'for i in a: pass' 10000 loops, best of 3: 189 usec per loop $ python2.6 -mtimeit -s 'a = list(range(10000))' 'for i in a: pass' 10000 loops, best of 3: 191 usec p...
Why is tuple faster than list?
3,340,539
35
2010-07-27T03:26:57Z
3,340,881
63
2010-07-27T05:05:56Z
[ "python", "performance", "list", "tuples" ]
I've just read in ["Dive into Python"](http://www.diveintopython3.net/native-datatypes.html#tuples) that "tuples are faster than lists". Tuple is immutable, and list is mutable, but I don't quite understand why tuple is faster. Anyone did a performance test on this?
The reported "speed of construction" ratio only holds for **constant** tuples (ones whose items are expressed by literals). Observe carefully (and repeat on your machine -- you just need to type the commands at a shell/command window!)...: ``` $ python3.1 -mtimeit -s'x,y,z=1,2,3' '[x,y,z]' 1000000 loops, best of 3: 0....
Why is tuple faster than list?
3,340,539
35
2010-07-27T03:26:57Z
3,341,629
12
2010-07-27T07:54:06Z
[ "python", "performance", "list", "tuples" ]
I've just read in ["Dive into Python"](http://www.diveintopython3.net/native-datatypes.html#tuples) that "tuples are faster than lists". Tuple is immutable, and list is mutable, but I don't quite understand why tuple is faster. Anyone did a performance test on this?
Alex gave a great answer, but I'm going to try to expand on a few things I think worth mentioning. Any performance differences are generally small and implementation specific: so don't bet the farm on them. In CPython, tuples are stored in a single block of memory, so creating a new tuple involves at worst a single ca...
Python3.0 TypeError
3,340,712
4
2010-07-27T04:20:02Z
3,340,741
9
2010-07-27T04:29:11Z
[ "python", "python-3.x" ]
Usually one comes across this problem in python3.0 while attempting a split() method on a bytes type object. > TypeError: Type str does'nt support the buffer API This issue can be resolved by using the split method after decoding the bytes type object. However, I find the error message rather ambiguous. Am I missing...
Just forget the existence of totally-obsolete, zero-reasons-to-keep-it-around 3.0, upgrade to 3.1 instead, and splitting bytes is just fine: ``` >>> x = bytes(b'ciao bella') >>> x.split() [b'ciao', b'bella'] ```
Filtering in Python/Django based on date, ignoring time
3,341,120
3
2010-07-27T06:09:05Z
3,341,206
7
2010-07-27T06:30:46Z
[ "python", "django", "datetime-format" ]
I'd like to filter objects to the day with datetime, but can't find examples on how to do this anywhere. This, for example, works perfectly in pulling together all following events: ``` @login_required def invoice_picker(request): """Grab a date from the URL and show all the invoicable deliveries for that day."""...
I don't think there's a good way to compare datetimes with dates. One way is the following: ``` filter(end__year=date.year, end__month=date.month, end__day=date.day) ``` The other is to use the [`range`](http://docs.djangoproject.com/en/1.2/ref/models/querysets/#range) lookup with the min time and max time for the da...
passing C++ classes instances to python with boost::python
3,342,216
13
2010-07-27T09:21:48Z
3,378,195
13
2010-07-31T13:00:49Z
[ "c++", "python", "boost", "boost-python" ]
I have a library which creates objects (instances of class A) and pass them to a python program which should be able to call their methods. Basically I have C++ class instances and I want to use them from python. Occasionally that object should be passed back to C++ for some manipulations. I created the following wra...
`boost::python` knows all about `boost::shared_ptr`, but you need to tell it that `boost::shared_ptr<A>` holds an instance of `A`, you do this by adding `boost::shared_ptr<A>` in the template argument list to `class_`, more information on this 'Held Type' is [here in the boost documentation](http://www.boost.org/doc/li...
How to use py.test from Python?
3,343,205
8
2010-07-27T11:41:30Z
3,348,115
15
2010-07-27T21:22:50Z
[ "python", "py.test" ]
I'm working in a project that recently switched to the [py.test](http://codespeak.net/py/dist/test/) unittest framework. I was used to call my tests from Eclipse, so that I can use the debugger (e.g. placing breakpoints to analyze how a test failure develops). Now this is no longer possible, since the only way to run t...
I think I can now answer my own question, it's pretty simple: ``` import py py.test.cmdline.main(args) ``` Then I can run this module and or start it with the integrated debugger. `args` is the list of command line arguments, so for example to run only particular tests I can use something like: ``` args_str = "-k t...
Obfuscating Python code?
3,344,115
8
2010-07-27T13:29:41Z
3,344,212
13
2010-07-27T13:39:43Z
[ "python" ]
I am looking for how to hide my Python source code. ``` print "hello World !" ``` How can I encode this example so that it isn't human-readable? I've been told to use base64 but I'm not sure how.
You can use the [`base64` module](http://docs.python.org/library/base64.html) to encode strings to stop [shoulder surfing](http://en.wikipedia.org/wiki/Shoulder_surfing_%28computer_security%29), but it's not going to stop someone finding your code if they have access to your files. You can then use the [`compile()` fu...
Obfuscating Python code?
3,344,115
8
2010-07-27T13:29:41Z
3,344,502
26
2010-07-27T14:11:15Z
[ "python" ]
I am looking for how to hide my Python source code. ``` print "hello World !" ``` How can I encode this example so that it isn't human-readable? I've been told to use base64 but I'm not sure how.
> so that it isn't human-readable? > > i mean all the file is encoded !! when you open it you can't understand anything .. ! that what i want As maximum, you can compile your sources into bytecode and then distribute only bytecode. But even this is reversible. Bytecode can be decompiled into semi-readable sources. Ba...
Obfuscating Python code?
3,344,115
8
2010-07-27T13:29:41Z
7,418,341
27
2011-09-14T14:49:36Z
[ "python" ]
I am looking for how to hide my Python source code. ``` print "hello World !" ``` How can I encode this example so that it isn't human-readable? I've been told to use base64 but I'm not sure how.
Python has a built-in compiler (to byte-code): ``` python -OO -m py_compile <your program.py> ``` produces a `.pyo` file that contains byte-code, and where docstrings are removed, etc. You can rename the `.pyo` file with a `.py` extension, and `python <your program.py>` runs like your program but does not contain you...
Why does the istitle() string method return false if the string is clearly in title-case?
3,344,218
3
2010-07-27T13:40:00Z
3,344,234
8
2010-07-27T13:42:29Z
[ "python", "string" ]
Of the `istitle()` string method, the Python 2.6.5 manual reads: > Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise. But in this case it returns fal...
`book.title()` does not change the variable `book`. It just returns the string in title case. ``` >>> book.title() 'What Every Programmer Must Know' >>> book # still not in title case 'what every programmer must know' >>> book.istitle() # hence it returns False. False >>> book.title().istitle() # retur...
Splitting a string separated by "\r\n" into a list of lines?
3,345,030
12
2010-07-27T15:09:04Z
3,345,052
25
2010-07-27T15:11:04Z
[ "python", "string" ]
I am reading in some data from the subprocess module's communicate method. It is coming in as a large string separated by "\r\n"s. I want to split this into a list of lines. How is this performed in python?
Use the splitlines method on the string. From the docs: > **str.splitlines([keepends])** > Return a list of the lines in the string, breaking at line boundaries. > Line breaks are not included in the > resulting list unless keepends is > given and true. This will do the right thing whether the line endings are "\r\n...
Django: Parse JSON in my template using Javascript
3,345,076
18
2010-07-27T15:13:26Z
3,345,111
44
2010-07-27T15:17:27Z
[ "python", "json", "django", "django-templates" ]
I have this in my view: ``` string_location = myaddress2 geodata = [] for place, (lat, lng) in g.geocode(string_location,exactly_one=False): geodata.append((place, (lat, lng))) geodata_results = len(geodata) data = {"geodata": geodata, "geodata_results":geodata_results } return render_to_...
You could use the built-in `json` module: ``` >>> import json >>> geodata = [ ( "Here", (1003,3004) ), ("There", (1.2,1.3)) ] >>> json.dumps(geodata) '[["Here", [1003, 3004]], ["There", [1.2, 1.3]]]' ``` You can then simply embed the resulting string inside a javascript script: ``` <script type='text/javascript'> va...
Django: Parse JSON in my template using Javascript
3,345,076
18
2010-07-27T15:13:26Z
3,349,367
19
2010-07-28T01:57:27Z
[ "python", "json", "django", "django-templates" ]
I have this in my view: ``` string_location = myaddress2 geodata = [] for place, (lat, lng) in g.geocode(string_location,exactly_one=False): geodata.append((place, (lat, lng))) geodata_results = len(geodata) data = {"geodata": geodata, "geodata_results":geodata_results } return render_to_...
Okay, I solved my problem and would like to answer my own question. I figured it would be better for the other users here. First, get the file here: <http://www.JSON.org/json_parse.js> ``` var geodata = json_parse("{{geodata|escapejs}}"); ``` I just used escapejs: <http://docs.djangoproject.com/en/dev/ref/templates/...
python: getting user input
3,345,202
74
2010-07-27T15:25:57Z
3,345,212
153
2010-07-27T15:27:26Z
[ "python", "user-input" ]
i am running this: ``` import csv import sys reader = csv.reader(open(sys.argv[0], "rb")) for row in reader: print row ``` and i get this in response: ``` ['import csv'] ['import sys'] ['reader = csv.reader(open(sys.argv[0]', ' "rb"))'] ['for row in reader:'] [' print row'] >>> ``` for the `sys.argv[0]` i wo...
Use the [`raw_input()` function](http://docs.python.org/library/functions.html#raw_input) to get input from users: ``` print "Enter a file name:", filename = raw_input() ``` or just: ``` filename = raw_input('Enter a file name: ') ```
python: getting user input
3,345,202
74
2010-07-27T15:25:57Z
3,345,269
21
2010-07-27T15:32:50Z
[ "python", "user-input" ]
i am running this: ``` import csv import sys reader = csv.reader(open(sys.argv[0], "rb")) for row in reader: print row ``` and i get this in response: ``` ['import csv'] ['import sys'] ['reader = csv.reader(open(sys.argv[0]', ' "rb"))'] ['for row in reader:'] [' print row'] >>> ``` for the `sys.argv[0]` i wo...
`sys.argv[0]` is not the first argument but the filename of the python program you are currently executing. I think you want `sys.argv[1]`
python: getting user input
3,345,202
74
2010-07-27T15:25:57Z
36,110,735
30
2016-03-20T06:04:21Z
[ "python", "user-input" ]
i am running this: ``` import csv import sys reader = csv.reader(open(sys.argv[0], "rb")) for row in reader: print row ``` and i get this in response: ``` ['import csv'] ['import sys'] ['reader = csv.reader(open(sys.argv[0]', ' "rb"))'] ['for row in reader:'] [' print row'] >>> ``` for the `sys.argv[0]` i wo...
In python 3.x, use `input()` instead of `raw_input()`
python csv: save results to csv file
3,345,336
7
2010-07-27T15:39:41Z
3,345,418
13
2010-07-27T15:48:26Z
[ "python", "csv" ]
``` import csv with open('test.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[1]] += 1 for row in data: if counter[row[1]] >= 4: writer = csv.writer(open("test1.csv", "wb")) writer.writerows(row) ``` i am getti...
Use `csv.writer`: ``` import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[0]] += 1 writer = csv.writer(open("/path/to/my/csv/file", 'w')) for row in data: if counter[row[0]] >= 4: writer....
Getting number of elements in an iterator in Python
3,345,785
51
2010-07-27T16:32:21Z
3,345,797
33
2010-07-27T16:34:50Z
[ "python", "iterator" ]
Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?
No, any method will require you to resolve every result. You can do ``` iter_length = len(list(iterable)) ``` but running that on an infinite iterator will of course never return. It also will consume the iterator and it will need to be reset if you want to use the contents. Telling us what real problem you're tryin...
Getting number of elements in an iterator in Python
3,345,785
51
2010-07-27T16:32:21Z
3,345,807
81
2010-07-27T16:35:35Z
[ "python", "iterator" ]
Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?
This code should work: ``` >>> iter = (i for i in range(50)) >>> sum(1 for _ in iter) 50 ``` Although it does iterate through each item and count them, it is the fastest way to do so.
Getting number of elements in an iterator in Python
3,345,785
51
2010-07-27T16:32:21Z
3,345,871
41
2010-07-27T16:42:54Z
[ "python", "iterator" ]
Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?
No. It's not possible. Example: ``` import random def gen(n): for i in xrange(n): if random.randint(0, 1) == 0: yield i iterator = gen(10) ``` Length of `iterator` is unknown until you iterate through it.
Getting number of elements in an iterator in Python
3,345,785
51
2010-07-27T16:32:21Z
3,345,902
10
2010-07-27T16:47:46Z
[ "python", "iterator" ]
Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?
An iterator is just an object which has a pointer to the next object to be read by some kind of buffer or stream, it's like a LinkedList where you don't know how many things you have until you iterate through them. Iterators are meant to be efficient because all they do is tell you what is next by references instead of...
Getting number of elements in an iterator in Python
3,345,785
51
2010-07-27T16:32:21Z
3,346,121
14
2010-07-27T17:17:25Z
[ "python", "iterator" ]
Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?
Kinda. You *could* check the `__length_hint__` method, but be warned that (at least up to Python 3.4, as gsnedders helpfully points out) it's a [undocumented implementation detail](http://mail.python.org/pipermail/python-dev/2009-April/088109.html) ([following message in thread](http://mail.python.org/pipermail/python-...
Getting number of elements in an iterator in Python
3,345,785
51
2010-07-27T16:32:21Z
3,505,917
7
2010-08-17T18:57:51Z
[ "python", "iterator" ]
Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?
Regarding your original question, the answer is still that there is no way in general to know the length of an iterator in Python. Given that you question is motivated by an application of the pysam library, I can give a more specific answer: I'm a contributer to PySAM and the definitive answer is that SAM/BAM files d...
Getting number of elements in an iterator in Python
3,345,785
51
2010-07-27T16:32:21Z
15,112,059
14
2013-02-27T12:22:39Z
[ "python", "iterator" ]
Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?
You cannot (except the type of a particular iterator implements some specific methods that make it possible). Generally, you may count iterator items only by consuming the iterator. One of probably the most efficient ways: ``` import itertools from collections import deque def count_iter_items(iterable): """ ...
Python: Deleting files of a certain age
3,345,953
8
2010-07-27T16:56:04Z
3,346,009
10
2010-07-27T17:02:58Z
[ "python" ]
So at the moment I'm trying to delete files listed in the directory that are 1 minute old, I will change that value once I have the script working. The code below returns the error: `AttributeError: 'str' object has no attribute 'mtime'` ``` import time import os #from path import path seven_days_ago = time.time()...
``` import time import os one_minute_ago = time.time() - 60 folder = '/home/rv/Desktop/test' os.chdir(folder) for somefile in os.listdir('.'): st=os.stat(somefile) mtime=st.st_mtime if mtime < one_minute_ago: print('remove %s'%somefile) # os.unlink(somefile) # uncomment only if you are sur...
How do I force Django to ignore any caches and reload data?
3,346,124
62
2010-07-27T17:17:43Z
3,778,912
7
2010-09-23T13:36:51Z
[ "python", "django", "caching" ]
I'm using the Django database models from a process that's not called from an HTTP request. The process is supposed to poll for new data every few seconds and do some processing on it. I have a loop that sleeps for a few seconds and then gets all unhandled data from the database. What I'm seeing is that after the firs...
We've struggled a fair bit with forcing django to refresh the "cache" - which it turns out wasn't really a cache at all but an artifact due to transactions. This might not apply to your example, but certainly in django views, by default, there's an implicit call to a transaction, which mysql then isolates from any chan...
How do I force Django to ignore any caches and reload data?
3,346,124
62
2010-07-27T17:17:43Z
7,794,220
89
2011-10-17T13:09:25Z
[ "python", "django", "caching" ]
I'm using the Django database models from a process that's not called from an HTTP request. The process is supposed to poll for new data every few seconds and do some processing on it. I have a loop that sleeps for a few seconds and then gets all unhandled data from the database. What I'm seeing is that after the firs...
Having had this problem and found two definitive solutions for it I thought it worth posting another answer. This is a problem with MySQL's default transaction mode. Django opens a transaction at the start, which means that by default you won't see changes made in the database. Demonstrate like this Run a django she...
Wrap long lines in Python
3,346,230
109
2010-07-27T17:30:42Z
3,346,279
18
2010-07-27T17:36:32Z
[ "python", "string" ]
How do I wrap long lines in Python without sacrificing indentation? For example: ``` def fun(): print '{0} Here is a really long sentence with {1}'.format(3, 5) ``` Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it: ``` def fun(): print '{0} Here is a rea...
You can use the fact that Python concatenates string literals which appear adjacent to each other: ``` >>> def fun(): ... print '{0} Here is a really long ' \ ... 'sentence with {1}'.format(3, 5) ```
Wrap long lines in Python
3,346,230
109
2010-07-27T17:30:42Z
3,346,283
20
2010-07-27T17:36:51Z
[ "python", "string" ]
How do I wrap long lines in Python without sacrificing indentation? For example: ``` def fun(): print '{0} Here is a really long sentence with {1}'.format(3, 5) ``` Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it: ``` def fun(): print '{0} Here is a rea...
You could use the following code where indentation doesn't matter: ``` >>> def fun(): return ('{0} Here is a really long' ' sentence with {1}').format(3, 5) ``` You just need to enclose string in the parentheses.
Wrap long lines in Python
3,346,230
109
2010-07-27T17:30:42Z
3,346,295
148
2010-07-27T17:37:59Z
[ "python", "string" ]
How do I wrap long lines in Python without sacrificing indentation? For example: ``` def fun(): print '{0} Here is a really long sentence with {1}'.format(3, 5) ``` Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it: ``` def fun(): print '{0} Here is a rea...
``` def fun(): print '{0} Here is a really long ' \ 'sentence with {1}'.format(3, 5) ``` Adjecent string literals are concatenated at compile time, just as in C. <http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation> is a good place to start for more info.
Wrap long lines in Python
3,346,230
109
2010-07-27T17:30:42Z
18,160,132
34
2013-08-10T08:32:59Z
[ "python", "string" ]
How do I wrap long lines in Python without sacrificing indentation? For example: ``` def fun(): print '{0} Here is a really long sentence with {1}'.format(3, 5) ``` Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it: ``` def fun(): print '{0} Here is a rea...
There are two approaches which are not mentioned above, but both of which solve the problem in a way which complies with [PEP 8](http://www.python.org/dev/peps/pep-0008/) *and* allow you to make better use of your space. They are: ``` msg = ( 'This message is so long, that it requires ' 'more than {x} lines.{s...
What is the most efficient way to get first and last line of a text file?
3,346,430
31
2010-07-27T17:58:24Z
3,346,492
31
2010-07-27T18:06:46Z
[ "python", "file", "seek" ]
I have a text file which contains a time stamp on each line. My goal is to find the time range. All the times are in order so the first line will be the earliest time and the last line will be the latest time. I only need the very first and very last line. What would be the most efficient way to get these lines in pyth...
[docs for io module](http://docs.python.org/2/library/io.html) ``` with open(fname, 'rb') as fh: first = next(fh).decode() fh.seek(-1024, 2) last = fh.readlines()[-1].decode() ``` The variable value here is 1024: it represents the average string length. I choose 1024 only for example. If you have an esti...
What is the most efficient way to get first and last line of a text file?
3,346,430
31
2010-07-27T17:58:24Z
3,346,788
18
2010-07-27T18:39:57Z
[ "python", "file", "seek" ]
I have a text file which contains a time stamp on each line. My goal is to find the time range. All the times are in order so the first line will be the earliest time and the last line will be the latest time. I only need the very first and very last line. What would be the most efficient way to get these lines in pyth...
Here's a modified version of SilentGhost's answer that will do what you want. ``` with open(fname, 'rb') as fh: first = next(fh) offs = -100 while True: fh.seek(offs, 2) lines = fh.readlines() if len(lines)>1: last = lines[-1] break offs *= 2 prin...
What is the most efficient way to get first and last line of a text file?
3,346,430
31
2010-07-27T17:58:24Z
18,603,065
31
2013-09-03T23:29:19Z
[ "python", "file", "seek" ]
I have a text file which contains a time stamp on each line. My goal is to find the time range. All the times are in order so the first line will be the earliest time and the last line will be the latest time. I only need the very first and very last line. What would be the most efficient way to get these lines in pyth...
You could open the file for reading and read the first line using the builtin readline(), then seek to the end of file and step backwards until you find the line's preceding EOL and read the last line from there. ``` with open(file, "rb") as f: first = f.readline() # Read the first line. f.seek(-2, 2) ...
Why is it not safe to modify sequence being iterated on?
3,346,696
13
2010-07-27T18:29:37Z
3,346,750
12
2010-07-27T18:35:36Z
[ "python" ]
> It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient: ...
This is a common problem in many languages. If you have a linear data structure, and you are iterating over it, something must keep track of where you are in the structure. It might be a current index, or a pointer, but it's some kind of finger pointing to the "current place". If you modify the list while the iteratio...
Why is it not safe to modify sequence being iterated on?
3,346,696
13
2010-07-27T18:29:37Z
3,346,779
10
2010-07-27T18:38:50Z
[ "python" ]
> It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient: ...
Without getting too technical: If you're iterating through a mutable sequence in Python and the sequence is changed while it's being iterated through, it is not always entirely clear what will happen. If you insert an element in the sequence while iterating through it, what would now reasonably be considered the "next...
Starting with Android: Java or Python (SL4A)
3,346,970
12
2010-07-27T19:04:54Z
3,347,588
15
2010-07-27T20:19:32Z
[ "java", "python", "android", "sl4a" ]
I just ordered an Android smartphone and want to start playing around with creating my own applications. Now the question is which language to use, the native Java or Python using SL4A (former ASE). I tend to Python, as I know it much better than Java, but I'm wondering what I would be missing using a "second class" l...
At the moment you cannot create a releasable program with Python (or any other scripting language) using SL4A. I have heard rumours that this is something Google is working on, but even if they do enable it Python apps are likely to be slow and power-hungry compared to Java. Also the scripting API only gives you access...
python -- callable iterator size?
3,347,102
5
2010-07-27T19:20:54Z
10,563,874
9
2012-05-12T12:46:32Z
[ "python", "iterator" ]
I am looking through some text file for a certain string with the method. `re.finditer(pattern,text)` I would like to know when this returns nothing. meaning that it could find nothing in the passed text. I know that callable iterators, have `next()` and `__iter__` I would like to know if I could get the size or fin...
Here is a solution that uses **less memory**, because it does not save the intermediate results, as do the other solutions that use "list": ``` print sum(1 for _ in re.finditer(pattern, text)) ``` All the other solutions have the disadvantage of consuming a lot of memory if the pattern is very frequent in the text, l...
csv writer not closing file
3,347,775
16
2010-07-27T20:41:13Z
3,347,826
14
2010-07-27T20:46:43Z
[ "python", "csv" ]
im reading a csv file and then writing a new one: ``` import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[11]] += 1 writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w')) for row in data: ...
You can break out the open command into its own variable, so that you can close it later. ``` f = open('/pythonwork/thefile_subset1.csv', 'w') writer = csv.writer(f) f.close() ``` `csv.writer` throws a `ValueError` if you try to write to a closed file.
csv writer not closing file
3,347,775
16
2010-07-27T20:41:13Z
3,348,183
17
2010-07-27T21:32:00Z
[ "python", "csv" ]
im reading a csv file and then writing a new one: ``` import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[11]] += 1 writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w')) for row in data: ...
``` with open('/pythonwork/thefile_subset1.csv', 'w') as outfile: writer = csv.writer(outfile) for row in data: if counter[row[11]] >= 500: writer.writerow(row) ```
confusing python urlencode order
3,347,870
4
2010-07-27T20:52:10Z
3,347,899
18
2010-07-27T20:54:42Z
[ "python", "urlencode" ]
okay, so according to <http://docs.python.org/library/urllib.html> "The order of parameters in the encoded string will match the order of parameter tuples in the sequence." except when I try to run this code: ``` import urllib values ={'one':'one', 'two':'two', 'three':'three', 'four':'fou...
Dictionaries are inherently unordered because of the way they are implemented. If you want them to be ordered, you should use a list of tuples instead (or a tuple of lists, or a tuple of tuples, or a list of lists...): ``` values = [ ('one', 'one'), ('two', 'two') ... ] ```
CSV file written with Python has blank lines between each row
3,348,460
73
2010-07-27T22:14:42Z
3,348,664
149
2010-07-27T22:55:15Z
[ "python", "csv" ]
``` import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[10]] += 1 with open('/pythonwork/thefile_subset11.csv', 'w') as outfile: writer = csv.writer(outfile) for row in data: ...
In Python 2, open `outfile` with mode `'wb'` instead of `'w'`. The `csv.writer` writes `\r\n` into the file directly. If you don't open the file in *binary* mode, it will write `\r\r\n` because on Windows *text* mode will translate each `\n` into `\r\n`. In Python 3 the required syntax changed, so open `outfile` with ...
CSV file written with Python has blank lines between each row
3,348,460
73
2010-07-27T22:14:42Z
3,348,729
10
2010-07-27T23:14:42Z
[ "python", "csv" ]
``` import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[10]] += 1 with open('/pythonwork/thefile_subset11.csv', 'w') as outfile: writer = csv.writer(outfile) for row in data: ...
The simple answer is that **csv files should always be opened in binary mode** whether for input or output, as otherwise on Windows there are problems with the line ending. Specifically on output the csv module will write `\r\n` (the standard CSV row terminator) and then (in text mode) the runtime will replace the `\n`...
CSV file written with Python has blank lines between each row
3,348,460
73
2010-07-27T22:14:42Z
21,804,265
8
2014-02-15T22:05:37Z
[ "python", "csv" ]
``` import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[10]] += 1 with open('/pythonwork/thefile_subset11.csv', 'w') as outfile: writer = csv.writer(outfile) for row in data: ...
Opening the file in binary mode "wb" will not work in Python 3+. Or rather, you'd have to convert your data to binary before writing it. That's just a hassle. Instead, you should keep it in text mode, but override the newline as empty. Like so: ``` with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as out...
Wrong ELF class - Python
3,348,538
3
2010-07-27T22:30:34Z
3,348,581
7
2010-07-27T22:38:41Z
[ "javascript", "python", "compression", "libraries", "lzw" ]
I'm trying to install this library for **LZJB** compression. [PyLZJB LINK](http://code.google.com/p/pylzjb/) The library is a binding for a C library, the file is located here [PyLZJB.so](http://code.google.com/p/pylzjb/downloads/detail?name=PyLZJB.so&can=2&q=) --- Unfortunately by copying to the site-packages direc...
You are running a 64 bit Python interpreter and trying to load a 32 bit extension and that is not allowed. You need to have both your Python interpreter and your extension compiled for the same architectures. While you could get a 32 bit Python interpreter, it would probably be better to get a 64 bit extension. What ...
Search for a file using a wildcard
3,348,753
25
2010-07-27T23:20:17Z
3,348,761
41
2010-07-27T23:23:05Z
[ "python", "file", "wildcard" ]
I want get a list of filenames with a search pattern with a wildcard. Like: ``` getFilenames.py c:\PathToFolder\* getFilenames.py c:\PathToFolder\FileType*.txt getFilenames.py c:\PathToFolder\FileTypeA.txt ``` How can I do this?
Like this: ``` >>> import glob >>> glob.glob('./[0-9].*') ['./1.gif', './2.txt'] >>> glob.glob('*.gif') ['1.gif', 'card.gif'] >>> glob.glob('?.gif') ['1.gif'] ``` This comes straight from here: <http://docs.python.org/library/glob.html>
Search for a file using a wildcard
3,348,753
25
2010-07-27T23:20:17Z
3,348,908
14
2010-07-27T23:57:46Z
[ "python", "file", "wildcard" ]
I want get a list of filenames with a search pattern with a wildcard. Like: ``` getFilenames.py c:\PathToFolder\* getFilenames.py c:\PathToFolder\FileType*.txt getFilenames.py c:\PathToFolder\FileTypeA.txt ``` How can I do this?
`glob` is useful if you are doing this in within python, however, your shell may not be passing in the `*` (I'm not familiar with the windows shell). For example, when I do the following: ``` import sys print sys.argv ``` On my shell, I type: ``` $ python test.py *.jpg ``` I get this: ``` ['test.py', 'test.jpg', ...
How to make tkinter repond events while waiting socket data?
3,348,757
5
2010-07-27T23:21:23Z
3,348,777
9
2010-07-27T23:25:10Z
[ "python", "event-handling", "tkinter" ]
I'm trying to make the app read data from a socket, but it takes some time and locks the interface, how do I make it respond to tk events while waiting?
Thats is easy! And you don’t even need threads! But you’ll have to restructure your I/O code a bit. Tk has the equivalent of Xt’s XtAddInput() call, which allows you to register a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. Here’s what you need: ``` fr...
How to round integers in python
3,348,825
45
2010-07-27T23:39:49Z
3,348,866
89
2010-07-27T23:48:18Z
[ "python" ]
I am trying to round integers in python. I looked at the built-in round() function but it seems that that rounds floats. My goal is to round integers to the closest multiple of 10. i.e.: 5-> 10, 4-> 0, 95->100, etc. 5 and higher should round up, 4 and lower should round down. This is the code I have that does this: ...
Actually, you could still use the round function: ``` >>> print round(1123.456789, -1) 1120.0 ``` This would round to the closest multiple of 10. To 100 would be -2 as the second argument and so forth.
How to round integers in python
3,348,825
45
2010-07-27T23:39:49Z
3,349,102
15
2010-07-28T00:40:41Z
[ "python" ]
I am trying to round integers in python. I looked at the built-in round() function but it seems that that rounds floats. My goal is to round integers to the closest multiple of 10. i.e.: 5-> 10, 4-> 0, 95->100, etc. 5 and higher should round up, 4 and lower should round down. This is the code I have that does this: ...
round() can take ints and negative numbers for places, which round to the left of the decimal. The return value is still a float, but a simple cast fixes that: ``` >>> int(round(5678,-1)) 5680 >>> int(round(5678,-2)) 5700 >>> int(round(5678,-3)) 6000 ```
Efficient way of setting Logging across a Package Module
3,348,958
9
2010-07-28T00:08:01Z
3,349,046
10
2010-07-28T00:27:23Z
[ "python", "logging", "module", "package" ]
I have a package that has several components in it that would benefit greatly from using logging and outputting useful information. What I do not want to do is to 'setup' proper logging for every single file with somewhere along these lines: ``` import logging logging.basicConfig(level=DEBUG) my_function = logging.ge...
If you want all the code in the various modules of your package to use the same logger object, you just need to (make that logger available -- see later -- and) call ``` mylogger.warning("Attenzione!") ``` or the like, rather than `logging.warning` &c. So, the problem reduces to making one `mylogger` object for the w...
How do greenlets work?
3,349,048
45
2010-07-28T00:27:42Z
3,349,137
26
2010-07-28T00:52:21Z
[ "python" ]
How are [greenlets](http://pypi.python.org/pypi/greenlet) implemented? Python uses the C stack for the interpreter and it heap-allocates Python stack frames, but beyond that, how does it allocate/swap stacks, how does it hook into the interpreter and function call mechanisms, and how does this interact with C extension...
If get and study the greenlet's [sources](http://pypi.python.org/packages/source/g/greenlet/greenlet-0.3.1.tar.gz#md5=8d75d7f3f659e915e286e1b0fa0e1c4d), you'll see at the top of `greenlet.c` a long comment that starts at line 16 with the following summary...: > A PyGreenlet is a range of C stack > addresses that must ...
How do greenlets work?
3,349,048
45
2010-07-28T00:27:42Z
17,447,308
25
2013-07-03T11:57:34Z
[ "python" ]
How are [greenlets](http://pypi.python.org/pypi/greenlet) implemented? Python uses the C stack for the interpreter and it heap-allocates Python stack frames, but beyond that, how does it allocate/swap stacks, how does it hook into the interpreter and function call mechanisms, and how does this interact with C extension...
When a python program runs, you have essentially two pieces of code running under the hood. First, the CPython interpreter C code running and using the standard C-stack to save its internal stack-frames. Second, the actual python interpreted bytecode which does not use the C-stack, but rather uses the heap to save its...
Python: Passing a function name as an argument in a function
3,349,157
10
2010-07-28T00:56:18Z
3,349,167
21
2010-07-28T00:58:58Z
[ "python" ]
I am trying to pass the name of a function into another function as an argument but I get an error: "TypeError: 'str' object is not callable". Here is a simplified example of the problem: ``` def doIt(a, func, y, z): result = z result = func(a, y, result) return result def dork1(arg1, arg2, arg3): thi...
If you want to pass the function's **name**, as you said and you're doing, of course you can't call it -- why would one "call a *name*"? It's meaningless. If you want to call it, pass the function itself, that is, most emphatically **not** ``` var = 'dork1' ``` but rather ``` var = dork1 ``` without quotes! **Edi...
Python variable assignment order of operations
3,349,908
3
2010-07-28T04:17:23Z
3,349,954
8
2010-07-28T04:27:39Z
[ "python", "function", "variable-assignment" ]
Is there a way to do a variable assignment inside a function call in python? Something like ``` curr= [] curr.append(num = num/2) ```
Nopey. Assignment is a [statement](http://docs.python.org/reference/simple_stmts.html#grammar-token-assignment_stmt). It is not an [expression](http://docs.python.org/reference/expressions.html#grammar-token-expression_list) as it is in C derived languages.
Iteration in python dictionary
3,350,091
4
2010-07-28T05:12:53Z
3,350,147
8
2010-07-28T05:27:31Z
[ "python", "dictionary", "order" ]
I populate a python dictionary based on few conditions. My question is: can we retrieve the dictionary in the same order as it is populated? ``` questions_dict={} data = str(header_arr[opt]) + str(row) questions_dict.update({data : xl_data}) valid_xl_format = 7 ...
To keep track of the order in which a dictionary is populated, you need a type different than `dict` (commonly known as "ordered dict"), such as those from the third-party [odict](http://www.voidspace.org.uk/python/odict.html) module, or, if you can upgrade to Python 2.7, [collections.OrderedDict](http://docs.python.or...
Python string match
3,351,218
12
2010-07-28T08:46:48Z
3,351,236
34
2010-07-28T08:49:48Z
[ "regex", "string", "python" ]
If a string contains `*SUBJECT123`, how do I determine that the string has `subject` in it in python?
``` if "subject" in mystring.lower(): # do something ```
Python string match
3,351,218
12
2010-07-28T08:46:48Z
3,351,248
11
2010-07-28T08:51:36Z
[ "regex", "string", "python" ]
If a string contains `*SUBJECT123`, how do I determine that the string has `subject` in it in python?
If you want to have `subject` match `SUBJECT`, you could use [`re`](http://docs.python.org/library/re.html) ``` import re if re.search('subject', your_string, re.IGNORECASE) ``` Or you could transform the string to lower case first and simply use: ``` if "subject" in your_string.lower() ```
How to remove all html tags from downloaded page
3,351,485
3
2010-07-28T09:22:05Z
3,351,680
25
2010-07-28T09:50:56Z
[ "python" ]
I have downloaded a page using urlopen. How do I remove all html tags from it? Is there any regexp to replace all <\*> tags?
I can also recommend [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) which is an easy to use html parser. There you would do something like: ``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html) all_text = ''.join(soup.findAll(text=True)) ``` This way you get all the text from a html ...
Python - randomly partition a list into n nearly equal parts
3,352,737
2
2010-07-28T12:20:56Z
3,352,761
13
2010-07-28T12:23:10Z
[ "python", "random", "slice" ]
I have read the answers to the [Python: Slicing a list into n nearly-equal-length partitions](http://stackoverflow.com/questions/2659900/python-slicing-a-list-into-n-nearly-equal-length-partitions) question. This is the [accepted answer](http://stackoverflow.com/questions/2659900/python-slicing-a-list-into-n-nearly-eq...
Call [`random.shuffle()`](http://docs.python.org/library/random.html#random.shuffle) on the list before partitioning it.
Python nose framework: How to stop execution upon first failure
3,352,862
34
2010-07-28T12:35:08Z
3,352,913
55
2010-07-28T12:41:24Z
[ "python", "unit-testing" ]
It seems that if a testcase fails, nose will attempt to execute the next testcases. How can I make nose to abort all execution upon the first error in any testcase? I tried sys.exit() but it gave me some ugly and lengthy messages about it
There is an option for nose: ``` -x, --stop Stop running tests after the first error or failure ``` Is this what you need? Following link can help you with all the options available for nosetests. <http://nose.readthedocs.org/en/latest/usage.html>
How to center a window on the screen in Tkinter?
3,352,918
25
2010-07-28T12:41:49Z
3,353,112
37
2010-07-28T13:06:24Z
[ "python", "tkinter", "centering" ]
I'm trying to center a tkinter window. I know I can programatically get the size of the window and the size of the screen and use that to set the geometry, but I'm wondering if there's a simpler way to center the window on the screen.
You can try to use the methods `winfo_screenwidth` and `winfo_screenheight`, which return respectively the width and height (in pixels) of your `Tk` instance (window), and with some basic math you can center your window: ``` import tkinter as tk def center(toplevel): toplevel.update_idletasks() w = toplevel....
How to center a window on the screen in Tkinter?
3,352,918
25
2010-07-28T12:41:49Z
10,018,670
20
2012-04-04T20:21:26Z
[ "python", "tkinter", "centering" ]
I'm trying to center a tkinter window. I know I can programatically get the size of the window and the size of the screen and use that to set the geometry, but I'm wondering if there's a simpler way to center the window on the screen.
The general approach to centering a window is to calculate the appropriate screen coordinates for the window's top left pixel: ``` x = (screen_width / 2) - (window_width / 2) y = (screen_height / 2) - (window_height / 2) ``` However, this is *not* sufficient for *accurately* centering a tkinter window (on Windows 7...
How to center a window on the screen in Tkinter?
3,352,918
25
2010-07-28T12:41:49Z
28,224,382
12
2015-01-29T20:52:38Z
[ "python", "tkinter", "centering" ]
I'm trying to center a tkinter window. I know I can programatically get the size of the window and the size of the screen and use that to set the geometry, but I'm wondering if there's a simpler way to center the window on the screen.
Tk provides a helper function that can do this as `tk::PlaceWindow`, but I don't believe it has been exposed as a wrapped method in Tkinter. You would center a widget using the following: ``` from tkinter import * app = Tk() app.eval('tk::PlaceWindow %s center' % app.winfo_pathname(app.winfo_id())) app.mainloop() ```...
Python: is there a C-like for loop available?
3,354,313
7
2010-07-28T15:13:44Z
3,354,329
14
2010-07-28T15:15:32Z
[ "python", "for-loop" ]
Can I do something like this in Python? ``` for (i = 0; i < 10; i++): if someCondition: i+=1 print i ``` I need to be able to skip some values based on a condition EDIT: All the solutions so far suggest pruning the initial range in one way or another, based on an already known condition. This is not useful ...
Yes, this is how I would do it ``` >>> for i in xrange(0, 10): ... if i == 4: ... continue ... print i, ... 0 1 2 3 5 6 7 8 9 ``` **EDIT** Based on the update to your original question... I would suggest you take a look at [optparse](http://docs.python.org/library/optparse.html)
Matplotlib: interactive plot on a web server
3,354,883
16
2010-07-28T16:06:06Z
3,355,060
16
2010-07-28T16:24:53Z
[ "python", "django", "web-applications", "matplotlib" ]
I'm currently using [Open Flash Chart 2](http://teethgrinder.co.uk/open-flash-chart-2/) on my django website, but I find it insufficiently customizable. (It's great when you want the usual barcharts, piecharts, but what about homemade shapes...). Although it's open source, I don't feel like diving in the Flex code. I'...
If you're looking for flash-like interactivity in a web application, matplotlib probably isn't what you're looking for. It's fine for rendering a static image to serve out in a web app, though. (and is amazingly flexible) However, there's been a lot of recent development on making matplotlib more oriented toward web i...
Reason for low Pylint ratings of Python standard library code
3,355,998
12
2010-07-28T18:09:56Z
3,356,008
10
2010-07-28T18:11:27Z
[ "python", "pylint" ]
A friend told me about Pylint and just out of curiosity, I ran it against some of the standard library modules. To my surprise, the ratings were low. Here are a few runs: ``` os.py Your code has been rated at 3.55/10 random.py Your code has been rated at 4.74/10 ``` I ran it on some more modules and the found the r...
Pylint's defaults are quite strict, and complain about things they should not. For example, if you use `foo(**kwargs)`, you get a message about using "magic". Sometimes it seems as if pylint is looking at Python from a Java programmer's point of view. You'd have to look at the specific messages and decide if you agree...
How i get the current language in django?
3,356,964
47
2010-07-28T20:01:16Z
3,357,141
81
2010-07-28T20:19:43Z
[ "python", "django", "internationalization" ]
How can I get the current language in the current thread in a model or in the admin?
Functions of particular interest are `django.utils.translation.get_language()` which returns the language used in the current thread. See [documentation](https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.translation.get_language).
How i get the current language in django?
3,356,964
47
2010-07-28T20:01:16Z
3,359,880
56
2010-07-29T06:11:25Z
[ "python", "django", "internationalization" ]
How can I get the current language in the current thread in a model or in the admin?
Or you can also get this in your views ``` request.LANGUAGE_CODE ```
python: exit out of two loops
3,357,255
22
2010-07-28T20:33:24Z
3,357,290
7
2010-07-28T20:37:44Z
[ "python" ]
``` for row in b: for drug in drug_input: for brand in brand_names[drug]: ``` from the third loop how do i exit the current loop and go to the next value of `for row in b:` ?
``` for row in b: more_drugs = True for drug in drug_input: for brand in brand_names[drug]: if something: more_drugs = False break if not more_drugs: break ``` Python doesn't have a control structure for breaking from two loops at once, so you need to ...
python: exit out of two loops
3,357,255
22
2010-07-28T20:33:24Z
3,357,305
19
2010-07-28T20:39:57Z
[ "python" ]
``` for row in b: for drug in drug_input: for brand in brand_names[drug]: ``` from the third loop how do i exit the current loop and go to the next value of `for row in b:` ?
This one uses a boolean to see if you are done yet: ``` done = False for x in xs: for y in ys: if bad: done = True break if done: break ``` This one will `continue` if no break was used. The `else` will be skipped over if there was a break, so it will see the next `bre...
maximum of 2 numbers
3,357,369
26
2010-07-28T20:49:09Z
3,357,376
9
2010-07-28T20:50:13Z
[ "python" ]
How to find the maximum of 2 numbers? ``` value = -9999 run = problem.getscore() ``` I need to compare the 2 values i.e `value` and `run` and find the maximum of 2. I need some python function to operate it?
`max(number_one, number_two)`
maximum of 2 numbers
3,357,369
26
2010-07-28T20:49:09Z
3,357,377
16
2010-07-28T20:50:14Z
[ "python" ]
How to find the maximum of 2 numbers? ``` value = -9999 run = problem.getscore() ``` I need to compare the 2 values i.e `value` and `run` and find the maximum of 2. I need some python function to operate it?
[`max()`](http://docs.python.org/library/functions.html#max)
maximum of 2 numbers
3,357,369
26
2010-07-28T20:49:09Z
3,357,385
7
2010-07-28T20:50:33Z
[ "python" ]
How to find the maximum of 2 numbers? ``` value = -9999 run = problem.getscore() ``` I need to compare the 2 values i.e `value` and `run` and find the maximum of 2. I need some python function to operate it?
You can use `max(value, run)` The function [`max`](http://docs.python.org/library/functions.html#max) takes any number of arguments, or (alternatively) an iterable, and returns the maximum value.
maximum of 2 numbers
3,357,369
26
2010-07-28T20:49:09Z
3,357,387
76
2010-07-28T20:50:36Z
[ "python" ]
How to find the maximum of 2 numbers? ``` value = -9999 run = problem.getscore() ``` I need to compare the 2 values i.e `value` and `run` and find the maximum of 2. I need some python function to operate it?
Use the builtin function `max`. Example: `max(2, 4)` returns 4. Just for giggles, there's a `min` as well...should you need it. :P
Using Python class as a data container
3,357,581
16
2010-07-28T21:18:36Z
3,357,598
8
2010-07-28T21:21:22Z
[ "python", "class", "dictionary", "struct" ]
Sometimes it makes sense to cluster related data together. I tend to do so with a dict, e.g., ``` self.group = dict(a=1, b=2, c=3) print self.group['a'] ``` One of my colleagues prefers to create a class ``` class groupClass(object): def __init__(a, b, c): self.a = a self.b = b self.c = c...
I prefer to follow [YAGNI](http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it) and use a dict.
Using Python class as a data container
3,357,581
16
2010-07-28T21:18:36Z
3,357,616
17
2010-07-28T21:23:38Z
[ "python", "class", "dictionary", "struct" ]
Sometimes it makes sense to cluster related data together. I tend to do so with a dict, e.g., ``` self.group = dict(a=1, b=2, c=3) print self.group['a'] ``` One of my colleagues prefers to create a class ``` class groupClass(object): def __init__(a, b, c): self.a = a self.b = b self.c = c...
If you're really never defining any class methods, a dict or a [namedtuple](http://docs.python.org/library/collections.html#collections.namedtuple) make far more sense, in my opinion. Simple+builtin is good! To each his own, though.
What is the difference between lists and tuples in Python?
3,357,984
6
2010-07-28T22:13:58Z
3,358,084
7
2010-07-28T22:31:06Z
[ "python", "list", "tuples" ]
Which is more efficient? What is the typical use of each?
Lists are mutable sequences, with lots and lots of methods (both mutating and non-mutating ones), that are most often used as general purpose containers (their items can be objects of any types at all, although it's sometimes considered better style for lists to have items that are of the same type or types to be used ...
Convert multiline string to single line string
3,358,426
3
2010-07-28T23:42:46Z
3,358,533
7
2010-07-29T00:06:58Z
[ "python", "string", "google-app-engine" ]
I'm using Google App Engine and I need to put a multiline string in the datastore. Unfortunately, GAE does not allow that. I need this string to be multiline, so is there any way to convert a multiline string to a single line string and store it?
You don't need no conversion: [google.appengine.ext.db.StringProperty](http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#StringProperty)(multiline=True)
A forgiving dictionary
3,358,580
9
2010-07-29T00:19:32Z
3,358,592
21
2010-07-29T00:22:05Z
[ "python", "hash", "table" ]
I am wondering how to create forgiving dictionary (one that returns a default value if a KeyError is raised). In the following code example I would get a KeyError; for example ``` a = {'one':1,'two':2} print a['three'] ``` In order not to get one I would 1. Have to catch the exeption or use get. I would like to not...
``` import collections a = collections.defaultdict(lambda: 3) a.update({'one':1,'two':2}) print a['three'] ``` emits `3` as required. You could also subclass `dict` yourself and override `__missing__`, but that doesn't make much sense when the `defaultdict` behavior (ignoring the exact missing key that's being looked ...
A forgiving dictionary
3,358,580
9
2010-07-29T00:19:32Z
3,358,593
7
2010-07-29T00:22:07Z
[ "python", "hash", "table" ]
I am wondering how to create forgiving dictionary (one that returns a default value if a KeyError is raised). In the following code example I would get a KeyError; for example ``` a = {'one':1,'two':2} print a['three'] ``` In order not to get one I would 1. Have to catch the exeption or use get. I would like to not...
> New in version 2.5: If a subclass of > dict defines a method \_\_missing\_\_(), > if the key key is not present, the > d[key] operation calls that method > with the key key as argument. The > d[key] operation then returns or > raises whatever is returned or raised > by the \_\_missing\_\_(key) call if the > key is no...
python dictionary is thread safe?
3,358,770
22
2010-07-29T01:07:06Z
3,358,790
25
2010-07-29T01:16:00Z
[ "python", "thread-safety" ]
Some stated that python dictionary is thread safe. Does it mean I can or cannot modify the items in a dictionary while iterating over it?
The two concepts are completely different. [Thread safety](http://en.wikipedia.org/wiki/Thread_safety) means that two threads cannot modify the same object at the same time, thereby leaving the system in an inconsistent state. That said, you cannot modify a dictionary while iterating over it. See the [documentation.](...
python dictionary is thread safe?
3,358,770
22
2010-07-29T01:07:06Z
3,358,793
12
2010-07-29T01:17:21Z
[ "python", "thread-safety" ]
Some stated that python dictionary is thread safe. Does it mean I can or cannot modify the items in a dictionary while iterating over it?
No. Recent version of python will raise an exception if you try to iterate over a dictionary that has changed size between iterations. ``` >>> d={'one':1, 'two':2} >>> for x in d: ... d['three']=3 ... print x ... two Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionar...
python dictionary is thread safe?
3,358,770
22
2010-07-29T01:07:06Z
3,358,974
53
2010-07-29T02:04:59Z
[ "python", "thread-safety" ]
Some stated that python dictionary is thread safe. Does it mean I can or cannot modify the items in a dictionary while iterating over it?
The other answers already correctly addressed what's apparently your actual question: > Does it mean I can or cannot modified > the items in a dictionary while > iterating over it? by explaining that thread safety has nothing to do with the issue, **and** in any case, no, you cannot modify a dict while iterating over...
How can I remove all elements matching an xpath in python using lxml?
3,359,151
13
2010-07-29T02:49:01Z
3,359,309
16
2010-07-29T03:32:49Z
[ "python", "lxml" ]
So I have some XML like this: ``` <bar> <foo>Something</foo> <baz> <foo>Hello</foo> <zap>Another</zap> <baz> <bar> ``` And I want to remove all the foo nodes. Something like this doesn't work ``` params = xml.xpath('//foo') for n in params: xml.getroot().remove(n) ``` Giving ``` ValueError: Eleme...
try: ``` for elem in xml.xpath( '//foo' ) : elem.getparent().remove(elem) ``` remove it from it's parent, not the root ( unless it IS a child of the root element )
A web crawler in python. Where should i start and what should i follow? - Help needed
3,359,712
6
2010-07-29T05:32:17Z
3,361,410
7
2010-07-29T10:15:57Z
[ "python", "web-crawler" ]
I have an intermediate knowledge in python. if i have to write a web crawler in python, what things should i follow and where should i begin. is there any specific tut? any advice would be of much help.. thanks
I strongly recommend taking a look at [Scrapy](http://www.scrapy.org/). The library can work with BeautifulSoup, or any of your preferred HTML parser. I personally use it with lxml.html. Out of the box, you receive several things for free: * Concurrent requests, thanks to Twisted * `CrawlSpider` objects recursively l...
Project euler in python (#53)
3,360,842
6
2010-07-29T09:00:10Z
3,360,889
8
2010-07-29T09:05:20Z
[ "python" ]
So I'm learning python so I'm going through some project euler problems. And I'm not sure if this is a python problem I'm having, or just me being retarded, but I seem to be getting the wrong answer for problem 53. Here's a link to the problem <http://projecteuler.net/index.php?section=problems&id=53> and this is my c...
`range( a, b)` does not include `b`.
Sql Alchemy connection time Out
3,360,951
27
2010-07-29T09:16:22Z
3,364,841
37
2010-07-29T16:31:24Z
[ "python", "session", "timeout", "sqlalchemy" ]
I am using `sqlalchemy` with `MySQL`, and executing query with sql expression. When executing a number of query then it time out. I found an [answer](http://groups.google.com/group/sqlalchemy/browse_thread/thread/b2bf9687aaee38af/cd9bcaed89b4dbb8) but it is not clear to me. Please, any one can help me? > TimeoutError:...
Whenever you create a new session in your code, make sure you close it. Just call `session.close()` When I got this error I thought I was closing all of my sessions, but I looked carefully and there was one new method where I wasn't. Closing the session in that method fixed this error for me.
Sql Alchemy connection time Out
3,360,951
27
2010-07-29T09:16:22Z
28,040,482
8
2015-01-20T08:16:29Z
[ "python", "session", "timeout", "sqlalchemy" ]
I am using `sqlalchemy` with `MySQL`, and executing query with sql expression. When executing a number of query then it time out. I found an [answer](http://groups.google.com/group/sqlalchemy/browse_thread/thread/b2bf9687aaee38af/cd9bcaed89b4dbb8) but it is not clear to me. Please, any one can help me? > TimeoutError:...
In multi-thread mode, if your concurrent request num is much more than the db connection pool size, it will throw the Queue Pool limit of size 5 overflow 10 reached **`error`**. try with this: ``` engine = create_engine('mysql://', convert_unicode=True, pool_size=20, max_overflow=100) to add the pool size ``` Add: ...
Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation?
3,362,413
2
2010-07-29T12:30:04Z
3,362,433
26
2010-07-29T12:31:42Z
[ "python", "variable-assignment", "list-comprehension", "side-effects" ]
``` >>> a=range(5) >>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects [0, 2, 4] >>> a [0, 1, 2, 3, 4] >>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment SyntaxError: invalid syntax >>> def setitem(listtochange,n,value): ## function to overcome limitation listtochange[n]=value...
Don't use list comprehensions to perform side-effects - that is not Pythonic. Use an explicit loop instead: ``` for i in range(0,len(a),2): a[i] = 3 ``` Apart the side-effects in list comprehensions being surprising and unexpected, you are constructing a result list that you never use which is wasteful and comple...
Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation?
3,362,413
2
2010-07-29T12:30:04Z
3,362,452
9
2010-07-29T12:33:22Z
[ "python", "variable-assignment", "list-comprehension", "side-effects" ]
``` >>> a=range(5) >>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects [0, 2, 4] >>> a [0, 1, 2, 3, 4] >>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment SyntaxError: invalid syntax >>> def setitem(listtochange,n,value): ## function to overcome limitation listtochange[n]=value...
Yes. And I recommend using ``` a[::2] = ['x'] * len(a[::2]) ``` instead. --- Edit: Microbenchmarks for Python 2.6: ``` ~:249$ python2.6 -m timeit -s 'a = range(2000)' 'a[::2] = [8] * len(a[::2])' 10000 loops, best of 3: 26.2 usec per loop ~:250$ python2.6 -m timeit -s 'a = range(2000)' 'a[::2] = [8] * (len(a)/2)...
How to send email attachments with Python
3,362,600
131
2010-07-29T12:50:55Z
3,362,673
13
2010-07-29T12:59:19Z
[ "python", "email" ]
I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the `smtplib`. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I find them hard to understand.
``` from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage import smtplib msg = MIMEMultipart() msg.attach(MIMEText(file("text.txt").read())) msg.attach(MIMEImage(file("image.png").read())) # to send mailer = smtplib.SMTP() mailer.connect() mailer.sendm...
How to send email attachments with Python
3,362,600
131
2010-07-29T12:50:55Z
3,363,254
189
2010-07-29T14:00:15Z
[ "python", "email" ]
I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the `smtplib`. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I find them hard to understand.
Here's another, adapted from [here](http://snippets.dzone.com/posts/show/2038): ``` import smtplib from os.path import basename from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate def sen...
How to send email attachments with Python
3,362,600
131
2010-07-29T12:50:55Z
3,363,538
41
2010-07-29T14:29:52Z
[ "python", "email" ]
I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the `smtplib`. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I find them hard to understand.
this is the code I ended up using: ``` import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Encoders SUBJECT = "Email Data" msg = MIMEMultipart() msg['Subject'] = SUBJECT msg['From'] = self.EMAIL_FROM msg['To'] = ', '.join(self.EMAIL_TO) part = MIMEBas...
How to send email attachments with Python
3,362,600
131
2010-07-29T12:50:55Z
16,509,278
30
2013-05-12T16:03:43Z
[ "python", "email" ]
I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the `smtplib`. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I find them hard to understand.
Here is the modified version from `Oli` for python 3 ``` import smtplib, os from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from email import encoders def send_mail( send_from, send_to, subject, tex...