title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Python: Why is ("hello" is "hello")? | 1,392,433 | <p>Why is <code>"hello" is "hello" == True</code> in Python?</p>
<p>I read the following <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">here</a>:</p>
<blockquote>
<p>If two string literals are equal, they have been put to same
memory location. A string is an immutable entity. No harm can
be done.</p>
</blockquote>
<p>So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?</p>
| 48 | 2009-09-08T07:13:19Z | 1,392,440 | <p>Python (like Java, C, C++, .NET) uses string pooling / interning. The interpreter realises that "hello" is the same as "hello", so it optimizes and uses the same location in memory.</p>
<p>Another goodie: "hell" + "o" is "hello" ==> True</p>
| 76 | 2009-09-08T07:15:09Z | [
"python",
"identity"
] |
Python: Why is ("hello" is "hello")? | 1,392,433 | <p>Why is <code>"hello" is "hello" == True</code> in Python?</p>
<p>I read the following <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">here</a>:</p>
<blockquote>
<p>If two string literals are equal, they have been put to same
memory location. A string is an immutable entity. No harm can
be done.</p>
</blockquote>
<p>So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?</p>
| 48 | 2009-09-08T07:13:19Z | 1,392,446 | <p>The Python interpreter/compiler parses the string literals, i.e. the quoted list of characters. When it does this, it can detect "I've seen this string before", and use the same representation as last time. It can do this since it knows that strings defined in this way cannot be changed.</p>
| 1 | 2009-09-08T07:16:24Z | [
"python",
"identity"
] |
Python: Why is ("hello" is "hello")? | 1,392,433 | <p>Why is <code>"hello" is "hello" == True</code> in Python?</p>
<p>I read the following <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">here</a>:</p>
<blockquote>
<p>If two string literals are equal, they have been put to same
memory location. A string is an immutable entity. No harm can
be done.</p>
</blockquote>
<p>So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?</p>
| 48 | 2009-09-08T07:13:19Z | 1,392,449 | <p>Literal strings are probably grouped based on their hash or something similar. Two of the same literal strings will be stored in the same memory, and any references both refer to that.</p>
<pre><code> Memory Code
-------
| myLine = "hello"
| /
|hello <
| \
| myLine = "hello"
-------
</code></pre>
| 12 | 2009-09-08T07:16:34Z | [
"python",
"identity"
] |
Python: Why is ("hello" is "hello")? | 1,392,433 | <p>Why is <code>"hello" is "hello" == True</code> in Python?</p>
<p>I read the following <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">here</a>:</p>
<blockquote>
<p>If two string literals are equal, they have been put to same
memory location. A string is an immutable entity. No harm can
be done.</p>
</blockquote>
<p>So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?</p>
| 48 | 2009-09-08T07:13:19Z | 1,392,451 | <p>The <code>is</code> operator returns true if both arguments are the same object. Your result is a consequence of this, and the quoted bit. </p>
<p>In the case of string literals, these are interned, meaning they are compared to known strings. If an identical string is already known, the literal takes that value, instead of an alternative one. Thus, they become the same object, and the expression is true.</p>
| 6 | 2009-09-08T07:16:54Z | [
"python",
"identity"
] |
Python: Why is ("hello" is "hello")? | 1,392,433 | <p>Why is <code>"hello" is "hello" == True</code> in Python?</p>
<p>I read the following <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">here</a>:</p>
<blockquote>
<p>If two string literals are equal, they have been put to same
memory location. A string is an immutable entity. No harm can
be done.</p>
</blockquote>
<p>So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?</p>
| 48 | 2009-09-08T07:13:19Z | 1,392,927 | <blockquote>
<p>So there is one and only one place in memory for every Python string?</p>
</blockquote>
<p>No, only ones the interpreter has decided to optimise, which is a decision based on a policy that isn't part of the language specification and which may change in different CPython versions.</p>
<p>eg. on my install (2.6.2 Linux):</p>
<pre><code>>>> 'X'*10 is 'X'*10
True
>>> 'X'*30 is 'X'*30
False
</code></pre>
<p>similarly for ints:</p>
<pre><code>>>> 2**8 is 2**8
True
>>> 2**9 is 2**9
False
</code></pre>
<p>So don't rely on 'string' is 'string': even just looking at the C implementation it isn't safe.</p>
| 55 | 2009-09-08T09:19:59Z | [
"python",
"identity"
] |
Python: Why is ("hello" is "hello")? | 1,392,433 | <p>Why is <code>"hello" is "hello" == True</code> in Python?</p>
<p>I read the following <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">here</a>:</p>
<blockquote>
<p>If two string literals are equal, they have been put to same
memory location. A string is an immutable entity. No harm can
be done.</p>
</blockquote>
<p>So there is one and only one place in memory for every Python string? Sounds pretty strange. What's going on here?</p>
| 48 | 2009-09-08T07:13:19Z | 1,392,928 | <p>I think if any two variables (not just strings) contain the same value, the value will be stored only once not twice and both the variables will point to the same location. This saves memory.</p>
| 0 | 2009-09-08T09:20:17Z | [
"python",
"identity"
] |
What python data structure and parser should I use with Apple's system_profiler? | 1,392,604 | <p>My problem is one like a simulated problem from
<a href="http://my.safaribooksonline.com/0596007973/pythoncook2-CHP-10-SECT-17" rel="nofollow">http://my.safaribooksonline.com/0596007973/pythoncook2-CHP-10-SECT-17</a>
which eventually made its way into Python Cookbook, 2nd Edition using an outdated xpath method from 2005 that I haven't been able to get to work with 10.6's build-in python(nor installing older packages) </p>
<p>I want to ... "retrieve detailed information about a Mac OS X system" using system_profiler to summarize it in a script each time a computer starts up(The script will launch on login).<br />
The information I'm gathering varies from SW versions to HW config.</p>
<p>An example line is,
system_profiler SPSoftwareDataType | grep 'Boot Volume'
which returns the startup volume name. I make 15 to 20 other calls for information. </p>
<p>I've tried to output the full 'system_profiler > data' and parse that using cat data | grep, but that's obviously inefficient to the point where it's been faster if I just run each line like my example above.<br />
18 seconds if ouputting to a file and cat | grep.</p>
<p>13 seconds if making individual calls</p>
<p>*I'm trying to make it as fast as possible. </p>
<p>I deduce that I probably need to create a dictionary and use keys to reference out the data but I'm wondering what's the most efficient way for me to parse and retrieve the data? I've seen a suggestion elsewhere to use system_profiler to output to XML and use a XML parser but I think there's probably some cache and parse method that does it more efficiently than outputting to a file first.</p>
| 0 | 2009-09-08T08:01:26Z | 1,392,719 | <p>Use the -xml option to <code>system_profiler</code> to format the output in a standard OS X plist format, then use Python's built-in <a href="http://docs.python.org/library/plistlib.html">plistlib</a> to parse into an appropriate data structure you can introspect. A simple example:</p>
<pre><code>>>> from subprocess import Popen, PIPE
>>> from plistlib import readPlistFromString
>>> from pprint import pprint
>>> sp = Popen(["system_profiler", "-xml"], stdout=PIPE).communicate()[0]
>>> pprint(readPlistFromString(sp))
[{'_dataType': 'SPHardwareDataType',
'_detailLevel': '-2',
'_items': [{'SMC_version_system': '1.21f4',
'_name': 'hardware_overview',
'boot_rom_version': 'IM71.007A.B03',
'bus_speed': '800 MHz',
'cpu_type': 'Intel Core 2 Duo',
...
</code></pre>
| 5 | 2009-09-08T08:30:58Z | [
"python",
"osx",
"parsing",
"profiler",
"system-profiler"
] |
Django template, how to make a dropdown box with the predefined value selected? | 1,392,706 | <p>I am trying to create a drop down list box with the selected value equal to a value passed from the template values, but with no success. Can anyone take a look and show me what I am doing wrong.</p>
<pre><code> <select name="movie">
{% for movie in movies %}
{% ifequal movie.id selected_movie.id %}
<option value="{{movie.key}}" selected="true">Movie {{movie.id}}: {{movie.name}}</option>
{% endifequal %}
{% ifnotequal movie.id selected_movie.id %}
<option value="{{movie.key}}">Movie {{movie.id}}: {{movie.name}}</option>
{% endifnotequal %}
{% endfor %}
</select>
</code></pre>
<p>In this example, movies and selected_movie are passed from the template values.
Please advice!</p>
| 4 | 2009-09-08T08:27:48Z | 1,392,747 | <p>Your code works for me with django 1.0.2 and firefox 3.5.</p>
<p>You can use {% else %} instead of {% ifnotequal %} and set selected="selected". Hope it helps.</p>
<pre><code><select name="movie">
{% for movie in movies %}
{% ifequal movie.id selected_movie.id %}
<option value="{{movie.key}}" selected="selected">Movie {{movie.id}}: {{movie.name}}</option>
{% else %}
<option value="{{movie.key}}">Movie {{movie.id}}: {{movie.name}}</option>
{% endifequal %}
{% endfor %}
</select>
</code></pre>
| 9 | 2009-09-08T08:40:05Z | [
"python",
"django",
"django-templates"
] |
Problem with subprocess.call | 1,392,757 | <p>In my current working directory I have the dir ROOT/ with some files inside.</p>
<p>I know I can exec <code>cp -r ROOT/* /dst</code> and I have no problems.</p>
<p>But if I open my Python console and I write this:</p>
<pre><code>import subprocess
subprocess.call(['cp', '-r', 'ROOT/*', '/dst'])
</code></pre>
<p>It doesn't work!</p>
<p>I have this error: <code>cp: cannot stat ROOT/*: No such file or directory</code></p>
<p>Can you help me?</p>
| 11 | 2009-09-08T08:42:10Z | 1,392,785 | <p>The <code>*</code> will not be expanded to filenames. This is a function of the shell. Here you actually want to copy a file named *. Use <code>subprocess.call()</code> with the parameter <code>shell=True</code>.</p>
| 4 | 2009-09-08T08:49:23Z | [
"python",
"subprocess"
] |
Problem with subprocess.call | 1,392,757 | <p>In my current working directory I have the dir ROOT/ with some files inside.</p>
<p>I know I can exec <code>cp -r ROOT/* /dst</code> and I have no problems.</p>
<p>But if I open my Python console and I write this:</p>
<pre><code>import subprocess
subprocess.call(['cp', '-r', 'ROOT/*', '/dst'])
</code></pre>
<p>It doesn't work!</p>
<p>I have this error: <code>cp: cannot stat ROOT/*: No such file or directory</code></p>
<p>Can you help me?</p>
| 11 | 2009-09-08T08:42:10Z | 1,392,905 | <p>Try</p>
<pre><code>subprocess.call('cp -r ROOT/* /dst', shell=True)
</code></pre>
<p>Note the use of a single string rather than an array here.</p>
<p>Or build up your own implementation with <a href="http://docs.python.org/library/os.html#os.listdir">listdir</a> and <a href="http://docs.python.org/library/shutil.html#shutil.copy">copy</a></p>
| 7 | 2009-09-08T09:16:02Z | [
"python",
"subprocess"
] |
Problem with subprocess.call | 1,392,757 | <p>In my current working directory I have the dir ROOT/ with some files inside.</p>
<p>I know I can exec <code>cp -r ROOT/* /dst</code> and I have no problems.</p>
<p>But if I open my Python console and I write this:</p>
<pre><code>import subprocess
subprocess.call(['cp', '-r', 'ROOT/*', '/dst'])
</code></pre>
<p>It doesn't work!</p>
<p>I have this error: <code>cp: cannot stat ROOT/*: No such file or directory</code></p>
<p>Can you help me?</p>
| 11 | 2009-09-08T08:42:10Z | 5,040,567 | <p>Just came across this while trying to do something similar.</p>
<blockquote>
<p>The * will not be expanded to filenames</p>
</blockquote>
<p>Exactly. If you look at the man page of <code>cp</code> you can call it with any number of source arguments and you can easily change the order of the arguments with the <code>-t</code> switch.</p>
<pre><code>import glob
import subprocess
subprocess.call(['cp', '-rt', '/dst'] + glob.glob('ROOT/*'))
</code></pre>
| 9 | 2011-02-18T11:10:52Z | [
"python",
"subprocess"
] |
Problem with subprocess.call | 1,392,757 | <p>In my current working directory I have the dir ROOT/ with some files inside.</p>
<p>I know I can exec <code>cp -r ROOT/* /dst</code> and I have no problems.</p>
<p>But if I open my Python console and I write this:</p>
<pre><code>import subprocess
subprocess.call(['cp', '-r', 'ROOT/*', '/dst'])
</code></pre>
<p>It doesn't work!</p>
<p>I have this error: <code>cp: cannot stat ROOT/*: No such file or directory</code></p>
<p>Can you help me?</p>
| 11 | 2009-09-08T08:42:10Z | 8,036,844 | <p>Provide the command as list instead of the string + list.</p>
<p>The following two commands are same:-</p>
<pre><code>First Command:-
test=subprocess.Popen(['rm','aa','bb'])
Second command:-
list1=['rm','aa','bb']
test=subprocess.Popen(list1)
</code></pre>
<p>So to copy multiple files, one need to get the list of files using blob and then add 'cp' to the front of list and destination to the end of list and provide the list to subprocess.Popen().</p>
<p>Like:-</p>
<pre><code>list1=blob.blob("*.py")
list1=['cp']+list1+['/home/rahul']
xx=subprocess.Popen(list1)
</code></pre>
<p>It will do the work.</p>
| 0 | 2011-11-07T13:00:58Z | [
"python",
"subprocess"
] |
using RSPython in MacOSX | 1,392,868 | <p>I am trying to install the
<a href="http://www.omegahat.org/RSPython/" rel="nofollow">R/SPlus - Python Interface (RSPython)</a> on my Mac OS X 10.4.11 with R version 2.7.2 (2008-08-25) and python 2.6.2 from fink.</p>
<p>The routine:</p>
<pre><code>sudo R CMD INSTALL -c RSPython_0.7-1.tar.gz
</code></pre>
<p>produced this error message:</p>
<pre><code>* Installing to library '/Library/Frameworks/R.framework/Resources/library'
* Installing *source* package 'RSPython' ...
checking for python... /sw/bin/python
Python version 2.6
Using threads
checking for gcc... gcc
checking for C compiler default output file name... configure: error: C compiler cannot create executables
See `config.log' for more details.
ERROR: configuration failed for package 'RSPython'
** Removing '/Library/Frameworks/R.framework/Versions/2.7/Resources/library/RSPython'
</code></pre>
<p>The config.log was not created o my system.</p>
<p>The contact e-mail address to the author does not work anymore, so I just hope somebody here tried the same already or can give me an alternative for running R routines in python.</p>
<p>Best regards,</p>
<p>Simon</p>
| 1 | 2009-09-08T09:09:10Z | 1,393,669 | <p>Try running R CMD CHECK RSPython_0.7-1.tar.gz
That should produce at least produce bunch of logs in a RSPython.Rcheck folder</p>
<p>You might get some clues in there. </p>
<p>Update ---
If you can get one of the other packages to work I'd recommend it. On my system (R 2.9.1 using system python (2.6) in /usr/bin/python), install works but then RSPython fails to run due to problems inside its .First.lib function. I expect you would need to hack the sources considerably to get it to work.</p>
| 1 | 2009-09-08T12:15:15Z | [
"python",
"install"
] |
using RSPython in MacOSX | 1,392,868 | <p>I am trying to install the
<a href="http://www.omegahat.org/RSPython/" rel="nofollow">R/SPlus - Python Interface (RSPython)</a> on my Mac OS X 10.4.11 with R version 2.7.2 (2008-08-25) and python 2.6.2 from fink.</p>
<p>The routine:</p>
<pre><code>sudo R CMD INSTALL -c RSPython_0.7-1.tar.gz
</code></pre>
<p>produced this error message:</p>
<pre><code>* Installing to library '/Library/Frameworks/R.framework/Resources/library'
* Installing *source* package 'RSPython' ...
checking for python... /sw/bin/python
Python version 2.6
Using threads
checking for gcc... gcc
checking for C compiler default output file name... configure: error: C compiler cannot create executables
See `config.log' for more details.
ERROR: configuration failed for package 'RSPython'
** Removing '/Library/Frameworks/R.framework/Versions/2.7/Resources/library/RSPython'
</code></pre>
<p>The config.log was not created o my system.</p>
<p>The contact e-mail address to the author does not work anymore, so I just hope somebody here tried the same already or can give me an alternative for running R routines in python.</p>
<p>Best regards,</p>
<p>Simon</p>
| 1 | 2009-09-08T09:09:10Z | 1,393,789 | <p>I found the <a href="http://rpy.sourceforge.net/" rel="nofollow">rpy</a> and <a href="http://rpy.sourceforge.net/" rel="nofollow">rpy2</a> packages and going to try those as an alternative to the older RSPython.</p>
<p>rpy2 is includes in fink's unstable distribution ... well, and it just works fine.</p>
| 0 | 2009-09-08T12:40:38Z | [
"python",
"install"
] |
using RSPython in MacOSX | 1,392,868 | <p>I am trying to install the
<a href="http://www.omegahat.org/RSPython/" rel="nofollow">R/SPlus - Python Interface (RSPython)</a> on my Mac OS X 10.4.11 with R version 2.7.2 (2008-08-25) and python 2.6.2 from fink.</p>
<p>The routine:</p>
<pre><code>sudo R CMD INSTALL -c RSPython_0.7-1.tar.gz
</code></pre>
<p>produced this error message:</p>
<pre><code>* Installing to library '/Library/Frameworks/R.framework/Resources/library'
* Installing *source* package 'RSPython' ...
checking for python... /sw/bin/python
Python version 2.6
Using threads
checking for gcc... gcc
checking for C compiler default output file name... configure: error: C compiler cannot create executables
See `config.log' for more details.
ERROR: configuration failed for package 'RSPython'
** Removing '/Library/Frameworks/R.framework/Versions/2.7/Resources/library/RSPython'
</code></pre>
<p>The config.log was not created o my system.</p>
<p>The contact e-mail address to the author does not work anymore, so I just hope somebody here tried the same already or can give me an alternative for running R routines in python.</p>
<p>Best regards,</p>
<p>Simon</p>
| 1 | 2009-09-08T09:09:10Z | 1,393,805 | <p>To debug this, simply unpack the tar file yourself (<code>tar xzvf RSPython_0.7-1.tar.gz</code>) and run <code>./configure</code> in the directory created. You should get a config.log file that you can examine.</p>
| 1 | 2009-09-08T12:44:32Z | [
"python",
"install"
] |
GTK Twitter Client | 1,392,872 | <p>I am learning Python and PyGTK.
I'm trying to write a Twitter client. Which widget is best suited for displaying the Tweets (Timeline). I can do it easily with textview but it doesn't support sub widgets to display users image. </p>
<p>Tried using TreeView but it seems to be an overkill and is too complex.</p>
<p>I'm using Glade</p>
| 1 | 2009-09-08T09:10:12Z | 1,392,924 | <p>I would suggest <a href="http://library.gnome.org/devel/gtk/stable/GtkTreeView.html" rel="nofollow">GtkTreeView</a>, too. I agree it's kind of complicated (especially if you had time with GTK+ 1.2.x to get used to <a href="http://library.gnome.org/devel/gtk/stable/GtkCList.html" rel="nofollow">GtkCList</a>, which is now deprecated). Still, it's a very powerful API and widget, and you will not regret learning it.</p>
<p>Trees are flexible and easy to use, and you will probably find more than once place where you can use one, so you will get a lot of use out of the learning.</p>
<p>There should be plenty of tutorials, showing the necessary steps.</p>
| 3 | 2009-09-08T09:19:27Z | [
"python",
"gtk",
"pygtk"
] |
GTK Twitter Client | 1,392,872 | <p>I am learning Python and PyGTK.
I'm trying to write a Twitter client. Which widget is best suited for displaying the Tweets (Timeline). I can do it easily with textview but it doesn't support sub widgets to display users image. </p>
<p>Tried using TreeView but it seems to be an overkill and is too complex.</p>
<p>I'm using Glade</p>
| 1 | 2009-09-08T09:10:12Z | 1,392,943 | <p>You could try Webkit (the browser rendering engine) using <a href="http://code.google.com/p/pywebkitgtk/" rel="nofollow">pywebkitgtk</a>. It let's you develop in web technologies (HTML, CSS, JS) on the desktop. I think Gwibber, the microblogging client, uses it.</p>
<p>The widget you'd have to use is <em>webkit.WebView</em>. I'm not able to post more links here, just google for "HOWTO Create Python GUIs using HTML".</p>
| 5 | 2009-09-08T09:24:27Z | [
"python",
"gtk",
"pygtk"
] |
GTK Twitter Client | 1,392,872 | <p>I am learning Python and PyGTK.
I'm trying to write a Twitter client. Which widget is best suited for displaying the Tweets (Timeline). I can do it easily with textview but it doesn't support sub widgets to display users image. </p>
<p>Tried using TreeView but it seems to be an overkill and is too complex.</p>
<p>I'm using Glade</p>
| 1 | 2009-09-08T09:10:12Z | 1,484,907 | <p>Actually the TreeView does support embedding images and widgets within the text. Checkout the PyGTK Tutorial section on TextView specifically: <a href="http://pygtk.org/pygtk2tutorial/sec-TextBuffers.html#id2855808" rel="nofollow">Inserting Images and Widgets</a></p>
| 1 | 2009-09-28T00:29:15Z | [
"python",
"gtk",
"pygtk"
] |
reloading .mo files for all processes/threads in django without a restart | 1,392,913 | <p>We are working on a .po file editor for translators. And the translators need to see the changes they are doing on the live website.</p>
<p>We managed to reload the .mo files for the current process/thread. but not for every process/thread. </p>
<p>Is there a possibility to accomplish this without bigger performance problems?</p>
| 3 | 2009-09-08T09:17:23Z | 1,401,004 | <p>I checked <a href="http://code.google.com/p/django-rosetta/" rel="nofollow">django-rosetta</a> and, as I suspected, they rely on the <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> AutoReload mechanism. This is what I would have suggested. For more details read <a href="http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode" rel="nofollow">Reloading Source Code</a>.</p>
| 2 | 2009-09-09T17:32:18Z | [
"python",
"django"
] |
reloading .mo files for all processes/threads in django without a restart | 1,392,913 | <p>We are working on a .po file editor for translators. And the translators need to see the changes they are doing on the live website.</p>
<p>We managed to reload the .mo files for the current process/thread. but not for every process/thread. </p>
<p>Is there a possibility to accomplish this without bigger performance problems?</p>
| 3 | 2009-09-08T09:17:23Z | 19,293,936 | <p>We had the same problem. Users must write translations direct on website. I've found middleware for django 1.1, that clear translation cache and try to use it in view with django 1.4.
order:</p>
<ol>
<li>user submit from with translation</li>
<li>methods parse form data and change *.po</li>
<li>-subrocess.Popen(["python", "manage.py", "compilemessages"], stderr=PIPE, stdout=PIPE) (to compile changed *.po)</li>
<li><p>function below to clear cache </p>
<pre><code>from django.utils import translation
from django.utils.translation import trans_real, get_language
from django.conf import settings
import gettext
if settings.USE_I18N:
try:
# Reset gettext.GNUTranslation cache.
gettext._translations = {}
# Reset Django by-language translation cache.
trans_real._translations = {}
# Delete Django current language translation cache.
trans_real._default = None
# Delete translation cache for the current thread,
# and re-activate the currently selected language (if any)
translation.activate(get_language())
except AttributeError:
pass
</code></pre></li>
</ol>
| 1 | 2013-10-10T10:58:54Z | [
"python",
"django"
] |
Java modified UTF-8 strings in Python | 1,393,004 | <p>I am interfacing with a Java application via Python. I need to be able to construct byte sequences which contain utf-8 strings. Java uses a modified utf-8 encoding in DataInputStream.readUTF() which is not supported by python (<a href="http://bugs.python.org/issue2857" rel="nofollow">yet at least</a>)</p>
<p>Can anybody point me in the right direction to construct java modified utf-8 strings in python?</p>
<p>Update #1: To see a little more about the java modified utf-8 check out the readUTF method from the DataInput interface on line 550 <a href="http://www.docjar.com/html/api/java/io/DataInput.java.html" rel="nofollow">here</a>, or <a href="http://java.sun.com/j2se/1.3/docs/api/java/io/DataInput.html#readUTF%28%29" rel="nofollow">here in the Java SE docs</a>.</p>
<p>Update #2: I am trying to interface with a third party JBoss web app which is using this modified utf8 format to read in strings via POST requests by calling DataInputStream.readUTF (sorry for any confusion regarding normal java utf8 string operation).</p>
<p>Thanks in advance.</p>
| 3 | 2009-09-08T09:40:02Z | 1,393,063 | <p>Okay, if you need to read the format of <code>DataInput.readUTF</code>, I suspect you'll just have to convert the (well-documented) format into Python.</p>
<p>It doesn't look like it would be particularly hard to do. After reading the length and then the binary data itself, I suggest you use a first pass to work out how many Unicode characters will be in the output, then construct a string accordingly in a second pass. Without knowing Python I don't know the ins and outs of how to efficiently construct a string, but given the linked specification I can't imagine it would be very hard. You might want to look at the source for the existing UTF-8 decoder as a starting point.</p>
| 1 | 2009-09-08T09:54:37Z | [
"java",
"python",
"utf-8"
] |
Java modified UTF-8 strings in Python | 1,393,004 | <p>I am interfacing with a Java application via Python. I need to be able to construct byte sequences which contain utf-8 strings. Java uses a modified utf-8 encoding in DataInputStream.readUTF() which is not supported by python (<a href="http://bugs.python.org/issue2857" rel="nofollow">yet at least</a>)</p>
<p>Can anybody point me in the right direction to construct java modified utf-8 strings in python?</p>
<p>Update #1: To see a little more about the java modified utf-8 check out the readUTF method from the DataInput interface on line 550 <a href="http://www.docjar.com/html/api/java/io/DataInput.java.html" rel="nofollow">here</a>, or <a href="http://java.sun.com/j2se/1.3/docs/api/java/io/DataInput.html#readUTF%28%29" rel="nofollow">here in the Java SE docs</a>.</p>
<p>Update #2: I am trying to interface with a third party JBoss web app which is using this modified utf8 format to read in strings via POST requests by calling DataInputStream.readUTF (sorry for any confusion regarding normal java utf8 string operation).</p>
<p>Thanks in advance.</p>
| 3 | 2009-09-08T09:40:02Z | 1,393,079 | <p>Maybe this can help you, although it looks like it's the reverse of what you're doing:</p>
<p><a href="http://www.phaedro.com/javapythonutf8/" rel="nofollow">Connecting a Java applet to a python SocketServer</a></p>
| 0 | 2009-09-08T09:58:45Z | [
"java",
"python",
"utf-8"
] |
Java modified UTF-8 strings in Python | 1,393,004 | <p>I am interfacing with a Java application via Python. I need to be able to construct byte sequences which contain utf-8 strings. Java uses a modified utf-8 encoding in DataInputStream.readUTF() which is not supported by python (<a href="http://bugs.python.org/issue2857" rel="nofollow">yet at least</a>)</p>
<p>Can anybody point me in the right direction to construct java modified utf-8 strings in python?</p>
<p>Update #1: To see a little more about the java modified utf-8 check out the readUTF method from the DataInput interface on line 550 <a href="http://www.docjar.com/html/api/java/io/DataInput.java.html" rel="nofollow">here</a>, or <a href="http://java.sun.com/j2se/1.3/docs/api/java/io/DataInput.html#readUTF%28%29" rel="nofollow">here in the Java SE docs</a>.</p>
<p>Update #2: I am trying to interface with a third party JBoss web app which is using this modified utf8 format to read in strings via POST requests by calling DataInputStream.readUTF (sorry for any confusion regarding normal java utf8 string operation).</p>
<p>Thanks in advance.</p>
| 3 | 2009-09-08T09:40:02Z | 1,393,579 | <p>You can ignore <strong>Modified UTF-8 Encoding</strong> (MUTF-8) and just treat it as UTF-8. On the Python side, you can just handle it like this,</p>
<ol>
<li>Convert the string into normal UTF-8 and stores bytes in a buffer.</li>
<li>Write the 2-byte buffer length (not the string length) as binary in big-endian. </li>
<li>Write the whole buffer.</li>
</ol>
<p>I've done this in PHP and Java didn't complain about my encoding at all (at least in Java 5).</p>
<p>MUTF-8 is mainly used for JNI and other systems with null-terminated strings. The only difference from normal UTF-8 is how U+0000 is encoded. Normal UTF-8 use 1 byte encoding (0x00) and MUTF-8 uses 2 bytes (0xC0 0x80). First of all, you shouldn't have U+0000 (an invalid codepoint) in any Unicode text. Secondly, <code>DataInputStream.readUTF()</code> doesn't enforce the encoding so it happily accepts either one.</p>
<p>EDIT: The Python code should look like this,</p>
<pre><code>def writeUTF(data, str):
utf8 = str.encode('utf-8')
length = len(utf8)
data.append(struct.pack('!H', length))
format = '!' + str(length) + 's'
data.append(struct.pack(format, utf8))
</code></pre>
| 5 | 2009-09-08T11:55:41Z | [
"java",
"python",
"utf-8"
] |
Pythonic way to "flatten" object hierarchy to nested dicts? | 1,393,010 | <p>I need to "flatten" objects into nested dicts of the object's properties. The objects I want to do this with are generally just containers for basic types or other objects which act in a similar way. For example:</p>
<pre><code>class foo(object):
bar = None
baz = None
class spam(object):
eggs = []
x = spam()
y = foo()
y.bar = True
y.baz = u"boz"
x.eggs.append(y)
</code></pre>
<p>What I need to "flatten" this to is:</p>
<pre><code>{ 'eggs': [ { 'bar': True, 'baz': u'boz' } ] }
</code></pre>
<p>Is there anything in the stdlib which can do this for me? If not, would I have to test <code>isinstance</code> against all known base-types to ensure I don't try to convert an object which can't be converted (eg: bool)?</p>
<p><strong>Edit:</strong></p>
<p>These are objects are being returned to my code from an external library and therefore I have no control over them. I could use them as-is in my methods, but it would be easier (safer?) to convert them to dicts - especially for unit testing.</p>
| 0 | 2009-09-08T09:41:50Z | 1,393,167 | <p>No, there is nothing in the standardlib. Yes, you would have to somehow test that the types are basic types like str, unicode, bool, int, float, long...</p>
<p>You could probably make a registry of methods to "serialize" different types, but that would only be useful if you have some types that should not have all it's attributes serialized, for example, or if you also need to flatten class attributes, etc.</p>
| 0 | 2009-09-08T10:21:28Z | [
"python"
] |
Pythonic way to "flatten" object hierarchy to nested dicts? | 1,393,010 | <p>I need to "flatten" objects into nested dicts of the object's properties. The objects I want to do this with are generally just containers for basic types or other objects which act in a similar way. For example:</p>
<pre><code>class foo(object):
bar = None
baz = None
class spam(object):
eggs = []
x = spam()
y = foo()
y.bar = True
y.baz = u"boz"
x.eggs.append(y)
</code></pre>
<p>What I need to "flatten" this to is:</p>
<pre><code>{ 'eggs': [ { 'bar': True, 'baz': u'boz' } ] }
</code></pre>
<p>Is there anything in the stdlib which can do this for me? If not, would I have to test <code>isinstance</code> against all known base-types to ensure I don't try to convert an object which can't be converted (eg: bool)?</p>
<p><strong>Edit:</strong></p>
<p>These are objects are being returned to my code from an external library and therefore I have no control over them. I could use them as-is in my methods, but it would be easier (safer?) to convert them to dicts - especially for unit testing.</p>
| 0 | 2009-09-08T09:41:50Z | 1,393,555 | <p>Almost every object has a dictionary (called <code>__dict__</code>), with all its methods and members.<br />
With some type checking, you can then write a function that filters out only the members you are interested in.</p>
<p>It is not a big task, but as chrispy said, it could worth to try looking at your problem from a completely different perspective.</p>
| 0 | 2009-09-08T11:50:53Z | [
"python"
] |
Pythonic way to "flatten" object hierarchy to nested dicts? | 1,393,010 | <p>I need to "flatten" objects into nested dicts of the object's properties. The objects I want to do this with are generally just containers for basic types or other objects which act in a similar way. For example:</p>
<pre><code>class foo(object):
bar = None
baz = None
class spam(object):
eggs = []
x = spam()
y = foo()
y.bar = True
y.baz = u"boz"
x.eggs.append(y)
</code></pre>
<p>What I need to "flatten" this to is:</p>
<pre><code>{ 'eggs': [ { 'bar': True, 'baz': u'boz' } ] }
</code></pre>
<p>Is there anything in the stdlib which can do this for me? If not, would I have to test <code>isinstance</code> against all known base-types to ensure I don't try to convert an object which can't be converted (eg: bool)?</p>
<p><strong>Edit:</strong></p>
<p>These are objects are being returned to my code from an external library and therefore I have no control over them. I could use them as-is in my methods, but it would be easier (safer?) to convert them to dicts - especially for unit testing.</p>
| 0 | 2009-09-08T09:41:50Z | 1,393,959 | <p><strong>Code:</strong> You may need to handle other iterable types though:</p>
<pre><code>def flatten(obj):
if obj is None:
return None
elif hasattr(obj, '__dict__') and obj.__dict__:
return dict([(k, flatten(v)) for (k, v) in obj.__dict__.items()])
elif isinstance(obj, (dict,)):
return dict([(k, flatten(v)) for (k, v) in obj.items()])
elif isinstance(obj, (list,)):
return [flatten(x) for x in obj]
elif isinstance(obj, (tuple,)):
return tuple([flatten(x) for x in obj])
else:
return obj
</code></pre>
<p><strong>Bug?</strong>
In your code instead of:</p>
<pre><code>class spam(object):
eggs = []
x = spam()
x.eggs.add(...)
</code></pre>
<p>please do:</p>
<pre><code>class spam(object):
eggs = None #// if you need this line at all though
x = spam()
x.eggs = []
x.eggs.add(...)
</code></pre>
<p>If you do not, then all instances of <code>spam</code> will share the same <code>eggs</code> list.</p>
| 2 | 2009-09-08T13:14:45Z | [
"python"
] |
Pythonic way to "flatten" object hierarchy to nested dicts? | 1,393,010 | <p>I need to "flatten" objects into nested dicts of the object's properties. The objects I want to do this with are generally just containers for basic types or other objects which act in a similar way. For example:</p>
<pre><code>class foo(object):
bar = None
baz = None
class spam(object):
eggs = []
x = spam()
y = foo()
y.bar = True
y.baz = u"boz"
x.eggs.append(y)
</code></pre>
<p>What I need to "flatten" this to is:</p>
<pre><code>{ 'eggs': [ { 'bar': True, 'baz': u'boz' } ] }
</code></pre>
<p>Is there anything in the stdlib which can do this for me? If not, would I have to test <code>isinstance</code> against all known base-types to ensure I don't try to convert an object which can't be converted (eg: bool)?</p>
<p><strong>Edit:</strong></p>
<p>These are objects are being returned to my code from an external library and therefore I have no control over them. I could use them as-is in my methods, but it would be easier (safer?) to convert them to dicts - especially for unit testing.</p>
| 0 | 2009-09-08T09:41:50Z | 1,401,621 | <p>Well, I'm not very proud of this, but is possible to do the following:</p>
<ol>
<li>Create a super class that has the serialization method and loop through its properties.</li>
<li>At runtime extend your classes using <strong>bases</strong> at runtime</li>
<li>Execute the class from the new super class. It should be able to access the <strong>dict</strong> data from the children and work.</li>
</ol>
<p>Here is an example:</p>
<p><code> </p>
<pre><code>class foo(object):
def __init__(self):
self.bar = None
self.baz = None
class spam(object):
delf __init__(self):
self.eggs = []
class Serializable():
def serialize(self):
result = {}
for property in self.__dict__.keys():
result[property] = self.__dict__[property]
return result
foo.__bases__ += (Serializable,)
spam.__bases__ += (Serializable,)
x = spam()
y = foo()
y.bar = True
y.baz = u"boz"
x.eggs.append(y)
y.serialize()
</code></pre>
<p></code>
Things to point out. If you do not set the var is init the <strong>dict</strong> willnot work 'cause it is accessing the instance variables not the class variables (I suppose you meant instance ones). Second, make sure Serializable DOES NOT inherit from object, it is does you will have a
<code>
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
</code></p>
<p>Hope it helps!</p>
<p>Edit: If you are just copying the <strong>dict</strong> use the deepcopy module, this is just an example :P</p>
| 0 | 2009-09-09T19:34:04Z | [
"python"
] |
Vim syntax highlighting 'else:' for Python | 1,393,075 | <p>I'm getting annoyed with the default python syntax highlighting in Vim.</p>
<p>It does not highlight the <code>else:</code> statement correctly.
Vim only highlights the else statement if I have some white space between the <code>else</code> and the colon <code>:</code>, so <code>else :</code> works, but <code>else:</code> does not.</p>
<p>It must be easy to fix.</p>
<p>I'm using Vim 7.2</p>
| 5 | 2009-09-08T09:58:00Z | 1,393,207 | <p>It should work by default.</p>
<p>Look for a file that is something like this:</p>
<pre><code>/usr/share/vim/vim72/syntax/python.vim
</code></pre>
<p>There should be a line there that looks like this:</p>
<pre><code>syn keyword pythonConditional if elif else
</code></pre>
<p>If not, investigate further. Does <code>elif</code> work?</p>
| 3 | 2009-09-08T10:30:29Z | [
"python",
"vim",
"syntax-highlighting",
"vim-syntax-highlighting"
] |
Vim syntax highlighting 'else:' for Python | 1,393,075 | <p>I'm getting annoyed with the default python syntax highlighting in Vim.</p>
<p>It does not highlight the <code>else:</code> statement correctly.
Vim only highlights the else statement if I have some white space between the <code>else</code> and the colon <code>:</code>, so <code>else :</code> works, but <code>else:</code> does not.</p>
<p>It must be easy to fix.</p>
<p>I'm using Vim 7.2</p>
| 5 | 2009-09-08T09:58:00Z | 1,393,230 | <p>Enable the filetype stuff so things are setup automatically.
I've python auto indenting and syntax highlighting setup for vim here:
<a href="http://www.pixelbeat.org/settings/.vimrc" rel="nofollow">http://www.pixelbeat.org/settings/.vimrc</a></p>
| 1 | 2009-09-08T10:35:12Z | [
"python",
"vim",
"syntax-highlighting",
"vim-syntax-highlighting"
] |
Vim syntax highlighting 'else:' for Python | 1,393,075 | <p>I'm getting annoyed with the default python syntax highlighting in Vim.</p>
<p>It does not highlight the <code>else:</code> statement correctly.
Vim only highlights the else statement if I have some white space between the <code>else</code> and the colon <code>:</code>, so <code>else :</code> works, but <code>else:</code> does not.</p>
<p>It must be easy to fix.</p>
<p>I'm using Vim 7.2</p>
| 5 | 2009-09-08T09:58:00Z | 1,410,674 | <p>I had below statement in my vimrc file. This made else: be tokenized as one word. After removing that else: syntax highlighting works just fine. </p>
<p><code>set iskeyword+=:</code></p>
| 5 | 2009-09-11T12:51:30Z | [
"python",
"vim",
"syntax-highlighting",
"vim-syntax-highlighting"
] |
Vim syntax highlighting 'else:' for Python | 1,393,075 | <p>I'm getting annoyed with the default python syntax highlighting in Vim.</p>
<p>It does not highlight the <code>else:</code> statement correctly.
Vim only highlights the else statement if I have some white space between the <code>else</code> and the colon <code>:</code>, so <code>else :</code> works, but <code>else:</code> does not.</p>
<p>It must be easy to fix.</p>
<p>I'm using Vim 7.2</p>
| 5 | 2009-09-08T09:58:00Z | 4,041,958 | <p>Note that the file in</p>
<pre><code>/usr/share/vim/vim72/syntax/python.vim
</code></pre>
<p>is not up to date for some reason.</p>
<p>Get the most recent version of the syntax highlight file from <a href="http://www.vim.org/scripts/script.php?script_id=790" rel="nofollow">http://www.vim.org/scripts/script.php?script_id=790</a></p>
| 3 | 2010-10-28T10:31:23Z | [
"python",
"vim",
"syntax-highlighting",
"vim-syntax-highlighting"
] |
Vim syntax highlighting 'else:' for Python | 1,393,075 | <p>I'm getting annoyed with the default python syntax highlighting in Vim.</p>
<p>It does not highlight the <code>else:</code> statement correctly.
Vim only highlights the else statement if I have some white space between the <code>else</code> and the colon <code>:</code>, so <code>else :</code> works, but <code>else:</code> does not.</p>
<p>It must be easy to fix.</p>
<p>I'm using Vim 7.2</p>
| 5 | 2009-09-08T09:58:00Z | 23,918,908 | <p>This periodically pops up, and I've taken to putting this in my vimrc:</p>
<pre><code>" No seriously, else: is the same as else
autocmd BufEnter,BufRead,BufNewFile *.py set iskeyword-=:
</code></pre>
| 2 | 2014-05-28T18:11:36Z | [
"python",
"vim",
"syntax-highlighting",
"vim-syntax-highlighting"
] |
Django: add image in an ImageField from image url | 1,393,202 | <p>please excuse me for my ugly english ;-)</p>
<p>Imagine this very simple model :</p>
<pre><code>class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
</code></pre>
<p>I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).</p>
<p>I think that I need to do something like this :</p>
<pre><code>from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
</code></pre>
<p>I hope that I've well explained the problem, if not tell me.</p>
<p>Thank you :)</p>
<p>Edit :</p>
<p>This may work but I don't know how to convert <code>content</code> to a django File :</p>
<pre><code>from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
</code></pre>
| 65 | 2009-09-08T10:29:43Z | 1,393,231 | <p><code>ImageField</code> is just a string, a path relative to your <code>MEDIA_ROOT</code> setting. Just save the file (you might want to use PIL to check it is an image) and populate the field with its filename.</p>
<p>So it differs from your code in that you need to save the output of your <code>urllib.urlopen</code> to file (inside your media location), work out the path, save that to your model.</p>
| 4 | 2009-09-08T10:35:58Z | [
"python",
"django",
"urllib",
"django-models"
] |
Django: add image in an ImageField from image url | 1,393,202 | <p>please excuse me for my ugly english ;-)</p>
<p>Imagine this very simple model :</p>
<pre><code>class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
</code></pre>
<p>I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).</p>
<p>I think that I need to do something like this :</p>
<pre><code>from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
</code></pre>
<p>I hope that I've well explained the problem, if not tell me.</p>
<p>Thank you :)</p>
<p>Edit :</p>
<p>This may work but I don't know how to convert <code>content</code> to a django File :</p>
<pre><code>from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
</code></pre>
| 65 | 2009-09-08T10:29:43Z | 1,393,316 | <pre>
<code>
from myapp.models import Photo
import urllib
from urlparse import urlparse
from django.core.files import File
img_url = 'http://www.site.com/image.jpg'
photo = Photo() # set any other fields, but don't commit to DB (ie. don't save())
name = urlparse(img_url).path.split('/')[-1]
content = urllib.urlretrieve(img_url)
# See also: http://docs.djangoproject.com/en/dev/ref/files/file/
photo.image.save(name, File(open(content[0])), save=True)
</code>
</pre>
| 22 | 2009-09-08T10:54:40Z | [
"python",
"django",
"urllib",
"django-models"
] |
Django: add image in an ImageField from image url | 1,393,202 | <p>please excuse me for my ugly english ;-)</p>
<p>Imagine this very simple model :</p>
<pre><code>class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
</code></pre>
<p>I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).</p>
<p>I think that I need to do something like this :</p>
<pre><code>from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
</code></pre>
<p>I hope that I've well explained the problem, if not tell me.</p>
<p>Thank you :)</p>
<p>Edit :</p>
<p>This may work but I don't know how to convert <code>content</code> to a django File :</p>
<pre><code>from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
</code></pre>
| 65 | 2009-09-08T10:29:43Z | 2,141,823 | <p>I just created <a href="http://www.djangosnippets.org/snippets/1890/">http://www.djangosnippets.org/snippets/1890/</a> for this same problem. The code is similar to pithyless' answer above except it uses urllib2.urlopen because urllib.urlretrieve doesn't perform any error handling by default so it's easy to get the contents of a 404/500 page instead of what you needed. You can create callback function & custom URLOpener subclass but I found it easier just to create my own temp file like this:</p>
<pre><code>from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()
im.file.save(img_filename, File(img_temp))
</code></pre>
| 80 | 2010-01-26T18:59:14Z | [
"python",
"django",
"urllib",
"django-models"
] |
Django: add image in an ImageField from image url | 1,393,202 | <p>please excuse me for my ugly english ;-)</p>
<p>Imagine this very simple model :</p>
<pre><code>class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
</code></pre>
<p>I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).</p>
<p>I think that I need to do something like this :</p>
<pre><code>from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
</code></pre>
<p>I hope that I've well explained the problem, if not tell me.</p>
<p>Thank you :)</p>
<p>Edit :</p>
<p>This may work but I don't know how to convert <code>content</code> to a django File :</p>
<pre><code>from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
</code></pre>
| 65 | 2009-09-08T10:29:43Z | 13,106,218 | <p>this is the right and working way</p>
<pre><code>class Product(models.Model):
upload_path = 'media/product'
image = models.ImageField(upload_to=upload_path, null=True, blank=True)
image_url = models.URLField(null=True, blank=True)
def save(self, *args, **kwargs):
if self.image_url:
import urllib, os
from urlparse import urlparse
filename = urlparse(self.image_url).path.split('/')[-1]
urllib.urlretrieve(self.image_url, os.path.join(file_save_dir, filename))
self.image = os.path.join(upload_path, filename)
self.image_url = ''
super(Product, self).save()
</code></pre>
| 1 | 2012-10-28T03:49:13Z | [
"python",
"django",
"urllib",
"django-models"
] |
Django: add image in an ImageField from image url | 1,393,202 | <p>please excuse me for my ugly english ;-)</p>
<p>Imagine this very simple model :</p>
<pre><code>class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
</code></pre>
<p>I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).</p>
<p>I think that I need to do something like this :</p>
<pre><code>from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
</code></pre>
<p>I hope that I've well explained the problem, if not tell me.</p>
<p>Thank you :)</p>
<p>Edit :</p>
<p>This may work but I don't know how to convert <code>content</code> to a django File :</p>
<pre><code>from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
</code></pre>
| 65 | 2009-09-08T10:29:43Z | 26,331,472 | <p>I do it this way on Python 3, which should work with simple adaptations on Python 2. This is based on my knowledge that the files Iâm retrieving are small. If yours arenât, Iâd probably recommend writing the response out to a file instead of buffering in memory.</p>
<p>BytesIO is needed because Django calls seek() on the file object, and urlopen responses donât support seeking. You could pass the bytes object returned by read() to Django's ContentFile instead.</p>
<pre><code>from io import BytesIO
from urllib.request import urlopen
from django.core.files import File
# url, filename, model_instance assumed to be provided
response = urlopen(url)
io = BytesIO(response.read())
model_instance.image_field.save(filename, File(io))
</code></pre>
| 2 | 2014-10-13T00:40:01Z | [
"python",
"django",
"urllib",
"django-models"
] |
Django: add image in an ImageField from image url | 1,393,202 | <p>please excuse me for my ugly english ;-)</p>
<p>Imagine this very simple model :</p>
<pre><code>class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
</code></pre>
<p>I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).</p>
<p>I think that I need to do something like this :</p>
<pre><code>from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
</code></pre>
<p>I hope that I've well explained the problem, if not tell me.</p>
<p>Thank you :)</p>
<p>Edit :</p>
<p>This may work but I don't know how to convert <code>content</code> to a django File :</p>
<pre><code>from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
</code></pre>
| 65 | 2009-09-08T10:29:43Z | 30,943,626 | <p>If you are using file uploading feature in your Django project, you must install Pillow first:</p>
<pre><code>pip install pillow==2.6.1
</code></pre>
<p>Remember to set the url for media files in settings.py:</p>
<pre><code>MEDIA_ROOT = 'media/'
</code></pre>
<p>Then, in your models.py, add the following image field:</p>
<pre><code>userlogo = models.ImageField(upload_to="userlogo/", blank=True, null=True)
</code></pre>
<p>After writing this code, migrate the model using:</p>
<pre><code>python manage.py makemigrations
python manage.py migrate
</code></pre>
<p>Now you can upload image files using the image field. The image files would get uploaded to YOUR_PROJECT_ROOT/media/userlogo directory. You <strong>dont</strong> need to create the 'userlogo' folder manually.</p>
| -1 | 2015-06-19T17:08:30Z | [
"python",
"django",
"urllib",
"django-models"
] |
Call a function from a running process | 1,393,242 | <p>my programm starts a subprocess, which has to send some kind of signal to the parent after initialization. It would be perfekt if i could set up a handler in parent, which is called when this signal is sent. Is there any way to do it?</p>
<p>Alendit</p>
| 0 | 2009-09-08T10:38:49Z | 1,393,268 | <p>You can use the <a href="http://docs.python.org/library/signal.html" rel="nofollow">signal module</a> from the Python standard library to register a signal handler. The subprocess would then use normal signal sending mechanisms.</p>
| 1 | 2009-09-08T10:44:05Z | [
"python",
"ipc",
"subprocess"
] |
Call a function from a running process | 1,393,242 | <p>my programm starts a subprocess, which has to send some kind of signal to the parent after initialization. It would be perfekt if i could set up a handler in parent, which is called when this signal is sent. Is there any way to do it?</p>
<p>Alendit</p>
| 0 | 2009-09-08T10:38:49Z | 1,393,346 | <p>Parent code:
</p>
<pre><code>import signal
def my_callback(signal, frame):
print "Signal %d received" % (signal,)
signal.signal(signal.SIGUSR1, my_callback)
# start child
</code></pre>
<p>Child code:
</p>
<pre><code>import os
import signal
signal.kill(os.getppid(), signal.SIGUSR1)
</code></pre>
<p>Be careful with this form of IPC because it has its issues, e.g.:</p>
<blockquote>
<p>In the original Unix systems, when a
handler that was established using
signal() was invoked by the
delivery of a signal, the disposition
of the signal would be reset to
SIG_DFL, and the system did not
block delivery of further instances
of the signal. System V also provides
these semantics for signal(). This
was bad because the signal might be
delivered again before the handler
had a chance to reestablish itself.
Furthermore, rapid deliveries of the
same signal could result in recursive
invocations of the handler.</p>
</blockquote>
<p>I recommend reading the whole <a href="http://linux.die.net/man/2/signal" rel="nofollow"><code>signal(2)</code></a> man page.</p>
| 2 | 2009-09-08T11:00:27Z | [
"python",
"ipc",
"subprocess"
] |
Call a function from a running process | 1,393,242 | <p>my programm starts a subprocess, which has to send some kind of signal to the parent after initialization. It would be perfekt if i could set up a handler in parent, which is called when this signal is sent. Is there any way to do it?</p>
<p>Alendit</p>
| 0 | 2009-09-08T10:38:49Z | 1,393,543 | <p>If you are using Python 2.6, you can use the <code>multiprocessing</code> module from the standard library, in particular pipes and queues. Simple example from the docs:</p>
<pre><code>from multiprocessing import Process, Pipe
def f(conn): #This code will be spawned as a new child process
conn.send([42, None, 'hello']) #The child process sends a msg to the pipe
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,)) # prepare to spawn the child
p.start() # spawn it
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join() #wait for child to exit
</code></pre>
<p>If you are using Python 2.4 or 2.5, don't despair - a backport is available <a href="http://pypi.python.org/pypi/multiprocessing/" rel="nofollow">here</a>.</p>
| 4 | 2009-09-08T11:49:08Z | [
"python",
"ipc",
"subprocess"
] |
In Python, given a URL to a text file, what is the simplest way to read the contents of the text file? | 1,393,324 | <p>In Python, when given the URL for a text file, what is the simplest way to access the contents off the text file and print the contents of the file out locally line-by-line without saving a local copy of the text file? </p>
<pre><code>TargetURL=http://www.myhost.com/SomeFile.txt
#read the file
#print first line
#print second line
#etc
</code></pre>
| 44 | 2009-09-08T10:56:08Z | 1,393,338 | <pre><code>import urllib2
f = urllib2.urlopen(target_url)
for l in f.readlines():
print l
</code></pre>
| 5 | 2009-09-08T10:59:27Z | [
"python"
] |
In Python, given a URL to a text file, what is the simplest way to read the contents of the text file? | 1,393,324 | <p>In Python, when given the URL for a text file, what is the simplest way to access the contents off the text file and print the contents of the file out locally line-by-line without saving a local copy of the text file? </p>
<pre><code>TargetURL=http://www.myhost.com/SomeFile.txt
#read the file
#print first line
#print second line
#etc
</code></pre>
| 44 | 2009-09-08T10:56:08Z | 1,393,355 | <pre><code>import urllib2
for line in urllib2.urlopen("http://www.myhost.com/SomeFile.txt"):
print line
</code></pre>
| 10 | 2009-09-08T11:02:09Z | [
"python"
] |
In Python, given a URL to a text file, what is the simplest way to read the contents of the text file? | 1,393,324 | <p>In Python, when given the URL for a text file, what is the simplest way to access the contents off the text file and print the contents of the file out locally line-by-line without saving a local copy of the text file? </p>
<pre><code>TargetURL=http://www.myhost.com/SomeFile.txt
#read the file
#print first line
#print second line
#etc
</code></pre>
| 44 | 2009-09-08T10:56:08Z | 1,393,367 | <p>Actually the simplest way is :</p>
<pre><code>import urllib2 # the lib that handles the url stuff
data = urllib2.urlopen(target_url) # it's a file like object and works just like a file
for line in data: # files are iterable
print line
</code></pre>
<p>You don't even need "readlines", as Will suggested. You could even shorten it to </p>
<pre><code>import urllib2
for line in urllib2.urlopen(target_url):
print line
</code></pre>
<p>But remember in Python, readability matters.</p>
<p>However, this is the simplest way but not the safe way because most of the time with network programming, you don't know if the amount of data to expect will be respected. So you'd generally better read a fixed and reasonable amount of data, something you know to be enough for the data you expect but will prevent your script from been flooded :</p>
<pre><code>import urllib2
data = urllib2.urlopen("http://www.google.com").read(20000) # read only 20 000 chars
data = data.split("\n") # then split it into lines
for line in data:
print line
</code></pre>
<blockquote>
<p>Edit 09/2016: In python 3 and up use <a href="https://docs.python.org/2/library/urllib.html" rel="nofollow">urllib.request</a> instead of urllib2</p>
</blockquote>
| 60 | 2009-09-08T11:04:28Z | [
"python"
] |
In Python, given a URL to a text file, what is the simplest way to read the contents of the text file? | 1,393,324 | <p>In Python, when given the URL for a text file, what is the simplest way to access the contents off the text file and print the contents of the file out locally line-by-line without saving a local copy of the text file? </p>
<pre><code>TargetURL=http://www.myhost.com/SomeFile.txt
#read the file
#print first line
#print second line
#etc
</code></pre>
| 44 | 2009-09-08T10:56:08Z | 1,396,288 | <p>There's really no need to read line-by-line. You can get the whole thing like this:</p>
<pre><code>import urllib
txt = urllib.urlopen(target_url).read()
</code></pre>
| 16 | 2009-09-08T20:55:15Z | [
"python"
] |
Terracotta for Python world? | 1,393,689 | <p>Would you know if something similar to <a href="http://www.terracotta.org/" rel="nofollow">Terracotta</a> (in Java world) exists for Python world? <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> ? Or something else.</p>
| 1 | 2009-09-08T12:20:23Z | 1,393,848 | <p>I think Twisted is the best alternative you can find.
Let me warn you that it will give you some headaches, as it forces you to code in a completely different way. But once you understand it, it's not that hard....</p>
<p><a href="http://twistedmatrix.com/projects/core/documentation/howto/index.html" rel="nofollow">http://twistedmatrix.com/projects/core/documentation/howto/index.html</a></p>
| 1 | 2009-09-08T12:54:32Z | [
"java",
"python",
"terracotta"
] |
Terracotta for Python world? | 1,393,689 | <p>Would you know if something similar to <a href="http://www.terracotta.org/" rel="nofollow">Terracotta</a> (in Java world) exists for Python world? <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> ? Or something else.</p>
| 1 | 2009-09-08T12:20:23Z | 1,393,879 | <p>If you want to use something that gives you a <a href="http://en.wikipedia.org/wiki/Distributed%5Fhash%5Ftable" rel="nofollow">Distributed Hashtable</a>/<a href="http://en.wikipedia.org/wiki/Tuple%5Fspace" rel="nofollow">Tuple Space</a> type of implementation, <a href="http://entangled.sourceforge.net/" rel="nofollow">Entangled</a> seems to be a Python implementation. I'm sure there are others out there though if you google for them.</p>
| 0 | 2009-09-08T12:59:56Z | [
"java",
"python",
"terracotta"
] |
Terracotta for Python world? | 1,393,689 | <p>Would you know if something similar to <a href="http://www.terracotta.org/" rel="nofollow">Terracotta</a> (in Java world) exists for Python world? <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> ? Or something else.</p>
| 1 | 2009-09-08T12:20:23Z | 1,849,570 | <p>try to run your code with JPython and use Terracotta ;)</p>
| 0 | 2009-12-04T20:48:18Z | [
"java",
"python",
"terracotta"
] |
Terracotta for Python world? | 1,393,689 | <p>Would you know if something similar to <a href="http://www.terracotta.org/" rel="nofollow">Terracotta</a> (in Java world) exists for Python world? <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> ? Or something else.</p>
| 1 | 2009-09-08T12:20:23Z | 2,201,172 | <p><a href="http://pyro.sourceforge.net/" rel="nofollow">Pyro</a> can be used similarly in python as terracotta in java</p>
| 1 | 2010-02-04T16:11:53Z | [
"java",
"python",
"terracotta"
] |
configuration filename convention | 1,393,731 | <p>Is there a general naming conventions for configuration files for a simple python program?</p>
<p>Thanks,</p>
<p>Udi</p>
| 2 | 2009-09-08T12:28:28Z | 1,393,736 | <p>A convention? Mine would be, if my program was called <code>"Bob"</code>, simply <code>"bob.cfg"</code>.</p>
<p>I have to admit, I didn't really suffer any angst in coming up with that convention. Maybe I've been here too long :-)</p>
<p>Of course, if your configuration information is of a specific format (e.g., XML), you could consider <code>"bob.xml"</code>. But, really, I think <code>".cfg"</code> just about sums up the intent as much as any convention could.</p>
<p>And, just to state the bleeding obvious, don't call your file <code>"bob.cfg"</code> if your program is actually called <code>"George"</code>.</p>
<p>Please don't take offense, I'm not really taking the mickey, just answering an interesting question in the tone of my strange sense of humor. You wouldn't be the first to misunderstand my brand of humor (my wife, for instance, despairs of it most days).</p>
| 4 | 2009-09-08T12:29:47Z | [
"python",
"configuration",
"naming-conventions"
] |
configuration filename convention | 1,393,731 | <p>Is there a general naming conventions for configuration files for a simple python program?</p>
<p>Thanks,</p>
<p>Udi</p>
| 2 | 2009-09-08T12:28:28Z | 1,393,751 | <p>I am not sure if you mean the file basename, of if your question also includes where to put the configuration file. Anyway, on location:</p>
<p>If it is a linux application, you should follow the <a href="http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html" rel="nofollow">XDG Base Directory specification</a> (XDG -> Cross-desktop).</p>
<p>It says you should put your configuration files inside a folder named after your program, in <code>$XDG_CONFIG_HOME/programname/</code> . <code>XDG_CONFIG_HOME</code> is normally <code>~/.config</code></p>
| 4 | 2009-09-08T12:34:00Z | [
"python",
"configuration",
"naming-conventions"
] |
configuration filename convention | 1,393,731 | <p>Is there a general naming conventions for configuration files for a simple python program?</p>
<p>Thanks,</p>
<p>Udi</p>
| 2 | 2009-09-08T12:28:28Z | 1,393,752 | <p>I don't think there's any convention for this. You may just use file with extension like: .ini, .cfg, .conf, .config, .pref or anything you like.</p>
| 0 | 2009-09-08T12:34:05Z | [
"python",
"configuration",
"naming-conventions"
] |
configuration filename convention | 1,393,731 | <p>Is there a general naming conventions for configuration files for a simple python program?</p>
<p>Thanks,</p>
<p>Udi</p>
| 2 | 2009-09-08T12:28:28Z | 1,393,754 | <p>.conf is a nice extension too. But since mostly configuration files are application specific, it does not really matter what extension they have as long as they are consistent (i.e do not use .conf with .cfg in the same application).</p>
| 2 | 2009-09-08T12:34:08Z | [
"python",
"configuration",
"naming-conventions"
] |
configuration filename convention | 1,393,731 | <p>Is there a general naming conventions for configuration files for a simple python program?</p>
<p>Thanks,</p>
<p>Udi</p>
| 2 | 2009-09-08T12:28:28Z | 1,394,828 | <p>Django uses <code>settings.py</code> I like that a lot. It's very clear.</p>
| 1 | 2009-09-08T16:03:19Z | [
"python",
"configuration",
"naming-conventions"
] |
Need advice how to represent a certain datastructure in Python | 1,393,849 | <p>I'm not sure how to represent a certain datastructure in Python. It consists of groups and users where each user must be a member of exactly one group and groups should be in turn contained in a container, groups and users will only be used within this container. Furthermore I need random access to groups and users. A JSON representation of example data would look like this:</p>
<pre><code>{
"groupa": {
"name": "groupa",
"description": "bla",
"members": {
"usera": {
"name": "usera",
"age": 38
},
"userb": {
"name": "userb",
"age": 20
}
}
},
"groupb": {
"name": "groupb",
"description": "bla bla",
"members": {
"userc": {
"name": "userc",
"age": 56
}
}
}
}
</code></pre>
<p>Simply using nested dict seems unsuited because users and groups all have well defined attributes. Because Groups and Users are only used within the container I came up with a nested class:</p>
<pre><code>class AccountContainer:
class Group:
def __init__(self, container, group):
self.name = group
self.members = {}
self.container = container
self.container.groups[self.name] = self # add myself to container
class User:
def __init__(self, group, user, age=None):
self.name = user
self.age = age
self.group = group
self.group.members[self.name] = self # add myself to group
def __init__(self):
self.groups = {}
def add_user(self, group, username, age=None):
# possibly check if group exists
self.groups[group].members[username] = AccountContainer.User(self.groups[group], username, age=age)
def add_group(self, group):
self.groups[group] = AccountContainer.Group(self, group)
# creating
c = AccountContainer()
c.add_group("groupa")
c.add_user("groupa", "usera")
# access
c.groups["groupa"].members["usera"].age = 38
# deleting
del(c.groups["groupa"].members["usera"])
</code></pre>
<ul>
<li>How would you represent such a datastructure?</li>
<li>Is this a reasonable approach?</li>
</ul>
<p>To me it seems a bit unnatural using a method to create a group or user while otherwise referring to dicts.</p>
| 1 | 2009-09-08T12:54:38Z | 1,393,899 | <p>It's generally good practice to <em>not</em> have objects know about what contains them. Pass the user in to the group, not the group into the user. Just because your current application only has "users" used once, one per group, one group per account, doesn't mean you should hardcode all your classes with that knowledge. What if you want to reuse the User class elsewhere? What if you later need to support multiple AccountContainers with users in common?</p>
<p>You may also get some mileage out of <a href="http://docs.python.org/library/collections.html#collections.namedtuple" rel="nofollow">named tuples</a>, especially for your users:</p>
<pre><code>User = collections.namedtuple('User', ('name', 'age'))
class Group:
def __init__(self, name, users=()):
self.name = name
self.members = dict((u.name, u) for u in users)
def add(user):
self.members[user.name] = user
</code></pre>
<p>et cetera</p>
| 2 | 2009-09-08T13:02:16Z | [
"python"
] |
Need advice how to represent a certain datastructure in Python | 1,393,849 | <p>I'm not sure how to represent a certain datastructure in Python. It consists of groups and users where each user must be a member of exactly one group and groups should be in turn contained in a container, groups and users will only be used within this container. Furthermore I need random access to groups and users. A JSON representation of example data would look like this:</p>
<pre><code>{
"groupa": {
"name": "groupa",
"description": "bla",
"members": {
"usera": {
"name": "usera",
"age": 38
},
"userb": {
"name": "userb",
"age": 20
}
}
},
"groupb": {
"name": "groupb",
"description": "bla bla",
"members": {
"userc": {
"name": "userc",
"age": 56
}
}
}
}
</code></pre>
<p>Simply using nested dict seems unsuited because users and groups all have well defined attributes. Because Groups and Users are only used within the container I came up with a nested class:</p>
<pre><code>class AccountContainer:
class Group:
def __init__(self, container, group):
self.name = group
self.members = {}
self.container = container
self.container.groups[self.name] = self # add myself to container
class User:
def __init__(self, group, user, age=None):
self.name = user
self.age = age
self.group = group
self.group.members[self.name] = self # add myself to group
def __init__(self):
self.groups = {}
def add_user(self, group, username, age=None):
# possibly check if group exists
self.groups[group].members[username] = AccountContainer.User(self.groups[group], username, age=age)
def add_group(self, group):
self.groups[group] = AccountContainer.Group(self, group)
# creating
c = AccountContainer()
c.add_group("groupa")
c.add_user("groupa", "usera")
# access
c.groups["groupa"].members["usera"].age = 38
# deleting
del(c.groups["groupa"].members["usera"])
</code></pre>
<ul>
<li>How would you represent such a datastructure?</li>
<li>Is this a reasonable approach?</li>
</ul>
<p>To me it seems a bit unnatural using a method to create a group or user while otherwise referring to dicts.</p>
| 1 | 2009-09-08T12:54:38Z | 1,393,912 | <p>I would feel comfortable using dicts. But I'd put the content in lists as a list instead of a dict will keep it clean and less redundant:</p>
<pre><code>[
{
"name": "groupa",
"description": "bla",
"members": [{"name": "usera", "age": 38},
{"name": "userb","age": 20}]
},
{
"name": "groupb",
"description": "bla bla",
"members": [{"name": "userc","age": 56}]
}
]
</code></pre>
<p><strong>Update</strong>:</p>
<p>You can still use random elements by the use of the random module:</p>
<pre><code>groups_list[random.randrange(len(group_list))]
</code></pre>
| 1 | 2009-09-08T13:06:05Z | [
"python"
] |
Need advice how to represent a certain datastructure in Python | 1,393,849 | <p>I'm not sure how to represent a certain datastructure in Python. It consists of groups and users where each user must be a member of exactly one group and groups should be in turn contained in a container, groups and users will only be used within this container. Furthermore I need random access to groups and users. A JSON representation of example data would look like this:</p>
<pre><code>{
"groupa": {
"name": "groupa",
"description": "bla",
"members": {
"usera": {
"name": "usera",
"age": 38
},
"userb": {
"name": "userb",
"age": 20
}
}
},
"groupb": {
"name": "groupb",
"description": "bla bla",
"members": {
"userc": {
"name": "userc",
"age": 56
}
}
}
}
</code></pre>
<p>Simply using nested dict seems unsuited because users and groups all have well defined attributes. Because Groups and Users are only used within the container I came up with a nested class:</p>
<pre><code>class AccountContainer:
class Group:
def __init__(self, container, group):
self.name = group
self.members = {}
self.container = container
self.container.groups[self.name] = self # add myself to container
class User:
def __init__(self, group, user, age=None):
self.name = user
self.age = age
self.group = group
self.group.members[self.name] = self # add myself to group
def __init__(self):
self.groups = {}
def add_user(self, group, username, age=None):
# possibly check if group exists
self.groups[group].members[username] = AccountContainer.User(self.groups[group], username, age=age)
def add_group(self, group):
self.groups[group] = AccountContainer.Group(self, group)
# creating
c = AccountContainer()
c.add_group("groupa")
c.add_user("groupa", "usera")
# access
c.groups["groupa"].members["usera"].age = 38
# deleting
del(c.groups["groupa"].members["usera"])
</code></pre>
<ul>
<li>How would you represent such a datastructure?</li>
<li>Is this a reasonable approach?</li>
</ul>
<p>To me it seems a bit unnatural using a method to create a group or user while otherwise referring to dicts.</p>
| 1 | 2009-09-08T12:54:38Z | 1,394,404 | <p>I think an abundance of behavior-less classes, in a multi-paradigm language (one like C++ or Python, that while supporting classes doesn't constrain you to use them when simpler structures will do), is a "design smell" -- the design equivalent of a <a href="http://en.wikipedia.org/wiki/Code%5Fsmell" rel="nofollow">"code smell"</a>, albeit a mild one.</p>
<p>If I was doing a code review of this, I'd point that out, although it's nowhere as bad as to have me insist on a re-factoring. Nested classes (that have no specific code-behavioral reason to be nested) compound this: they offer no specific benefits and can on the other hand "get in the way", for example, in Python, by interfering with serialization (pickling).</p>
<p>In addition to good old dicts and full-fledged classes, Python 2.6 offers the handy alternative of <a href="http://docs.python.org/library/collections.html#collections.namedtuple" rel="nofollow">namedtuple</a>s for "structs" with a predefined set of attributes; they seem particularly suitable to this use case.</p>
<p>The handy "add this group/user to that container/group" functionality that's combined in your <code>add...</code> and <code>__init__</code> methods can be refactored into standalone functions (so can accessors, even though that's less of a problem -- hiding internal structure into standalone accessors gets you closer to respecting the <a href="http://en.wikipedia.org/wiki/Law%5Fof%5FDemeter" rel="nofollow">Law of Demeter</a>).</p>
| 5 | 2009-09-08T14:41:33Z | [
"python"
] |
Need advice how to represent a certain datastructure in Python | 1,393,849 | <p>I'm not sure how to represent a certain datastructure in Python. It consists of groups and users where each user must be a member of exactly one group and groups should be in turn contained in a container, groups and users will only be used within this container. Furthermore I need random access to groups and users. A JSON representation of example data would look like this:</p>
<pre><code>{
"groupa": {
"name": "groupa",
"description": "bla",
"members": {
"usera": {
"name": "usera",
"age": 38
},
"userb": {
"name": "userb",
"age": 20
}
}
},
"groupb": {
"name": "groupb",
"description": "bla bla",
"members": {
"userc": {
"name": "userc",
"age": 56
}
}
}
}
</code></pre>
<p>Simply using nested dict seems unsuited because users and groups all have well defined attributes. Because Groups and Users are only used within the container I came up with a nested class:</p>
<pre><code>class AccountContainer:
class Group:
def __init__(self, container, group):
self.name = group
self.members = {}
self.container = container
self.container.groups[self.name] = self # add myself to container
class User:
def __init__(self, group, user, age=None):
self.name = user
self.age = age
self.group = group
self.group.members[self.name] = self # add myself to group
def __init__(self):
self.groups = {}
def add_user(self, group, username, age=None):
# possibly check if group exists
self.groups[group].members[username] = AccountContainer.User(self.groups[group], username, age=age)
def add_group(self, group):
self.groups[group] = AccountContainer.Group(self, group)
# creating
c = AccountContainer()
c.add_group("groupa")
c.add_user("groupa", "usera")
# access
c.groups["groupa"].members["usera"].age = 38
# deleting
del(c.groups["groupa"].members["usera"])
</code></pre>
<ul>
<li>How would you represent such a datastructure?</li>
<li>Is this a reasonable approach?</li>
</ul>
<p>To me it seems a bit unnatural using a method to create a group or user while otherwise referring to dicts.</p>
| 1 | 2009-09-08T12:54:38Z | 1,402,287 | <p>To echo Alex's answer.... these nested classes reek of code smell to me. </p>
<p>Simpler maybe:</p>
<pre><code>def Group(name=None,description=None,members=None):
if name is None:
name = "UNK!" # some reasonable default
if members is None:
members = dict()
return dict(name = ...., members = ....)
</code></pre>
<p>In your original proposal, your objects are just glorified dicts anyway, and the only reason to use objects (in this code) are to get a cleaner <strong>init</strong> to handle empty attributes. Making them into functions that return actual dicts is nearly as clean, and much easier. Named-tuples seem like an even better solution though, as previously pointed out. </p>
<p>This (nested dicts approach) has the benefit of being trivial to construct from /dump to json.</p>
| 0 | 2009-09-09T21:44:55Z | [
"python"
] |
Change Vim command to work in MS-Windows? Use make to check python syntax | 1,394,058 | <p><code>:make</code> provides a list of errors which can be navigated through in order to fix.</p>
<p>The problem is that <a href="http://vim.wikia.com/wiki/Python%5F-%5Fcheck%5Fsyntax%5Fand%5Frun%5Fscript" rel="nofollow">this script only works in Unix based OSes.</a></p>
<pre><code>autocmd BufRead *.py set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\"
autocmd BufRead *.py set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m
</code></pre>
<p>Anyone could help me make it work or provide the equivalent for Windows XP?</p>
| 2 | 2009-09-08T13:31:54Z | 1,394,158 | <p>For the first part to work, you must first add python to your PATH variable.</p>
<p><a href="http://vlaurie.com/computers2/Articles/environment.htm" rel="nofollow">http://vlaurie.com/computers2/Articles/environment.htm</a></p>
<p>python.exe should be placed in:</p>
<pre><code>c:\PythonXX\bin
</code></pre>
<p>But I'm not that sure, check it out before adding that one.</p>
| 1 | 2009-09-08T13:52:09Z | [
"python",
"windows",
"vim",
"windows-xp"
] |
In Python, what is the best way to execute a local Linux command stored in a string? | 1,394,198 | <p>In Python, what is the simplest way to execute a local Linux command stored in a string while catching any potential exceptions that are thrown and logging the output of the Linux command and any caught errors to a common log file? </p>
<pre><code>String logfile = â/dev/logâ
String cmd = âlsâ
#try
#execute cmd sending output to >> logfile
#catch sending caught error to >> logfile
</code></pre>
| 6 | 2009-09-08T14:00:48Z | 1,394,233 | <p>subprocess is the best module for this.</p>
<p>You have different ways to run you scripts, in separate threads, or in the same waiting for each command to finish. Check the whole docs that are more than useful:</p>
<p><a href="http://docs.python.org/library/subprocess.html" rel="nofollow">http://docs.python.org/library/subprocess.html</a></p>
| 0 | 2009-09-08T14:06:05Z | [
"python"
] |
In Python, what is the best way to execute a local Linux command stored in a string? | 1,394,198 | <p>In Python, what is the simplest way to execute a local Linux command stored in a string while catching any potential exceptions that are thrown and logging the output of the Linux command and any caught errors to a common log file? </p>
<pre><code>String logfile = â/dev/logâ
String cmd = âlsâ
#try
#execute cmd sending output to >> logfile
#catch sending caught error to >> logfile
</code></pre>
| 6 | 2009-09-08T14:00:48Z | 1,394,253 | <p>Using the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen">subprocess</a> module is the correct way to do it:</p>
<pre><code>import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
["ls"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
logfile.write(output)
logfile.close()
</code></pre>
<p><strong>EDIT</strong>
subprocess expects the commands as a list so to run "ls -l" you need to do this:</p>
<pre><code>output, error = subprocess.Popen(
["ls", "-l"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
</code></pre>
<p>To generalize it a little bit.</p>
<pre><code>command = "ls -la"
output, error = subprocess.Popen(
command.split(' '), stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
</code></pre>
<p>Alternately you can do this, the output will go directly to the logfile so the output variable will be empty in this case:</p>
<pre><code>import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
["ls"], stdout=logfile,
stderr=subprocess.PIPE).communicate()
</code></pre>
| 13 | 2009-09-08T14:10:02Z | [
"python"
] |
In Python, what is the best way to execute a local Linux command stored in a string? | 1,394,198 | <p>In Python, what is the simplest way to execute a local Linux command stored in a string while catching any potential exceptions that are thrown and logging the output of the Linux command and any caught errors to a common log file? </p>
<pre><code>String logfile = â/dev/logâ
String cmd = âlsâ
#try
#execute cmd sending output to >> logfile
#catch sending caught error to >> logfile
</code></pre>
| 6 | 2009-09-08T14:00:48Z | 1,394,343 | <p>Check out <code>commands</code> module.</p>
<pre><code> import commands
f = open('logfile.log', 'w')
try:
exe = 'ls'
content = commands.getoutput(exe)
f.write(content)
except Exception, text:
f.write(text)
f.close()
</code></pre>
<p>Specifying <code>Exception</code> as an exception class after <code>except</code> will tell Python to catch all possible exceptions.</p>
| -2 | 2009-09-08T14:29:04Z | [
"python"
] |
python: combine sort-key-functions itemgetter and str.lower | 1,394,475 | <p>I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters.</p>
<pre><code>dict1 = {'name':'peter','phone':'12355'}
dict2 = {'name':'Paul','phone':'545435'}
dict3 = {'name':'klaus','phone':'55345'}
dict4 = {'name':'Krishna','phone':'12345'}
dict5 = {'name':'Ali','phone':'53453'}
dict6 = {'name':'Hans','phone':'765756'}
list_of_dicts = [dict1,dict2,dict3,dict4,dict5,dict6]
key_field = 'name'
list_of_dicts.sort(key=itemgetter(key_field))
# how to combine key=itemgetter(key_field) and key=str.lower?
for list_field in list_of_dicts:
print list_field[key_field]
</code></pre>
<p>should provide</p>
<pre><code>Ali, Hans, klaus, Krishna, Paul, peter
</code></pre>
<p>and not</p>
<pre><code>klaus, peter, Ali, Hans, Krishna, Paul
</code></pre>
| 5 | 2009-09-08T14:56:24Z | 1,394,512 | <pre><code>def lower_getter(field):
def _getter(obj):
return obj[field].lower()
return _getter
list_of_dicts.sort(key=lower_getter(key_field))
</code></pre>
| 2 | 2009-09-08T15:02:38Z | [
"python",
"function",
"sorting",
"key"
] |
python: combine sort-key-functions itemgetter and str.lower | 1,394,475 | <p>I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters.</p>
<pre><code>dict1 = {'name':'peter','phone':'12355'}
dict2 = {'name':'Paul','phone':'545435'}
dict3 = {'name':'klaus','phone':'55345'}
dict4 = {'name':'Krishna','phone':'12345'}
dict5 = {'name':'Ali','phone':'53453'}
dict6 = {'name':'Hans','phone':'765756'}
list_of_dicts = [dict1,dict2,dict3,dict4,dict5,dict6]
key_field = 'name'
list_of_dicts.sort(key=itemgetter(key_field))
# how to combine key=itemgetter(key_field) and key=str.lower?
for list_field in list_of_dicts:
print list_field[key_field]
</code></pre>
<p>should provide</p>
<pre><code>Ali, Hans, klaus, Krishna, Paul, peter
</code></pre>
<p>and not</p>
<pre><code>klaus, peter, Ali, Hans, Krishna, Paul
</code></pre>
| 5 | 2009-09-08T14:56:24Z | 1,394,530 | <p>How about this:</p>
<pre><code>list_of_dicts.sort(key=lambda a: a['name'].lower())
</code></pre>
| 11 | 2009-09-08T15:06:47Z | [
"python",
"function",
"sorting",
"key"
] |
python: combine sort-key-functions itemgetter and str.lower | 1,394,475 | <p>I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters.</p>
<pre><code>dict1 = {'name':'peter','phone':'12355'}
dict2 = {'name':'Paul','phone':'545435'}
dict3 = {'name':'klaus','phone':'55345'}
dict4 = {'name':'Krishna','phone':'12345'}
dict5 = {'name':'Ali','phone':'53453'}
dict6 = {'name':'Hans','phone':'765756'}
list_of_dicts = [dict1,dict2,dict3,dict4,dict5,dict6]
key_field = 'name'
list_of_dicts.sort(key=itemgetter(key_field))
# how to combine key=itemgetter(key_field) and key=str.lower?
for list_field in list_of_dicts:
print list_field[key_field]
</code></pre>
<p>should provide</p>
<pre><code>Ali, Hans, klaus, Krishna, Paul, peter
</code></pre>
<p>and not</p>
<pre><code>klaus, peter, Ali, Hans, Krishna, Paul
</code></pre>
| 5 | 2009-09-08T14:56:24Z | 1,394,609 | <p>In the general case, you'll want to write your key-extraction function for sorting purposes; only in special (though important) cases it happens that you can just reuse an existing callable to extract the keys for you, or just conjoin a couple of existing ones (in a "quick and dirty" way using <code>lambda</code>, since there's no built-in way to do function composition).</p>
<p>If you often need to perform these two kinds of operations for key extraction (get an item and call a method on that item), I suggest:</p>
<pre><code>def combiner(itemkey, methodname, *a, **k):
def keyextractor(container):
item = container[itemkey]
method = getattr(item, methodname)
return method(*a, **k)
return keyextractor
</code></pre>
<p>so <code>listofdicts.sort(key=combiner('name', 'lower'))</code> will work in your case.</p>
<p>Note that while excessive generalization has costs, tasteful and moderate generalization (leaving the item key, method name, and method arguments if any, as runtime-determined, in this case) generally has benefits -- one general function, not more complex than a dozen specific and specialized ones (with the extractor, method to call, or both, hardwired in their code), will be easier to maintain (and, of course, much easier to reuse!-).</p>
| 9 | 2009-09-08T15:19:54Z | [
"python",
"function",
"sorting",
"key"
] |
python: combine sort-key-functions itemgetter and str.lower | 1,394,475 | <p>I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters.</p>
<pre><code>dict1 = {'name':'peter','phone':'12355'}
dict2 = {'name':'Paul','phone':'545435'}
dict3 = {'name':'klaus','phone':'55345'}
dict4 = {'name':'Krishna','phone':'12345'}
dict5 = {'name':'Ali','phone':'53453'}
dict6 = {'name':'Hans','phone':'765756'}
list_of_dicts = [dict1,dict2,dict3,dict4,dict5,dict6]
key_field = 'name'
list_of_dicts.sort(key=itemgetter(key_field))
# how to combine key=itemgetter(key_field) and key=str.lower?
for list_field in list_of_dicts:
print list_field[key_field]
</code></pre>
<p>should provide</p>
<pre><code>Ali, Hans, klaus, Krishna, Paul, peter
</code></pre>
<p>and not</p>
<pre><code>klaus, peter, Ali, Hans, Krishna, Paul
</code></pre>
| 5 | 2009-09-08T14:56:24Z | 1,394,862 | <p>You probably should go with a lambda for the sake of readability. But as an interesting study into higher order functions, here's the extended version of q-combinator in Python (also known as the queer bird combinator). This allows you to create a new function by composing two functions</p>
<pre><code> def compose(inner_func, *outer_funcs):
if not outer_funcs:
return inner_func
outer_func = compose(*outer_funcs)
return lambda *args, **kwargs: outer_func(inner_func(*args, **kwargs))
from operator import itemgetter, methodcaller
name_lowered = compose(itemgetter('name'), methodcaller('lower'))
print(name_lowered( {'name': 'Foo'} ))
</code></pre>
<p>If you reverse the definitions of inner and outer in the <code>compose</code> function, you get the more traditional b-combinator (bluebird). I like the q-combinator more because of the similarity to unix pipes.</p>
| 4 | 2009-09-08T16:11:40Z | [
"python",
"function",
"sorting",
"key"
] |
python: combine sort-key-functions itemgetter and str.lower | 1,394,475 | <p>I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters.</p>
<pre><code>dict1 = {'name':'peter','phone':'12355'}
dict2 = {'name':'Paul','phone':'545435'}
dict3 = {'name':'klaus','phone':'55345'}
dict4 = {'name':'Krishna','phone':'12345'}
dict5 = {'name':'Ali','phone':'53453'}
dict6 = {'name':'Hans','phone':'765756'}
list_of_dicts = [dict1,dict2,dict3,dict4,dict5,dict6]
key_field = 'name'
list_of_dicts.sort(key=itemgetter(key_field))
# how to combine key=itemgetter(key_field) and key=str.lower?
for list_field in list_of_dicts:
print list_field[key_field]
</code></pre>
<p>should provide</p>
<pre><code>Ali, Hans, klaus, Krishna, Paul, peter
</code></pre>
<p>and not</p>
<pre><code>klaus, peter, Ali, Hans, Krishna, Paul
</code></pre>
| 5 | 2009-09-08T14:56:24Z | 1,395,099 | <p>This solution will use your system locale, and as a bonus, it will sort eventual other characters according to the current locale as well (Will put "ü" after "u" in a german locale etc).</p>
<pre><code>from locale import setlocale, strxfrm, LC_ALL
import operator
# call setlocale to init current locale
setlocale(LC_ALL, "")
def locale_keyfunc(keyfunc):
def locale_wrapper(obj):
return strxfrm(keyfunc(obj))
return locale_wrapper
list_of_dicts.sort(key=locale_keyfunc(operator.itemgetter("name")))
</code></pre>
<p>This of course uses that the locale sort is the User interface "natural" sort that you wish to emulate with .lower().</p>
<p>I'm amazed that python's <code>locale</code> module is unknown and unused, it for sure is an important component in the application I write (translated to multiple languages, but the locale module is important for even getting <em>one</em> module right. Case in point: in swedish 'V' and 'W' sort alike, so you have to collate them. <code>locale</code> does all that for you.).
In the <code>POSIX</code> locale (not default), this will revert to sorting "a" after "Z".</p>
| 4 | 2009-09-08T17:03:17Z | [
"python",
"function",
"sorting",
"key"
] |
python: combine sort-key-functions itemgetter and str.lower | 1,394,475 | <p>I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters.</p>
<pre><code>dict1 = {'name':'peter','phone':'12355'}
dict2 = {'name':'Paul','phone':'545435'}
dict3 = {'name':'klaus','phone':'55345'}
dict4 = {'name':'Krishna','phone':'12345'}
dict5 = {'name':'Ali','phone':'53453'}
dict6 = {'name':'Hans','phone':'765756'}
list_of_dicts = [dict1,dict2,dict3,dict4,dict5,dict6]
key_field = 'name'
list_of_dicts.sort(key=itemgetter(key_field))
# how to combine key=itemgetter(key_field) and key=str.lower?
for list_field in list_of_dicts:
print list_field[key_field]
</code></pre>
<p>should provide</p>
<pre><code>Ali, Hans, klaus, Krishna, Paul, peter
</code></pre>
<p>and not</p>
<pre><code>klaus, peter, Ali, Hans, Krishna, Paul
</code></pre>
| 5 | 2009-09-08T14:56:24Z | 1,396,477 | <p>Personally, I wish there were two functions in the Python standard library (probably in functools):</p>
<pre><code>def compose(*funcs):
"""
Compose any number of unary functions into a single unary
function.
>>> import textwrap
>>> str.strip(textwrap.dedent(compose.__doc__)) == compose(str.strip, textwrap.dedent)(compose.__doc__)
True
"""
compose_two = lambda f1, f2: lambda v: f1(f2(v))
return reduce(compose_two, funcs)
def method_caller(method_name, *args, **kwargs):
"""
Return a function that will call a named method on the
target object with optional positional and keyword
arguments.
>>> lower = method_caller('lower')
>>> lower('MyString')
'mystring'
"""
def call_method(target):
func = getattr(target, method_name)
return func(*args, **kwargs)
return call_method
</code></pre>
<p>I have implemented these for my own use in <a href="https://svn.jaraco.com/jaraco/python/jaraco.util/jaraco/util/functools.py" rel="nofollow">jaraco.util.functools</a>. </p>
<p>Either way, now your code is quite clear, self-documented, and robust (IMO).</p>
<pre><code>lower = method_caller('lower')
get_name = itemgetter('name')
lowered_name = compose(lower, get_name)
list_of_dicts.sort(key=lowered_name)
</code></pre>
| 4 | 2009-09-08T21:41:22Z | [
"python",
"function",
"sorting",
"key"
] |
python: combine sort-key-functions itemgetter and str.lower | 1,394,475 | <p>I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters.</p>
<pre><code>dict1 = {'name':'peter','phone':'12355'}
dict2 = {'name':'Paul','phone':'545435'}
dict3 = {'name':'klaus','phone':'55345'}
dict4 = {'name':'Krishna','phone':'12345'}
dict5 = {'name':'Ali','phone':'53453'}
dict6 = {'name':'Hans','phone':'765756'}
list_of_dicts = [dict1,dict2,dict3,dict4,dict5,dict6]
key_field = 'name'
list_of_dicts.sort(key=itemgetter(key_field))
# how to combine key=itemgetter(key_field) and key=str.lower?
for list_field in list_of_dicts:
print list_field[key_field]
</code></pre>
<p>should provide</p>
<pre><code>Ali, Hans, klaus, Krishna, Paul, peter
</code></pre>
<p>and not</p>
<pre><code>klaus, peter, Ali, Hans, Krishna, Paul
</code></pre>
| 5 | 2009-09-08T14:56:24Z | 7,810,937 | <pre><code>from functools import partial
def nested_funcs(*funcs):
return partial(reduce, lambda arg, func: func(arg), funcs)
sorted(list_of_dicts, key=nested_funcs(itemgetter('name'), str.strip, str.lower))
</code></pre>
| 3 | 2011-10-18T16:58:26Z | [
"python",
"function",
"sorting",
"key"
] |
How do I propagate C++ exceptions to Python in a SWIG wrapper library? | 1,394,484 | <p>I'm writing a SWIG wrapper around a custom C++ library which defines its own C++ exception types. The library's exception types are richer and more specific than standard exceptions. (For example, one class represents parse errors and has a collection of line numbers.) How do I propagate those exceptions back to Python while preserving the type of the exception?</p>
| 20 | 2009-09-08T14:57:44Z | 1,394,531 | <p>From the <a href="http://www.swig.org/Doc1.1/HTML/Exceptions.html" rel="nofollow">swig documentation</a> </p>
<pre><code>%except(python) {
try {
$function
}
catch (RangeError) {
PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
return NULL;
}
}
</code></pre>
| 0 | 2009-09-08T15:06:53Z | [
"python",
"exception",
"swig"
] |
How do I propagate C++ exceptions to Python in a SWIG wrapper library? | 1,394,484 | <p>I'm writing a SWIG wrapper around a custom C++ library which defines its own C++ exception types. The library's exception types are richer and more specific than standard exceptions. (For example, one class represents parse errors and has a collection of line numbers.) How do I propagate those exceptions back to Python while preserving the type of the exception?</p>
| 20 | 2009-09-08T14:57:44Z | 1,394,539 | <p>Is the <a href="http://www.swig.org/Doc1.1/HTML/Exceptions.html" rel="nofollow">swig exception documentation</a> any help? It mentions <a href="http://www.swig.org/Doc1.1/HTML/Exceptions.html#n5" rel="nofollow">defining different exception handlers</a>..</p>
| 0 | 2009-09-08T15:08:15Z | [
"python",
"exception",
"swig"
] |
How do I propagate C++ exceptions to Python in a SWIG wrapper library? | 1,394,484 | <p>I'm writing a SWIG wrapper around a custom C++ library which defines its own C++ exception types. The library's exception types are richer and more specific than standard exceptions. (For example, one class represents parse errors and has a collection of line numbers.) How do I propagate those exceptions back to Python while preserving the type of the exception?</p>
| 20 | 2009-09-08T14:57:44Z | 1,513,274 | <p>I know this question is a few weeks old but I just found it as I was researching a solution for myself. So I'll take a stab at an answer, but I'll warn in advance it may not be an attractive solution since swig interface files can be more complicated than hand coding the wrapper. Also, as far as I can tell, the swig documentation never deals directly with user defined exceptions.</p>
<p>Let's say you want to throw the following exception from your c++ code module, mylibrary.cpp, along with a little error message to be caught in your python code:</p>
<pre><code>throw MyException("Highly irregular condition..."); /* C++ code */
</code></pre>
<p>MyException is a user exception defined elsewhere.</p>
<p>Before you begin, make a note of how this exception should be caught in your python. For our purposes here, let's say you have python code such as the following:</p>
<pre><code>import mylibrary
try:
s = mylibrary.do_something('foobar')
except mylibrary.MyException, e:
print(e)
</code></pre>
<p>I think this describes your problem.</p>
<p>My solution involves making four additions to your swig interface file (mylibrary.i) as follows:</p>
<p>Step 1:
In the header directive (the usually unnamed %{...%} block) add a declaration for the pointer to the python aware exception, which we will call pMyException. Step 2 below will define this:</p>
<pre><code>%{
#define SWIG_FILE_WITH_INIT /* for eg */
extern char* do_something(char*); /* or #include "mylibrary.h" etc */
static PyObject* pMyException; /* add this! */
%}
</code></pre>
<p>Step 2:
Add an initialization directive (the "m" is particularly egregious, but that's what swig v1.3.40 currently needs at that point in its constructed wrapper file) - pMyException was declared in step 1 above:</p>
<pre><code>%init %{
pMyException = PyErr_NewException("_mylibrary.MyException", NULL, NULL);
Py_INCREF(pMyException);
PyModule_AddObject(m, "MyException", pMyException);
%}
</code></pre>
<p>Step 3:
As mentioned in an earlier post, we need an exception directive - note "%except(python)" is deprecated. This will wrap the c+++ function "do_something" in a try-except block which catches the c++ exception and converts it to the python exception defined in step 2 above:</p>
<pre><code>%exception do_something {
try {
$action
} catch (MyException &e) {
PyErr_SetString(pMyException, const_cast<char*>(e.what()));
SWIG_fail;
}
}
/* The usual functions to be wrapped are listed here: */
extern char* do_something(char*);
</code></pre>
<p>Step 4:
Because swig sets up a python wrapping (a 'shadow' module) around the .pyd dll, we also need to make sure our python code can 'see through' to the .pyd file. The following worked for me and it's preferable to editing the swig py wrapper code directly:</p>
<pre><code>%pythoncode %{
MyException = _mylibrary.MyException
%}
</code></pre>
<p>It's probably too late to be of much use to the original poster, but perhaps somebody else will find the suggestions above of some use. For small jobs you may prefer the cleanness of a hand-coded c++ extension wrapper to the confusion of a swig interface file.</p>
<hr>
<p>Added:</p>
<p>In my interface file listing above, I omitted the standard module directive because I only wanted to describe the additions necessary to make exceptions work. But your module line should look like:</p>
<pre><code>%module mylibrary
</code></pre>
<p>Also, your setup.py (if you are using distutils, which I recommend at least to get started) should have code similar to the following, otherwise step 4 will fail when _mylibrary is not recognized:</p>
<pre><code>/* setup.py: */
from distutils.core import setup, Extension
mylibrary_module = Extension('_mylibrary', extra_compile_args = ['/EHsc'],
sources=['mylibrary_wrap.cpp', 'mylibrary.cpp'],)
setup(name="mylibrary",
version="1.0",
description='Testing user defined exceptions...',
ext_modules=[mylibrary_module],
py_modules = ["mylibrary"],)
</code></pre>
<p>Note the compile flag /EHsc, which I needed on Windows to compile exceptions. Your platform may not require that flag; google has the details.</p>
<p>I have tested the code using my own names which I have converted here to "mylibrary" and "MyException" to help in generalizing the solution. Hopefully the transcription errors are few or none. The main points are the %init and %pythoncode directives along with</p>
<pre><code>static PyObject* pMyException;
</code></pre>
<p>in the header directive.</p>
<p>Hope that clarifies the solution.</p>
| 15 | 2009-10-03T09:10:42Z | [
"python",
"exception",
"swig"
] |
How do I propagate C++ exceptions to Python in a SWIG wrapper library? | 1,394,484 | <p>I'm writing a SWIG wrapper around a custom C++ library which defines its own C++ exception types. The library's exception types are richer and more specific than standard exceptions. (For example, one class represents parse errors and has a collection of line numbers.) How do I propagate those exceptions back to Python while preserving the type of the exception?</p>
| 20 | 2009-09-08T14:57:44Z | 14,073,400 | <p>I'll add a bit here, since the example given here now says that "%except(python)" is
deprecated...</p>
<p>You can now (as of swig 1.3.40, anyhow) do totally generic, script-language-independent translation. My example would be:</p>
<pre><code>%exception {
try {
$action
} catch (myException &e) {
std::string s("myModule error: "), s2(e.what());
s = s + s2;
SWIG_exception(SWIG_RuntimeError, s.c_str());
} catch (myOtherException &e) {
std::string s("otherModule error: "), s2(e.what());
s = s + s2;
SWIG_exception(SWIG_RuntimeError, s.c_str());
} catch (...) {
SWIG_exception(SWIG_RuntimeError, "unknown exception");
}
}
</code></pre>
<p>This will generate a RuntimeError exception in any supported scripting language,
including Python, without getting python specific stuff in your other headers.</p>
<p>You need to put this <em>before</em> the calls that want this exception handling.</p>
| 5 | 2012-12-28T17:34:49Z | [
"python",
"exception",
"swig"
] |
How do I propagate C++ exceptions to Python in a SWIG wrapper library? | 1,394,484 | <p>I'm writing a SWIG wrapper around a custom C++ library which defines its own C++ exception types. The library's exception types are richer and more specific than standard exceptions. (For example, one class represents parse errors and has a collection of line numbers.) How do I propagate those exceptions back to Python while preserving the type of the exception?</p>
| 20 | 2009-09-08T14:57:44Z | 30,078,393 | <p>U can also use:</p>
<p>catches: <a href="http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_catches" rel="nofollow">http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_catches</a></p>
<p>Example:</p>
<pre class="lang-cpp prettyprint-override"><code>%catches(std::exception, std::string, int, ...);
</code></pre>
<p>which generates for each function a try catch block:</p>
<pre class="lang-cpp prettyprint-override"><code> try {
result = (namespace::Function *)new namespace::Function ((uint16_t const *)arg1);
}
catch(std::exception &_e) {
SWIG_exception_fail(SWIG_SystemError, (&_e)->what());
}
catch(std::string &_e) {
SWIG_Python_Raise(SWIG_From_std_string(static_cast< std::string >(_e)), "std::string", 0); SWIG_fail;
}
catch(int &_e) {
SWIG_Python_Raise(SWIG_From_int(static_cast< int >(_e)), "int", 0); SWIG_fail;
}
catch(...) {
SWIG_exception_fail(SWIG_RuntimeError,"unknown exception");
}
</code></pre>
| -1 | 2015-05-06T13:34:38Z | [
"python",
"exception",
"swig"
] |
How do I copy a remote image in python? | 1,394,721 | <p>I need to copy a remote image (for example <code>http://example.com/image.jpg</code>) to my server. Is this possible?</p>
<p>How do you verify that this is indeed an image?</p>
| 14 | 2009-09-08T15:40:05Z | 1,394,732 | <p>Downloading stuff</p>
<pre><code>import urllib
url = "http://example.com/image.jpg"
fname = "image.jpg"
urllib.urlretrieve( url, fname )
</code></pre>
<p>Verifying that it is a image can be done in many ways. The hardest check is opening the file with the Python Image Library and see if it throws an error. </p>
<p>If you want to check the file type before downloading, look at the mime-type the remote server gives.</p>
<pre><code>import urllib
url = "http://example.com/image.jpg"
fname = "image.jpg"
opener = urllib.urlopen( url )
if opener.headers.maintype == 'image':
# you get the idea
open( fname, 'wb').write( opener.read() )
</code></pre>
| 5 | 2009-09-08T15:43:14Z | [
"python",
"download",
"file-copying"
] |
How do I copy a remote image in python? | 1,394,721 | <p>I need to copy a remote image (for example <code>http://example.com/image.jpg</code>) to my server. Is this possible?</p>
<p>How do you verify that this is indeed an image?</p>
| 14 | 2009-09-08T15:40:05Z | 1,394,744 | <p>To download:</p>
<pre><code>import urllib2
img = urllib2.urlopen("http://example.com/image.jpg").read()
</code></pre>
<p>To verify can use <a href="http://www.pythonware.com/products/pil/">PIL</a></p>
<pre><code>import StringIO
from PIL import Image
try:
im = Image.open(StringIO.StringIO(img))
im.verify()
except Exception, e:
# The image is not valid
</code></pre>
<p><strong>If you just want to verify this is an image even if the image data is not valid:</strong> You can use <a href="http://docs.python.org/library/imghdr.html">imghdr</a></p>
<pre><code>import imghdr
imghdr.what('ignore', img)
</code></pre>
<p>The method checks the headers and determines the image type. It will return None if the image was not identifiable.</p>
| 28 | 2009-09-08T15:45:41Z | [
"python",
"download",
"file-copying"
] |
How do I copy a remote image in python? | 1,394,721 | <p>I need to copy a remote image (for example <code>http://example.com/image.jpg</code>) to my server. Is this possible?</p>
<p>How do you verify that this is indeed an image?</p>
| 14 | 2009-09-08T15:40:05Z | 1,645,960 | <p>Same thing using httplib2...</p>
<pre><code>from PIL import Image
from StringIO import StringIO
from httplib2 import Http
# retrieve image
http = Http()
request, content = http.request('http://www.server.com/path/to/image.jpg')
im = Image.open(StringIO(content))
# is it valid?
try:
im.verify()
except Exception:
pass # not valid
</code></pre>
| 1 | 2009-10-29T19:21:04Z | [
"python",
"download",
"file-copying"
] |
How do I copy a remote image in python? | 1,394,721 | <p>I need to copy a remote image (for example <code>http://example.com/image.jpg</code>) to my server. Is this possible?</p>
<p>How do you verify that this is indeed an image?</p>
| 14 | 2009-09-08T15:40:05Z | 28,306,886 | <p>For the portion of the question with respect to <strong>copying</strong> a remote image, here's an answer inspired by <a href="http://stackoverflow.com/a/8221125/1497596">this answer</a>:</p>
<pre><code>import urllib2
import shutil
url = 'http://dummyimage.com/100' # returns a dynamically generated PNG
local_file_name = 'dummy100x100.png'
remote_file = urllib2.urlopen(url)
with open(local_file_name, 'wb') as local_file:
shutil.copyfileobj(remote_file, local_file)
</code></pre>
<p>Note that this approach will work for copying a remote file of any binary media type.</p>
| 0 | 2015-02-03T19:13:43Z | [
"python",
"download",
"file-copying"
] |
Converting vb.net code to python for educational purposes. Output of a numeric value not occuring | 1,394,737 | <p>My day job is mainly coding in vb.net, so I am very familiar with it. While doing my first few dozen project euler problems, I used vb.net just to get the hang of the problem styles. Now I'd like to use project euler to help me learn a new language and have been running a couple in python. However. I've hit a snag.</p>
<p>The following code will print the largest prime factor of a given number:</p>
<pre><code>Protected Function isPrime(ByVal n As Long) As Boolean
If n = 2 Then
Return True
End If
If n Mod 2 = 0 Then
Return False
End If
Dim maxFactor As Long = Math.Sqrt(n)
Dim i As Integer = 3
While i <= maxFactor
If n Mod i = 0 Then
Return False
End If
i = i + 2
End While
Return True
End Function
Protected Sub LargestPrimeFactor(ByVal n As Long)
Dim factor As Long = Math.Sqrt(n) ''#largest factor of n will be sqrt(n)
While factor > 2
If (n Mod factor) = 0 Then
If isPrime(factor) Then
Me.lblAnswer.Text = factor
factor = 0
End If
End If
factor = factor - 1
End While
End Sub
</code></pre>
<p>This vb.net code runs perfectly. The equivalent in python, I believe to be:</p>
<pre><code>from math import sqrt
def IsPrime(n):
if n==2: return true
if not n % 2: return false
maxFactor = sqrt(n)
i = 3
while i <= maxFactor:
if not n % i: return false
i += 2
return true
n = 600851475143
factor = sqrt(n)
while factor > 2:
if not n % factor:
if IsPrime(factor):
print factor
factor = 0
factor -= 1
</code></pre>
<p>However, the factor never ends up printing. Am I missing a nuance of python? Where might I have gone wrong? Thanks :)</p>
| 4 | 2009-09-08T15:43:48Z | 1,394,817 | <p>Previous solutions generate wrong answer.</p>
<ol>
<li>VB.net code operates on integers, and your Python code operates on floats, and this apparently fails somewhere.</li>
<li>As mentioned before, keyword capitalization (True/False).</li>
<li>You can use foo % bar == 0 with no problem.</li>
<li>You missed one level of indentation in "factor = 0" line.</li>
</ol>
<p>This code produces the correct answer, 6857:</p>
<pre><code>from math import sqrt
def IsPrime(n):
if n==2: return True
if n % 2 == 0: return False
maxFactor = long(sqrt(n))
i = 3
while i <= maxFactor:
if n % i == 0: return False
i += 2
return True
n = 600851475143
factor = long(sqrt(n))
while factor > 2:
if n % factor == 0:
if IsPrime(factor):
print factor
factor = 0
factor -= 1
</code></pre>
| 2 | 2009-09-08T16:01:22Z | [
"python",
"vb.net"
] |
How to do "hit any key" in python? | 1,394,956 | <p>How would I do a "hit any key" (or grab a menu option) in Python?</p>
<ul>
<li>raw_input requires you hit return.</li>
<li>Windows msvcrt has getch() and getche().</li>
</ul>
<p>Is there a portable way to do this using the standard libs?</p>
| 24 | 2009-09-08T16:32:27Z | 1,394,975 | <p>From the <a href="http://www.python.org/doc/faq/library/#how-do-i-get-a-single-keypress-at-a-time" rel="nofollow">python docs</a>:</p>
<pre><code>import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", `c`
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
</code></pre>
<p>This only works for Unix variants though. I don't think there is a cross-platform way.</p>
| 4 | 2009-09-08T16:37:11Z | [
"python"
] |
How to do "hit any key" in python? | 1,394,956 | <p>How would I do a "hit any key" (or grab a menu option) in Python?</p>
<ul>
<li>raw_input requires you hit return.</li>
<li>Windows msvcrt has getch() and getche().</li>
</ul>
<p>Is there a portable way to do this using the standard libs?</p>
| 24 | 2009-09-08T16:32:27Z | 1,394,994 | <pre><code>try:
# Win32
from msvcrt import getch
except ImportError:
# UNIX
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
</code></pre>
| 30 | 2009-09-08T16:41:04Z | [
"python"
] |
How to do "hit any key" in python? | 1,394,956 | <p>How would I do a "hit any key" (or grab a menu option) in Python?</p>
<ul>
<li>raw_input requires you hit return.</li>
<li>Windows msvcrt has getch() and getche().</li>
</ul>
<p>Is there a portable way to do this using the standard libs?</p>
| 24 | 2009-09-08T16:32:27Z | 1,395,006 | <pre><code>try:
os.system('pause') #windows, doesn't require enter
except whatever_it_is:
os.system('read -p "Press any key to continue"') #linux
</code></pre>
| 9 | 2009-09-08T16:43:11Z | [
"python"
] |
How to do "hit any key" in python? | 1,394,956 | <p>How would I do a "hit any key" (or grab a menu option) in Python?</p>
<ul>
<li>raw_input requires you hit return.</li>
<li>Windows msvcrt has getch() and getche().</li>
</ul>
<p>Is there a portable way to do this using the standard libs?</p>
| 24 | 2009-09-08T16:32:27Z | 11,932,011 | <p>on linux platform, I use <code>os.system</code> to call <code>/sbin/getkey</code> command, e.g.</p>
<pre><code>continue_ = os.system('/sbin/getkey -m "Please any key within %d seconds to continue..." -c 10')
if continue_:
...
else:
...
</code></pre>
<p>The benefit is it will show an countdown seconds to user, very interesting :)</p>
| 0 | 2012-08-13T09:59:58Z | [
"python"
] |
How to do "hit any key" in python? | 1,394,956 | <p>How would I do a "hit any key" (or grab a menu option) in Python?</p>
<ul>
<li>raw_input requires you hit return.</li>
<li>Windows msvcrt has getch() and getche().</li>
</ul>
<p>Is there a portable way to do this using the standard libs?</p>
| 24 | 2009-09-08T16:32:27Z | 33,966,614 | <p>A couple years ago I wrote a small library to do this in a cross-platform way (inspired directly by John Millikin's answer above). In addition to <code>getch</code>, it comes with a <code>pause</code> function that prints <code>'Press any key to continue . . .'</code>:</p>
<pre><code>pause()
</code></pre>
<p>You can provide a custom message too:</p>
<pre><code>pause('Hit any key')
</code></pre>
<p>If the next step is to exit, it also comes with a convenience function that calls <code>sys.exit(status)</code>:</p>
<pre><code>pause_exit(status=0, message='Hit any key')
</code></pre>
<p>Install with <code>pip install py-getch</code>, or <a href="https://github.com/joeyespo/py-getch" rel="nofollow">check it out here</a>.</p>
| 2 | 2015-11-28T01:06:57Z | [
"python"
] |
Parsing SQL with Python | 1,394,998 | <p>I want to create a SQL interface on top of a non-relational data store. Non-relational data store, but it makes sense to access the data in a relational manner.</p>
<p>I am looking into using <a href="http://www.antlr.org/">ANTLR</a> to produce an AST that represents the SQL as a relational algebra expression. Then return data by evaluating/walking the tree.</p>
<p>I have never implemented a parser before, and I would therefore like some advice on how to best implement a SQL parser and evaluator.</p>
<ul>
<li>Does the approach described above sound about right?</li>
<li>Are there other tools/libraries I should look into? Like <a href="http://www.dabeaz.com/ply/">PLY</a> or <a href="http://pyparsing.wikispaces.com/">Pyparsing</a>.</li>
<li>Pointers to articles, books or source code that will help me is appreciated.</li>
</ul>
<p><strong>Update:</strong></p>
<p>I implemented a simple SQL parser using pyparsing. Combined with Python code that implement the relational operations against my data store, this was fairly simple.</p>
<p>As I said in one of the comments, the point of the exercise was to make the data available to reporting engines. To do this, I probably will need to implement an ODBC driver. This is probably a lot of work.</p>
| 29 | 2009-09-08T16:42:03Z | 1,395,013 | <p><a href="http://www.reddit.com/r/Python/comments/99i6u/help%5Fpythonreddit%5Fseeking%5Fa%5Fsql%5Fparser/">This reddit post</a> suggests <a href="http://code.google.com/p/python-sqlparse/">Python-sqlparse</a> as an existing implementation, among a couple other links.</p>
| 5 | 2009-09-08T16:44:31Z | [
"python",
"sql",
"parsing",
"pyparsing"
] |
Parsing SQL with Python | 1,394,998 | <p>I want to create a SQL interface on top of a non-relational data store. Non-relational data store, but it makes sense to access the data in a relational manner.</p>
<p>I am looking into using <a href="http://www.antlr.org/">ANTLR</a> to produce an AST that represents the SQL as a relational algebra expression. Then return data by evaluating/walking the tree.</p>
<p>I have never implemented a parser before, and I would therefore like some advice on how to best implement a SQL parser and evaluator.</p>
<ul>
<li>Does the approach described above sound about right?</li>
<li>Are there other tools/libraries I should look into? Like <a href="http://www.dabeaz.com/ply/">PLY</a> or <a href="http://pyparsing.wikispaces.com/">Pyparsing</a>.</li>
<li>Pointers to articles, books or source code that will help me is appreciated.</li>
</ul>
<p><strong>Update:</strong></p>
<p>I implemented a simple SQL parser using pyparsing. Combined with Python code that implement the relational operations against my data store, this was fairly simple.</p>
<p>As I said in one of the comments, the point of the exercise was to make the data available to reporting engines. To do this, I probably will need to implement an ODBC driver. This is probably a lot of work.</p>
| 29 | 2009-09-08T16:42:03Z | 1,395,854 | <p>I have looked into this issue quite extensively. Python-sqlparse is a non validating parser which is not really what you need. The examples in antlr need a lot of work to convert to a nice ast in python. The sql standard grammers are <a href="http://savage.net.au/SQL/">here</a>, but it would be a full time job to convert them yourself and it is likely that you would only need a subset of them i.e no joins. You could try looking at the <a href="http://gadfly.sourceforge.net/">gadfly</a> (a python sql database) as well, but I avoided it as they used their own parsing tool.</p>
<p>For my case, I only essentially needed a where clause. I tried <a href="http://code.gustavonarea.net/booleano/">booleneo</a> (a boolean expression parser) written with pyparsing but ended up using pyparsing from scratch. The first link in the reddit post of Mark Rushakoff gives a sql example using it. <a href="http://whoosh.ca/">Whoosh</a> a full text search engine also uses it but I have not looked at the source to see how.</p>
<p>Pyparsing is very easy to use and you can very easily customize it to not be exactly the same as sql (most of the syntax you will not need). I did not like ply as it uses some magic using naming conventions.</p>
<p>In short give pyparsing a try, it will most likely be powerful enough to do what you need and the simple integration with python (with easy callbacks and error handling) will make the experience pretty painless. </p>
| 25 | 2009-09-08T19:25:54Z | [
"python",
"sql",
"parsing",
"pyparsing"
] |
Parsing SQL with Python | 1,394,998 | <p>I want to create a SQL interface on top of a non-relational data store. Non-relational data store, but it makes sense to access the data in a relational manner.</p>
<p>I am looking into using <a href="http://www.antlr.org/">ANTLR</a> to produce an AST that represents the SQL as a relational algebra expression. Then return data by evaluating/walking the tree.</p>
<p>I have never implemented a parser before, and I would therefore like some advice on how to best implement a SQL parser and evaluator.</p>
<ul>
<li>Does the approach described above sound about right?</li>
<li>Are there other tools/libraries I should look into? Like <a href="http://www.dabeaz.com/ply/">PLY</a> or <a href="http://pyparsing.wikispaces.com/">Pyparsing</a>.</li>
<li>Pointers to articles, books or source code that will help me is appreciated.</li>
</ul>
<p><strong>Update:</strong></p>
<p>I implemented a simple SQL parser using pyparsing. Combined with Python code that implement the relational operations against my data store, this was fairly simple.</p>
<p>As I said in one of the comments, the point of the exercise was to make the data available to reporting engines. To do this, I probably will need to implement an ODBC driver. This is probably a lot of work.</p>
| 29 | 2009-09-08T16:42:03Z | 4,866,734 | <p>Of course, it may be best to leverage <a href="http://code.google.com/p/python-sqlparse" rel="nofollow">python-sqlparse on Google Code</a></p>
<p>UPDATE: Now I see that this has been suggested - I concur that this is worthwhile:</p>
| 0 | 2011-02-01T18:55:08Z | [
"python",
"sql",
"parsing",
"pyparsing"
] |
How can I make `bin(30)` return `00011110` instead of `0b11110`? | 1,395,356 | <p>What does the "b" stand for in the output of bin(30): "0b11110"? Is there any way I can get rid of this "b"? How can I get the output of bin() to always return a standard 8 digit output?</p>
| 15 | 2009-09-08T17:53:38Z | 1,395,376 | <p>0b is like 0x - it indicates the number is formatted in binary (0x indicates the number is in hex).</p>
<p>See <a href="http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python">How do you express binary literals in python?</a></p>
<p>See <a href="http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax">http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax</a></p>
<p>To strip off the 0b it's easiest to use string slicing: <code>bin(30)[2:]</code></p>
<p>And similarly for format to 8 characters wide:</p>
<pre><code>('00000000'+bin(30)[2:])[-8:]
</code></pre>
<p>Alternatively you can use the <a href="http://www.python.org/dev/peps/pep-3101/">string formatter</a> (in 2.6+) to do it all in one step:</p>
<pre><code>"{0:08b}".format(30)
</code></pre>
| 21 | 2009-09-08T17:56:26Z | [
"python"
] |
How can I make `bin(30)` return `00011110` instead of `0b11110`? | 1,395,356 | <p>What does the "b" stand for in the output of bin(30): "0b11110"? Is there any way I can get rid of this "b"? How can I get the output of bin() to always return a standard 8 digit output?</p>
| 15 | 2009-09-08T17:53:38Z | 1,395,408 | <p>Using <a href="http://docs.python.org/library/stdtypes.html#str.zfill">zfill()</a>:</p>
<blockquote>
<p>Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than len(s).</p>
</blockquote>
<pre><code>>>> bin(30)[2:].zfill(8)
'00011110'
>>>
</code></pre>
| 29 | 2009-09-08T18:02:31Z | [
"python"
] |
How can I make `bin(30)` return `00011110` instead of `0b11110`? | 1,395,356 | <p>What does the "b" stand for in the output of bin(30): "0b11110"? Is there any way I can get rid of this "b"? How can I get the output of bin() to always return a standard 8 digit output?</p>
| 15 | 2009-09-08T17:53:38Z | 22,863,621 | <pre><code>>>> print format(30, 'b')
11110
>>> print format(30, 'b').zfill(8)
00011110
</code></pre>
<p>Should do. Here <code>'b'</code> stands for binary just like <code>'x'</code>, <code>'o'</code> & <code>'d'</code> for hexadecimal, octal and decimal respectively. </p>
| 8 | 2014-04-04T13:02:10Z | [
"python"
] |
Managing resources in a Python project | 1,395,593 | <p>I have a Python project in which I am using many non-code files. Currently these are all images, but I might use other kinds of files in the future. What would be a good scheme for storing and referencing these files?</p>
<p>I considered just making a folder "resources" in the main directory, but there is a problem; Some images are used from within sub-packages of my project. Storing these images that way would lead to coupling, which is a disadvantage.</p>
<p>Also, I need a way to access these files which is independent on what my current directory is.</p>
| 15 | 2009-09-08T18:37:39Z | 1,395,673 | <p>You can always have a separate "resources" folder in each subpackage which needs it, and use <code>os.path</code> functions to get to these from the <code>__file__</code> values of your subpackages. To illustrate what I mean, I created the following <code>__init__.py</code> file in three locations:</p>
<pre>
c:\temp\topp (top-level package)
c:\temp\topp\sub1 (subpackage 1)
c:\temp\topp\sub2 (subpackage 2)
</pre>
<p>Here's the <code>__init__.py</code> file:</p>
<pre><code>import os.path
resource_path = os.path.join(os.path.split(__file__)[0], "resources")
print resource_path
</code></pre>
<p>In c:\temp\work, I create an app, topapp.py, as follows:</p>
<pre><code>import topp
import topp.sub1
import topp.sub2
</code></pre>
<p>This respresents the application using the <code>topp</code> package and subpackages. Then I run it:</p>
<pre>
C:\temp\work>topapp
Traceback (most recent call last):
File "C:\temp\work\topapp.py", line 1, in
import topp
ImportError: No module named topp
</pre>
<p>That's as expected. We set the PYTHONPATH to simulate having our package on the path:</p>
<pre>
C:\temp\work>set PYTHONPATH=c:\temp
C:\temp\work>topapp
c:\temp\topp\resources
c:\temp\topp\sub1\resources
c:\temp\topp\sub2\resources
</pre>
<p>As you can see, the resource paths resolved correctly to the location of the actual (sub)packages on the path.</p>
<p><strong>Update:</strong> <a href="http://www.py2exe.org/index.cgi/data%5Ffiles" rel="nofollow">Here</a>'s the relevant py2exe documentation.</p>
| 3 | 2009-09-08T18:50:26Z | [
"python",
"resources",
"setuptools",
"distutils",
"decoupling"
] |
Managing resources in a Python project | 1,395,593 | <p>I have a Python project in which I am using many non-code files. Currently these are all images, but I might use other kinds of files in the future. What would be a good scheme for storing and referencing these files?</p>
<p>I considered just making a folder "resources" in the main directory, but there is a problem; Some images are used from within sub-packages of my project. Storing these images that way would lead to coupling, which is a disadvantage.</p>
<p>Also, I need a way to access these files which is independent on what my current directory is.</p>
| 15 | 2009-09-08T18:37:39Z | 1,396,657 | <p>You may want to use <code>pkg_resources</code> library that comes with <code>setuptools</code>.</p>
<p>For example, I've made up a quick little package <code>"proj"</code> to illustrate the resource organization scheme I'd use:</p>
<pre>proj/setup.py
proj/proj/__init__.py
proj/proj/code.py
proj/proj/resources/__init__.py
proj/proj/resources/images/__init__.py
proj/proj/resources/images/pic1.png
proj/proj/resources/images/pic2.png
</pre>
<p>Notice how I keep all resources in a separate subpackage.</p>
<p><code>"code.py"</code> shows how <code>pkg_resources</code> is used to refer to the resource objects:</p>
<pre><code>from pkg_resources import resource_string, resource_listdir
# Itemize data files under proj/resources/images:
print resource_listdir('proj.resources.images', '')
# Get the data file bytes:
print resource_string('proj.resources.images', 'pic2.png').encode('base64')
</code></pre>
If you run it, you get:
<pre>['__init__.py', '__init__.pyc', 'pic1.png', 'pic2.png']
iVBORw0KGgoAAAANSUhE ...
</pre>
<p>If you need to treat a resource as a fileobject, use <code>resource_stream()</code>.</p>
<p>The code accessing the resources may be anywhere within the subpackage structure of your project, it just needs to refer to subpackage containing the images by full name: <code>proj.resources.images</code>, in this case.</p>
<p>Here's <code>"setup.py"</code>:</p>
<pre><code>#!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='proj',
packages=find_packages(),
package_data={'': ['*.png']})
</code></pre>
<p><em>Caveat:</em>
To test things "locally", that is w/o installing the package first, you'll have to invoke your test scripts from directory that has <code>setup.py</code>. If you're in the same directory as <code>code.py</code>, Python won't know about <code>proj</code> package. So things like <code>proj.resources</code> won't resolve.</p>
| 17 | 2009-09-08T22:22:05Z | [
"python",
"resources",
"setuptools",
"distutils",
"decoupling"
] |
Managing resources in a Python project | 1,395,593 | <p>I have a Python project in which I am using many non-code files. Currently these are all images, but I might use other kinds of files in the future. What would be a good scheme for storing and referencing these files?</p>
<p>I considered just making a folder "resources" in the main directory, but there is a problem; Some images are used from within sub-packages of my project. Storing these images that way would lead to coupling, which is a disadvantage.</p>
<p>Also, I need a way to access these files which is independent on what my current directory is.</p>
| 15 | 2009-09-08T18:37:39Z | 1,472,725 | <p>@ pycon2009, there was a presentation on distutils and setuptools. You can find all of the videos here</p>
<p><a href="http://pycon.blip.tv/file/2061520/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 1</a></p>
<p><a href="http://pycon.blip.tv/file/2061678/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 2</a> </p>
<p><a href="http://pycon.blip.tv/file/2061724/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 3</a></p>
<p>In these videos, they describe how to include static resources in your package. I believe its in part 2.</p>
<p>With setuptools, you can define dependancies, this would allow you to have 2 packages that use resources from 3rd package. </p>
<p>Setuptools also gives you a standard way of accessing these resources and allows you to use relative paths inside of your packages, which eliminates the need to worry about where your packages are installed.</p>
| 1 | 2009-09-24T16:16:28Z | [
"python",
"resources",
"setuptools",
"distutils",
"decoupling"
] |
Trouble with simple Python Code | 1,395,603 | <p>I'm learning Python, and I'm having trouble with this simple piece of code:</p>
<pre><code>a = raw_input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
</code></pre>
<p>It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or negative number or zero. I'm guessing there's a simple solution, but i can't find it ;-)</p>
<p>Thanks in advance</p>
| 4 | 2009-09-08T18:39:48Z | 1,395,613 | <p><code>raw_input</code> is stored as a string, not an integer.</p>
<p>Try using <code>a = int(a)</code> before performing comparisons. </p>
| 2 | 2009-09-08T18:41:28Z | [
"python"
] |
Trouble with simple Python Code | 1,395,603 | <p>I'm learning Python, and I'm having trouble with this simple piece of code:</p>
<pre><code>a = raw_input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
</code></pre>
<p>It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or negative number or zero. I'm guessing there's a simple solution, but i can't find it ;-)</p>
<p>Thanks in advance</p>
| 4 | 2009-09-08T18:39:48Z | 1,395,615 | <pre><code>raw_input
</code></pre>
<p>returns a string so you need to convert <code>a</code> which is a string to an integer first: <code>a = int(a)</code></p>
| 5 | 2009-09-08T18:41:36Z | [
"python"
] |
Trouble with simple Python Code | 1,395,603 | <p>I'm learning Python, and I'm having trouble with this simple piece of code:</p>
<pre><code>a = raw_input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
</code></pre>
<p>It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or negative number or zero. I'm guessing there's a simple solution, but i can't find it ;-)</p>
<p>Thanks in advance</p>
| 4 | 2009-09-08T18:39:48Z | 1,395,617 | <p>That's because <code>a</code> is a string as inputted. Use <code>int()</code> to convert it to an integer before doing numeric comparisons.</p>
<pre><code>a = int(raw_input('Enter a number: '))
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
</code></pre>
<p>Alternatively, <code>input()</code> will do type conversion for you.</p>
<pre><code>a = input('Enter a number: ')
</code></pre>
| 7 | 2009-09-08T18:42:13Z | [
"python"
] |
Trouble with simple Python Code | 1,395,603 | <p>I'm learning Python, and I'm having trouble with this simple piece of code:</p>
<pre><code>a = raw_input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
</code></pre>
<p>It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or negative number or zero. I'm guessing there's a simple solution, but i can't find it ;-)</p>
<p>Thanks in advance</p>
| 4 | 2009-09-08T18:39:48Z | 1,395,623 | <p>raw input will return a string, not an integer. To convert it, try adding this line immediately after your raw_input statement:</p>
<p>a = int(a)</p>
<p>This will convert the string to an integer. You can crash it by giving it non-numeric data, though, so be careful.</p>
| 1 | 2009-09-08T18:42:36Z | [
"python"
] |
Trouble with simple Python Code | 1,395,603 | <p>I'm learning Python, and I'm having trouble with this simple piece of code:</p>
<pre><code>a = raw_input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
</code></pre>
<p>It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or negative number or zero. I'm guessing there's a simple solution, but i can't find it ;-)</p>
<p>Thanks in advance</p>
| 4 | 2009-09-08T18:39:48Z | 1,395,635 | <p>Because you are using <code>raw_input</code> you are getting the value as a String, which is always considered greater than 0 (even if the String is '-10')</p>
<p>Instead, try using input('Enter a number: ') and python will do the type conversion for you.</p>
<p>The final code would look like this:</p>
<pre><code>a = input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
</code></pre>
<p>However, as a number of folks have pointed out, using input() may lead to an error because it actually interprets the python objects passed in.</p>
<p>A safer way to handle this can be to cast raw_input with the desired type, as in:</p>
<pre><code>a = int( raw_input('Enter a number: '))
</code></pre>
<p>But beware, you will still need to do some error handling here to avoid trouble!</p>
| 7 | 2009-09-08T18:43:50Z | [
"python"
] |
Trouble with simple Python Code | 1,395,603 | <p>I'm learning Python, and I'm having trouble with this simple piece of code:</p>
<pre><code>a = raw_input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
</code></pre>
<p>It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or negative number or zero. I'm guessing there's a simple solution, but i can't find it ;-)</p>
<p>Thanks in advance</p>
| 4 | 2009-09-08T18:39:48Z | 1,396,057 | <p>Expanding on my comment on the <a href="http://stackoverflow.com/questions/1395603/trouble-with-simple-python-code/1395635#1395635">accepted answer</a>, here's how I would do it.</p>
<pre><code>value = None
getting_input = True
while getting_input:
try:
value = int(raw_input('Gimme a number: '))
getting_input = False
except ValueError:
print "That's not a number... try again."
if value > 0:
print 'Positive'
elif value < 0:
print 'Negative'
else:
print 'Null'
</code></pre>
| 7 | 2009-09-08T20:07:12Z | [
"python"
] |
Pervasive 8 and Python | 1,395,786 | <p>Is it possible to access a Pervasive 8 (not Pervasive SQL) database from python?</p>
| 1 | 2009-09-08T19:10:59Z | 1,397,698 | <p>I'm not familiar with Pervasive, but from a quick web search it looks like people are using some kind of ODBC driver to access Pervasive 8.</p>
<p>ODBC databases can be used from python in Windows using PyODBC: <a href="http://code.google.com/p/pyodbc/" rel="nofollow">http://code.google.com/p/pyodbc/</a></p>
| 2 | 2009-09-09T05:30:53Z | [
"python",
"database",
"pervasive"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.