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 list |
|---|---|---|---|---|---|---|---|---|---|
how to get the function declaration or definitions using regex | 943,391 | <p>I want to get only function prototypes like</p>
<pre><code>int my_func(char, int, float)
void my_func1(void)
my_func2()
</code></pre>
<p>from C files using regex and python.</p>
<p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
| 4 | 2009-06-03T06:45:13Z | 943,429 | <p>This is a convenient script I wrote for such tasks but it wont give the function types. It's only for function names and the argument list.</p>
<pre><code># Exctract routine signatures from a C++ module
import re
def loadtxt(filename):
"Load text file into a string. I let FILE exceptions to pass."
f = open(filename)
txt = ''.join(f.readlines())
f.close()
return txt
# regex group1, name group2, arguments group3
rproc = r"((?<=[\s:~])(\w+)\s*\(([\w\s,<>\[\].=&':/*]*?)\)\s*(const)?\s*(?={))"
code = loadtxt('your file name here')
cppwords = ['if', 'while', 'do', 'for', 'switch']
procs = [(i.group(2), i.group(3)) for i in re.finditer(rproc, code) \
if i.group(2) not in cppwords]
for i in procs: print i[0] + '(' + i[1] + ')'
</code></pre>
| 6 | 2009-06-03T06:58:45Z | [
"python",
"regex"
] |
how to get the function declaration or definitions using regex | 943,391 | <p>I want to get only function prototypes like</p>
<pre><code>int my_func(char, int, float)
void my_func1(void)
my_func2()
</code></pre>
<p>from C files using regex and python.</p>
<p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
| 4 | 2009-06-03T06:45:13Z | 943,486 | <p>See if your C compiler has an option to output a file of just the prototypes of what it is compiling. For gcc, it's -aux-info FILENAME</p>
| 2 | 2009-06-03T07:23:46Z | [
"python",
"regex"
] |
how to get the function declaration or definitions using regex | 943,391 | <p>I want to get only function prototypes like</p>
<pre><code>int my_func(char, int, float)
void my_func1(void)
my_func2()
</code></pre>
<p>from C files using regex and python.</p>
<p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
| 4 | 2009-06-03T06:45:13Z | 943,520 | <p>I think regex isn't best solution in your case. There are many traps like comments, text in string etc., but if your function prototypes share common style:</p>
<pre><code>type fun_name(args);
</code></pre>
<p>then <code>\w+ \w+\(.*\);</code> should work in most cases:</p>
<pre><code>mn> egrep "\w+ \w+\(.*\);" *.h
md5.h:extern bool md5_hash(const void *buff, size_t len, char *hexsum);
md5file.h:int check_md5files(const char *filewithsums, const char *filemd5sum);
</code></pre>
| 0 | 2009-06-03T07:40:44Z | [
"python",
"regex"
] |
how to get the function declaration or definitions using regex | 943,391 | <p>I want to get only function prototypes like</p>
<pre><code>int my_func(char, int, float)
void my_func1(void)
my_func2()
</code></pre>
<p>from C files using regex and python.</p>
<p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
| 4 | 2009-06-03T06:45:13Z | 943,870 | <p>I think this one should do the work:</p>
<pre><code>r"^\s*[\w_][\w\d_]*\s*.*\s*[\w_][\w\d_]*\s*\(.*\)\s*$"
</code></pre>
<p>which will be expanded into:</p>
<pre><code>string begin:
^
any number of whitespaces (including none):
\s*
return type:
- start with letter or _:
[\w_]
- continue with any letter, digit or _:
[\w\d_]*
any number of whitespaces:
\s*
any number of any characters
(for allow pointers, arrays and so on,
could be replaced with more detailed checking):
.*
any number of whitespaces:
\s*
function name:
- start with letter or _:
[\w_]
- continue with any letter, digit or _:
[\w\d_]*
any number of whitespaces:
\s*
open arguments list:
\(
arguments (allow none):
.*
close arguments list:
\)
any number of whitespaces:
\s*
string end:
$
</code></pre>
<p>It's not totally correct for matching all possible combinations, but should work in more cases. If you want it to be more accurate, just let me know.</p>
<p>EDIT:
Disclaimer - I'm quite new to both Python and Regex, so please be indulgent ;)</p>
| 1 | 2009-06-03T09:44:56Z | [
"python",
"regex"
] |
how to get the function declaration or definitions using regex | 943,391 | <p>I want to get only function prototypes like</p>
<pre><code>int my_func(char, int, float)
void my_func1(void)
my_func2()
</code></pre>
<p>from C files using regex and python.</p>
<p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
| 4 | 2009-06-03T06:45:13Z | 944,421 | <p>There are LOTS of pitfalls trying to "parse" C code (or extract some information at least) with just regular expressions, I will definitely borrow a C for your favourite parser generator (say Bison or whatever alternative there is for Python, there are C grammar as examples everywhere) and add the actions in the corresponding rules.</p>
<p>Also, do not forget to run the C preprocessor on the file before parsing.</p>
| 1 | 2009-06-03T12:20:31Z | [
"python",
"regex"
] |
how to get the function declaration or definitions using regex | 943,391 | <p>I want to get only function prototypes like</p>
<pre><code>int my_func(char, int, float)
void my_func1(void)
my_func2()
</code></pre>
<p>from C files using regex and python.</p>
<p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
| 4 | 2009-06-03T06:45:13Z | 33,208,691 | <p>The regular expression below consider also the definition of destructor or const functions:</p>
<pre><code>^\s*\~{0,1}[\w_][\w\d_]*\s*.*\s*[\w_][\w\d_]*\s*\(.*\)\s*(const){0,1}$
</code></pre>
| 0 | 2015-10-19T07:19:21Z | [
"python",
"regex"
] |
how to get the function declaration or definitions using regex | 943,391 | <p>I want to get only function prototypes like</p>
<pre><code>int my_func(char, int, float)
void my_func1(void)
my_func2()
</code></pre>
<p>from C files using regex and python.</p>
<p>Here is my regex format: <code>".*\(.*|[\r\n]\)\n"</code></p>
| 4 | 2009-06-03T06:45:13Z | 36,995,949 | <p>I built on Nick Dandoulakis's <a href="http://stackoverflow.com/a/943429/724752">answer</a> for a similar use case. I wanted to find the definition of the <code>socket</code> function in glibc. This finds a bunch of functions with "socket" in the name but <code>socket</code> was not found, highlighting what many others have said: there are probably better ways to extract this information, like tools provided by compilers.</p>
<pre class="lang-py prettyprint-override"><code># find_functions.py
#
# Extract routine signatures from a C++ module
import re
import sys
def loadtxt(filename):
# Load text file into a string. Ignore FILE exceptions.
f = open(filename)
txt = ''.join(f.readlines())
f.close()
return txt
# regex group1, name group2, arguments group3
rproc = r"((?<=[\s:~])(\w+)\s*\(([\w\s,<>\[\].=&':/*]*?)\)\s*(const)?\s*(?={))"
file = sys.argv[1]
code = loadtxt(file)
cppwords = ['if', 'while', 'do', 'for', 'switch']
procs = [(i.group(1)) for i in re.finditer(rproc, code) \
if i.group(2) not in cppwords]
for i in procs: print file + ": " + i
</code></pre>
<p>Then</p>
<pre><code>$ cd glibc
$ find . -name "*.c" -print0 | xargs -0 -n 1 python find_functions.py | grep ':.*socket'
./hurd/hurdsock.c: _hurd_socket_server (int domain, int dead)
./manual/examples/mkfsock.c: make_named_socket (const char *filename)
./manual/examples/mkisock.c: make_socket (uint16_t port)
./nscd/connections.c: close_sockets (void)
./nscd/nscd.c: nscd_open_socket (void)
./nscd/nscd_helper.c: wait_on_socket (int sock, long int usectmo)
./nscd/nscd_helper.c: open_socket (request_type type, const char *key, size_t keylen)
./nscd/nscd_helper.c: __nscd_open_socket (const char *key, size_t keylen, request_type type,
./socket/socket.c: __socket (int domain, int type, int protocol)
./socket/socketpair.c: socketpair (int domain, int type, int protocol, int fds[2])
./sunrpc/key_call.c: key_call_socket (u_long proc, xdrproc_t xdr_arg, char *arg,
./sunrpc/pm_getport.c: __get_socket (struct sockaddr_in *saddr)
./sysdeps/mach/hurd/socket.c: __socket (int domain, int type, int protocol)
./sysdeps/mach/hurd/socketpair.c: __socketpair (int domain, int type, int protocol, int fds[2])
./sysdeps/unix/sysv/linux/socket.c: __socket (int fd, int type, int domain)
./sysdeps/unix/sysv/linux/socketpair.c: __socketpair (int domain, int type, int protocol, int sv[2])
</code></pre>
<p>In my case, <a href="http://stackoverflow.com/questions/8658747/socket-function-definition">this</a> and <a href="http://www.skyfree.org/linux/kernel_network/socket.html" rel="nofollow">this</a> might help me, except it seems like I will need to read assembly code to reuse the strategy described there.</p>
| 0 | 2016-05-03T05:02:17Z | [
"python",
"regex"
] |
Python: Getting file modification times with greater resolution than a second | 943,503 | <p><code>os.path.getmtime()</code> and <code>os.stat()</code> seem to return values in whole seconds only.</p>
<p>Is this the greatest resolution possible on either a Windows or OSX file system, or is there a way of getting greater resolution on file times?</p>
| 3 | 2009-06-03T07:32:36Z | 943,532 | <p><a href="http://docs.python.org/library/os.html#os.stat" rel="nofollow">The documentation for os.stat()</a> has a note that says:</p>
<blockquote>
<p>The exact meaning and resolution of
the st_atime, st_mtime, and st_ctime
members depends on the operating
system and the file system. For
example, on Windows systems using the
FAT or FAT32 file systems, st_mtime
has 2-second resolution, and st_atime
has only 1-day resolution. See your
operating system documentation for
details.</p>
</blockquote>
<p>On for instance <a href="http://msdn.microsoft.com/en-us/library/ms724284%28VS.85%29.aspx" rel="nofollow">Windows</a>, the FILETIME structure used to represent file times uses a 100-nanosecond resolution. I would expect Python to "know" this, and give you the best possible resolution. Is it possible that you're using files on a FAT filesystem?</p>
| 3 | 2009-06-03T07:44:30Z | [
"python",
"windows",
"osx",
"filesystems",
"timestamp"
] |
Python: Getting file modification times with greater resolution than a second | 943,503 | <p><code>os.path.getmtime()</code> and <code>os.stat()</code> seem to return values in whole seconds only.</p>
<p>Is this the greatest resolution possible on either a Windows or OSX file system, or is there a way of getting greater resolution on file times?</p>
| 3 | 2009-06-03T07:32:36Z | 943,537 | <p>HFS+ (used by OS X) has a date resolution of <a href="http://en.wikipedia.org/wiki/HFS%5FPlus" rel="nofollow">one second</a>.</p>
| 3 | 2009-06-03T07:46:47Z | [
"python",
"windows",
"osx",
"filesystems",
"timestamp"
] |
Python: Getting file modification times with greater resolution than a second | 943,503 | <p><code>os.path.getmtime()</code> and <code>os.stat()</code> seem to return values in whole seconds only.</p>
<p>Is this the greatest resolution possible on either a Windows or OSX file system, or is there a way of getting greater resolution on file times?</p>
| 3 | 2009-06-03T07:32:36Z | 943,563 | <p>As documented in <a href="http://docs.python.org/library/os" rel="nofollow">the Python <code>os</code> module</a>, it is a portable interface to OS-specific functionality. Depending on what platform you're running on, you will get different behaviour.</p>
<p>Specifically, the modification time returned by <code>stat</code> calls is dependent on the filesystem where the files reside. For example, for entries in a FAT filesystem, the finest resolution for modification time is 2 seconds. Other filesystems will have different resolutions.</p>
| 1 | 2009-06-03T07:55:03Z | [
"python",
"windows",
"osx",
"filesystems",
"timestamp"
] |
String manipulation in Cython | 943,809 | <p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p>
<p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff like that.)</p>
<p>I am currently looking into porting some of the code to <a href="http://www.cython.org/">Cython</a> after hearing many good things about it. However, it seems that the main focus of Cython is numerical calculations and working with strings is barely documented.</p>
<p>Unicode might also be a big issue. </p>
<p>My questions are:</p>
<ol>
<li>Should I even bother with Cython for string stuff? Does anyone have experience with this type of processing in cython and can share?</li>
<li>Am I missing something in the Cython docs? Does anyone know of a tutorial/reference/documentation about working with strings in Cython?</li>
</ol>
| 19 | 2009-06-03T09:19:23Z | 944,512 | <p>I voted up the 'profile it' answer, but wanted to add this: where possible the best optimisation you can make is to use Python standard libraries or built-in functions to perform the tasks you want. These are typically implemented in C and will provide performance broadly equivalent to any extension, including extensions written in Cython. If your algorithms are performing character by character loops in Python then those should be the first things to go, if possible.</p>
<p>But if you have algorithms that can't be reworked in terms of built-ins or other existing standard libraries, Cython seems like a reasonable approach. It just compiles pseudo-Python down to native code and is as suited to string operations as any other operation, really. But I'm not convinced you will see a great benefit from using Cython if you just hand it idiomatic Python code. The maximum benefit will come if you are able to rewrite some or all of each algorithm in C so that low-level operations are not constantly translating variables across the Python/C barrier.</p>
<p>Finally, Unicode - you've implied it might be 'a big issue' but haven't specified how you're using it. Cython will presumably produce C code that calls the relevant Python APIs that handle Unicode so the functionality is unlikely to be limited. However handling Unicode strings in C is non-trivial and may mean that the idea of rewriting some of your algorithms in C for better performance isn't worth the effort. A lot of classic string algorithms simply won't work on many Unicode encodings, which aren't 'strings' in the traditional sense of having 1 unit of storage per character.</p>
| 9 | 2009-06-03T12:41:38Z | [
"python",
"string",
"cython"
] |
String manipulation in Cython | 943,809 | <p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p>
<p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff like that.)</p>
<p>I am currently looking into porting some of the code to <a href="http://www.cython.org/">Cython</a> after hearing many good things about it. However, it seems that the main focus of Cython is numerical calculations and working with strings is barely documented.</p>
<p>Unicode might also be a big issue. </p>
<p>My questions are:</p>
<ol>
<li>Should I even bother with Cython for string stuff? Does anyone have experience with this type of processing in cython and can share?</li>
<li>Am I missing something in the Cython docs? Does anyone know of a tutorial/reference/documentation about working with strings in Cython?</li>
</ol>
| 19 | 2009-06-03T09:19:23Z | 1,560,811 | <p>This is a very interesting issue. Cython at its core is a tool to integrate python with C data types. It doesn't supply any functionality to assist in dealing with strings, probably because there isn't as much demand for that as there is for specific Numpy functionality.</p>
<p>Having said that, you could well use Cython to interface with existing C/C++ libraries designed to handle the types of problems you describe. For processing HTML/XML you might want to look into <a href="http://xmlsoft.org/" rel="nofollow">libxml</a> for example. However there are (of course) <a href="http://codespeak.net/lxml/" rel="nofollow">ready-made python bindings</a> already available for just that. I've used lxml extensively for processing HTML and it does all I need and does it <em>fast</em>, plus it handles unicode pretty well.</p>
<p>In your case I would imagine a combination of lxml and custom made C functions would be best. For example you could "easily" make a fast function for finding longest substrings in C, as that could be done at the byte level (recall that a string in C is just a char*, which is an array of bytes). Then you could map those back to python (which Cython will make real easy for you) and carry on in unicode abstracted heaven :). Certainly not trivial, but may be worth the effort if your app's performance relies on it.</p>
<p>Then there are of course nice (albeit non-trivial) approaches to working with unicode in C/C++. <a href="http://evanjones.ca/unicode-in-c.html" rel="nofollow">This article</a> by Evan Jones may help you decide if it's worth the effort.</p>
| 4 | 2009-10-13T15:02:17Z | [
"python",
"string",
"cython"
] |
String manipulation in Cython | 943,809 | <p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p>
<p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff like that.)</p>
<p>I am currently looking into porting some of the code to <a href="http://www.cython.org/">Cython</a> after hearing many good things about it. However, it seems that the main focus of Cython is numerical calculations and working with strings is barely documented.</p>
<p>Unicode might also be a big issue. </p>
<p>My questions are:</p>
<ol>
<li>Should I even bother with Cython for string stuff? Does anyone have experience with this type of processing in cython and can share?</li>
<li>Am I missing something in the Cython docs? Does anyone know of a tutorial/reference/documentation about working with strings in Cython?</li>
</ol>
| 19 | 2009-06-03T09:19:23Z | 1,803,176 | <p>Just for completeness, what I ended up doing is just write (some of) the string manipulation code in C.</p>
<p>As it turns out, it's <a href="http://en.wikibooks.org/wiki/Python%5FProgramming/Extending%5Fwith%5FC">ridiculously easy</a> to get started writing c extensions to python. Unicode strings are just arrays of Py_UNICODE, which is an int or a short depending on the python build.</p>
<p>I got a x20 improvement converting code like</p>
<pre><code>s = re.sub(r' +', ' ', s)
</code></pre>
<p>to c. I got similar improvements with more complicated regexps, but the c code becomes crazy complex very quickly.</p>
<p>Overall, my throughput went up 20% after the rewrite. I am now looking for more things to rewrite...</p>
| 5 | 2009-11-26T11:36:11Z | [
"python",
"string",
"cython"
] |
String manipulation in Cython | 943,809 | <p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p>
<p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff like that.)</p>
<p>I am currently looking into porting some of the code to <a href="http://www.cython.org/">Cython</a> after hearing many good things about it. However, it seems that the main focus of Cython is numerical calculations and working with strings is barely documented.</p>
<p>Unicode might also be a big issue. </p>
<p>My questions are:</p>
<ol>
<li>Should I even bother with Cython for string stuff? Does anyone have experience with this type of processing in cython and can share?</li>
<li>Am I missing something in the Cython docs? Does anyone know of a tutorial/reference/documentation about working with strings in Cython?</li>
</ol>
| 19 | 2009-06-03T09:19:23Z | 1,806,183 | <p>"Ridiculously easy" is a very relative term. "Getting started" is just that. Writing robust extensions in C requires very careful attention to things like reference counting, memory allocation/freeing, and error handling. Cython does much of that for you.</p>
<p>A non-unicode string in Cython is either a Python str object, or it's an array of char, as in C. What Cython-specific documentation do you think that you need?</p>
<p>I recommend that you try Cython for yourself. BUT before you do that, I strongly recommend that you examine your Python code for inefficiencies. Sometimes you can get big speedups ridiculously easily.</p>
<p>For example, compressing runs of space characters ... using</p>
<pre><code>re.sub(' +', ' ', s) # one space in pattern
</code></pre>
<p>means that in the presumably not uncommon case where a run has a length of 1, it will be replacing a space with a space. If all the runs have length 1, it will create a new replacement string when it could easily just increment (or not decrement, or whatever) the reference count of the input string and pass that back.</p>
<pre><code>re.sub(' +', ' ', s) # two spaces in pattern
</code></pre>
<p>produces exactly the same results and may run faster ... let's see:</p>
<p>All runs length 1: It runs at 3.4 times the speed. Not shown: the longer the input string, the better it gets.</p>
<pre><code>\python26\python -mtimeit -s"s='now is the winter of our discontent'; import re; x = re.compile(' +').sub" "x(' ', s)"
100000 loops, best of 3: 8.26 usec per loop
\python26\python -mtimeit -s"s='now is the winter of our discontent'; import re; x = re.compile(' +').sub" "x(' ', s)"
100000 loops, best of 3: 2.41 usec per loop
</code></pre>
<p>With one run having length 2, the speed ratio is 2.5. With all runs having length 2, the speed ratio is 1.2. All things considered, not a bad return on an investment of 1 keystroke.</p>
| 7 | 2009-11-26T23:57:05Z | [
"python",
"string",
"cython"
] |
String manipulation in Cython | 943,809 | <p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p>
<p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff like that.)</p>
<p>I am currently looking into porting some of the code to <a href="http://www.cython.org/">Cython</a> after hearing many good things about it. However, it seems that the main focus of Cython is numerical calculations and working with strings is barely documented.</p>
<p>Unicode might also be a big issue. </p>
<p>My questions are:</p>
<ol>
<li>Should I even bother with Cython for string stuff? Does anyone have experience with this type of processing in cython and can share?</li>
<li>Am I missing something in the Cython docs? Does anyone know of a tutorial/reference/documentation about working with strings in Cython?</li>
</ol>
| 19 | 2009-06-03T09:19:23Z | 5,687,072 | <p>Note that Cython actually has support for CPython's Py_UNICODE type, so, for example, you can directly iterate over unicode strings or compare characters at C speed. See</p>
<p><a href="http://docs.cython.org/src/tutorial/strings.html" rel="nofollow">http://docs.cython.org/src/tutorial/strings.html</a></p>
| 3 | 2011-04-16T14:15:20Z | [
"python",
"string",
"cython"
] |
String manipulation in Cython | 943,809 | <p>I have code that does some very CPU-intensive string manipulations and I was looking for ways to improve performance.</p>
<p>(EDIT: I'm doing stuff like finding longest common substring, running lots of regular expressions which might be better expressed as state machines in c, stripping comments from HTML, stuff like that.)</p>
<p>I am currently looking into porting some of the code to <a href="http://www.cython.org/">Cython</a> after hearing many good things about it. However, it seems that the main focus of Cython is numerical calculations and working with strings is barely documented.</p>
<p>Unicode might also be a big issue. </p>
<p>My questions are:</p>
<ol>
<li>Should I even bother with Cython for string stuff? Does anyone have experience with this type of processing in cython and can share?</li>
<li>Am I missing something in the Cython docs? Does anyone know of a tutorial/reference/documentation about working with strings in Cython?</li>
</ol>
| 19 | 2009-06-03T09:19:23Z | 9,335,037 | <p>I've been recently introduced to Cython and have had great success wrapping large C and C++ libraries for use in significant projects. Some of the generated Python extensions are in fact already running in our production environment. So, first off, Cython is, imo, definitely a good choice.</p>
<p>That being said, you should consider whether you really want to write all your code in Cython or whether you want to write C/C++ code and simply make those functions accessible from Cython. Obviously this will in part depend on your comfort level with C and/or C++.</p>
<p>As your working with Strings, you could probably make you life simpler by using <code>std::string</code> from C++ as opposed to <code>char*</code>. It can be imported into cython very easily with <code>from libcpp.string cimport string</code> then variables can be declared with the string type via the standard cython <code>cdef string ...</code></p>
| 2 | 2012-02-17T20:37:35Z | [
"python",
"string",
"cython"
] |
Connect to a running instance of Visual Studio 2003 using COM, build and read output | 943,863 | <p>For Visual Studio 6.0, I can connect to a running instance like:</p>
<pre><code>o = GetActiveObject("MSDev.Application")
</code></pre>
<ul>
<li>What prog ID do I use for Visual Studio 2003?</li>
<li>How do I execute a 'Build Solution' once I have the COM object that references the VS2003 instance?</li>
<li>How do I get the string contents of the build output window after executing the build solution command?</li>
</ul>
<p>Yes, I am aware that I can build a solution from the command line. But in this case, I need to connect to a running instance of Visual Studio.</p>
<p>EDIT: found and submitted an answer, see below.</p>
| 1 | 2009-06-03T09:43:16Z | 944,009 | <p>After a bit of research (mainly looking at EnvDTE docs), I found the solution to this myself:</p>
<p>To build current solution (code in Python):</p>
<pre><code>def build_active_solution(progid="VisualStudio.DTE.7.1"):
from win32com.client import GetActiveObject
dte = GetActiveObject(progid)
sb = dte.Solution.SolutionBuild
sb.Build(True)
output = dte.Windows['Output'].Object.ActivePane.TextDocument.Selection
output.SelectAll()
return output.Text
</code></pre>
| 2 | 2009-06-03T10:19:43Z | [
"python",
"visual-studio",
"com"
] |
pygtk gui freezes with pyjack thread | 944,161 | <p>I have a program that records audio from firewire device (FA-66) with Jack connection. The interface is created with pygtk and the recording with py-jack (<a href="http://sourceforge.net/projects/py-jack/" rel="nofollow">http://sourceforge.net/projects/py-jack/</a>). The recording is done in a different thread because the GUI must be used at the same time for viewing results from the audio.</p>
<p>The problem is that when I start the recording thread, the GUI becomes very slow to respond. I have gtk.gdk function start_threads() at the beginning of the main thread. If I've got it right, I don't need threads_enter() and threads_leave(), because the recording doesn't affect the GUI. Please correct if I'm wrong.</p>
<p>The function jack.process() records audio from three microphones. If I replace it, for example, with time.sleep(2), everything works ok.</p>
<p>What is the best way to create threading in this case? Why does the jack.process freeze the GUI? Does it take all the cpu time or something?
Samples of my code below:</p>
<p>soundrecorder.py:</p>
<pre><code>...
def start(self):
Thread(target=self._start).start()
def _start(self):
while self.eventhandler.record.isSet():
data = self._jackRecord(self.sample_length)
self.datahandler.queue.put(data)
def _jackRecord(self, length):
capture = Numeric.zeros((self.inputs, int(self.sample_rate * length)), 'f')
output = Numeric.zeros((self.inputs, self.buffer_size), 'f')
i = 0
while i < capture.shape[1] - self.buffer_size:
try:
jack.process(output, capture[:,i:i+self.buffer_size])
i += self.buffer_size
except:
pass
return capture
</code></pre>
<p>eventhandler.py:
recordStart() and recordStop() are simply callback functions that are called when start and stop buttons are pressed.</p>
<pre><code>...
def recordStart(self, widget, data=None):
if not self.record.isSet():
self.record.set()
self.soundrecorder = SoundRecorder(self, self.datahandler)
self.soundrecorder.connect()
self.soundrecorder.start()
def recordStop(self, widget, data=None):
if self.record.isSet():
self.record.clear()
del(self.soundrecorder)
</code></pre>
| 0 | 2009-06-03T11:06:56Z | 945,377 | <p>You misunderstand how threads work. </p>
<p>Threads don't help you in this case. </p>
<blockquote>
<p><em>"Then when one sample is recorded, it will be analyzed and the results are
shown in the GUI. At the same time the
next sample is already being
recorded."</em></p>
</blockquote>
<p><strong>WRONG</strong>. Threads don't do two things at the same time. In python there's a global lock that prevent two threads from running python code or touching python objects at the same time. And besides that, two things don't ever happen at the same time if you don't have two CPUs or cores. The threading mechanism just switches between them executing a fixed number of instructions of each at a time.</p>
<p>Threads also add a processing, memory and code complexibility overhead for <strong>no benefit</strong>. Python code using threads run <strong>slower</strong> and have <strong>lower performance</strong> than if it was single-threaded. There are only a few exceptions for this rule and your case is not one of them.</p>
<p>You probably want to rewrite your recording loop as a callback and integrate it with the GTK loop (you'll get better performance than using threads).</p>
<p>For that, use a <a href="http://pygtk.org/docs/pygobject/gobject-functions.html#function-gobject--idle-add" rel="nofollow"><code>gobject.idle_add</code></a> with a big priority.</p>
<p>If you want to run two things really at "the same time", using two processors/cores, you want to launch another process. Launch a process to collect data and transmit it via some inter-process communication mechanism to the other process that is analizing and plotting data. <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module can help you with that.</p>
| 2 | 2009-06-03T15:20:15Z | [
"python",
"multithreading",
"pygtk"
] |
Method that gets called on module deletion in Python | 944,336 | <p>Is there a method that I can add to my module, which will get called when destructing the class?</p>
<p>We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.</p>
<p>Was hoping there would be a <code>__del__</code> method either for modules or classes that don't have instances?</p>
| 4 | 2009-06-03T12:00:03Z | 944,354 | <p>Use the del method:</p>
<pre><code>class Foo:
def __init__(self):
print "constructor called."
def __del__(self):
print "destructor called."
</code></pre>
| -1 | 2009-06-03T12:04:26Z | [
"python",
"destructor",
"shutdown"
] |
Method that gets called on module deletion in Python | 944,336 | <p>Is there a method that I can add to my module, which will get called when destructing the class?</p>
<p>We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.</p>
<p>Was hoping there would be a <code>__del__</code> method either for modules or classes that don't have instances?</p>
| 4 | 2009-06-03T12:00:03Z | 944,358 | <p>The class destructor method you're looking for is <code>__del__</code>. There are some nuances to when it's called, and to how exceptions and subclassing should be handled in <code>__del__</code>, so be sure to read the <a href="http://docs.python.org/reference/datamodel.html#special-method-names" rel="nofollow">official docs</a>.</p>
<p>A quick note on terminology, too: in python a <code>module</code> is the file in which your code is located... a namespace, in essence. A single module can contain many classes, variables, and functions. The <code>__del__</code> method is located on the class, not on the module.</p>
| 0 | 2009-06-03T12:05:17Z | [
"python",
"destructor",
"shutdown"
] |
Method that gets called on module deletion in Python | 944,336 | <p>Is there a method that I can add to my module, which will get called when destructing the class?</p>
<p>We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.</p>
<p>Was hoping there would be a <code>__del__</code> method either for modules or classes that don't have instances?</p>
| 4 | 2009-06-03T12:00:03Z | 944,359 | <p>When destructing which class? I though you said module?</p>
<p>Your module lives until the interpreter stops. you can add something to run at that time using the "atexit" module:</p>
<pre><code>import atexit
atexit.register(myfunction)
</code></pre>
<p><hr /></p>
<p>EDIT: Based on your comments.</p>
<p>Since you don't want it as a destructor, my answer above is correct. Just def another function (or static method if you wish) and register it with the atexit:</p>
<pre><code>def close_database():
proceed_to_close()
import atexit
atexit.register(close_database)
</code></pre>
<p>Now a quick note on your definition.</p>
<p>You said the class doesn't have any instances. So why make it a class? Why not define the functions in the module level instead? modules are first-class objects, cached and imported only once...</p>
<p>Example, instead of defining <code>database.py</code>:</p>
<pre><code>class DataBase(object):
@staticmethod
def execute_some_query(query):
code_here()
some_code()
@staticmethod
def close_database():
proceed_to_close()
import atexit ; atexit.register(DataBase.close_database)
</code></pre>
<p>and using:</p>
<pre><code>from database import DataBase
DataBase.execute_some_query(query)
</code></pre>
<p>You could do this instead on <code>database.py</code>:</p>
<pre><code>def execute_some_query(query):
code_here()
some_code()
def close_database():
proceed_to_close()
import atexit ; atexit.register(close_database)
</code></pre>
<p>And use it like this:</p>
<pre><code>import database
database.execute_some_query(query)
</code></pre>
<p><hr /></p>
<p>Or better yet: Use <a href="http://www.sqlalchemy.org/">sqlalchemy</a> and avoid all this trouble of creating your own database interface.</p>
| 16 | 2009-06-03T12:05:17Z | [
"python",
"destructor",
"shutdown"
] |
Method that gets called on module deletion in Python | 944,336 | <p>Is there a method that I can add to my module, which will get called when destructing the class?</p>
<p>We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.</p>
<p>Was hoping there would be a <code>__del__</code> method either for modules or classes that don't have instances?</p>
| 4 | 2009-06-03T12:00:03Z | 15,322,774 | <p>Tested using bpython...</p>
<pre><code>>>> import atexit
>>> class Test( object ):
... @staticmethod
... def __cleanup__():
... print("cleanup")
... atexit.register(Test.__cleanup__)
...
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 6, in Test
NameError: name 'Test' is not defined
</code></pre>
| 0 | 2013-03-10T13:30:32Z | [
"python",
"destructor",
"shutdown"
] |
copy worksheet from one spreadsheet to another | 944,419 | <p>Is it possible to copy spreadsheets with gdata API or worksheets from one spreadsheet to other? For now i copy all cells from one worksheet to another. One cell per request. It is too slow. I read about "cell batch processing" and write this code:</p>
<pre>
<code>
src_key = 'rFQqEnFWuR6qoU2HEfdVuTw'; dst_key = 'rPCVJ80MHt7K2EVlXNqytLQ'
sheetcl = gdata.spreadsheet.service.SpreadsheetsService('x@gmail.com','p')
dcs = gdata.docs.service.DocsService('x@gmail.com', 'p')
src_worksheets = sheetcl.GetWorksheetsFeed(src_key)
dst_worksheets = sheetcl.GetWorksheetsFeed(dst_key)
for src_worksheet, dst_worksheet in zip(src_worksheets.entry, dst_worksheets.entry):
sheet_id = src_worksheet.id.text.split('/')[-1]
dst_sheet_id = dst_worksheet.id.text.split('/')[-1]
cells_feed = sheetcl.GetCellsFeed(src_key, sheet_id)
dst_cells_feed = sheetcl.GetCellsFeed(dst_key, dst_sheet_id)
for cell in cells_feed.entry:
dst_cells_feed.AddInsert(cell)
sheetcl.ExecuteBatch(dst_cells_feed, dst_cells_feed.GetBatchLink().href)
</code>
</pre>
<p>But it doesn't work. As I suppose reason is that each cell in inner loop has its id which consist of spreadsheet_id:</p>
<pre>
<code>
>>> cell.id.text
'http://spreadsheets.google.com/feeds/cells/rFQqEnFWuR6qoU2HEfdVuTw/default/private/full/R1C1'
>>>
</code>
</pre>
| 1 | 2009-06-03T12:20:22Z | 1,615,889 | <p>You probably should be using a <a href="http://code.google.com/apis/spreadsheets/data/1.0/developers%5Fguide%5Fpython.html#cellsQueryExample" rel="nofollow">cell range query</a> to get a whole row at a time, then <a href="http://code.google.com/apis/spreadsheets/data/1.0/developers%5Fguide%5Fpython.html#addRow" rel="nofollow">inserting rows</a> in the target spreadsheet.</p>
| 1 | 2009-10-23T21:05:02Z | [
"python",
"gdata-api",
"google-docs",
"gdata"
] |
Execution of a OS command from a Python daemon | 944,501 | <p>I've got a daemon.py with a callback. How should I make the handler function execute a OS command?</p>
| 0 | 2009-06-03T12:39:03Z | 944,508 | <p>when i learned Python some time ago, I used:</p>
<pre><code>import os
os.system('ls -lt')
</code></pre>
<p>but it seems like in Python 3.x, the recommended use is <a href="http://docs.python.org/library/commands.html" rel="nofollow">commands</a> or <a href="http://docs.python.org/library/os.html#os.popen" rel="nofollow">os.popen()</a></p>
| -2 | 2009-06-03T12:40:34Z | [
"python",
"bash",
"operating-system",
"command",
"handler"
] |
Efficient way of creating recursive paths Python | 944,536 | <p>Hi
I need a simple function to create a path in Python where the parent may or may not exist. </p>
<p>From python documentation os.makedirs will fail if one of the parents exists.</p>
<p>I have written the below method as which works by makes as many sub directories as necessary.</p>
<p>Does this look efficient?</p>
<pre><code>def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
</code></pre>
<p>Regards</p>
<p>Mark</p>
| 13 | 2009-06-03T12:46:07Z | 944,561 | <blockquote>
<p>"From python documentation <code>os.makedirs</code> will fail if one of the parents exists."</p>
</blockquote>
<p>No, <a href="http://docs.python.org/library/os.html#os.makedirs"><code>os.makedirs</code></a> will fail if the directory itself already exists. It won't fail if just any of the parent directories already exists.</p>
| 42 | 2009-06-03T12:50:37Z | [
"python",
"path",
"operating-system"
] |
Efficient way of creating recursive paths Python | 944,536 | <p>Hi
I need a simple function to create a path in Python where the parent may or may not exist. </p>
<p>From python documentation os.makedirs will fail if one of the parents exists.</p>
<p>I have written the below method as which works by makes as many sub directories as necessary.</p>
<p>Does this look efficient?</p>
<pre><code>def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
</code></pre>
<p>Regards</p>
<p>Mark</p>
| 13 | 2009-06-03T12:46:07Z | 7,016,628 | <p>Rough draft:</p>
<pre><code>import os
class Path(str):
"""
A helper class that allows easy contactenation
of path components, creation of directory trees,
amongst other things.
"""
@property
def isdir(self):
return os.path.isdir(self)
@property
def isfile(self):
return os.path.isfile(self)
def exists(self):
exists = False
if self.isfile:
try:
f = open(self)
f.close()
exists = True
except IOError:
exists = False
else:
return self.isdir
return exists
def mktree(self, dirname):
"""Create a directory tree in this directory."""
newdir = self + dirname
if newdir.exists():
return newdir
path = dirname.split('/') or [dirname]
current_path = self + path.pop(0)
while True:
try:
os.mkdir(current_path)
except OSError as e:
if not e.args[0] == 17:
raise e
current_path = current_path + path.pop(0)
continue
if len(path) == 0:
break
return current_path
def up(self):
"""
Return a new Path object set a the parent
directory of the current instance.
"""
return Path('/'.join(self.split('/')[:-1]))
def __repr__(self):
return "<Path: {0}>".format(self)
def __add__(x, y):
return Path(x.rstrip('/') + '/' + y.lstrip('/'))
</code></pre>
| 4 | 2011-08-10T19:30:17Z | [
"python",
"path",
"operating-system"
] |
Efficient way of creating recursive paths Python | 944,536 | <p>Hi
I need a simple function to create a path in Python where the parent may or may not exist. </p>
<p>From python documentation os.makedirs will fail if one of the parents exists.</p>
<p>I have written the below method as which works by makes as many sub directories as necessary.</p>
<p>Does this look efficient?</p>
<pre><code>def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
</code></pre>
<p>Regards</p>
<p>Mark</p>
| 13 | 2009-06-03T12:46:07Z | 13,183,555 | <p>Try this code, it checks if path exists till n sub directory level, and create directory if not exists.</p>
<pre><code>def pathtodir(path):
if not os.path.exists(path):
l=[]
p = "/"
l = path.split("/")
i = 1
while i < len(l):
p = p + l[i] + "/"
i = i + 1
if not os.path.exists(p):
os.mkdir(p, 0755)
</code></pre>
| 2 | 2012-11-01T18:46:58Z | [
"python",
"path",
"operating-system"
] |
Efficient way of creating recursive paths Python | 944,536 | <p>Hi
I need a simple function to create a path in Python where the parent may or may not exist. </p>
<p>From python documentation os.makedirs will fail if one of the parents exists.</p>
<p>I have written the below method as which works by makes as many sub directories as necessary.</p>
<p>Does this look efficient?</p>
<pre><code>def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
</code></pre>
<p>Regards</p>
<p>Mark</p>
| 13 | 2009-06-03T12:46:07Z | 21,349,806 | <p>Here's my take, which lets the system libraries do all the path-wrangling. Any errors other than the directory already existing are propagated.</p>
<pre><code>import os, errno
def ensure_dir(dirname):
"""
Ensure that a named directory exists; if it does not, attempt to create it.
"""
try:
os.makedirs(dirname)
except OSError, e:
if e.errno != errno.EEXIST:
raise
</code></pre>
| 12 | 2014-01-25T11:15:18Z | [
"python",
"path",
"operating-system"
] |
Efficient way of creating recursive paths Python | 944,536 | <p>Hi
I need a simple function to create a path in Python where the parent may or may not exist. </p>
<p>From python documentation os.makedirs will fail if one of the parents exists.</p>
<p>I have written the below method as which works by makes as many sub directories as necessary.</p>
<p>Does this look efficient?</p>
<pre><code>def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
</code></pre>
<p>Regards</p>
<p>Mark</p>
| 13 | 2009-06-03T12:46:07Z | 24,973,246 | <p>I found this question while researching a way to make simple directory trees inside of a project directory.</p>
<p>I am somewhat new to Python, and I struggle when data structures get too complex, i.e. nested. It is much easier on my brain's mental mapping to keep track of small lists of iterables, so I came up with two very basic defs to help me with directory tree creation.</p>
<p>The example takes four objects to create a tree: </p>
<ol>
<li>a root directory path = PROJECT_HOME</li>
<li>a home path = home (created if it doesn't exist, not overwritten)</li>
<li>an iterable of directory names that will go inside of home = branches (created inside of the home, not overwritten)</li>
<li>a dictionary of keyed iterables that map onto the branches = leaves (each value created inside of each mapped branch, not overwritten)</li>
<li><p>If any directory exists, it is not overwritten and the error passes silently.</p>
<pre><code>import os
from os.path import join as path_join
import errno
def make_node(node):
try:
os.makedirs(node)
except OSError, e:
if e.errno != errno.EEXIST:
raise
def create_tree(home, branches, leaves):
for branch in branches:
parent = path_join(home, branch)
make_node(parent)
children = leaves.get(branch, [])
for child in children:
child = os.path.join(parent, child)
make_node(child)
if __name__ == "__main__":
try: # create inside of PROJECT_HOME if it exists
PROJECT_HOME = os.environ['PROJECT_HOME']
except KeyError: # otherwise in user's home directory
PROJECT_HOME = os.expanduser('~')
home = os.path.join(PROJECT_HOME, 'test_directory_tree')
create_tree(home, branches=[], leaves={})
branches = (
'docs',
'scripts',
)
leaves = (
('rst', 'html', ),
('python', 'bash', )
)
leaves = dict(list(zip(branches, leaves)))
create_tree(home, branches, leaves)
python_home = os.path.join(home, 'scripts', 'python')
branches = (
'os',
'sys',
'text_processing',
)
leaves = {}
leaves = dict(list(zip(branches, leaves)))
create_tree(python_home, branches, leaves)
after_thought_home = os.path.join(home, 'docs', 'after_thought')
branches = (
'child_0',
'child_1',
)
leaves = (
('sub_0', 'sub_1'),
(),
)
leaves = dict(list(zip(branches, leaves)))
create_tree(after_thought_home, branches, leaves)
</code></pre></li>
</ol>
<p>The directory tree that this example creates looks like this:</p>
<pre><code> dev/test_directory_tree/
âââ docs
â  âââ after_thought
â  â  âââ child_0
â  â  â  âââ sub_0
â  â  â  âââ sub_1
â  â  âââ child_1
â  âââ html
â  âââ rst
âââ scripts
âââ bash
âââ python
âââ os
âââ sys
âââ text_processing
</code></pre>
| 1 | 2014-07-26T16:42:28Z | [
"python",
"path",
"operating-system"
] |
Efficient way of creating recursive paths Python | 944,536 | <p>Hi
I need a simple function to create a path in Python where the parent may or may not exist. </p>
<p>From python documentation os.makedirs will fail if one of the parents exists.</p>
<p>I have written the below method as which works by makes as many sub directories as necessary.</p>
<p>Does this look efficient?</p>
<pre><code>def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
</code></pre>
<p>Regards</p>
<p>Mark</p>
| 13 | 2009-06-03T12:46:07Z | 29,508,062 | <p>With python ( >=3.4.1 ) there is exist_ok parameter for os.makedirs.</p>
<blockquote>
<p>If exist_ok is False (the default), an OSError is raised if the target
directory already exists.</p>
</blockquote>
<p>So if you use like exist_ok=True there won't be any problem for Recursive directory creation.</p>
<blockquote>
<p>Note : exist_ok comes with python 3.2 on the other hand there was a bug
about raising exception even if you set to True. So try using python >=
3.4.1 ( fixed in that version )</p>
</blockquote>
| 2 | 2015-04-08T07:04:39Z | [
"python",
"path",
"operating-system"
] |
Efficient way of creating recursive paths Python | 944,536 | <p>Hi
I need a simple function to create a path in Python where the parent may or may not exist. </p>
<p>From python documentation os.makedirs will fail if one of the parents exists.</p>
<p>I have written the below method as which works by makes as many sub directories as necessary.</p>
<p>Does this look efficient?</p>
<pre><code>def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
</code></pre>
<p>Regards</p>
<p>Mark</p>
| 13 | 2009-06-03T12:46:07Z | 38,077,347 | <p><a href="https://gist.github.com/samuelsh/b837f8ab8b33c344f01128568dd12019" rel="nofollow">This code</a> will generate directory tree with given depth and width, using recursive function call:</p>
<pre><code>#!/usr/bin/python2.6
import sys
import os
def build_dir_tree(base, depth, width):
print("Call #%d" % depth)
if depth >= 0:
curr_depth = depth
depth -= 1
for i in xrange(width):
# first creating all folder at current depth
os.makedirs('%s/Dir_#%d_level_%d' % (base, i, curr_depth))
dirs = os.walk(base).next()[1]
for dir in dirs:
newbase = os.path.join(base,dir)
build_dir_tree(newbase, depth, width)
else:
return
if not sys.argv[1:]:
print('No base path given')
sys.exit(1)
print('path: %s, depth: %d, width: %d' % (sys.argv[1], int(sys.argv[2]), int(sys.argv[3])))
build_dir_tree(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
</code></pre>
| 0 | 2016-06-28T13:15:55Z | [
"python",
"path",
"operating-system"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 944,660 | <p>To be able to automatically throw an error when x become less than zero throughout the function. You can use <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors">class descriptors</a>. Here is an example:</p>
<pre><code>class LessThanZeroException(Exception):
pass
class variable(object):
def __init__(self, value=0):
self.__x = value
def __set__(self, obj, value):
if value < 0:
raise LessThanZeroException('x is less than zero')
self.__x = value
def __get__(self, obj, objType):
return self.__x
class MyClass(object):
x = variable()
>>> m = MyClass()
>>> m.x = 10
>>> m.x -= 20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my.py", line 7, in __set__
raise LessThanZeroException('x is less than zero')
LessThanZeroException: x is less than zero
</code></pre>
| 102 | 2009-06-03T13:12:18Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 944,661 | <p>The only thing that's really wrong with this approach is that it's hard to make a very descriptive exception using assert statements. If you're looking for the simpler syntax, remember you <em>can</em> also do something like this:</p>
<pre><code>class XLessThanZeroException(Exception):
pass
def CheckX(x):
if x < 0:
raise XLessThanZeroException()
def foo(x):
CheckX(x)
#do stuff here
</code></pre>
<p>Another problem is that using assert for normal condition-checking is that it makes it difficult to disable the debugging asserts using the -O flag.</p>
| 13 | 2009-06-03T13:12:25Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 945,135 | <p>Asserts should be used to test conditions that <em>should never happen</em>. The purpose is to crash early in the case of a corrupt program state.</p>
<p>Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes.</p>
<p><hr /></p>
<p>For example, if you're writing a function to read from a configuration file into a <code>dict</code>, improper formatting in the file should raise a <code>ConfigurationSyntaxError</code>, while you can <code>assert</code> that you're not about to return <code>None</code>.</p>
<p><hr /></p>
<p>In your example, if <code>x</code> is a value set via a user interface or from an external source, an exception is best.</p>
<p>If <code>x</code> is only set by your own code in the same program, go with an assertion.</p>
| 509 | 2009-06-03T14:34:29Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 1,838,411 | <p><strong>"assert" statements are removed when the compilation is optimized</strong>. So, yes, there are both performance and functional differences.</p>
<blockquote>
<p>The current code generator emits no code for an assert statement when optimization is requested at compile time. - <a href="http://docs.python.org/reference/simple_stmts.html#the-assert-statement">Python 2.6.4 Docs</a></p>
</blockquote>
<p>If you use <code>assert</code> to implement application functionality, then optimize the deployment to production, you will be plagued by "but-it-works-in-dev" defects.</p>
<p>See <a href="http://docs.python.org/using/cmdline.html?highlight=optimization%20options#envvar-PYTHONOPTIMIZE">PYTHONOPTIMIZE</a> and <a href="http://docs.python.org/using/cmdline.html?highlight=optimization%20options#miscellaneous-options">-O -OO</a></p>
| 242 | 2009-12-03T08:15:24Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 1,839,402 | <p>In addition to the other answers, asserts themselves throw exceptions, but only AssertionErrors. From a utilitarian standpoint, assertions aren't suitable for when you need fine grain control over which exceptions you catch.</p>
| 14 | 2009-12-03T11:37:29Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 7,759,918 | <p>There's a framework called JBoss <a href="http://www.jboss.org/drools" rel="nofollow">Drools</a> for java that does runtime monitoring to assert business rules, which answers the second part of your question. However, I am unsure if there is such a framework for python. </p>
| 2 | 2011-10-13T20:15:01Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 15,237,844 | <p>As has been said previously, assertions should be used when your code SHOULD NOT ever reach a point, meaning there is a bug there. Probably the most useful reason I can see to use an assertion is an invariant/pre/postcondition. These are something that must be true at the start or end of each iteration of a loop or a function.</p>
<p>For example, a recursive function (2 seperate functions so 1 handles bad input and the other handles bad code, cause it's hard to distinguish with recursion). This would make it obvious if I forgot to write the if statement, what had gone wrong.</p>
<pre><code>def SumToN(n):
if n <= 0:
raise ValueError, "N must be greater than or equal to 0"
else:
return RecursiveSum(n)
def RecursiveSum(n):
#precondition: n >= 0
assert(n >= 0)
if n == 0:
return 0
return RecursiveSum(n - 1) + n
#postcondition: returned sum of 1 to n
</code></pre>
<p>These loop invariants often can be represented with an assertion.</p>
| 5 | 2013-03-06T02:22:48Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 18,980,471 | <p>Assume you work on 200,000 lines of code with four colleagues Alice, Bernd, Carl, and Daphne.
They call your code, you call their code.</p>
<p>Then <code>assert</code> has <strong>four roles</strong>:</p>
<ol>
<li><p><strong>Inform Alice, Bernd, Carl, and Daphne what your code expects.</strong><br>
Assume you have a method that processes a list of tuples and the program logic can break if those tuples are not immutable:</p>
<pre><code>def mymethod(listOfTuples):
assert(all(type(tp)==tuple for tp in listOfTuples))
</code></pre>
<p>This is more trustworthy than equivalent information in the documentation
and much easier to maintain.</p></li>
<li><p><strong>Inform the computer what your code expects.</strong><br>
<code>assert</code> enforces proper behavior from the callers of your code.
If your code calls Alices's and Bernd's code calls yours,
then without the <code>assert</code>, if the program crashes in Alices code,
Bernd might assume it was Alice's fault,
Alice investigates and might assume it was your fault,
you investigate and tell Bernd it was in fact his.
Lots of work lost.<br>
With asserts, whoever gets a call wrong, they will quickly be able to see it was
their fault, not yours. Alice, Bernd, and you all benefit.
Saves immense amounts of time.</p></li>
<li><p><strong>Inform the readers of your code (including yourself) what your code has achieved at some point.</strong><br>
Assume you have a list of entries and each of them can be clean (which is good)
or it can be smorsh, trale, gullup, or twinkled (which are all not acceptable).
If it's smorsh it must be unsmorshed; if it's trale it must be baludoed;
if it's gullup it must be trotted (and then possibly paced, too);
if it's twinkled it must be twinkled again except on Thursdays.
You get the idea: It's complicated stuff.
But the end result is (or ought to be) that all entries are clean.
The Right Thing(TM) to do is to summarize the effect of your
cleaning loop as</p>
<pre><code>assert(all(entry.isClean() for entry in mylist))
</code></pre>
<p>This statements saves a headache for everybody trying to understand
what <em>exactly</em> it is that the wonderful loop is achieving.
And the most frequent of these people will likely be yourself.</p></li>
<li><p><strong>Inform the computer what your code has achieved at some point.</strong><br>
Should you ever forget to pace an entry needing it after trotting,
the <code>assert</code> will save your day and avoid that your code
breaks dear Daphne's much later.</p></li>
</ol>
<p>In my mind, <code>assert</code>'s two purposes of documentation (1 and 3) and
safeguard (2 and 4) are equally valuable.<br>
Informing the people may even be <em>more</em> valuable than informing the computer
because it can prevent the very mistakes the <code>assert</code> aims to catch (in case 1)
and plenty of subsequent mistakes in any case.</p>
| 76 | 2013-09-24T11:33:18Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 18,980,730 | <p>As for "<em>Is there a performance issue</em>?":<br></p>
<ul>
<li><p>Please remember to <em>"make it work first before you make it work fast"</em>.<br>
Very few percent of any program are usually relevant for its speed.
You can always kick out or simplify an <code>assert</code> if it ever proves to
be a performance problem -- and most of them never will.</p></li>
<li><p>Be pragmatic:<br>
Assume you have a method that processes a non-empty list of tuples and the program logic will break if those tuples are not immutable. You should write:</p>
<pre><code>def mymethod(listOfTuples):
assert(all(type(tp)==tuple for tp in listOfTuples))
</code></pre>
<p>This is probably fine if your lists tend to be ten entries long, but
it can become a problem if they have a million entries.
But rather than discarding this valuable check entirely you could
simply downgrade it to</p>
<pre><code>def mymethod(listOfTuples):
assert(type(listOfTuples[0])==tuple) # in fact _all_ must be tuples!
</code></pre>
<p>which is cheap but will likely catch 97% of the actual program errors anyway.</p></li>
</ul>
| 2 | 2013-09-24T11:45:09Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 29,521,626 | <p>In IDE's such as PTVS, PyCharm, Wing <code>assert isinstance()</code> statements can be used to enable code completion for some unclear objects.</p>
| 3 | 2015-04-08T17:40:32Z | [
"python",
"assert",
"raise"
] |
Best practice for Python Assert | 944,592 | <ol>
<li><p>Is there a performance or code maintenance issue with using <code>assert</code> as part of the standard code instead of using it just for debugging purposes?</p>
<p>Is</p>
<pre><code>assert x >= 0, 'x is less than zero'
</code></pre>
<p>better or worse than </p>
<pre><code>if x < 0:
raise Exception, 'x is less than zero'
</code></pre></li>
<li><p>Also, is there any way to set a business rule like <code>if x < 0 raise error</code> that is always checked without the <code>try/except/finally</code> so, if at anytime throughout the code <code>x</code> is less than 0 an error is raised, like if you set <code>assert x < 0</code> at the start of a function, anywhere within the function where <code>x</code> becomes less then 0 an exception is raised?</p></li>
</ol>
| 291 | 2009-06-03T12:57:16Z | 40,084,762 | <p>An Assert is to check -<br/>
<strong>1. the valid condition,<br/>
2. the valid statement,<br/>
3. true logic;<br/></strong>
of source code. Instead of failing the whole project it gives an alarm that something is not appropriate in your source file.</p>
<p>In example 1, since variable 'str' is not nul. So no any assert or exception get raised.</p>
<p><strong>Example 1:</strong></p>
<pre><code>#!/usr/bin/python
str = 'hello Pyhton!'
strNull = 'string is Null'
if __debug__:
if not str: raise AssertionError(strNull)
print str
if __debug__:
print 'FileName '.ljust(30,'.'),(__name__)
print 'FilePath '.ljust(30,'.'),(__file__)
------------------------------------------------------
Output:
hello Pyhton!
FileName ..................... hello
FilePath ..................... C:/Python\hello.py
</code></pre>
<p>In example 2, var 'str' is nul. So we are saving the user from going ahead of faulty program by <strong>assert</strong> statement. </p>
<p><strong>Example 2:</strong></p>
<pre><code>#!/usr/bin/python
str = ''
strNull = 'NULL String'
if __debug__:
if not str: raise AssertionError(strNull)
print str
if __debug__:
print 'FileName '.ljust(30,'.'),(__name__)
print 'FilePath '.ljust(30,'.'),(__file__)
------------------------------------------------------
Output:
AssertionError: NULL String
</code></pre>
<p>The moment we don't want debug and realized the assertion issue in the source code. Disable the optimization flag</p>
<p><strong>python -O assertStatement.py</strong><br/>
nothing will get print </p>
| 0 | 2016-10-17T11:04:16Z | [
"python",
"assert",
"raise"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 944,712 | <p>The usual way to test for a NaN is to see if it's equal to itself:</p>
<pre><code>def isNaN(num):
return num != num
</code></pre>
| 106 | 2009-06-03T13:22:05Z | [
"python",
"math"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 944,733 | <p><a href="http://docs.python.org/library/math.html#math.isnan">math.isnan()</a></p>
<blockquote>
<p>Checks if the float x is a NaN (not a number). NaNs are part of the IEEE 754 standards. Operation like but not limited to inf * 0, inf / inf or any operation involving a NaN, e.g. nan * 1, return a NaN.</p>
<p><em>New in version 2.6.</em></p>
</blockquote>
<pre><code>>>> import math
>>> x=float('nan')
>>> math.isnan(x)
True
>>>
</code></pre>
| 407 | 2009-06-03T13:24:37Z | [
"python",
"math"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 944,734 | <p><a href="http://docs.python.org/library/math.html#math.isnan">math.isnan()</a></p>
<p>or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it <em>is</em> a number) the comparison should succeed.</p>
| 12 | 2009-06-03T13:24:51Z | [
"python",
"math"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 944,756 | <p><code>numpy.isnan(float)</code> tells you if it's <code>NaN</code> or not in Python 2.5.</p>
| 42 | 2009-06-03T13:28:31Z | [
"python",
"math"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 2,138,383 | <p>Another method if you're stuck on <2.6, you don't have numpy, and you don't have IEEE 754 support:</p>
<pre><code>def isNaN(x):
return str(x) == str(1e400*0)
</code></pre>
| 9 | 2010-01-26T09:10:53Z | [
"python",
"math"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 3,060,088 | <p>With python < 2.6 I ended up with</p>
<pre><code>def isNaN(x):
return str(float(x)).lower() == 'nan'
</code></pre>
<p>This works for me with python 2.5.1 on a Solaris 5.9 box and with python 2.6.5 on Ubuntu 10 </p>
| 9 | 2010-06-17T08:35:39Z | [
"python",
"math"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 11,334,997 | <p>Well I entered this post, because i've had some issues with the function:</p>
<pre><code>math.isnan()
</code></pre>
<p>There are problem when you run this code:</p>
<pre><code>a = "hello"
math.isnan(a)
</code></pre>
<p>It raises exception.
My solution for that is to make another check:</p>
<pre><code>def is_nan(x):
return isinstance(x, float) and math.isnan(x)
</code></pre>
| 5 | 2012-07-04T20:15:28Z | [
"python",
"math"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 12,588,878 | <p>I actually just ran into this, but for me it was checking for nan, -inf, or inf. I just used</p>
<pre><code>if float('-inf') < float(num) < float('inf'):
</code></pre>
<p>This is true for numbers, false for nan and both inf, and will raise an exception for things like strings or other types (which is probably a good thing). Also this does not require importing any libraries like math or numpy (numpy is so damn big it doubles the size of any compiled application).</p>
| 19 | 2012-09-25T18:22:03Z | [
"python",
"math"
] |
How to check for NaN in python? | 944,700 | <p><code>float('nan')</code> results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.</p>
| 300 | 2009-06-03T13:19:54Z | 37,985,974 | <p>I am receiving the data from a web-service that sends <code>NaN</code> as a string <code>'Nan'</code>. But there could be other sorts of string in my data as well, so a simple <code>float(value)</code> could throw an exception. I used the following variant of the accepted answer:</p>
<pre><code>def isnan(value):
try:
import math
return math.isnan(float(value))
except:
return False
</code></pre>
<p>Requirement:</p>
<pre><code>isnan('hello') == False
isnan('NaN') == True
isnan(100) == False
isnan(float('nan')) = True
</code></pre>
| 0 | 2016-06-23T08:22:33Z | [
"python",
"math"
] |
How to extract nested tables from HTML? | 944,860 | <p>I have an HTML file (encoded in utf-8). I open it with <code>codecs.open()</code>. The file architecture is:</p>
<pre><code><html>
// header
<body>
// some text
<table>
// some rows with cells here
// some cells contains tables
</table>
// maybe some text here
<table>
// a form and other stuff
</table>
// probably some more text
</body></html>
</code></pre>
<p>I need to retrieve only first table (discard the one with form). Omit all input before first <code><table></code> and after corresponding <code></table></code>. Some cells contains also paragraphs, bolds and scripts. There is no more than one nested table per row of main table.</p>
<p>How can I extract it to get a list of rows, where each elements holds plain (unicode string) cell's data and a list of rows for each nested table? There's no more than 1 level of nesting.</p>
<p>I tried HTMLParse, PyParse and re module, but can't get this working.
I'm quite new to Python.</p>
| 4 | 2009-06-03T13:48:39Z | 944,968 | <p>Try <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">beautiful soup</a></p>
<p>In principle you need to use a real parser (which Beaut. Soup is), regex cannot deal with nested elements, for computer sciencey reasons (finite state machines can't parse context-free grammars, IIRC)</p>
| 4 | 2009-06-03T14:07:04Z | [
"python",
"html",
"html-table",
"extract"
] |
How to extract nested tables from HTML? | 944,860 | <p>I have an HTML file (encoded in utf-8). I open it with <code>codecs.open()</code>. The file architecture is:</p>
<pre><code><html>
// header
<body>
// some text
<table>
// some rows with cells here
// some cells contains tables
</table>
// maybe some text here
<table>
// a form and other stuff
</table>
// probably some more text
</body></html>
</code></pre>
<p>I need to retrieve only first table (discard the one with form). Omit all input before first <code><table></code> and after corresponding <code></table></code>. Some cells contains also paragraphs, bolds and scripts. There is no more than one nested table per row of main table.</p>
<p>How can I extract it to get a list of rows, where each elements holds plain (unicode string) cell's data and a list of rows for each nested table? There's no more than 1 level of nesting.</p>
<p>I tried HTMLParse, PyParse and re module, but can't get this working.
I'm quite new to Python.</p>
| 4 | 2009-06-03T13:48:39Z | 945,011 | <p>If the HTML is well-formed you can parse it into a DOM tree and use XPath to extract the table you want. I usually use <a href="http://codespeak.net/lxml/index.html" rel="nofollow">lxml</a> for parsing XML, and <a href="http://codespeak.net/lxml/parsing.html" rel="nofollow">it can parse HTML as well</a>.</p>
<p>The XPath for pulling out the first table would be "//table[1]".</p>
| 2 | 2009-06-03T14:13:23Z | [
"python",
"html",
"html-table",
"extract"
] |
How to extract nested tables from HTML? | 944,860 | <p>I have an HTML file (encoded in utf-8). I open it with <code>codecs.open()</code>. The file architecture is:</p>
<pre><code><html>
// header
<body>
// some text
<table>
// some rows with cells here
// some cells contains tables
</table>
// maybe some text here
<table>
// a form and other stuff
</table>
// probably some more text
</body></html>
</code></pre>
<p>I need to retrieve only first table (discard the one with form). Omit all input before first <code><table></code> and after corresponding <code></table></code>. Some cells contains also paragraphs, bolds and scripts. There is no more than one nested table per row of main table.</p>
<p>How can I extract it to get a list of rows, where each elements holds plain (unicode string) cell's data and a list of rows for each nested table? There's no more than 1 level of nesting.</p>
<p>I tried HTMLParse, PyParse and re module, but can't get this working.
I'm quite new to Python.</p>
| 4 | 2009-06-03T13:48:39Z | 945,097 | <p>You may like <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. I'm not sure I really understood what you want to do with that structure, but maybe this example will help...</p>
<pre><code>import lxml.html
def process_row(row):
for cell in row.xpath('./td'):
inner_tables = cell.xpath('./table')
if len(inner_tables) < 1:
yield cell.text_content()
else:
yield [process_table(t) for t in inner_tables]
def process_table(table):
return [process_row(row) for row in table.xpath('./tr')]
html = lxml.html.parse('test.html')
first_table = html.xpath('//body/table[1]')[0]
data = process_table(first_table))
</code></pre>
| 3 | 2009-06-03T14:29:27Z | [
"python",
"html",
"html-table",
"extract"
] |
Numpy: Should I use newaxis or None? | 944,863 | <p>In numpy one can use the 'newaxis' object in the slicing syntax to create an axis of length one, e.g.:</p>
<pre><code>import numpy as np
print np.zeros((3,5))[:,np.newaxis,:].shape
# shape will be (3,1,5)
</code></pre>
<p>The <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis">documentation states</a> that one can also use <code>None</code> instead of <code>newaxis</code>, the effect is exactly the same.</p>
<p>Is there any reason to choose one over the other? Is there any general preference or style guide? My impression is that <code>newaxis</code> is more popular, probably because it is more explicit. So is there any reason why <code>None</code> is allowed?</p>
| 57 | 2009-06-03T13:48:45Z | 945,313 | <p><code>None</code> is allowed because <code>numpy.newaxis</code> is merely an alias for <code>None</code>.</p>
<pre><code>In [1]: import numpy
In [2]: numpy.newaxis is None
Out[2]: True
</code></pre>
<p>The authors probably chose it because they needed a convenient constant, and <code>None</code> was available.</p>
<p>As for why you should prefer <code>newaxis</code> over <code>None</code>: mainly it's because it's more explicit, and partly because someday the <code>numpy</code> authors might change it to something other than <code>None</code>. (They're not planning to, and probably won't, but there's no good reason to prefer <code>None</code>.)</p>
| 65 | 2009-06-03T15:05:52Z | [
"python",
"numpy"
] |
Publish feeds using Django | 945,001 | <p>I'm publishing a feed from a Django application.</p>
<p>I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed.</p>
<p>Here's the method I've created on my Feed class</p>
<pre>
def item_pubdate(self, item):
return item.date
</pre>
<p>this method never gets called....</p>
| 0 | 2009-06-03T14:12:40Z | 945,016 | <p>This is how mine is setup, and it is working.</p>
<pre><code>class AllFeed(Feed):
def item_pubdate(self, item):
return item.date
</code></pre>
| 0 | 2009-06-03T14:14:57Z | [
"python",
"django",
"rss"
] |
Publish feeds using Django | 945,001 | <p>I'm publishing a feed from a Django application.</p>
<p>I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed.</p>
<p>Here's the method I've created on my Feed class</p>
<pre>
def item_pubdate(self, item):
return item.date
</pre>
<p>this method never gets called....</p>
| 0 | 2009-06-03T14:12:40Z | 1,095,528 | <p>I've been banging my head against this one for a while. It seems that the django rss system need a "datetime" object instead of just the date (since it wants a time zone, and the date object doesn't have a time, let alone a time zone...)</p>
<p>I might be wrong though, but it's something that I've found via the error logs.</p>
| 0 | 2009-07-08T00:23:18Z | [
"python",
"django",
"rss"
] |
Publish feeds using Django | 945,001 | <p>I'm publishing a feed from a Django application.</p>
<p>I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed.</p>
<p>Here's the method I've created on my Feed class</p>
<pre>
def item_pubdate(self, item):
return item.date
</pre>
<p>this method never gets called....</p>
| 0 | 2009-06-03T14:12:40Z | 1,169,884 | <p>According to the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#feed-class-reference" rel="nofollow">Feed Class Reference</a> in the Django documentation, the item_pubdate field is supposed to return a datetime.datetime object. If item.date is just a DateField and not a DateTimeField, that might be causing the problem. If that is the case you could change the method to make a datetime and then return that.</p>
<pre><code>import datetime
def item_pubdate(self, item):
return datetime.datetime.combine(item.date, datetime.time())
</code></pre>
| 3 | 2009-07-23T06:06:30Z | [
"python",
"django",
"rss"
] |
DBus interface properties | 945,007 | <p>How do I get the list of available DBus interface properties?</p>
<p>I am writing a script that would be tracking specific type of usb devices connections. A way to distinguish the connections to be tracked from all usb connections I guess is to check the properties of signals' interfaces DBus is sending on a usb connection. I'd like to get the list of all such properties to chose the relevant.</p>
<p>My code is:</p>
<pre><code> import sys
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gobject
def deviceAdded(udi):
device = bus.get_object("org.freedesktop.Hal", udi)
device_if = dbus.Interface(device, 'org.freedesktop.Hal.Device')
if device_if.GetPropertyString('info.subsystem') == 'usb_device':
#
# Properties can be accesed like this:
# vendor_id = device_if.GetPropertyInteger('usb_device.vendor_id')
#
# how to get the list of all properties?
#
# do something
def deviceRemoved(udi):
# do something
pass
if __name__ == "__main__":
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
bus.add_signal_receiver(
deviceAdded,
'DeviceAdded',
'org.freedesktop.Hal.Manager',
'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
bus.add_signal_receiver(
deviceRemoved,
'DeviceRemoved',
'org.freedesktop.Hal.Manager',
'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
loop = gobject.MainLoop()
try:
loop.run()
except KeyboardInterrupt:
print "usb-device-tracker: keyboad interrupt received, shutting down"
loop.quit()
sys.exit(0)
</code></pre>
| 4 | 2009-06-03T14:13:14Z | 989,948 | <p>First of all, check hal documentation and sources, they are always your friend.</p>
<pre><code>import dbus
bus = dbus.SystemBus()
dev = bus.get_object("org.freedesktop.Hal", u'/org/freedesktop/Hal/devices/computer_logicaldev_input')
iface = dbus.Interface(dev, 'org.freedesktop.Hal.Device')
props = iface.GetAllProperties()
print "\n".join(("%s: %s" % (k, props[k]) for k in props))
</code></pre>
<p>As a last resort you can always find properties you are interested in with 'lshal' command.</p>
| 3 | 2009-06-13T04:06:51Z | [
"python",
"properties",
"interface",
"dbus"
] |
DBus interface properties | 945,007 | <p>How do I get the list of available DBus interface properties?</p>
<p>I am writing a script that would be tracking specific type of usb devices connections. A way to distinguish the connections to be tracked from all usb connections I guess is to check the properties of signals' interfaces DBus is sending on a usb connection. I'd like to get the list of all such properties to chose the relevant.</p>
<p>My code is:</p>
<pre><code> import sys
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gobject
def deviceAdded(udi):
device = bus.get_object("org.freedesktop.Hal", udi)
device_if = dbus.Interface(device, 'org.freedesktop.Hal.Device')
if device_if.GetPropertyString('info.subsystem') == 'usb_device':
#
# Properties can be accesed like this:
# vendor_id = device_if.GetPropertyInteger('usb_device.vendor_id')
#
# how to get the list of all properties?
#
# do something
def deviceRemoved(udi):
# do something
pass
if __name__ == "__main__":
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
bus.add_signal_receiver(
deviceAdded,
'DeviceAdded',
'org.freedesktop.Hal.Manager',
'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
bus.add_signal_receiver(
deviceRemoved,
'DeviceRemoved',
'org.freedesktop.Hal.Manager',
'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
loop = gobject.MainLoop()
try:
loop.run()
except KeyboardInterrupt:
print "usb-device-tracker: keyboad interrupt received, shutting down"
loop.quit()
sys.exit(0)
</code></pre>
| 4 | 2009-06-03T14:13:14Z | 1,993,780 | <p>In general, you can use the <a href="http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties" rel="nofollow"><code>GetAll</code></a> method on the <code>org.freedesktop.DBus.Properties</code> interface.</p>
| 1 | 2010-01-03T02:48:43Z | [
"python",
"properties",
"interface",
"dbus"
] |
DBus interface properties | 945,007 | <p>How do I get the list of available DBus interface properties?</p>
<p>I am writing a script that would be tracking specific type of usb devices connections. A way to distinguish the connections to be tracked from all usb connections I guess is to check the properties of signals' interfaces DBus is sending on a usb connection. I'd like to get the list of all such properties to chose the relevant.</p>
<p>My code is:</p>
<pre><code> import sys
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gobject
def deviceAdded(udi):
device = bus.get_object("org.freedesktop.Hal", udi)
device_if = dbus.Interface(device, 'org.freedesktop.Hal.Device')
if device_if.GetPropertyString('info.subsystem') == 'usb_device':
#
# Properties can be accesed like this:
# vendor_id = device_if.GetPropertyInteger('usb_device.vendor_id')
#
# how to get the list of all properties?
#
# do something
def deviceRemoved(udi):
# do something
pass
if __name__ == "__main__":
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
bus.add_signal_receiver(
deviceAdded,
'DeviceAdded',
'org.freedesktop.Hal.Manager',
'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
bus.add_signal_receiver(
deviceRemoved,
'DeviceRemoved',
'org.freedesktop.Hal.Manager',
'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
loop = gobject.MainLoop()
try:
loop.run()
except KeyboardInterrupt:
print "usb-device-tracker: keyboad interrupt received, shutting down"
loop.quit()
sys.exit(0)
</code></pre>
| 4 | 2009-06-03T14:13:14Z | 24,126,305 | <p>I recently encountered the same issue (not with Hal specifically). I'm not sure if this holds universally but it can (at least very often) be retrieved via the <code>org.freedesktop.DBus.Properties</code> interface (as @daf suggested).</p>
<pre><code>bus = dbus.SystemBus()
device = bus.get_object(...)
your_interface = 'org.freedesktop.Hal.Device' # for this example
props_iface = dbus.Interface(device, 'org.freedesktop.DBus.Properties')
properties = props_iface.GetAll(your_interface) #properties is a dbus.Dictionary
</code></pre>
| 0 | 2014-06-09T18:15:06Z | [
"python",
"properties",
"interface",
"dbus"
] |
How can I script the creation of a movie from a set of images? | 945,250 | <p>I managed to get a set of images loaded using Python. </p>
<p>I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation procedure: </p>
<ul>
<li>download .dmg</li>
<li>click</li>
<li>move into the application folder</li>
</ul>
<p>I do not want to expend a lot of effort to install the video editing program. Just something simple that works.</p>
<p><hr /></p>
<h3>Questions</h3>
<ol>
<li><p>What format should I aim for? I need my video to be playable on Linux, Mac, and Windows systems. The images are graphs, so we are speaking of discreet images, not photographs. It should be pretty easy to compress it. There will be about 1000 images, so this will be a short movie.</p></li>
<li><p>What tools should I use to produce the actual video? I need to either do it directly from Python using a library designed for this purpose, or by scripting command-line tools called from Python. </p></li>
</ol>
| 8 | 2009-06-03T14:54:29Z | 945,389 | <p>Do you have to use python? There are other tools that are created just for these purposes. For example, to use <a href="http://electron.mit.edu/~gsteele/ffmpeg/" rel="nofollow">ffmpeg or mencoder</a>.</p>
| 4 | 2009-06-03T15:22:45Z | [
"python",
"osx",
"video"
] |
How can I script the creation of a movie from a set of images? | 945,250 | <p>I managed to get a set of images loaded using Python. </p>
<p>I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation procedure: </p>
<ul>
<li>download .dmg</li>
<li>click</li>
<li>move into the application folder</li>
</ul>
<p>I do not want to expend a lot of effort to install the video editing program. Just something simple that works.</p>
<p><hr /></p>
<h3>Questions</h3>
<ol>
<li><p>What format should I aim for? I need my video to be playable on Linux, Mac, and Windows systems. The images are graphs, so we are speaking of discreet images, not photographs. It should be pretty easy to compress it. There will be about 1000 images, so this will be a short movie.</p></li>
<li><p>What tools should I use to produce the actual video? I need to either do it directly from Python using a library designed for this purpose, or by scripting command-line tools called from Python. </p></li>
</ol>
| 8 | 2009-06-03T14:54:29Z | 945,570 | <p>You may use OpenCV. And it can be installed on Mac. Also, it has a <a href="http://opencv.willowgarage.com/wiki/PythonInterface">python interface</a>.</p>
<p>I have slightly modified a program taken from <a href="http://morphm.ensmp.fr/wiki/morphee-admin/How%5Fto%5Fuse%5FMorph-M%5Fwith%5FOpenCV%5F">here</a>, but don't know if it compiles, and can't check it.</p>
<pre><code>import opencv
from opencv.cv import *
from opencv.highgui import *
isColor = 1
fps = 25 # or 30, frames per second
frameW = 256 # images width
frameH = 256 # images height
writer = cvCreateVideoWriter("video.avi",-1,
fps,cvSize(frameW,frameH),isColor)
#-----------------------------
#Writing the video file:
#-----------------------------
nFrames = 70; #number of frames
for i in range(nFrames):
img = cvLoadImage("image_number_%d.png"%i) #specify filename and the extension
# add the frame to the video
cvWriteFrame(writer,img)
cvReleaseVideoWriter(writer) #
</code></pre>
| 8 | 2009-06-03T16:00:47Z | [
"python",
"osx",
"video"
] |
How can I script the creation of a movie from a set of images? | 945,250 | <p>I managed to get a set of images loaded using Python. </p>
<p>I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation procedure: </p>
<ul>
<li>download .dmg</li>
<li>click</li>
<li>move into the application folder</li>
</ul>
<p>I do not want to expend a lot of effort to install the video editing program. Just something simple that works.</p>
<p><hr /></p>
<h3>Questions</h3>
<ol>
<li><p>What format should I aim for? I need my video to be playable on Linux, Mac, and Windows systems. The images are graphs, so we are speaking of discreet images, not photographs. It should be pretty easy to compress it. There will be about 1000 images, so this will be a short movie.</p></li>
<li><p>What tools should I use to produce the actual video? I need to either do it directly from Python using a library designed for this purpose, or by scripting command-line tools called from Python. </p></li>
</ol>
| 8 | 2009-06-03T14:54:29Z | 945,829 | <p>If you're not averse to using the command-line, there's the <code>convert</code> command from the ImageMagick package. It's available for Mac, Linux, Windows. See <a href="http://www.imagemagick.org/script/index.php">http://www.imagemagick.org/script/index.php</a>.</p>
<p>It supports a huge number of image formats and you can output your movie as an mpeg file:</p>
<pre><code>convert -quality 100 *.png outvideo.mpeg
</code></pre>
<p>or as animated gifs for uploading to webpages:</p>
<pre><code>convert -set delay 3 -loop 0 -scale 50% *.png animation.gif
</code></pre>
<p>More options for the <code>convert</code> command available here: <a href="http://www.imagemagick.org/Usage/anim_basics/">ImageMagick v6 Examples -
Animation Basics</a></p>
| 19 | 2009-06-03T16:53:53Z | [
"python",
"osx",
"video"
] |
Why doesn't anyone care about this MySQLdb bug? is it a bug? | 945,482 | <p>TL;DR: I've supplied a patch for a bug I found and I've got 0 feedback on it. I'm wondering if it's a bug at all. This is not a rant. Please read this and if you may be affected by it check the fix.</p>
<p>I have found and reported this MySQLdb bug some weeks ago (edit: 6 weeks ago), sent a patch, posted it on a couple of ORM's forums, mailed the MySQLdb author, mailed some people talking about handling deadlocks, mailed ORM authors and I'm still waiting for any kind of feedback.</p>
<p>This bug caused me a lot of grief and the only explanations I can find on the feedback is that either no one uses "SELECT ... FOR UPDATE" in python with mysql or that this is not a bug.</p>
<p>Basically the problem is that deadlocks and "lock wait timeout" exceptions are NOT being raised when issuing a "SELECT ... FOR UPDATE" using a MySQLdb cursor.
Instead, the statement fails silently and returns an empty resultset, which any application will interpret as if there were no rows matched.</p>
<p>I've tested the SVN version and it's still affected. Tested on the default installations of Ubuntu Intrepid, Jaunty and Debian Lenny and those are affected too. The current version installed by easy_install (1.2.3c1) is affected.</p>
<p>This affects SQLAlchemy and SQLObject too and probably any ORM that used MySQLdb cursors is affected too.</p>
<p>This script can reproduce a deadlock that will trigger the bug (just change the user/pass in get_conn, it will create the necessary tables):</p>
<pre><code>import time
import threading
import traceback
import logging
import MySQLdb
def get_conn():
return MySQLdb.connect(host='localhost', db='TESTS',
user='tito', passwd='testing123')
class DeadlockTestThread(threading.Thread):
def __init__(self, order):
super(DeadlockTestThread, self).__init__()
self.first_select_done = threading.Event()
self.do_the_second_one = threading.Event()
self.order = order
def log(self, msg):
logging.info('%s: %s' % (self.getName(), msg))
def run(self):
db = get_conn()
c = db.cursor()
c.execute('BEGIN;')
query = 'SELECT * FROM locktest%i FOR UPDATE;'
try:
try:
c.execute(query % self.order[0])
self.first_select_done.set()
self.do_the_second_one.wait()
c.execute(query % self.order[1])
self.log('2nd SELECT OK, we got %i rows' % len(c.fetchall()))
c.execute('SHOW WARNINGS;')
self.log('SHOW WARNINGS: %s' % str(c.fetchall()))
except:
self.log('Failed! Rolling back')
c.execute('ROLLBACK;')
raise
else:
c.execute('COMMIT;')
finally:
c.close()
db.close()
def init():
db = get_conn()
# Create the tables.
c = db.cursor()
c.execute('DROP TABLE IF EXISTS locktest1;')
c.execute('DROP TABLE IF EXISTS locktest2;')
c.execute('''CREATE TABLE locktest1 (
a int(11), PRIMARY KEY(a)
) ENGINE=innodb;''')
c.execute('''CREATE TABLE locktest2 (
a int(11), PRIMARY KEY(a)
) ENGINE=innodb;''')
c.close()
# Insert some data.
c = db.cursor()
c.execute('BEGIN;')
c.execute('INSERT INTO locktest1 VALUES (123456);')
c.execute('INSERT INTO locktest2 VALUES (123456);')
c.execute('COMMIT;')
c.close()
db.close()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
init()
t1 = DeadlockTestThread(order=[1, 2])
t2 = DeadlockTestThread(order=[2, 1])
t1.start()
t2.start()
# Wait till both threads did the 1st select.
t1.first_select_done.wait()
t2.first_select_done.wait()
# Let thread 1 continue, it will get wait for the lock
# at this point.
t1.do_the_second_one.set()
# Just make sure thread 1 is waiting for the lock.
time.sleep(0.1)
# This will trigger the deadlock and thread-2 will
# fail silently, getting 0 rows.
t2.do_the_second_one.set()
t1.join()
t2.join()
</code></pre>
<p>The output of running this on an unpatched MySQLdb is this:</p>
<pre><code>$ python bug_mysqldb_deadlock.py
INFO:root:Thread-2: 2nd SELECT OK, we got 0 rows
INFO:root:Thread-2: SHOW WARNINGS: (('Error', 1213L, 'Deadlock found when trying to get lock; try restarting transaction'),)
INFO:root:Thread-1: 2nd SELECT OK, we got 1 rows
INFO:root:Thread-1: SHOW WARNINGS: ()
</code></pre>
<p>You can see that Thread-2 got 0 rows from a table we know has 1 and only issuing a "SHOW WARNINGS" statement you can see what happened.
If you check "SHOW ENGINE INNODB STATUS" you will see this line in the log "*** WE ROLL BACK TRANSACTION (2)", everything that happens after the failing select on Thread-2 is on a half rolled back transaction.</p>
<p>After applying the patch (check the ticket for it, url below), this is the output of running the script:</p>
<pre><code>$ python bug_mysqldb_deadlock.py
INFO:root:Thread-2: Failed! Rolling back
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.4/threading.py", line 442, in __bootstrap
self.run()
File "bug_mysqldb_deadlock.py", line 33, in run
c.execute(query % self.order[1])
File "/home/koba/Desarollo/InetPub/IBSRL/VirtualEnv-1.0-p2.4/lib/python2.4/site-packages/MySQL_python-1.2.2-py2.4-linux-x86_64.egg/MySQLdb/cursors.py", line 178, in execute
self.errorhandler(self, exc, value)
File "/home/koba/Desarollo/InetPub/IBSRL/VirtualEnv-1.0-p2.4/lib/python2.4/site-packages/MySQL_python-1.2.2-py2.4-linux-x86_64.egg/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1213, 'Deadlock found when trying to get lock; try restarting transaction')
INFO:root:Thread-1: 2nd SELECT OK, we got 1 rows
INFO:root:Thread-1: SHOW WARNINGS: ()
</code></pre>
<p>In this case an exception is raised on Thread-2 and it rolls back properly.</p>
<p>So, what's your opinion?, is this a bug? no one cares or am I just crazy?</p>
<p>This is the ticket I opened on SF: <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=2776267&group_id=22307&atid=374932">http://sourceforge.net/tracker/index.php?func=detail&aid=2776267&group_id=22307&atid=374932</a></p>
| 10 | 2009-06-03T15:41:34Z | 945,519 | <blockquote>
<p>Why doesnât anyone care about this
MySQLdb bug?</p>
</blockquote>
<p>bugs can take a while to prioritize, research, verify the problem, find a fix, test the fix, make sure the fix fix does not break anything else. I would suggest you deploy a work around, since it could take some time for this fix to arrive for you.</p>
| 7 | 2009-06-03T15:48:58Z | [
"python",
"deadlock",
"mysql"
] |
is there a multiple format specifier in Python? | 945,972 | <p>I have a data table 44 columns wide that I need to write to file. I don't want to write:</p>
<pre><code>outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...))
</code></pre>
<p>In Fortran you can specify multiple format specifiers easily:</p>
<pre><code>write (*,"(3f8.3)") a,b,c
</code></pre>
<p>Is there a similar capability in Python?</p>
| 7 | 2009-06-03T17:18:53Z | 945,988 | <p>Are you asking about</p>
<pre><code>format= "%i" + ",%f"*len(row) + "\n"
outfile.write( format % ([i]+row))
</code></pre>
| 3 | 2009-06-03T17:21:14Z | [
"python"
] |
is there a multiple format specifier in Python? | 945,972 | <p>I have a data table 44 columns wide that I need to write to file. I don't want to write:</p>
<pre><code>outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...))
</code></pre>
<p>In Fortran you can specify multiple format specifiers easily:</p>
<pre><code>write (*,"(3f8.3)") a,b,c
</code></pre>
<p>Is there a similar capability in Python?</p>
| 7 | 2009-06-03T17:18:53Z | 945,994 | <pre><code>>>> "%d " * 3
'%d %d %d '
>>> "%d " * 3 % (1,2,3)
'1 2 3 '
</code></pre>
| 20 | 2009-06-03T17:21:59Z | [
"python"
] |
is there a multiple format specifier in Python? | 945,972 | <p>I have a data table 44 columns wide that I need to write to file. I don't want to write:</p>
<pre><code>outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...))
</code></pre>
<p>In Fortran you can specify multiple format specifiers easily:</p>
<pre><code>write (*,"(3f8.3)") a,b,c
</code></pre>
<p>Is there a similar capability in Python?</p>
| 7 | 2009-06-03T17:18:53Z | 946,026 | <p>Is not exactly the same, but you can try something like this:</p>
<pre><code>values=[1,2.1,3,4,5] #you can use variables instead of values of course
outfile.write(",".join(["%f" % value for value in values]));
</code></pre>
| 0 | 2009-06-03T17:28:19Z | [
"python"
] |
is there a multiple format specifier in Python? | 945,972 | <p>I have a data table 44 columns wide that I need to write to file. I don't want to write:</p>
<pre><code>outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...))
</code></pre>
<p>In Fortran you can specify multiple format specifiers easily:</p>
<pre><code>write (*,"(3f8.3)") a,b,c
</code></pre>
<p>Is there a similar capability in Python?</p>
| 7 | 2009-06-03T17:18:53Z | 947,192 | <p>Note that I think it'd be much better to do something like:</p>
<pre><code>outfile.write(", ".join(map(str, row)))
</code></pre>
<p>...which isn't what you asked for, but is better in a couple of ways.</p>
| 0 | 2009-06-03T20:55:26Z | [
"python"
] |
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote() | 946,170 | <p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p>
<p>The closest I've come across are <a href="http://www.w3schools.com/jsref/jsref%5Fescape.asp"><code>escape()</code></a>, <a href="http://www.w3schools.com/jsref/jsref%5FencodeURI.asp"><code>encodeURI()</code></a>, and <a href="http://www.w3schools.com/jsref/jsref%5FencodeURIComponent.asp"><code>encodeURIComponent()</code></a> (and their corresponding un-encoding functions), but they don't encode/decode the same set of special characters as far as I can tell.</p>
<p>Thanks,<br />
Cameron</p>
| 22 | 2009-06-03T17:51:28Z | 946,380 | <p>OK, I think I'm going to go with a hybrid custom set of functions:</p>
<p>Encode: Use encodeURIComponent(), then put slashes back in.<br>
Decode: Decode any %hex values found.</p>
<p>Here's a more complete variant of what I ended up using (it handles Unicode properly, too):</p>
<pre><code>function quoteUrl(url, safe) {
if (typeof(safe) !== 'string') {
safe = '/'; // Don't escape slashes by default
}
url = encodeURIComponent(url);
// Unescape characters that were in the safe list
toUnencode = [ ];
for (var i = safe.length - 1; i >= 0; --i) {
var encoded = encodeURIComponent(safe[i]);
if (encoded !== safe.charAt(i)) { // Ignore safe char if it wasn't escaped
toUnencode.push(encoded);
}
}
url = url.replace(new RegExp(toUnencode.join('|'), 'ig'), decodeURIComponent);
return url;
}
var unquoteUrl = decodeURIComponent; // Make alias to have symmetric function names
</code></pre>
<p>Note that if you don't need "safe" characters when encoding (<code>'/'</code> by default in Python), then you can just use the built-in <code>encodeURIComponent()</code> and <code>decodeURIComponent()</code> functions directly.</p>
<p>Also, if there are Unicode characters (i.e. characters with codepoint >= 128) in the string, then to maintain compatibility with JavaScript's <code>encodeURIComponent()</code>, the Python <code>quote_url()</code> would have to be:</p>
<pre><code>def quote_url(url, safe):
"""URL-encodes a string (either str (i.e. ASCII) or unicode);
uses de-facto UTF-8 encoding to handle Unicode codepoints in given string.
"""
return urllib.quote(unicode(url).encode('utf-8'), safe)
</code></pre>
<p>And <code>unquote_url()</code> would be:</p>
<pre><code>def unquote_url(url):
"""Decodes a URL that was encoded using quote_url.
Returns a unicode instance.
"""
return urllib.unquote(url).decode('utf-8')
</code></pre>
| 5 | 2009-06-03T18:30:19Z | [
"javascript",
"python",
"url",
"encoding"
] |
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote() | 946,170 | <p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p>
<p>The closest I've come across are <a href="http://www.w3schools.com/jsref/jsref%5Fescape.asp"><code>escape()</code></a>, <a href="http://www.w3schools.com/jsref/jsref%5FencodeURI.asp"><code>encodeURI()</code></a>, and <a href="http://www.w3schools.com/jsref/jsref%5FencodeURIComponent.asp"><code>encodeURIComponent()</code></a> (and their corresponding un-encoding functions), but they don't encode/decode the same set of special characters as far as I can tell.</p>
<p>Thanks,<br />
Cameron</p>
| 22 | 2009-06-03T17:51:28Z | 946,656 | <p>Try a regex. Something like this:</p>
<pre><code>mystring.replace(/[\xFF-\xFFFF]/g, "%" + "$&".charCodeAt(0));
</code></pre>
<p>That will replace any character above ordinal 255 with its corresponding %HEX representation.</p>
| 1 | 2009-06-03T19:26:24Z | [
"javascript",
"python",
"url",
"encoding"
] |
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote() | 946,170 | <p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p>
<p>The closest I've come across are <a href="http://www.w3schools.com/jsref/jsref%5Fescape.asp"><code>escape()</code></a>, <a href="http://www.w3schools.com/jsref/jsref%5FencodeURI.asp"><code>encodeURI()</code></a>, and <a href="http://www.w3schools.com/jsref/jsref%5FencodeURIComponent.asp"><code>encodeURIComponent()</code></a> (and their corresponding un-encoding functions), but they don't encode/decode the same set of special characters as far as I can tell.</p>
<p>Thanks,<br />
Cameron</p>
| 22 | 2009-06-03T17:51:28Z | 2,947,168 | <p>Python: <code>urllib.quote</code></p>
<p>Javascript:<code>unescape</code></p>
<p>I haven't done extensive testing but for my purposes it works most of the time. I guess you have some specific characters that don't work. Maybe if I use some Asian text or something it will break :)</p>
<p>This came up when I googled so I put this in for all the others, if not specifically for the original question.</p>
| 1 | 2010-06-01T03:47:21Z | [
"javascript",
"python",
"url",
"encoding"
] |
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote() | 946,170 | <p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p>
<p>The closest I've come across are <a href="http://www.w3schools.com/jsref/jsref%5Fescape.asp"><code>escape()</code></a>, <a href="http://www.w3schools.com/jsref/jsref%5FencodeURI.asp"><code>encodeURI()</code></a>, and <a href="http://www.w3schools.com/jsref/jsref%5FencodeURIComponent.asp"><code>encodeURIComponent()</code></a> (and their corresponding un-encoding functions), but they don't encode/decode the same set of special characters as far as I can tell.</p>
<p>Thanks,<br />
Cameron</p>
| 22 | 2009-06-03T17:51:28Z | 6,618,858 | <p>For the record:</p>
<pre><code>JavaScript | Python
-----------------------------------
encodeURI(str) | urllib.quote(str, safe='~@#$&()*!+=:;,.?/\'');
-----------------------------------
encodeURIComponent(str) | urllib.quote(str, safe='~()*!.\'')
</code></pre>
| 44 | 2011-07-08T00:58:30Z | [
"javascript",
"python",
"url",
"encoding"
] |
Equivalent Javascript Functions for Python's urllib.quote() and urllib.unquote() | 946,170 | <p>Are there any equivalent Javascript functions for Python's <a href="http://docs.python.org/library/urllib.html#urllib.quote"><code>urllib.quote()</code></a> and <a href="http://docs.python.org/library/urllib.html#urllib.unquote"><code>urllib.unquote()</code></a>?</p>
<p>The closest I've come across are <a href="http://www.w3schools.com/jsref/jsref%5Fescape.asp"><code>escape()</code></a>, <a href="http://www.w3schools.com/jsref/jsref%5FencodeURI.asp"><code>encodeURI()</code></a>, and <a href="http://www.w3schools.com/jsref/jsref%5FencodeURIComponent.asp"><code>encodeURIComponent()</code></a> (and their corresponding un-encoding functions), but they don't encode/decode the same set of special characters as far as I can tell.</p>
<p>Thanks,<br />
Cameron</p>
| 22 | 2009-06-03T17:51:28Z | 35,343,767 | <p>The requests library is a bit more popular if you don't mind the extra dependency</p>
<pre><code>from requests.utils import quote
quote(str)
</code></pre>
| 1 | 2016-02-11T15:44:50Z | [
"javascript",
"python",
"url",
"encoding"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 946,906 | <p>How about this?</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [x for x, y in enumerate(tuple_list) if y[1] == 7]
[1]
>>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']
[2]
</code></pre>
<p>As pointed out in the comments, this would get all matches. To just get the first one, you can do:</p>
<pre><code>>>> [y[0] for y in tuple_list].index('kumquat')
2
</code></pre>
<p>There is a good discussion in the comments as to the speed difference between all the solutions posted. I may be a little biased but I would personally stick to a one-liner as the speed we're talking about is pretty insignificant versus creating functions and importing modules for this problem, but if you are planning on doing this to a very large amount of elements you might want to look at the other answers provided, as they are faster than what I provided.</p>
| 47 | 2009-06-03T20:07:23Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 946,940 | <p>One possibility is to use the <a href="http://docs.python.org/library/operator.html#operator.itemgetter">itemgetter</a> function from the <code>operator</code> module:</p>
<pre><code>import operator
f = operator.itemgetter(0)
print map(f, tuple_list).index("cherry") # yields 1
</code></pre>
<p>The call to <code>itemgetter</code> returns a function that will do the equivalent of <code>foo[0]</code> for anything passed to it. Using <code>map</code>, you then apply that function to each tuple, extracting the info into a new list, on which you then call <code>index</code> as normal.</p>
<pre><code>map(f, tuple_list)
</code></pre>
<p>is equivalent to:</p>
<pre><code>[f(tuple_list[0]), f(tuple_list[1]), ...etc]
</code></pre>
<p>which in turn is equivalent to:</p>
<pre><code>[tuple_list[0][0], tuple_list[1][0], tuple_list[2][0]]
</code></pre>
<p>which gives:</p>
<pre><code>["pineapple", "cherry", ...etc]
</code></pre>
| 8 | 2009-06-03T20:12:28Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 947,166 | <p>You can do this with a list comprehension and index()</p>
<pre><code>tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x[0] for x in tuple_list].index("kumquat")
2
[x[1] for x in tuple_list].index(7)
1
</code></pre>
| 4 | 2009-06-03T20:50:48Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 947,184 | <p>Those list comprehensions are messy after a while.</p>
<h3>I like this Pythonic approach:</h3>
<pre><code>from operator import itemgetter
def collect(l, index):
return map(itemgetter(index), l)
# And now you can write this:
collect(tuple_list,0).index("cherry") # = 1
collect(tuple_list,1).index("3") # = 2
</code></pre>
<h3>If you need your code to be all super performant:</h3>
<pre><code># Stops iterating through the list as soon as it finds the value
def getIndexOfTuple(l, index, value):
for pos,t in enumerate(l):
if t[index] == value:
return pos
# Matches behavior of list.index
raise ValueError("list.index(x): x not in list")
getIndexOfTuple(tuple_list, 0, "cherry") # = 1
</code></pre>
| 24 | 2009-06-03T20:54:10Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 6,850,520 | <p>I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:</p>
<p>Using the enumerator method to match on sub-indices in a list of tuples.
e.g.</p>
<pre><code>li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]
# want pos of item having [22,44] in positions 1 and 3:
def getIndexOfTupleWithIndices(li, indices, vals):
# if index is a tuple of subindices to match against:
for pos,k in enumerate(li):
match = True
for i in indices:
if k[i] != vals[i]:
match = False
break;
if (match):
return pos
# Matches behavior of list.index
raise ValueError("list.index(x): x not in list")
idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals) # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals) # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals) # = 4
</code></pre>
| 2 | 2011-07-27T20:02:43Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 11,106,344 | <p>ok, it might be a mistake in <code>vals(j)</code>, the correction is:</p>
<pre><code>def getIndex(li,indices,vals):
for pos,k in enumerate(lista):
match = True
for i in indices:
if k[i] != vals[indices.index(i)]:
match = False
break
if(match):
return pos
</code></pre>
| 1 | 2012-06-19T17:38:27Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 12,919,542 | <pre><code>tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
def eachtuple(tupple, pos1, val):
for e in tupple:
if e == val:
return True
for e in tuple_list:
if eachtuple(e, 1, 7) is True:
print tuple_list.index(e)
for e in tuple_list:
if eachtuple(e, 0, "kumquat") is True:
print tuple_list.index(e)
</code></pre>
| 1 | 2012-10-16T16:44:44Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 14,364,040 | <pre><code>z = list(zip(*tuple_list))
z[1][z[0].index('persimon')]
</code></pre>
| 0 | 2013-01-16T17:19:20Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 35,446,495 | <p>Inspired by <a href="http://stackoverflow.com/questions/35446421/finding-a-specific-value-from-list-of-dictionary-in-python#35446432">this question</a>, I found this quite elegant:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> next(i for i, t in enumerate(tuple_list) if t[1] == 7)
1
>>> next(i for i, t in enumerate(tuple_list) if t[0] == "kumquat")
2
</code></pre>
| 1 | 2016-02-17T01:49:51Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
Using Python's list index() method on a list of tuples or objects? | 946,860 | <p>Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:</p>
<pre><code>>>> some_list = ["apple", "pear", "banana", "grape"]
>>> some_list.index("pear")
1
>>> some_list.index("grape")
3
</code></pre>
<p>Is there a graceful (idiomatic) way to extend this to lists of complex objects, like tuples? Ideally, I'd like to be able to do something like this:</p>
<pre><code>>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> some_list.getIndexOfTuple(1, 7)
1
>>> some_list.getIndexOfTuple(0, "kumquat")
2
</code></pre>
<p>getIndexOfTuple() is just a hypothetical method that accepts a sub-index and a value, and then returns the index of the list item with the given value at that sub-index. I hope</p>
<p>Is there some way to achieve that general result, using list comprehensions or lambas or something "in-line" like that? I think I could write my own class and method, but I don't want to reinvent the wheel if Python already has a way to do it.</p>
| 34 | 2009-06-03T20:01:51Z | 37,022,206 | <p>No body suggest lambdas?</p>
<p>Y try this and works. I come to this post searching answer. I don't found that I like, but I feel a insingth :P</p>
<pre><code> l #[['rana', 1, 1], ['pato', 1, 1], ['perro', 1, 1]]
map(lambda x:x[0], l).index("pato") #1
</code></pre>
<p>Edit to add examples: </p>
<pre><code> l=[['rana', 1, 1], ['pato', 2, 1], ['perro', 1, 1], ['pato', 2, 2], ['pato', 2, 2]]
</code></pre>
<p>extract all items by condition:
filter(lambda x:x[0]=="pato", l) #[['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]</p>
<p>extract all items by condition with index:</p>
<pre><code> >>> filter(lambda x:x[1][0]=="pato", enumerate(l))
[(1, ['pato', 2, 1]), (3, ['pato', 2, 2]), (4, ['pato', 2, 2])]
>>> map(lambda x:x[1],_)
[['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]
</code></pre>
<p>Note:_ variable only works in interactive interpreter y normal text file _ need explicti assign, ie _=filter(lambda x:x[1][0]=="pato", enumerate(l))</p>
| 0 | 2016-05-04T08:21:41Z | [
"python",
"list",
"tuples",
"reverse-lookup"
] |
How to execute a process remotely using python | 946,946 | <p>I want to connect too and execute a process on a remote server using python. I want to be able to get the return code and stderr(if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from python script.</p>
<p>Cheers.</p>
| 19 | 2009-06-03T20:12:56Z | 946,962 | <p>Well, you can call ssh from python...</p>
<pre><code>import subprocess
ret = subprocess.call(["ssh", "user@host", "program"]);
# or, with stderr:
prog = subprocess.Popen(["ssh", "user@host", "program"], stderr=subprocess.PIPE)
errdata = prog.communicate()[1]
</code></pre>
| 16 | 2009-06-03T20:15:42Z | [
"python",
"ssh"
] |
How to execute a process remotely using python | 946,946 | <p>I want to connect too and execute a process on a remote server using python. I want to be able to get the return code and stderr(if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from python script.</p>
<p>Cheers.</p>
| 19 | 2009-06-03T20:12:56Z | 8,798,354 | <p>Use the <a href="http://pypi.python.org/pypi/paramiko/">ssh module called paramiko</a> which was created for this purpose instead of using <code>subprocess</code>. Here's an example below:</p>
<pre><code>from paramiko import SSHClient
client = SSHClient()
client.load_system_host_keys()
client.connect("hostname", username="user")
stdin, stdout, stderr = client.exec_command('program')
print "stderr: ", stderr.readlines()
print "pwd: ", stdout.readlines()
</code></pre>
<p>UPDATE: The example used to use the <code>ssh</code> module, but that is now deprecated and <a href="http://pypi.python.org/pypi/paramiko/">paramiko</a> is the up-to-date module that provides ssh functionality in python.</p>
| 29 | 2012-01-10T03:55:15Z | [
"python",
"ssh"
] |
How to execute a process remotely using python | 946,946 | <p>I want to connect too and execute a process on a remote server using python. I want to be able to get the return code and stderr(if any) of the process. Has anyone ever done anything like this before. I have done it with ssh, but I want to do it from python script.</p>
<p>Cheers.</p>
| 19 | 2009-06-03T20:12:56Z | 12,491,631 | <p>Maybe if you want to wrap the nuts and bolts of the ssh calls you could use <a href="http://docs.fabfile.org" rel="nofollow">Fabric</a>
This library is geared towards deployment and server management, but it could also be useful for these kind of problems.</p>
<p>Also have a look at <a href="http://docs.celeryproject.org/en/latest/index.html" rel="nofollow">Celery</a>. This implements a task queue for Python/Django on various brokers. Maybe an overkill for your problem, but if you are going to call more functions on multiple machines it will save you a lot of headache managing your connections. </p>
| 3 | 2012-09-19T09:09:26Z | [
"python",
"ssh"
] |
Get file creation time with Python on Mac | 946,967 | <p>Python's os.path.getctime on the Mac (and under Unix in general) does not give the date when a file was created but "the time of the last change" (according to the docs at least). On the other hand in the Finder I can see the real file creation time so this information is kept by HFS+.</p>
<p>Do you have any suggestions on how to obtain the file creation time on the Mac in a Python program? </p>
| 7 | 2009-06-03T20:16:51Z | 946,985 | <p>ctime differs on the platform: <em>On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time</em>. That's because Unices usually don't preserve the "original" creation time.</p>
<p>That said you can access all information that the OS provides with the <a href="http://docs.python.org/library/stat.html" rel="nofollow">stat</a> module.</p>
<blockquote>
<p>The stat module defines constants and functions for interpreting the results of os.stat(), os.fstat() and os.lstat() (if they exist). For complete details about the stat, fstat and lstat calls, consult the documentation for your system.</p>
<p>stat.ST_CTIME<br />
The âctimeâ as reported by the operating system. On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time (see platform documentation for details).</p>
</blockquote>
| 1 | 2009-06-03T20:20:03Z | [
"python",
"osx"
] |
Get file creation time with Python on Mac | 946,967 | <p>Python's os.path.getctime on the Mac (and under Unix in general) does not give the date when a file was created but "the time of the last change" (according to the docs at least). On the other hand in the Finder I can see the real file creation time so this information is kept by HFS+.</p>
<p>Do you have any suggestions on how to obtain the file creation time on the Mac in a Python program? </p>
| 7 | 2009-06-03T20:16:51Z | 947,239 | <p>Use the <a href="https://docs.python.org/3/library/os.html#os.stat_result.st_birthtime" rel="nofollow"><strong><code>st_birthtime</code></strong></a> property on the result of a call to <a href="https://docs.python.org/3/library/os.html#os.stat" rel="nofollow"><code>os.stat()</code></a> (or <code>fstat</code>/<code>lstat</code>).</p>
<pre><code>def get_creation_time(path):
return os.stat(path).st_birthtime
</code></pre>
<p>You can convert the integer result to a datetime object using <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp" rel="nofollow"><code>datetime.datetime.fromtimestamp()</code></a>.</p>
<p><sub>For some reason I don't think this worked on Mac OS X when this answer was first written, but I could be mistaken, and it does work now, even with older versions of Python. The old answer is below for posterity.</sub></p>
<hr>
<p>Using <code>ctypes</code> to access the system call <code>stat64</code> (works with Python 2.5+):</p>
<pre><code>from ctypes import *
class struct_timespec(Structure):
_fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)]
class struct_stat64(Structure):
_fields_ = [
('st_dev', c_int32),
('st_mode', c_uint16),
('st_nlink', c_uint16),
('st_ino', c_uint64),
('st_uid', c_uint32),
('st_gid', c_uint32),
('st_rdev', c_int32),
('st_atimespec', struct_timespec),
('st_mtimespec', struct_timespec),
('st_ctimespec', struct_timespec),
('st_birthtimespec', struct_timespec),
('dont_care', c_uint64 * 8)
]
libc = CDLL('libc.dylib') # or /usr/lib/libc.dylib
stat64 = libc.stat64
stat64.argtypes = [c_char_p, POINTER(struct_stat64)]
def get_creation_time(path):
buf = struct_stat64()
rv = stat64(path, pointer(buf))
if rv != 0:
raise OSError("Couldn't stat file %r" % path)
return buf.st_birthtimespec.tv_sec
</code></pre>
<p>Using <code>subprocess</code> to call the <code>stat</code> utility:</p>
<pre><code>import subprocess
def get_creation_time(path):
p = subprocess.Popen(['stat', '-f%B', path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.wait():
raise OSError(p.stderr.read().rstrip())
else:
return int(p.stdout.read())
</code></pre>
| 14 | 2009-06-03T21:02:52Z | [
"python",
"osx"
] |
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field | 947,077 | <p>I am using <strong>Ubuntu 9.04</strong></p>
<p>I have installed the following package versions:</p>
<pre><code>unixodbc and unixodbc-dev: 2.2.11-16build3
tdsodbc: 0.82-4
libsybdb5: 0.82-4
freetds-common and freetds-dev: 0.82-4
</code></pre>
<p>I have configured <code>/etc/unixodbc.ini</code> like this:</p>
<pre><code>[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/odbc/libtdsodbc.so
Setup = /usr/lib/odbc/libtdsS.so
CPTimeout =
CPReuse =
UsageCount = 2
</code></pre>
<p>I have configured <code>/etc/freetds/freetds.conf</code> like this:</p>
<pre><code>[global]
tds version = 8.0
client charset = UTF-8
</code></pre>
<p>I have grabbed pyodbc revision <code>31e2fae4adbf1b2af1726e5668a3414cf46b454f</code> from <code>http://github.com/mkleehammer/pyodbc</code> and installed it using "<code>python setup.py install</code>"</p>
<p>I have a windows machine with <em>Microsoft SQL Server 2000</em> installed on my local network, up and listening on the local ip address 10.32.42.69. I have an empty database created with name "Common". I have the user "sa" with password "secret" with full priviledges.</p>
<p>I am using the following python code to setup the connection:</p>
<pre><code>import pyodbc
odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS"
con = pyodbc.connect(s)
cur = con.cursor()
cur.execute('''
CREATE TABLE testing (
id INTEGER NOT NULL IDENTITY(1,1),
name NVARCHAR(200) NULL,
PRIMARY KEY (id)
)
''')
con.commit()
</code></pre>
<p>Everything <strong>WORKS</strong> up to this point. I have used SQLServer's Enterprise Manager on the server and the new table is there.
Now I want to insert some data on the table.</p>
<pre><code>cur = con.cursor()
cur.execute('INSERT INTO testing (name) VALUES (?)', (u'something',))
</code></pre>
<p>That fails!! Here's the error I get:</p>
<pre><code>pyodbc.Error: ('HY004', '[HY004] [FreeTDS][SQL Server]Invalid data type
(0) (SQLBindParameter)'
</code></pre>
<p>Since my client is configured to use UTF-8 I thought I could solve by encoding data to UTF-8. That works, but then I get back strange data:</p>
<pre><code>cur = con.cursor()
cur.execute('DELETE FROM testing')
cur.execute('INSERT INTO testing (name) VALUES (?)', (u'somé string'.encode('utf-8'),))
con.commit()
# fetching data back
cur = con.cursor()
cur.execute('SELECT name FROM testing')
data = cur.fetchone()
print type(data[0]), data[0]
</code></pre>
<p>That gives no error, but the data returned is not the same data sent! I get:</p>
<pre><code><type 'unicode'> somé string
</code></pre>
<p>That is, pyodbc won't accept an unicode object directly, but it returns unicode objects back to me! And the encoding is being mixed up!</p>
<p>Now for the question:</p>
<p>I want code to insert unicode data in a NVARCHAR and/or NTEXT field. When I query back, I want the same data I inserted back.</p>
<p>That can be by configuring the system differently, or by using a wrapper function able to convert the data correctly to/from unicode when inserting or retrieving</p>
<p>That's not asking much, is it?</p>
| 21 | 2009-06-03T20:35:24Z | 953,881 | <p>I use UCS-2 to interact with SQL Server, not UTF-8.</p>
<p>Correction: I changed the .freetds.conf entry so that the client uses UTF-8</p>
<pre><code> tds version = 8.0
client charset = UTF-8
text size = 32768
</code></pre>
<p>Now, bind values work fine for UTF-8 encoded strings.
The driver converts transparently between the UCS-2 used for storage on the dataserver side and the UTF-8 encoded strings given to/taken from the client.</p>
<p>This is with pyodbc 2.0 on Solaris 10 running Python 2.5 and FreeTDS freetds-0.82.1.dev.20081111 and SQL Server 2008</p>
<pre>
import pyodbc
test_string = u"""Comment ça va ? Très bien ?"""
print type(test_string),repr(test_string)
utf8 = 'utf8:' + test_string.encode('UTF-8')
print type(utf8), repr(utf8)
c = pyodbc.connect('DSN=SA_SQL_SERVER_TEST;UID=XXX;PWD=XXX')
cur = c.cursor()
# This does not work as test_string is not UTF-encoded
try:
cur.execute('INSERT unicode_test(t) VALUES(?)', test_string)
c.commit()
except pyodbc.Error,e:
print e
# This one does:
try:
cur.execute('INSERT unicode_test(t) VALUES(?)', utf8)
c.commit()
except pyodbc.Error,e:
print e
</pre>
<p>Here is the output from the test table (I had manually put in a bunch of test data via Management Studio)</p>
<pre>
In [41]: for i in cur.execute('SELECT t FROM unicode_test'):
....: print i
....:
....:
('this is not a banana', )
('\xc3\x85kergatan 24', )
('\xc3\x85kergatan 24', )
('\xe6\xb0\xb4 this is code-point 63CF', )
('Mich\xc3\xa9l', )
('Comment a va ? Trs bien ?', )
('utf8:Comment \xc3\xa7a va ? Tr\xc3\xa8s bien ?', )
</pre>
<p>I was able to put in some in unicode code points directly into the table from Management Studio by the 'Edit Top 200 rows' dialog and entering the hex digits for the unicode code point and then pressing Alt-X</p>
| 1 | 2009-06-05T01:28:17Z | [
"python",
"sql-server",
"unicode",
"utf-8",
"pyodbc"
] |
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field | 947,077 | <p>I am using <strong>Ubuntu 9.04</strong></p>
<p>I have installed the following package versions:</p>
<pre><code>unixodbc and unixodbc-dev: 2.2.11-16build3
tdsodbc: 0.82-4
libsybdb5: 0.82-4
freetds-common and freetds-dev: 0.82-4
</code></pre>
<p>I have configured <code>/etc/unixodbc.ini</code> like this:</p>
<pre><code>[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/odbc/libtdsodbc.so
Setup = /usr/lib/odbc/libtdsS.so
CPTimeout =
CPReuse =
UsageCount = 2
</code></pre>
<p>I have configured <code>/etc/freetds/freetds.conf</code> like this:</p>
<pre><code>[global]
tds version = 8.0
client charset = UTF-8
</code></pre>
<p>I have grabbed pyodbc revision <code>31e2fae4adbf1b2af1726e5668a3414cf46b454f</code> from <code>http://github.com/mkleehammer/pyodbc</code> and installed it using "<code>python setup.py install</code>"</p>
<p>I have a windows machine with <em>Microsoft SQL Server 2000</em> installed on my local network, up and listening on the local ip address 10.32.42.69. I have an empty database created with name "Common". I have the user "sa" with password "secret" with full priviledges.</p>
<p>I am using the following python code to setup the connection:</p>
<pre><code>import pyodbc
odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS"
con = pyodbc.connect(s)
cur = con.cursor()
cur.execute('''
CREATE TABLE testing (
id INTEGER NOT NULL IDENTITY(1,1),
name NVARCHAR(200) NULL,
PRIMARY KEY (id)
)
''')
con.commit()
</code></pre>
<p>Everything <strong>WORKS</strong> up to this point. I have used SQLServer's Enterprise Manager on the server and the new table is there.
Now I want to insert some data on the table.</p>
<pre><code>cur = con.cursor()
cur.execute('INSERT INTO testing (name) VALUES (?)', (u'something',))
</code></pre>
<p>That fails!! Here's the error I get:</p>
<pre><code>pyodbc.Error: ('HY004', '[HY004] [FreeTDS][SQL Server]Invalid data type
(0) (SQLBindParameter)'
</code></pre>
<p>Since my client is configured to use UTF-8 I thought I could solve by encoding data to UTF-8. That works, but then I get back strange data:</p>
<pre><code>cur = con.cursor()
cur.execute('DELETE FROM testing')
cur.execute('INSERT INTO testing (name) VALUES (?)', (u'somé string'.encode('utf-8'),))
con.commit()
# fetching data back
cur = con.cursor()
cur.execute('SELECT name FROM testing')
data = cur.fetchone()
print type(data[0]), data[0]
</code></pre>
<p>That gives no error, but the data returned is not the same data sent! I get:</p>
<pre><code><type 'unicode'> somé string
</code></pre>
<p>That is, pyodbc won't accept an unicode object directly, but it returns unicode objects back to me! And the encoding is being mixed up!</p>
<p>Now for the question:</p>
<p>I want code to insert unicode data in a NVARCHAR and/or NTEXT field. When I query back, I want the same data I inserted back.</p>
<p>That can be by configuring the system differently, or by using a wrapper function able to convert the data correctly to/from unicode when inserting or retrieving</p>
<p>That's not asking much, is it?</p>
| 21 | 2009-06-03T20:35:24Z | 964,825 | <p>I can remember having this kind of stupid problems using odbc drivers, even if that time it was a java+oracle combination.</p>
<p>The core thing is that odbc driver apparently encodes the query string when sending it to the DB. Even if the field is Unicode, and if you provide Unicode, in some cases it does not seem to matter.</p>
<p>You need to ensure that what is sent by the driver has the same encoding as your Database (not only server, but also database). Otherwise, of course you get funky characters because either the client or the server is mixing things up when encoding/or decoding. Do you have any idea of the charset (codepoint as MS like to say) that your server is using as a default for decoding data?</p>
<h2>Collation has nothing to do with this problem :)</h2>
<p>See <a href="http://msdn.microsoft.com/en-us/library/aa174903%28SQL.80%29.aspx">that MS page</a> for example. For Unicode fields, collation is used only to define the sort order in the column, <strong>not</strong> to specify how the data is stored. </p>
<p>If you store your data as Unicode, there is an Unique way to represent it, that's the purpose of Unicode: no need to define a charset that is compatible with all the languages that you are going to use :) </p>
<p>The question here is "what happens when I give data to the server that is <em>not</em> Unicode?". For example: </p>
<ul>
<li>When I send an UTF-8 string to the server, how does it understand it?</li>
<li>When I send an UTF-16 string to the server, how does it understand it?</li>
<li>When I send a Latin1 string to the server, how does it understand it?</li>
</ul>
<p>From the server perspective, all these 3 strings are only a stream of bytes. The server cannot guess the encoding in which you encoded them. Which means that you <em>will</em> get troubles if your odbc client ends up sending <em>bytestrings</em> (an encoded string) to the server instead of sending <em>unicode</em> data: if you do so, the server will use a predefined encoding (that was my question: what encoding the server will use? Since it is not guessing, it must be a parameter value), and if the string had been encoded using a different encoding, <em>dzing</em>, data will get corrupted.</p>
<p>It's exactly similar as doing in Python:</p>
<pre><code>uni = u'Hey my name is André'
in_utf8 = uni.encode('utf-8')
# send the utf-8 data to server
# send(in_utf8)
# on server side
# server receives it. But server is Japanese.
# So the server treats the data with the National charset, shift-jis:
some_string = in_utf8 # some_string = receive()
decoded = some_string.decode('sjis')
</code></pre>
<p>Just try it. It's fun. The decoded string is supposed to be "Hey my name is André", but is "Hey my name is Andrï¾ï½©". é gets replaced by Japanese ï¾ï½©</p>
<p>Hence my suggestion: you need to ensure that pyodbc is able to send directly the data as Unicode. If pyodbc fails to do this, you will get unexpected results.</p>
<p>And I described the problem in the Client to Server way. But the same sort of issues can arise when communicating back from the Server to the Client. If the Client cannot understand Unicode data, you'll likely get into troubles.</p>
<h2>FreeTDS handles Unicode for you.</h2>
<p>Actually, FreeTDS takes care of things for you and translates all the data to UCS2 unicode. (<a href="http://www.freetds.org/userguide/unicodefreetds.htm">Source</a>).</p>
<ul>
<li>Server <--> FreeTDS : UCS2 data</li>
<li>FreeTDS <--> pyodbc : encoded strings, encoded in UTF-8 (from <code>/etc/freetds/freetds.conf</code>)</li>
</ul>
<p>So I would expect your application to work correctly if you pass UTF-8 data to pyodbc. In fact, as this <a href="http://code.google.com/p/django-pyodbc/issues/detail?id=41">django-pyodbc ticket</a> states, django-pyodbc communicates in UTF-8 with pyodbc, so you should be fine. </p>
<h3>FreeTDS 0.82</h3>
<p>However, <a href="http://code.google.com/p/django-pyodbc/issues/detail?id=41#c1">cramm0</a> says that FreeTDS 0.82 is not completely bugfree, and that there are significant differences between 0.82 and the official patched 0.82 version that can be found <a href="http://freetds.sourceforge.net/">here</a>. You should probably try using the patched FreeTDS</p>
<p><hr /></p>
<p><strong>Edited</strong>: <em>removed old data, which had nothing to do with FreeTDS but was only relevant to Easysoft commercial odbc driver. Sorry.</em></p>
| 20 | 2009-06-08T13:06:21Z | [
"python",
"sql-server",
"unicode",
"utf-8",
"pyodbc"
] |
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field | 947,077 | <p>I am using <strong>Ubuntu 9.04</strong></p>
<p>I have installed the following package versions:</p>
<pre><code>unixodbc and unixodbc-dev: 2.2.11-16build3
tdsodbc: 0.82-4
libsybdb5: 0.82-4
freetds-common and freetds-dev: 0.82-4
</code></pre>
<p>I have configured <code>/etc/unixodbc.ini</code> like this:</p>
<pre><code>[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/odbc/libtdsodbc.so
Setup = /usr/lib/odbc/libtdsS.so
CPTimeout =
CPReuse =
UsageCount = 2
</code></pre>
<p>I have configured <code>/etc/freetds/freetds.conf</code> like this:</p>
<pre><code>[global]
tds version = 8.0
client charset = UTF-8
</code></pre>
<p>I have grabbed pyodbc revision <code>31e2fae4adbf1b2af1726e5668a3414cf46b454f</code> from <code>http://github.com/mkleehammer/pyodbc</code> and installed it using "<code>python setup.py install</code>"</p>
<p>I have a windows machine with <em>Microsoft SQL Server 2000</em> installed on my local network, up and listening on the local ip address 10.32.42.69. I have an empty database created with name "Common". I have the user "sa" with password "secret" with full priviledges.</p>
<p>I am using the following python code to setup the connection:</p>
<pre><code>import pyodbc
odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS"
con = pyodbc.connect(s)
cur = con.cursor()
cur.execute('''
CREATE TABLE testing (
id INTEGER NOT NULL IDENTITY(1,1),
name NVARCHAR(200) NULL,
PRIMARY KEY (id)
)
''')
con.commit()
</code></pre>
<p>Everything <strong>WORKS</strong> up to this point. I have used SQLServer's Enterprise Manager on the server and the new table is there.
Now I want to insert some data on the table.</p>
<pre><code>cur = con.cursor()
cur.execute('INSERT INTO testing (name) VALUES (?)', (u'something',))
</code></pre>
<p>That fails!! Here's the error I get:</p>
<pre><code>pyodbc.Error: ('HY004', '[HY004] [FreeTDS][SQL Server]Invalid data type
(0) (SQLBindParameter)'
</code></pre>
<p>Since my client is configured to use UTF-8 I thought I could solve by encoding data to UTF-8. That works, but then I get back strange data:</p>
<pre><code>cur = con.cursor()
cur.execute('DELETE FROM testing')
cur.execute('INSERT INTO testing (name) VALUES (?)', (u'somé string'.encode('utf-8'),))
con.commit()
# fetching data back
cur = con.cursor()
cur.execute('SELECT name FROM testing')
data = cur.fetchone()
print type(data[0]), data[0]
</code></pre>
<p>That gives no error, but the data returned is not the same data sent! I get:</p>
<pre><code><type 'unicode'> somé string
</code></pre>
<p>That is, pyodbc won't accept an unicode object directly, but it returns unicode objects back to me! And the encoding is being mixed up!</p>
<p>Now for the question:</p>
<p>I want code to insert unicode data in a NVARCHAR and/or NTEXT field. When I query back, I want the same data I inserted back.</p>
<p>That can be by configuring the system differently, or by using a wrapper function able to convert the data correctly to/from unicode when inserting or retrieving</p>
<p>That's not asking much, is it?</p>
| 21 | 2009-06-03T20:35:24Z | 994,431 | <p>Are you sure it's INSERT that's causing problem not reading?
There's a bug open on pyodbc <a href="http://code.google.com/p/pyodbc/issues/detail?id=13" rel="nofollow">Problem fetching NTEXT and NVARCHAR data</a>.</p>
| 0 | 2009-06-15T03:50:11Z | [
"python",
"sql-server",
"unicode",
"utf-8",
"pyodbc"
] |
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field | 947,077 | <p>I am using <strong>Ubuntu 9.04</strong></p>
<p>I have installed the following package versions:</p>
<pre><code>unixodbc and unixodbc-dev: 2.2.11-16build3
tdsodbc: 0.82-4
libsybdb5: 0.82-4
freetds-common and freetds-dev: 0.82-4
</code></pre>
<p>I have configured <code>/etc/unixodbc.ini</code> like this:</p>
<pre><code>[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/odbc/libtdsodbc.so
Setup = /usr/lib/odbc/libtdsS.so
CPTimeout =
CPReuse =
UsageCount = 2
</code></pre>
<p>I have configured <code>/etc/freetds/freetds.conf</code> like this:</p>
<pre><code>[global]
tds version = 8.0
client charset = UTF-8
</code></pre>
<p>I have grabbed pyodbc revision <code>31e2fae4adbf1b2af1726e5668a3414cf46b454f</code> from <code>http://github.com/mkleehammer/pyodbc</code> and installed it using "<code>python setup.py install</code>"</p>
<p>I have a windows machine with <em>Microsoft SQL Server 2000</em> installed on my local network, up and listening on the local ip address 10.32.42.69. I have an empty database created with name "Common". I have the user "sa" with password "secret" with full priviledges.</p>
<p>I am using the following python code to setup the connection:</p>
<pre><code>import pyodbc
odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS"
con = pyodbc.connect(s)
cur = con.cursor()
cur.execute('''
CREATE TABLE testing (
id INTEGER NOT NULL IDENTITY(1,1),
name NVARCHAR(200) NULL,
PRIMARY KEY (id)
)
''')
con.commit()
</code></pre>
<p>Everything <strong>WORKS</strong> up to this point. I have used SQLServer's Enterprise Manager on the server and the new table is there.
Now I want to insert some data on the table.</p>
<pre><code>cur = con.cursor()
cur.execute('INSERT INTO testing (name) VALUES (?)', (u'something',))
</code></pre>
<p>That fails!! Here's the error I get:</p>
<pre><code>pyodbc.Error: ('HY004', '[HY004] [FreeTDS][SQL Server]Invalid data type
(0) (SQLBindParameter)'
</code></pre>
<p>Since my client is configured to use UTF-8 I thought I could solve by encoding data to UTF-8. That works, but then I get back strange data:</p>
<pre><code>cur = con.cursor()
cur.execute('DELETE FROM testing')
cur.execute('INSERT INTO testing (name) VALUES (?)', (u'somé string'.encode('utf-8'),))
con.commit()
# fetching data back
cur = con.cursor()
cur.execute('SELECT name FROM testing')
data = cur.fetchone()
print type(data[0]), data[0]
</code></pre>
<p>That gives no error, but the data returned is not the same data sent! I get:</p>
<pre><code><type 'unicode'> somé string
</code></pre>
<p>That is, pyodbc won't accept an unicode object directly, but it returns unicode objects back to me! And the encoding is being mixed up!</p>
<p>Now for the question:</p>
<p>I want code to insert unicode data in a NVARCHAR and/or NTEXT field. When I query back, I want the same data I inserted back.</p>
<p>That can be by configuring the system differently, or by using a wrapper function able to convert the data correctly to/from unicode when inserting or retrieving</p>
<p>That's not asking much, is it?</p>
| 21 | 2009-06-03T20:35:24Z | 7,929,603 | <p>I had the same problem when trying to bind unicode parameter:
'[HY004] [FreeTDS][SQL Server]Invalid data type (0) (SQLBindParameter)'</p>
<p>I solved it by upgrading freetds to version 0.91. </p>
<p>I use pyodbc 2.1.11. I had to apply <a href="http://code.google.com/p/pyodbc/issues/attachmentText?id=170&aid=1700009000&name=pyodbc_sqlwchar.patch&token=b1544dc75931626188818536df608f3d%20this" rel="nofollow">this</a> patch to make it work with unicode, otherwise I was getting memory corruption errors occasionally. </p>
| 1 | 2011-10-28T12:59:48Z | [
"python",
"sql-server",
"unicode",
"utf-8",
"pyodbc"
] |
Custom simple Python HTTP server not serving css files | 947,372 | <p>I had found written in python, a very simple http server, it's do_get method looks like this:</p>
<pre><code>def do_GET(self):
try:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers();
filepath = self.path
print filepath, USTAW['rootwww']
f = file("./www" + filepath)
s = f.readline();
while s != "":
self.wfile.write(s);
s = f.readline();
return
except IOError:
self.send_error(404,'File Not Found: %s ' % filepath)
</code></pre>
<p>It works ok, besides the fact - that it is not serving any css files ( it is rendered without css). Anyone got a suggestion / solution for this quirk?</p>
<p>Best regards,
praavDa</p>
| 4 | 2009-06-03T21:31:32Z | 947,442 | <p>You're explicitly serving all files as <code>Content-type: text/html</code>, where you need to serve CSS files as <code>Content-type: text/css</code>. See <a href="http://css-discuss.incutio.com/?page=MozillaCssMimeType">this page on the CSS-Discuss Wiki</a> for details. Web servers usually have a lookup table to map from file extension to Content-Type.</p>
| 9 | 2009-06-03T21:44:24Z | [
"python",
"css",
"http"
] |
Custom simple Python HTTP server not serving css files | 947,372 | <p>I had found written in python, a very simple http server, it's do_get method looks like this:</p>
<pre><code>def do_GET(self):
try:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers();
filepath = self.path
print filepath, USTAW['rootwww']
f = file("./www" + filepath)
s = f.readline();
while s != "":
self.wfile.write(s);
s = f.readline();
return
except IOError:
self.send_error(404,'File Not Found: %s ' % filepath)
</code></pre>
<p>It works ok, besides the fact - that it is not serving any css files ( it is rendered without css). Anyone got a suggestion / solution for this quirk?</p>
<p>Best regards,
praavDa</p>
| 4 | 2009-06-03T21:31:32Z | 947,443 | <p>it seems to be returning the html mimetype for all files:</p>
<pre><code>self.send_header('Content-type', 'text/html')
</code></pre>
<p>Also, it seems to be pretty bad. Why are you interested in this sucky server? Look at cherrypy or paste for good python implementations of HTTP server and a good code to study.</p>
<p><hr /></p>
<p><strong>EDIT</strong>: Trying to fix it for you:</p>
<pre><code>import os
import mimetypes
#...
def do_GET(self):
try:
filepath = self.path
print filepath, USTAW['rootwww']
f = open(os.path.join('.', 'www', filepath))
except IOError:
self.send_error(404,'File Not Found: %s ' % filepath)
else:
self.send_response(200)
mimetype, _ = mimetypes.guess_type(filepath)
self.send_header('Content-type', mimetype)
self.end_headers()
for s in f:
self.wfile.write(s)
</code></pre>
| 5 | 2009-06-03T21:44:47Z | [
"python",
"css",
"http"
] |
Custom simple Python HTTP server not serving css files | 947,372 | <p>I had found written in python, a very simple http server, it's do_get method looks like this:</p>
<pre><code>def do_GET(self):
try:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers();
filepath = self.path
print filepath, USTAW['rootwww']
f = file("./www" + filepath)
s = f.readline();
while s != "":
self.wfile.write(s);
s = f.readline();
return
except IOError:
self.send_error(404,'File Not Found: %s ' % filepath)
</code></pre>
<p>It works ok, besides the fact - that it is not serving any css files ( it is rendered without css). Anyone got a suggestion / solution for this quirk?</p>
<p>Best regards,
praavDa</p>
| 4 | 2009-06-03T21:31:32Z | 947,592 | <p>See <a href="http://hg.python.org/cpython/file/3481c6f36e55/Lib/SimpleHTTPServer.py" rel="nofollow"><code>SimpleHTTPServer.py</code></a> in the standard library for a safer, saner implementation that you can customize if you need.</p>
| 2 | 2009-06-03T22:28:02Z | [
"python",
"css",
"http"
] |
How to I reload global vars on every page refresh in DJango | 947,436 | <p>Here is my problem. DJango continues to store all the global objects after the first run of a script. For instance, an object you instantiate in views.py globally will be there until you restart the app server. This is fine unless your object is tied to some outside resource that may time out. Now the way I was thinking to correct was some sort of factory method that checks if the object is instantiated and creates it if it's not, and then returns it. However, the this fails because the object exists there since the last page request, so a factory method is always returning the object that was instantiated during the first request.</p>
<p>What I am looking for is a way to trigger something to happen on a per request basis. I have seen ways of doing this by implementing your own middleware, but I think that is overkill. Does anyone know of some reserved methods or some other per request trigger.</p>
| 0 | 2009-06-03T21:43:37Z | 947,486 | <p>Simple: Don't use global objects.
If you want an object inside the view, instantiate it inside the view, not as global. That way it will be collected after the view ends.</p>
| 6 | 2009-06-03T21:56:42Z | [
"python",
"django"
] |
Strip all non-numeric characters (except for ".") from a string in Python | 947,776 | <p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p>
<pre><code>val = ''.join([c for c in val if c in '1234567890.'])
</code></pre>
<p>What would you do?</p>
| 37 | 2009-06-03T23:12:00Z | 947,789 | <pre><code>>>> import re
>>> non_decimal = re.compile(r'[^\d.]+')
>>> non_decimal.sub('', '12.34fe4e')
'12.344'
</code></pre>
| 80 | 2009-06-03T23:14:46Z | [
"python"
] |
Strip all non-numeric characters (except for ".") from a string in Python | 947,776 | <p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p>
<pre><code>val = ''.join([c for c in val if c in '1234567890.'])
</code></pre>
<p>What would you do?</p>
| 37 | 2009-06-03T23:12:00Z | 947,868 | <p>Here's some sample code:</p>
<pre><code>$ cat a.py
a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw'
for i in xrange(1000000):
''.join([c for c in a if c in '1234567890.'])
</code></pre>
<hr>
<pre><code>$ cat b.py
import re
non_decimal = re.compile(r'[^\d.]+')
a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw'
for i in xrange(1000000):
non_decimal.sub('', a)
</code></pre>
<hr>
<pre><code>$ cat c.py
a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw'
for i in xrange(1000000):
''.join([c for c in a if c.isdigit() or c == '.'])
</code></pre>
<hr>
<pre><code>$ cat d.py
a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw'
for i in xrange(1000000):
b = []
for c in a:
if c.isdigit() or c == '.': continue
b.append(c)
''.join(b)
</code></pre>
<p>And the timing results:</p>
<hr>
<pre><code>$ time python a.py
real 0m24.735s
user 0m21.049s
sys 0m0.456s
$ time python b.py
real 0m10.775s
user 0m9.817s
sys 0m0.236s
$ time python c.py
real 0m38.255s
user 0m32.718s
sys 0m0.724s
$ time python d.py
real 0m46.040s
user 0m41.515s
sys 0m0.832s
</code></pre>
<hr>
<p>Looks like the regex is the winner so far. </p>
<p>Personally, I find the regex just as readable as the list comprehension. If you're doing it just a few times then you'll probably take a bigger hit on compiling the regex. Do what jives with your code and coding style.</p>
| 13 | 2009-06-03T23:44:12Z | [
"python"
] |
Strip all non-numeric characters (except for ".") from a string in Python | 947,776 | <p>I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:</p>
<pre><code>val = ''.join([c for c in val if c in '1234567890.'])
</code></pre>
<p>What would you do?</p>
| 37 | 2009-06-03T23:12:00Z | 948,855 | <p>Another 'pythonic' approach</p>
<p><code>filter( lambda x: x in '0123456789.', s )</code></p>
<p>but regex is faster.</p>
| 10 | 2009-06-04T06:24:02Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.