title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Python's sys.path value
897,792
<p>Where is Python's sys.path initialized from?</p> <p><strong>UPD</strong>: Python is adding some paths before refering to PYTHONPATH:</p> <pre><code> &gt;&gt;&gt; import sys &gt;&gt;&gt; from pprint import pprint as p &gt;&gt;&gt; p(sys.path) ['', 'C:\\Python25\\lib\\site-packages\\setuptools-0....
54
2009-05-22T13:19:05Z
897,810
<p>"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"</p> <p>-- <a href="http://docs.python.org/library/sys.html#sys.path">http://docs.python.org/library/sys.html#sys.path</a></p>
28
2009-05-22T13:21:25Z
[ "python", "path", "sys" ]
Python's sys.path value
897,792
<p>Where is Python's sys.path initialized from?</p> <p><strong>UPD</strong>: Python is adding some paths before refering to PYTHONPATH:</p> <pre><code> &gt;&gt;&gt; import sys &gt;&gt;&gt; from pprint import pprint as p &gt;&gt;&gt; p(sys.path) ['', 'C:\\Python25\\lib\\site-packages\\setuptools-0....
54
2009-05-22T13:19:05Z
38,403,654
<p>Python really tries hard to intelligently set <a href="https://docs.python.org/2/library/sys.html#sys.path" rel="nofollow"><code>sys.path</code></a>. How it is set can get <a href="https://github.com/python/cpython/blob/master/Modules/getpath.c" rel="nofollow">really</a> <a href="https://github.com/python/cpython/bl...
7
2016-07-15T19:19:54Z
[ "python", "path", "sys" ]
Python equivalent of PHP's memory_get_usage()?
897,941
<p>I've already <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">found the following question</a>, but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external librari...
18
2009-05-22T13:49:41Z
897,965
<p>try <a href="http://guppy-pe.sourceforge.net/#Heapy" rel="nofollow">heapy</a></p>
2
2009-05-22T13:57:02Z
[ "python" ]
Python equivalent of PHP's memory_get_usage()?
897,941
<p>I've already <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">found the following question</a>, but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external librari...
18
2009-05-22T13:49:41Z
898,406
<p>A simple solution for Linux and other systems with <code>/proc/self/status</code> is the following code, which I use in a project of mine:</p> <pre><code>def memory_usage(): """Memory usage of the current process in kilobytes.""" status = None result = {'peak': 0, 'rss': 0} try: # This will ...
23
2009-05-22T15:14:38Z
[ "python" ]
Python equivalent of PHP's memory_get_usage()?
897,941
<p>I've already <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">found the following question</a>, but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external librari...
18
2009-05-22T13:49:41Z
7,669,279
<p>You could also use the <code>getrusage()</code> function from the standard library module <code>resource</code>. The resulting object has the attribute <code>ru_maxrss</code>, which gives total memory usage for the calling process:</p> <pre><code>&gt;&gt;&gt; import resource &gt;&gt;&gt; resource.getrusage(resource...
15
2011-10-06T00:41:21Z
[ "python" ]
Python equivalent of PHP's memory_get_usage()?
897,941
<p>I've already <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">found the following question</a>, but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external librari...
18
2009-05-22T13:49:41Z
12,912,618
<p>Accepted answer rules, but it might be easier (and more portable) to use <a href="https://github.com/giampaolo/psutil" rel="nofollow">psutil</a>. It does the same and a lot more.</p> <p>UPDATE: <a href="http://packages.python.org/Pympler/muppy.html" rel="nofollow">muppy</a> is also very convenient (and much better ...
10
2012-10-16T10:26:49Z
[ "python" ]
File I/O in the Python 3 C API
898,136
<p>The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects.</p> <p>Before, in 2.X, you could use</p> <pre><code>PyObject* PyFile_FromString(char *filename, char *mode) </code></pre> <p>to create a Python file object, e.g:</p> <pre><code>PyObject *myFile = PyFile_FromString("test.txt"...
4
2009-05-22T14:23:39Z
898,160
<p><a href="http://docs.python.org/3.0/c-api/file.html" rel="nofollow">This page</a> claims the API is:</p> <pre><code>PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *newline, int closefd); </code></pre> <p>Not sure if that means it's not possible to have Python open the file from t...
3
2009-05-22T14:32:28Z
[ "python", "python-3.x", "python-c-api" ]
File I/O in the Python 3 C API
898,136
<p>The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects.</p> <p>Before, in 2.X, you could use</p> <pre><code>PyObject* PyFile_FromString(char *filename, char *mode) </code></pre> <p>to create a Python file object, e.g:</p> <pre><code>PyObject *myFile = PyFile_FromString("test.txt"...
4
2009-05-22T14:23:39Z
900,918
<p>You can do it the old(new?)-fashioned way, by just calling the io module.</p> <p>This code works, but it does no error checking. See the docs for explanation.</p> <pre><code>PyObject *ioMod, *openedFile; PyGILState_STATE gilState = PyGILState_Ensure(); ioMod = PyImport_ImportModule("io"); openedFile = PyObject...
5
2009-05-23T05:21:37Z
[ "python", "python-3.x", "python-c-api" ]
Convert list of lists to delimited string
898,391
<p>How do I do the following in Python 2.2 using built-in modules only?</p> <p>I have a list of lists like this:<br /> [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]</p> <p>And from it I'd like to produce a string representation of a table like this where the columns are delimited by tabs and the rows by ne...
5
2009-05-22T15:11:44Z
898,404
<p>Like this, perhaps:</p> <pre><code>lists = [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]] result = "\n".join("\t".join(map(str,l)) for l in lists) </code></pre> <p>This joins all the inner lists using tabs, and concatenates the resulting list of strings using newlines.</p> <p>It uses a feature called <a...
17
2009-05-22T15:13:44Z
[ "python" ]
Convert list of lists to delimited string
898,391
<p>How do I do the following in Python 2.2 using built-in modules only?</p> <p>I have a list of lists like this:<br /> [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]</p> <p>And from it I'd like to produce a string representation of a table like this where the columns are delimited by tabs and the rows by ne...
5
2009-05-22T15:11:44Z
898,411
<pre><code># rows contains the list of lists lines = [] for row in rows: lines.append('\t'.join(map(str, row))) result = '\n'.join(lines) </code></pre>
4
2009-05-22T15:15:39Z
[ "python" ]
Django shopping cart/basket solution (or should I DIM)?
898,426
<p>I'm about to build a site that has about half a dozen fairly similar products. They're all DVDs so they fit into a very "fixed" database very well. I was going to make a DVD model. Tag them up. All very simple. All very easy.</p> <p>But we need to be able to sell them. The current site outsources the whole purchasi...
1
2009-05-22T15:19:03Z
898,520
<p>There is an open source solution available: <a href="http://www.getlfs.com" rel="nofollow">http://www.getlfs.com</a><br /> I don't know if you could tweak it to suit you but it's based on the technologies you mention. The license is very liberal and it is heavily maintained.</p>
2
2009-05-22T15:36:26Z
[ "python", "django", "e-commerce", "shopping-cart" ]
Django shopping cart/basket solution (or should I DIM)?
898,426
<p>I'm about to build a site that has about half a dozen fairly similar products. They're all DVDs so they fit into a very "fixed" database very well. I was going to make a DVD model. Tag them up. All very simple. All very easy.</p> <p>But we need to be able to sell them. The current site outsources the whole purchasi...
1
2009-05-22T15:19:03Z
899,393
<p>Since you asked: if your needs are that limited, it does sound like a DIY situation to me. I don't see what's so fiddly about it; what complexity there is is all in the pricing formula, and you're planning to supply that either way. Add in Django's built-in session support and you're most of the way there.</p>
3
2009-05-22T18:46:41Z
[ "python", "django", "e-commerce", "shopping-cart" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
898,690
<p>are you in unix? if so, then try:</p> <pre><code>isBinary = os.system("file -b" + name + " | grep text &gt; /dev/null") </code></pre> <p>The shell return values are inverted (0 is ok, so if it finds "text" then it will return a 0, and in Python that is a False expression).</p>
1
2009-05-22T16:14:35Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
898,691
<p>Usually you have to guess.</p> <p>You can look at the extensions as one clue, if the files have them.</p> <p>You can also recognise know binary formats, and ignore those.</p> <p>Otherwise see what proportion of non-printable ASCII bytes you have and take a guess from that.</p> <p>You can also try decoding from U...
4
2009-05-22T16:14:44Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
898,723
<p>You can also use the mimetypes module:</p> <pre><code>import mimetypes ... mime = mimetypes.guess_type(file) </code></pre> <p>It's fairly easy to compile a list of binary mime types. For example Apache distributes with a mime.types file that you could parse into a set of lists, binary and text and then check to se...
25
2009-05-22T16:21:50Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
898,729
<p>If it helps, many many binary types begin with a magic numbers. <a href="http://www.garykessler.net/library/file%5Fsigs.html">Here is a list</a> of file signatures.</p>
8
2009-05-22T16:23:17Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
898,759
<p>Here's a suggestion that uses the Unix <a href="http://en.wikipedia.org/wiki/File%5F%28Unix%29">file</a> command:</p> <pre><code>import re import subprocess def istext(path): return (re.search(r':.* text', subprocess.Popen(["file", '-L', path], stdo...
5
2009-05-22T16:28:25Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
899,956
<p>If you're not on Windows, you can use <a href="http://pypi.python.org/pypi/python-magic/0.1" rel="nofollow">Python Magic</a> to determine the filetype. Then you can check if it is a text/ mime type.</p>
3
2009-05-22T20:55:56Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
3,002,505
<p>Try this:</p> <pre><code>def is_binary(filename): """Return true if the given filename is binary. @raise EnvironmentError: if the file does not exist or cannot be accessed. @attention: found @ http://bytes.com/topic/python/answers/21222-determine-file-type-binary-text on 6/08/2010 @author: Trent Mic...
9
2010-06-09T01:14:54Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
3,388,546
<p>I guess that the best solution is to use the guess_type function. It holds a list with several mimetypes and you can also include your own types. Here come the script that I did to solve my problem:</p> <pre><code>from mimetypes import guess_type from mimetypes import add_type def __init__(self): self.__ad...
1
2010-08-02T14:11:20Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
7,392,391
<p>Yet another method <a href="https://github.com/file/file/blob/f2a6e7cb7db9b5fd86100403df6b2f830c7f22ba/src/encoding.c#L151-L228">based on file(1) behavior</a>:</p> <pre><code>&gt;&gt;&gt; textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f}) &gt;&gt;&gt; is_binary_string = lambda bytes: bool...
34
2011-09-12T18:44:23Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
8,723,624
<p>I came here looking for exactly the same thing--a comprehensive solution provided by the standard library to detect binary or text. After reviewing the options people suggested, the nix <strong>file</strong> command looks to be the best choice (I'm only developing for linux boxen). Some others posted solutions using...
1
2012-01-04T07:51:21Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
11,301,631
<p>Shorter solution, with UTF-16 warning:</p> <pre><code>def is_binary(filename): """ Return true if the given filename appears to be binary. File is considered to be binary if it contains a NULL byte. FIXME: This approach incorrectly reports UTF-16 as binary. """ with open(filename, 'rb') as f...
3
2012-07-02T21:45:13Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
26,797,705
<p>Use <a href="https://pypi.python.org/pypi/binaryornot/" rel="nofollow">binaryornot</a> library (<a href="https://github.com/audreyr/binaryornot" rel="nofollow">GitHub</a>).</p> <p>It is very simple and based on the code found in this stackoverflow question.</p> <p>You can actually write this in 2 lines of code, ho...
3
2014-11-07T09:10:05Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
30,273,352
<p>If you're using python3 (and utf-8) it's quite straight forward, just open the file in text mode and stop processing if you get <code>UnicodeDecodeError</code>. Python3 will use unicode when handling file in text mode (and bytearray in binary mode) - if your encoding can't decode arbitrary files it's quite likely th...
0
2015-05-16T08:14:24Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
30,572,545
<p>Most of the programs consider the file to be binary (which is any file that is not "line-oriented") if they contains a <a href="https://en.wikipedia.org/wiki/Null_character" rel="nofollow">NULL character</a>.</p> <p>Here is perl's version of <code>pp_fttext()</code> (<code>pp_sys.c</code>) implemented in Python:</p...
-1
2015-06-01T11:39:45Z
[ "python", "file", "binary" ]
How can I detect if a file is binary (non-text) in python?
898,669
<p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p> <p>In the past I...
63
2009-05-22T16:09:50Z
30,580,748
<p>Simpler way is to check if the file consist NULL character (<code>\x00</code>) by using <code>in</code> operator, for instance:</p> <pre><code>b'\x00' in open("foo.bar", 'rb').read() </code></pre> <p>See below the complete example:</p> <pre><code>#!/usr/bin/env python3 import argparse if __name__ == '__main__': ...
-1
2015-06-01T18:35:59Z
[ "python", "file", "binary" ]
How do you set the text direction for a TextTable Cell in OpenOffice?
898,739
<p>I want to set the text direction for some cells in a TextTable so that they are vertical (i.e., the text is landscape instead of portrait). You can do this in Writer by selecting the cell(s), and going to: Table - Text Properties - Text Flow - Text Direction</p> <p>However, I cannot figure out how to do this throug...
1
2009-05-22T16:24:54Z
1,664,320
<p>I finally figured this out after all these months!</p> <p>You have to set the "WritingMode" property for the cell. In C#:</p> <pre><code>XCell cell = table.getCellByName(cellName); ((XPropertySet)cell).setPropertyValue("WritingMode", new Any((short) WritingMode.TB_RL)); </code></pre> <p>I haven't tried it in pyt...
0
2009-11-02T23:09:47Z
[ "c#", "python", "openoffice.org", "openoffice-writer", "uno" ]
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically?
898,773
<p>Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this:</p> <blockquote> <p>[{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]</p> </blockquote> <p>And I want it sorted alphabetical...
3
2009-05-22T16:33:27Z
898,790
<p>Use the <a href="http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys" rel="nofollow">key</a> parameter of sort or sorted.</p> <p>For example:</p> <pre><code>dicts = [ {'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20} ] def total_last(d): if ...
0
2009-05-22T16:38:08Z
[ "python", "list", "sorting", "dictionary" ]
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically?
898,773
<p>Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this:</p> <blockquote> <p>[{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]</p> </blockquote> <p>And I want it sorted alphabetical...
3
2009-05-22T16:33:27Z
898,791
<p>The best approach here is to decorate the sort key... Python will sort a tuple by the tuple components in order, so build a tuple key with your sorting criteria:</p> <pre><code>sorted(list_of_dicts, key=lambda d: (d['Name'] == 'TOTAL', d['Name'].lower())) </code></pre> <p>This results in a sort key of:</p> <ul> <...
10
2009-05-22T16:38:18Z
[ "python", "list", "sorting", "dictionary" ]
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically?
898,773
<p>Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this:</p> <blockquote> <p>[{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]</p> </blockquote> <p>And I want it sorted alphabetical...
3
2009-05-22T16:33:27Z
898,796
<pre><code>&gt;&gt;&gt; lst = [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}] &gt;&gt;&gt; lst.sort(key=lambda d: (d['Name']=='TOTAL',d['Name'].lower())) &gt;&gt;&gt; print lst [{'Name': 'ABC Company', 'Rank': 20}, {'Name': 'Woo Company', 'Rank': 15}, {'Name': 'TOTAL...
1
2009-05-22T16:39:07Z
[ "python", "list", "sorting", "dictionary" ]
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically?
898,773
<p>Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this:</p> <blockquote> <p>[{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]</p> </blockquote> <p>And I want it sorted alphabetical...
3
2009-05-22T16:33:27Z
898,798
<p>Well, I would sort it in multiple passes, using list's sort method.</p> <pre><code>list = [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}] list.sort(key = lambda x: x['Name']) # Sorted by Name, alphabetically list.sort(key = lambda x: 'b' if x['Name'] == 'TOTAL'...
-1
2009-05-22T16:39:27Z
[ "python", "list", "sorting", "dictionary" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
899,106
<p>You should use mocking, as someday You might want to change Your logger to a, say, database one. You won't be happy if it'll try to connect to the database during nosetests.</p> <p>Mocking will continue to work even if standard output will be suppressed.</p> <p>I have used <a href="http://code.google.com/p/pymox/w...
1
2009-05-22T17:52:39Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
899,109
<p>Found <a href="http://www.fubar.si/2009/3/4/mocking-logging-python-module-for-unittests" rel="nofollow">one answer</a> since I posted this. Not bad.</p>
0
2009-05-22T17:52:55Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
900,340
<p>As a follow up to Reef's answer, I took a liberty of coding up an example using <a href="http://code.google.com/p/pymox/" rel="nofollow">pymox</a>. It introduces some extra helper functions that make it easier to stub functions and methods.</p> <pre><code>import logging # Code under test: class Server(object): ...
3
2009-05-22T22:57:26Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
1,049,375
<p>I used to mock loggers, but in this situation I found best to use logging handlers, so I wrote this one based on <a href="http://www.fubar.si/2009/3/4/mocking-logging-python-module-for-unittests">the document suggested by jkp</a>:</p> <pre><code>class MockLoggingHandler(logging.Handler): """Mock logging handler...
15
2009-06-26T14:13:44Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
14,666,268
<p>Fortunately this is not something that you have to write yourself; the <code>testfixtures</code> package provides a context manager that captures all logging output that occurs in the body of the <code>with</code> statement. You can find the package here:</p> <p><a href="http://pypi.python.org/pypi/testfixtures">ht...
18
2013-02-02T20:36:27Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
20,553,331
<p>This answer extends the work done in <a href="http://stackoverflow.com/a/1049375/1286628">http://stackoverflow.com/a/1049375/1286628</a>. The handler is largely the same (the constructor is more idiomatic, using <code>super</code>, and <code>emit</code> is now thread safe for testing asynchronous code such as Celery...
11
2013-12-12T20:15:41Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
27,272,467
<p>The <code>ExpectLog</code> class implemented in tornado is a great utility:</p> <pre><code>with ExpectLog('channel', 'message regex'): do_it() </code></pre> <p><a href="http://tornado.readthedocs.org/en/latest/_modules/tornado/testing.html#ExpectLog" rel="nofollow">http://tornado.readthedocs.org/en/latest/_mod...
0
2014-12-03T13:03:35Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
28,306,238
<p>Brandon's answer:</p> <pre><code>pip install testfixtures </code></pre> <p>snippet:</p> <pre><code>import logging from testfixtures import LogCapture logger = logging.getLogger('') with LogCapture() as logs: # my awesome code logger.error('My code logged an error') assert 'My code logged an error' in st...
5
2015-02-03T18:33:46Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
34,734,362
<p>Keying off @Reef's answer, I did tried the code below. It works well for me both for Python 2.7 (if you install <a href="https://pypi.python.org/pypi/mock" rel="nofollow">mock</a>) and for Python 3.4.</p> <pre><code>""" Demo using a mock to test logging output. """ import logging try: import unittest except Im...
0
2016-01-12T01:54:46Z
[ "python", "unit-testing", "mocking", "nose" ]
How should I verify a log message when testing Python code under nose?
899,067
<p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p> <p>I know that nose already captures logging output through it's logging plugin, b...
19
2009-05-22T17:42:46Z
34,920,727
<p>From python 3.4 on, the standard <em>unittest</em> library offers a new test assertion context manager, <code>assertLogs</code>. From the <a href="https://docs.python.org/3.4/library/unittest.html#unittest.TestCase.assertLogs">docs</a>:</p> <pre><code>with self.assertLogs('foo', level='INFO') as cm: logging.get...
5
2016-01-21T10:08:28Z
[ "python", "unit-testing", "mocking", "nose" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
899,149
<p>The best way is:</p> <pre><code>outfile.write("\n".join(itemlist)) </code></pre>
115
2009-05-22T17:58:40Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
899,176
<blockquote> <p><strong>EDIT</strong> Adding info from <a href="http://stackoverflow.com/users/306312/thomas">Thomas</a>' comment</p> <p>Don't forget to open the file first</p> <p>thefile = open('test.txt', 'w')</p> </blockquote> <p>I'd use a loop:</p> <pre><code>for item in thelist: thefile.write("%s\n...
313
2009-05-22T18:04:21Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
899,199
<p>What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements, or are you just trying to serialize a list to disk for later use by the same python app. If the second case is it, you should be <a href="http://docs.python.org/library/pickle.html">...
130
2009-05-22T18:10:04Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
899,254
<p>Yet another way. Serialize to json using <a href="http://code.google.com/p/simplejson/">simplejson</a> (included as <a href="http://docs.python.org/library/json.html">json</a> in python 2.6):</p> <pre><code>&gt;&gt;&gt; import simplejson &gt;&gt;&gt; f = open('output.txt', 'w') &gt;&gt;&gt; simplejson.dump([1,2,3,...
46
2009-05-22T18:20:19Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
899,301
<pre><code>file.write('\n'.join(list)) </code></pre>
8
2009-05-22T18:29:47Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
5,032,851
<p>I thought it would be interesting to explore the benefits of using a genexp, so here's my take.</p> <p>The example in the question uses square brackets to create a temporary list, and so is equivalent to:</p> <pre><code>file.writelines( list( "%s\n" % item for item in list ) ) </code></pre> <p>Which needlessly co...
21
2011-02-17T18:13:19Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
5,787,168
<p>Let avg be the list, then:</p> <pre><code>In [29]: a = n.array((avg)) In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f') </code></pre> <p>You can use <code>%e</code> or <code>%s</code> depending on your requirement.</p>
-1
2011-04-26T07:16:32Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
6,791,534
<p>Using <strong>Python 3</strong> syntax:</p> <pre><code>with open(filepath, 'w') as file_handler: for item in the_list: file_handler.write("{}\n".format(item)) </code></pre> <p>This is platform-independent.</p>
28
2011-07-22T14:30:50Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
16,452,689
<h1>In General</h1> <p>Following is the syntax for <strong>writelines()</strong> method</p> <pre><code>fileObject.writelines( sequence ) </code></pre> <h1>Example</h1> <pre><code>#!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") seq = ["This is 6th line\n", "This is 7th line"] # Write sequence of lines ...
10
2013-05-09T01:01:40Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
17,638,623
<pre><code>poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' f = open('poem.txt', 'w') # open for 'w'riting f.write(poem) # write text to file f.close() # close the file </code></pre> <p>How It Works: First, open a file by using the built-in open function and s...
-1
2013-07-14T10:37:44Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
32,107,439
<p>Why don't you try</p> <pre><code>file.write(str(list)) </code></pre>
0
2015-08-19T23:47:34Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
32,508,983
<pre><code>with open ("test.txt","w")as fp: for line in list12: fp.write(line+"\n") </code></pre>
4
2015-09-10T18:14:57Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
32,876,198
<p>You can also use the print function if you're on python3 as follows.</p> <pre><code>f = open("myfile.txt","wb") print(mylist, file=f) </code></pre>
4
2015-09-30T21:50:24Z
[ "python", "file", "list", "file-io", "newline" ]
Writing a list to a file with Python
899,103
<p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p> <pre><code>file.writelines(["%s\n" % item for item in list]) </code></pre> <p>It seems like there would be a standard way...</p>
214
2009-05-22T17:52:18Z
33,775,428
<p>Serialize list into text file with comma sepparated value</p> <pre><code>mylist = dir() with open('filename.txt','w') as f: f.write( ','.join( mylist ) ) </code></pre>
5
2015-11-18T08:51:01Z
[ "python", "file", "list", "file-io", "newline" ]
Python-like list comprehension in Java
899,138
<p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p> <p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and ...
42
2009-05-22T17:57:13Z
899,165
<p>The <a href="http://code.google.com/p/google-collections/">Google Collections library</a> has lots of classes for working with collections and iterators at a much higher level than plain Java supports, and in a functional manner (filter, map, fold, etc.). It defines Function and Predicate interfaces and methods that...
15
2009-05-22T18:02:12Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
Python-like list comprehension in Java
899,138
<p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p> <p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and ...
42
2009-05-22T17:57:13Z
899,172
<p>Basically, you create a Function interface:</p> <pre><code>public interface Func&lt;In, Out&gt; { public Out apply(In in); } </code></pre> <p>and then pass in an anonymous subclass to your method.</p> <p>Your method could either apply the function to each element in-place:</p> <pre><code>public static &lt;T&...
31
2009-05-22T18:03:05Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
Python-like list comprehension in Java
899,138
<p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p> <p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and ...
42
2009-05-22T17:57:13Z
899,429
<p>Apache Commons <a href="http://commons.apache.org/collections/api-release/org/apache/commons/collections/CollectionUtils.html#transform%28java.util.Collection,%20org.apache.commons.collections.Transformer%29" rel="nofollow">CollectionsUtil.transform(Collection, Transformer)</a> is another option.</p>
5
2009-05-22T18:54:46Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
Python-like list comprehension in Java
899,138
<p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p> <p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and ...
42
2009-05-22T17:57:13Z
16,732,216
<p>In Java 8 you can use method references:</p> <pre><code>List&lt;String&gt; list = ...; list.replaceAll(String::toUpperCase); </code></pre> <p>Or, if you want to create a new list instance:</p> <pre><code>List&lt;String&gt; upper = list.stream().map(String::toUpperCase).collect(Collectors.toList()); </code></pre>
9
2013-05-24T09:52:55Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
Python-like list comprehension in Java
899,138
<p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p> <p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and ...
42
2009-05-22T17:57:13Z
30,923,596
<p>I'm building this project to write list comprehension in Java, now is a proof of concept in <a href="https://github.com/farolfo/list-comprehension-in-java" rel="nofollow">https://github.com/farolfo/list-comprehension-in-java</a></p> <p>Examples</p> <pre><code>// { x | x E {1,2,3,4} ^ x is even } // gives {2,4} Pr...
1
2015-06-18T18:58:19Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
Python-like list comprehension in Java
899,138
<p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p> <p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and ...
42
2009-05-22T17:57:13Z
39,101,269
<p>You can use lambdas for the function, like so:</p> <pre><code>class Comprehension&lt;T&gt; { /** *in: List int *func: Function to do to each entry */ public List&lt;T&gt; comp(List&lt;T&gt; in, Function&lt;T, T&gt; func) { List&lt;T&gt; out = new ArrayList&lt;T&gt;(); for(T o: in...
0
2016-08-23T12:29:58Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
How to find a file upwardly in Python?
899,273
<p>What is the best way to find a file "upwardly" in Python? (Ideally it would work on Windows too). E.g.,</p> <pre><code>&gt;&gt;&gt; os.makedirs('/tmp/foo/bar/baz/qux') &gt;&gt;&gt; open('/tmp/foo/findme.txt', 'w').close() &gt;&gt;&gt; os.chdir('/tmp/foo/bar/baz/qux') &gt;&gt;&gt; findup('findme.txt') '/tmp/foo/fi...
2
2009-05-22T18:23:48Z
899,297
<p>The module os.path has what you need, in particular: abspath() (if the path is not absolute), dirname(), isfile(), and join().</p> <pre><code>dir = os.path.curdir() filename = None while True: filename = os.path.join(dir, 'filename') if os.path.isfile(filename): break updir = os.path.dirname(dir...
1
2009-05-22T18:28:23Z
[ "python" ]
How to find a file upwardly in Python?
899,273
<p>What is the best way to find a file "upwardly" in Python? (Ideally it would work on Windows too). E.g.,</p> <pre><code>&gt;&gt;&gt; os.makedirs('/tmp/foo/bar/baz/qux') &gt;&gt;&gt; open('/tmp/foo/findme.txt', 'w').close() &gt;&gt;&gt; os.chdir('/tmp/foo/bar/baz/qux') &gt;&gt;&gt; findup('findme.txt') '/tmp/foo/fi...
2
2009-05-22T18:23:48Z
899,616
<pre><code>import os def findup(filename): drive, thisdir = os.path.splitdrive(os.getcwd()) while True: fullpath = os.path.join(drive, thisdir, filename) if os.path.isfile(fullpath): return fullpath if thisdir == os.path.sep: #root dir raise LookupError('file not...
4
2009-05-22T19:33:25Z
[ "python" ]
How to find a file upwardly in Python?
899,273
<p>What is the best way to find a file "upwardly" in Python? (Ideally it would work on Windows too). E.g.,</p> <pre><code>&gt;&gt;&gt; os.makedirs('/tmp/foo/bar/baz/qux') &gt;&gt;&gt; open('/tmp/foo/findme.txt', 'w').close() &gt;&gt;&gt; os.chdir('/tmp/foo/bar/baz/qux') &gt;&gt;&gt; findup('findme.txt') '/tmp/foo/fi...
2
2009-05-22T18:23:48Z
29,198,207
<p>I found myself in need of a findup function similar to the node.js version as well, opted for a recursive implementation:</p> <pre><code>import os def findup(filename, dir = os.getcwd()): def inner(drive, dir, filename): filepath = os.path.join(drive, dir, filename) if os.path.isfile(filepath):...
0
2015-03-22T18:31:45Z
[ "python" ]
Python, how to parse strings to look like sys.argv
899,276
<p>I would like to parse a string like this:</p> <pre><code>-o 1 --long "Some long string" </code></pre> <p>into this:</p> <pre><code>["-o", "1", "--long", 'Some long string'] </code></pre> <p>or similar.</p> <p>This is different than either getopt, or optparse, which <em>start</em> with sys.argv parsed input (...
24
2009-05-22T18:24:25Z
899,314
<p>I believe you want the <a href="http://docs.python.org/library/shlex.html">shlex</a> module.</p> <pre><code>&gt;&gt;&gt; import shlex &gt;&gt;&gt; shlex.split('-o 1 --long "Some long string"') ['-o', '1', '--long', 'Some long string'] </code></pre>
44
2009-05-22T18:33:07Z
[ "python", "parsing", "argv" ]
Python, how to parse strings to look like sys.argv
899,276
<p>I would like to parse a string like this:</p> <pre><code>-o 1 --long "Some long string" </code></pre> <p>into this:</p> <pre><code>["-o", "1", "--long", 'Some long string'] </code></pre> <p>or similar.</p> <p>This is different than either getopt, or optparse, which <em>start</em> with sys.argv parsed input (...
24
2009-05-22T18:24:25Z
16,532,488
<p>Before I was aware of <a href="http://docs.python.org/2/library/shlex.html#shlex.split" rel="nofollow"><code>shlex.split</code></a>, I made the following:</p> <pre><code>import sys _WORD_DIVIDERS = set((' ', '\t', '\r', '\n')) _QUOTE_CHARS_DICT = { '\\': '\\', ' ': ' ', '"': '"', 'r': '...
0
2013-05-13T22:55:23Z
[ "python", "parsing", "argv" ]
Bundling PyQwt with py2exe
899,658
<p>I have a standard setup script for py2exe with which I bundle PyQt-based applications into Windows .exe files.</p> <p>Today I tried a simple script that uses the PyQwt module, and it doesn't seem to work. py2exe runs alright, but when I execute the .exe it creates, it dumps the following into a log file and doesn't...
2
2009-05-22T19:46:12Z
931,562
<p>py2exe is not the only way, and maybe not the best way, to put together exe files for Python apps -- in particular, it hardly if at all supports pyqt. Please, I beseech you, check out <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a>, which DOES know about PyQt (and Linux, and Mac, should you care...
4
2009-05-31T07:30:49Z
[ "python", "pyqt", "py2exe" ]
Bundling PyQwt with py2exe
899,658
<p>I have a standard setup script for py2exe with which I bundle PyQt-based applications into Windows .exe files.</p> <p>Today I tried a simple script that uses the PyQwt module, and it doesn't seem to work. py2exe runs alright, but when I execute the .exe it creates, it dumps the following into a log file and doesn't...
2
2009-05-22T19:46:12Z
957,048
<p>Some options:</p> <ol> <li>Try playing with the py2xe <code>bundle_files options</code> (3, 2, 1) (especially if you put them all in one big library zip, some dlls don't like that).</li> <li>Make sure a copy of <code>msvcp71.dll</code> exists under windows\system32 or in the directory of your executable.</li> <li>T...
1
2009-06-05T17:16:14Z
[ "python", "pyqt", "py2exe" ]
Pad an integer using a regular expression
899,804
<p>I'm using regular expressions with a python framework to pad a specific number in a version number:</p> <p>10.2.11</p> <p>I want to transform the second element to be padded with a zero, so it looks like this:</p> <p>10.02.11</p> <p>My regular expression looks like this: </p> <pre><code>^(\d{2}\.)(\d{1})([\.].*...
1
2009-05-22T20:18:36Z
899,824
<p>Does your library support <a href="http://docs.python.org/howto/regex.html#non-capturing-and-named-groups" rel="nofollow">named groups</a>? That might solve your problem.</p>
0
2009-05-22T20:23:48Z
[ "python", "regex" ]
Pad an integer using a regular expression
899,804
<p>I'm using regular expressions with a python framework to pad a specific number in a version number:</p> <p>10.2.11</p> <p>I want to transform the second element to be padded with a zero, so it looks like this:</p> <p>10.02.11</p> <p>My regular expression looks like this: </p> <pre><code>^(\d{2}\.)(\d{1})([\.].*...
1
2009-05-22T20:18:36Z
899,826
<p>Try this:</p> <pre><code>(^\d(?=\.)|(?&lt;=\.)\d(?=\.)|(?&lt;=\.)\d$) </code></pre> <p>And replace the match by <code>0\1</code>. This will make any number at least two digits long.</p>
1
2009-05-22T20:24:13Z
[ "python", "regex" ]
Pad an integer using a regular expression
899,804
<p>I'm using regular expressions with a python framework to pad a specific number in a version number:</p> <p>10.2.11</p> <p>I want to transform the second element to be padded with a zero, so it looks like this:</p> <p>10.02.11</p> <p>My regular expression looks like this: </p> <pre><code>^(\d{2}\.)(\d{1})([\.].*...
1
2009-05-22T20:18:36Z
899,895
<p>What about removing the <code>.</code> from the regex?</p> <pre><code>^(\d{2})\.(\d{1})[\.](.*) </code></pre> <p>replace with:</p> <pre><code>\1.0\2.\3 </code></pre>
1
2009-05-22T20:40:34Z
[ "python", "regex" ]
Pad an integer using a regular expression
899,804
<p>I'm using regular expressions with a python framework to pad a specific number in a version number:</p> <p>10.2.11</p> <p>I want to transform the second element to be padded with a zero, so it looks like this:</p> <p>10.02.11</p> <p>My regular expression looks like this: </p> <pre><code>^(\d{2}\.)(\d{1})([\.].*...
1
2009-05-22T20:18:36Z
900,223
<p>How about a completely different approach?</p> <pre><code>nums = version_string.split('.') print ".".join("%02d" % int(n) for n in nums) </code></pre>
3
2009-05-22T22:16:14Z
[ "python", "regex" ]
pywikipedia name wikiquote is not defined?
900,306
<p>I'm writing a bot for Wikipedia but have a problem. When I want to get stuff from another Wikimedia site I get the error - error-name 'wikiquote' is not defined.</p> <p>This is when I start the code off like this-</p> <pre><code>import wikipedia site = wikiquote.getSite() </code></pre> <p>Yet if I was to start ...
1
2009-05-22T22:39:57Z
900,320
<p><code>wikiquote</code> is not defined or imported anywhere in your script. So it is understandable that your code does not work.</p> <p>According to <a href="http://meta.wikimedia.org/wiki/Wikipedia.py#Page%5Fclass.2C%5Fsite%5Fclass%5Fand%5Fwikipedia.stopme.28.29%5Ffunction" rel="nofollow">documentation of pywikipe...
2
2009-05-22T22:48:28Z
[ "python", "python-2.6", "pywikipedia" ]
pywikipedia name wikiquote is not defined?
900,306
<p>I'm writing a bot for Wikipedia but have a problem. When I want to get stuff from another Wikimedia site I get the error - error-name 'wikiquote' is not defined.</p> <p>This is when I start the code off like this-</p> <pre><code>import wikipedia site = wikiquote.getSite() </code></pre> <p>Yet if I was to start ...
1
2009-05-22T22:39:57Z
900,381
<p>If you're only running this for yourself, it doesn't matter, but pywikipedia bots should let the user control which site they're run against (and which account is used). Users specify these settings in the <code>user-config.py</code> file, as described <a href="http://meta.wikimedia.org/wiki/Using%5Fthe%5Fpython%5F...
0
2009-05-22T23:12:48Z
[ "python", "python-2.6", "pywikipedia" ]
Getting the caller function name inside another function in Python?
900,392
<p>If you have 2 functions like:</p> <pre><code>def A def B </code></pre> <p>and A calls B, can you get who is calling B inside B, like:</p> <pre><code>def A () : B () def B () : this.caller.name </code></pre>
57
2009-05-22T23:19:16Z
900,404
<p>You can use the <a href="http://docs.python.org/library/inspect.html">inspect</a> module to get the calling stack. It returns a list of frame records. The third element in each record is the caller name. What you want is this:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; def f(): ... print inspect.st...
75
2009-05-22T23:24:18Z
[ "python", "debugging" ]
Getting the caller function name inside another function in Python?
900,392
<p>If you have 2 functions like:</p> <pre><code>def A def B </code></pre> <p>and A calls B, can you get who is calling B inside B, like:</p> <pre><code>def A () : B () def B () : this.caller.name </code></pre>
57
2009-05-22T23:19:16Z
900,413
<p><code>sys._getframe(1).f_code.co_name</code> like in the example below:</p> <pre> >>> def foo(): ... global x ... x = sys._getframe(1) ... >>> def y(): foo() ... >>> y() >>> x.f_code.co_name 'y' >>> </pre>
6
2009-05-22T23:27:35Z
[ "python", "debugging" ]
Getting the caller function name inside another function in Python?
900,392
<p>If you have 2 functions like:</p> <pre><code>def A def B </code></pre> <p>and A calls B, can you get who is calling B inside B, like:</p> <pre><code>def A () : B () def B () : this.caller.name </code></pre>
57
2009-05-22T23:19:16Z
11,626,868
<p>you can user the logging module and specify the %(filename)s option in BaseConfig()</p> <pre><code>import logging logging.basicConfig(filename='/tmp/test.log', level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(funcName)s |%(message)s') def A(): logging.info('info') </code></pre>
2
2012-07-24T08:20:05Z
[ "python", "debugging" ]
Getting the caller function name inside another function in Python?
900,392
<p>If you have 2 functions like:</p> <pre><code>def A def B </code></pre> <p>and A calls B, can you get who is calling B inside B, like:</p> <pre><code>def A () : B () def B () : this.caller.name </code></pre>
57
2009-05-22T23:19:16Z
28,185,561
<p>There are two ways, using <code>sys</code> and <code>inspect</code> modules:</p> <ul> <li><code>sys._getframe(1).f_code.co_name</code></li> <li><code>inspect.stack()[1][3]</code></li> </ul> <p>The <code>stack()</code> form is less readable and is implementation dependent since it calls <code>sys._getframe()</code>...
6
2015-01-28T05:52:56Z
[ "python", "debugging" ]
Getting the caller function name inside another function in Python?
900,392
<p>If you have 2 functions like:</p> <pre><code>def A def B </code></pre> <p>and A calls B, can you get who is calling B inside B, like:</p> <pre><code>def A () : B () def B () : this.caller.name </code></pre>
57
2009-05-22T23:19:16Z
38,536,474
<p>This works for me! :D</p> <pre><code>&gt;&gt;&gt; def a(): ... import sys ... print sys._getframe(1).f_code.co_name ... &gt;&gt;&gt; def b(): ... a() ... ... &gt;&gt;&gt; b() b &gt;&gt;&gt; </code></pre>
1
2016-07-22T23:12:58Z
[ "python", "debugging" ]
Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents?
900,396
<p>Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces, </p> <pre><code>[('tupleValueA','tupleValueB'), 'someString', ('anotherTupleA','anotherTupleB')] </code></pre> <p>I want to read the lines in. Now I can read the...
0
2009-05-22T23:20:32Z
900,410
<p>What you are looking for is <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow">eval</a>. But please keep in mind that this function will evaluate and execute the lines. So don't run it on untrusted input ever!</p> <pre><code>&gt;&gt;&gt; print eval("[('tupleValueA', 1), 'someString']") [('t...
2
2009-05-22T23:26:54Z
[ "python", "string", "tuples" ]
Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents?
900,396
<p>Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces, </p> <pre><code>[('tupleValueA','tupleValueB'), 'someString', ('anotherTupleA','anotherTupleB')] </code></pre> <p>I want to read the lines in. Now I can read the...
0
2009-05-22T23:20:32Z
900,446
<p>The problem you describe is conventionally referred to as <a href="http://en.wikipedia.org/wiki/Serialization" rel="nofollow">serialization</a>. <a href="http://en.wikipedia.org/wiki/JSON" rel="nofollow">JavaScript Object Notation (JSON)</a> is one popular serialization protocol.</p>
0
2009-05-22T23:46:04Z
[ "python", "string", "tuples" ]
Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents?
900,396
<p>Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces, </p> <pre><code>[('tupleValueA','tupleValueB'), 'someString', ('anotherTupleA','anotherTupleB')] </code></pre> <p>I want to read the lines in. Now I can read the...
0
2009-05-22T23:20:32Z
900,464
<p>Probably it would be better to store the data with a module like <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a> in the first place, instead of using normal strings. This way you avoid a lot of problems that come with <code>eval</code> and get a more robust solution.</p>
0
2009-05-22T23:51:51Z
[ "python", "string", "tuples" ]
Elegant way to compare sequences
900,420
<p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p> <pre><code>def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return ...
9
2009-05-22T23:32:56Z
900,426
<p>Convert both sequences to lists, and use builtin list comparison. It should be sufficient, unless your sequences are really large.</p> <pre><code>list(a) == list(b) </code></pre> <p>Edit:</p> <p>Testing done by schickb shows that using tuples is slightly faster:</p> <pre><code>tuple(a) == tuple(b) </code></pre>
17
2009-05-22T23:36:48Z
[ "python" ]
Elegant way to compare sequences
900,420
<p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p> <pre><code>def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return ...
9
2009-05-22T23:32:56Z
900,444
<p>You can determine the equality of any two iterables (strings, tuples, lists, even custom sequences) without creating and storing duplicate lists by using the following:</p> <pre><code>all(x == y for x, y in itertools.izip_longest(a, b)) </code></pre> <p>Note that if the two iterables are not the same length, the s...
11
2009-05-22T23:45:37Z
[ "python" ]
Elegant way to compare sequences
900,420
<p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p> <pre><code>def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return ...
9
2009-05-22T23:32:56Z
900,488
<p>Since you put the word "equality" in quotes, I assume that you would like to know how the lists are the same and how the are different. Check out <strong>difflib</strong> which has a SequenceMatcher class:</p> <pre><code> sm = difflib.SequenceMatcher(None, a, b) for opcode in sm.get_opcodes(): print...
1
2009-05-23T00:03:33Z
[ "python" ]
Elegant way to compare sequences
900,420
<p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p> <pre><code>def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return ...
9
2009-05-22T23:32:56Z
900,490
<p>It's probably not as efficient, but it looks funky:</p> <pre><code>def cmpLists(a, b): return len(a) == len(b) and (False not in [a[i] == b[i] for i in range(0,len(a)]) </code></pre> <p>I don't know the "all" function that <a href="http://stackoverflow.com/questions/900420/elegant-way-to-compare-sequences/9004...
0
2009-05-23T00:05:15Z
[ "python" ]
Elegant way to compare sequences
900,420
<p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p> <pre><code>def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return ...
9
2009-05-22T23:32:56Z
900,533
<p>It looks like tuple(a) == tuple(b) is the best overall choice. Or perhaps tuple comparison with a preceding len check if they'll often be different lengths. This does create extra lists, but hopefully not an issue except for really huge lists. Here is my comparison of the various alternatives suggested:</p> <pre><c...
2
2009-05-23T00:34:34Z
[ "python" ]
Elegant way to compare sequences
900,420
<p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p> <pre><code>def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return ...
9
2009-05-22T23:32:56Z
903,677
<p>This "functional" code should be fast and generic enough for all purposes.</p> <pre><code># python 2.6 ≤ x &lt; 3.0 import operator, itertools as it def seq_cmp(seqa, seqb): return all(it.starmap(operator.eq, it.izip_longest(seqa, seqb))) </code></pre> <p>If on Python 2.5, use the definition for izip_longes...
0
2009-05-24T12:29:19Z
[ "python" ]
Elegant way to compare sequences
900,420
<p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p> <pre><code>def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return ...
9
2009-05-22T23:32:56Z
3,439,976
<p>Apart from the extra memory used by creating temporary lists/tuples, those answers will lose out to short circuiting generator solutions for large sequences when the inequality occurs early in the sequences</p> <pre><code>from itertools import starmap, izip from operator import eq all(starmap(eq, izip(x, y))) </cod...
4
2010-08-09T12:30:27Z
[ "python" ]
Elegant way to compare sequences
900,420
<p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p> <pre><code>def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return ...
9
2009-05-22T23:32:56Z
38,861,758
<p>I think it's a good idea to special case when both sequences are type <code>list</code>. Comparing two lists is faster (and more memory efficient) than converting both to tuples.</p> <p>In the case that either <code>a</code> or <code>b</code> are not lists, they are both converted to <code>tuple</code>. There is no...
0
2016-08-09T23:01:38Z
[ "python" ]
Understanding python imports
900,591
<p>In the process of learning Django and Python. I can't make sense of this.</p> <p>(Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.)</p> <pre><code>from helloworld.views import * # &lt;&lt;-- this works from helloworld import views # &lt;&lt;-- this doesn't work...
2
2009-05-23T01:04:11Z
900,611
<pre><code>from helloworld.views import * # &lt;&lt;-- this works from helloworld import views # &lt;&lt;-- this doesn't work from helloworld.app import views # &lt;&lt;-- but this works. why? </code></pre> <p>#2 and #3 are <em>not</em> the same.</p> <p>The second one imports <code>views</...
4
2009-05-23T01:18:24Z
[ "python", "django", "import" ]
Understanding python imports
900,591
<p>In the process of learning Django and Python. I can't make sense of this.</p> <p>(Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.)</p> <pre><code>from helloworld.views import * # &lt;&lt;-- this works from helloworld import views # &lt;&lt;-- this doesn't work...
2
2009-05-23T01:04:11Z
900,615
<p>As sykora alluded, helloworld is not in-and-of-itself a package, so #2 won't work. You would need a helloworld.py, appropriately set up.</p> <p>I asked about import a couple of days ago, this might help: <a href="http://stackoverflow.com/questions/860672/lay-out-import-pathing-in-python-straight-and-simple">http:/...
1
2009-05-23T01:21:44Z
[ "python", "django", "import" ]
Understanding python imports
900,591
<p>In the process of learning Django and Python. I can't make sense of this.</p> <p>(Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.)</p> <pre><code>from helloworld.views import * # &lt;&lt;-- this works from helloworld import views # &lt;&lt;-- this doesn't work...
2
2009-05-23T01:04:11Z
900,724
<p>Python imports can import two different kinds of things: modules and objects.</p> <pre><code>import x </code></pre> <p>Imports an entire module named <code>x</code>.</p> <pre><code>import x.y </code></pre> <p>Imports a module named <code>y</code> and it's container <code>x</code>. You refer to <code>x.y</code>....
7
2009-05-23T02:35:50Z
[ "python", "django", "import" ]
Need help with the class and instance concept in Python
900,929
<p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p> <p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat tr...
2
2009-05-23T05:32:13Z
900,940
<p>Your question is really rather broad as classes and instances/objects are vital parts of object-oriented programming, so this is not really Python specific. I recommend you buy some books on this as, while initially basic, it can get pretty in-depth. <a href="http://en.wikipedia.org/wiki/Class-based%5Fprogramming" r...
7
2009-05-23T05:40:03Z
[ "python" ]
Need help with the class and instance concept in Python
900,929
<p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p> <p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat tr...
2
2009-05-23T05:32:13Z
900,943
<p>In part it is confusing due to the dynamically typed nature of Python, which allows you to operate on a class and an instance in essentially the same way. In other languages, the difference is more concrete in that a class provides a template by which to create an object (instance) and cannot be as directly manipula...
0
2009-05-23T05:41:45Z
[ "python" ]
Need help with the class and instance concept in Python
900,929
<p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p> <p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat tr...
2
2009-05-23T05:32:13Z
900,948
<p>It's fairly simple actually. You know how in python they say "everything is an object". Well in simplistic terms you can think of any object as being an 'instance' and the instructions to create an object as the class. Or in biological terms DNA is the class and you are an instance of DNA.</p> <pre><code>class Huma...
2
2009-05-23T05:44:14Z
[ "python" ]
Need help with the class and instance concept in Python
900,929
<p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p> <p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat tr...
2
2009-05-23T05:32:13Z
900,953
<p>I am not sure of what level of knowledge you have, so I apologize if this answer is too simplified (then just ignore it).</p> <p>A class is a template for an object. Like a blueprint for a car. The instance of a class is like an actual car. So you have one blueprint, but you can have several different instances of ...
3
2009-05-23T05:46:44Z
[ "python" ]
Need help with the class and instance concept in Python
900,929
<p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p> <p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat tr...
2
2009-05-23T05:32:13Z
901,368
<p>See <a href="http://homepage.mac.com/s_lott/books/python/htmlchunks/ch21.html" rel="nofollow">http://homepage.mac.com/s_lott/books/python/htmlchunks/ch21.html</a></p> <blockquote> <p>Object-oriented programming permits us to organize our programs around the interactions of objects. A class provides the defi...
1
2009-05-23T11:29:44Z
[ "python" ]
Django not picking up changes to INSTALLED_APPS in settings.py
901,061
<p>I'm trying to get South to work - it worked fine on my PC, but I'm struggling to deploy it on my webhost.</p> <p>Right now it seems that any changes I make to add/remove items from INSTALLED_APPS aren't being picked up by <code>syncdb</code> or <code>diffsettings</code>. I've added <code>south</code> to my list of ...
2
2009-05-23T07:15:26Z
901,846
<p>If you write a migration for an application, syncdb wont work. You have to use </p> <pre><code>manage.py migrate </code></pre> <p>syncdb wont work for applications which are hooked under migration using south. Those applications model change will be noticed only depending on south migration history.</p> <p><a hre...
3
2009-05-23T16:22:33Z
[ "python", "django" ]